skills-layer 0.2.16 → 0.2.17
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/package.json +1 -1
- package/public/skills-layer-public.mjs +29 -29
|
@@ -2019,7 +2019,7 @@ Next:
|
|
|
2019
2019
|
`).trimStart().split(/\n\s*\n/u)[0].split(/\r?\n/u).map(o=>o.trim()).filter(Boolean)}function gee(e){return[...new Set([...e.matchAll(/--[a-z0-9][a-z0-9-]*/giu)].map(t=>t[0]).sort())]}var hee=Object.freeze(["--ascii","--api-key","--base-url","--color","--detail","--help","--json","--motion","--no-color","--no-interactive","--no-motion","--output-format","--screen-reader","--ui"]),yee=Object.freeze({"auth mfa recovery-codes":Object.freeze(["--code","--mfa-code"])}),vee=Object.freeze(Dg.map(e=>{let t=e.split(" "),n=_o(t[0],t.slice(1));if(!n)throw new Error(`Public command manifest could not resolve focused help for ${e}.`);let r=See(e,n.usage),o=!Dg.some(s=>s!==e&&s.startsWith(`${e} `))&&r.length>0?"command":"help_topic";return Object.freeze({path:e,kind:o,pathSegments:Object.freeze(t),aliases:Object.freeze(bee(e)),usage:r.join(`
|
|
2020
2020
|
`)||n.usage,positionals:Object.freeze(_ee(r.join(`
|
|
2021
2021
|
`)||n.usage)),options:Object.freeze([...new Set([...o==="command"?xee(r.join(`
|
|
2022
|
-
`)):n.options,...yee[e]??[],"--json"])]),inheritedOptions:hee,outputModes:Object.freeze(["human","json","stream-json"]),mutability:Cee(n.sideEffects),humanInLoop:Iee(n),fixturePrerequisites:Object.freeze([...n.requiresLogin?["authenticated_account"]:[],...n.requiresNetwork?["reachable_backend"]:[]]),examples:Object.freeze(n.examples),availability:"public"})})),kee=new Map(vee.map(e=>[e.path,e]));function mN(e){let t=e.map(n=>n.trim().toLowerCase()).filter(Boolean);for(let n=t.length;n>=1;n-=1){let r=kee.get(t.slice(0,n).join(" "));if(r)return r}return null}function wee(e,t){let n=new Set([...e.options,...e.inheritedOptions]),r=t.indexOf("--"),i=r===-1?t:t.slice(0,r);for(let o of i){if(!o.startsWith("--"))continue;let s=o.split("=",1)[0];if(!n.has(s))return s.slice(2)}return null}var gN=wee;function bee(e){return e==="find"?["search"]:e==="workspaces"?["workspace"]:[]}function _ee(e){return[...new Set([...e.matchAll(/<([^>]+)>/gu)].map(t=>t[1]))]}function See(e,t){let n=`skills-layer ${e}`;return t.split(/\r?\n/u).map(r=>r.trim()).filter(r=>r===n||r.startsWith(`${n} `))}function xee(e){return[...new Set([...e.matchAll(/--[a-z][a-z0-9-]*/gu)].map(t=>t[0]))]}function Cee(e){let t=e.some(r=>r.includes("local")||r.includes("credential")),n=e.some(r=>r.includes("cloud_write")||r.includes("payment"));return t&&n?"mixed":n?"cloud_write":t?"local_write":"read_only"}function Iee(e){return e.sideEffects.includes("payment_mutation")?"financial":e.mayOpenBrowser?"browser":e.mayPrompt?"prompt":"none"}import{posix as Pee,win32 as Aee}from"node:path";function hN(e,t){let n=t==="win32"?Aee:Pee;if(t==="win32"){let o=rI(e.APPDATA,e.USERPROFILE,e.HOME);if(!o)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(o,"skills-layer")}let r=rI(e.XDG_CONFIG_HOME);if(r)return n.join(r,"skills-layer");let i=rI(e.HOME);if(!i)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(i,".skills-layer")}function rI(...e){return e.map(t=>t?.trim()).find(t=>!!t)}var Ree=/^[\u00a0\u2007\u202f\ufeff]+|[\u00a0\u2007\u202f\ufeff]+$/gu,Eee=/^\[(https?:\/\/[^\]\r\n]+)\]\((https?:\/\/[^)\r\n]+)\)$/u;function yN(e){let t=e.indexOf("--");return e.map((n,r)=>{if(t!==-1&&r>t)return n;let i=n.replace(Ree,""),o=Eee.exec(i);return o&&o[1]===o[2]?o[1]:i})}var vN={enterprise_member_already_active:E("conflict","conflict",!1,!1,"This person is already an active Enterprise member.",[4]),local_cleanup_incomplete:E("human_action_required","error",!0,!0,"Unlock the OS credential store and retry logout to finish local cleanup.",[4,5]),admin_step_up_invalid:E("security_verification_failed","error",!1,!0,"Verify your administrator step-up key in the private operator checkout.",[4]),verification_code_locked:E("rate_limited","rate_limited",!0,!0,"This code is locked. Request a new code after the retry time.",[4]),conflicting_flags:E("invalid_input","error",!1,!0,"Choose a value or its clear flag, not both.",[4]),flag_value_missing:E("invalid_input","error",!1,!0,"Supply a value for the flag.",[4]),rights_attestation_required:E("precondition_required","error",!1,!0,"Public and unlisted releases require confirmation of distribution rights.",[4]),rights_attestation_invalid:E("invalid_input","error",!1,!0,"Supply a supported rights basis and public distribution scope.",[4]),catalogue_artifact_unavailable:E("backend_unreachable","error",!0,!0,"The catalogue artifact could not be downloaded; retry export.",[4]),admin_mfa_required:E("human_action_required","human_action_required",!1,!0,"Enable MFA with skills-layer auth mfa setup, then retry.",[4]),admin_mfa_unavailable:E("backend_unreachable","unavailable",!0,!0,"Administrator MFA is unavailable; contact the deployment operator.",[5]),source_read_unavailable:E("backend_unreachable","source_unavailable",!1,!0,"The source could not be read completely. Its package has not been assessed.",[5]),command_failed:E("internal_error","error",!1,!1,"The command could not be completed.",[5]),resource_not_found:E("not_found","not_found",!1,!0,"The requested resource was not found.",[4]),permission_denied:E("permission_denied","error",!1,!1,"This credential cannot perform the requested operation.",[4]),login_required:E("login_required","login_required",!1,!0,"Sign in is required.",[4]),unauthorized:E("login_required","login_required",!1,!0,"Sign in is required.",[4]),api_key_invalid_or_expired:E("login_required","login_required",!1,!0,"The saved API key is no longer valid. Sign in again to use account features.",[4]),confirmation_required:E("confirmation_required","human_action_required",!1,!0,"Human confirmation is required.",[4]),mfa_setup_required:E("human_action_required","human_action_required",!1,!0,"MFA setup is required.",[4]),login_mfa_required:E("human_action_required","human_action_required",!1,!0,"A second authentication factor is required.",[4]),login_mfa_input_invalid:E("invalid_input","error",!1,!0,"Provide exactly one supported MFA proof.",[4]),login_mfa_invalid:E("security_verification_failed","error",!1,!0,"The MFA proof was invalid or already used.",[4]),login_security_unavailable:E("security_verification_failed","security_unavailable",!0,!0,"Login security is unavailable.",[5]),mfa_challenge_locked:E("rate_limited","rate_limited",!0,!0,"The MFA challenge is temporarily locked.",[4]),social_secure_continuation_unavailable:E("security_verification_failed","security_unavailable",!1,!0,"Secure social continuation is unavailable.",[4,5]),social_continuation_terminal:E("security_verification_failed","error",!1,!0,"The social continuation ended without authorization.",[4]),verification_code_expired:E("human_action_required","error",!1,!0,"The verification code expired.",[4]),payout_human_confirmation_required:E("human_action_required","human_action_required",!1,!0,"Human payout confirmation is required.",[4]),security_report_requires_action:E("policy_blocked","blocked",!1,!0,"The security report requires action.",[4]),trust_report_not_actionable:E("policy_blocked","blocked",!1,!0,"The trust report does not permit this transition.",[4]),trust_report_authority_mismatch:E("security_verification_failed","blocked",!1,!0,"Trust evidence does not match the exact artifact generation.",[4,5]),trust_report_required_evidence_unavailable:E("verification_pending","action_required",!0,!0,"Required trust evidence is unavailable or incomplete.",[2,4,5]),sarif_source_mapping_required:E("precondition_required","error",!1,!0,"Repository SARIF requires verified repository-relative source locations.",[4]),sarif_security_evidence_required:E("precondition_required","error",!1,!0,"Runtime-audit SARIF requires typed security evidence.",[4]),sarif_rule_mapping_required:E("precondition_required","error",!1,!0,"Runtime-audit SARIF requires an explicit reviewed rule mapping for every actionable event.",[4]),sarif_profile_unsupported:E("invalid_input","error",!1,!0,"The requested SARIF profile is not available for this report audience.",[4]),cloud_trust_ledger_mismatch:E("security_verification_failed","blocked",!1,!0,"This exact public skill generation is temporarily unavailable because its Cloud Trust Ledger attestation does not match. A Skills Layer operator must re-attest the exact generation before install.",[4]),api_key_active_limit_reached:E("quota_exceeded","conflict",!1,!0,"The active API-key limit has been reached.",[4]),rate_limited:E("rate_limited","rate_limited",!0,!0,"The request rate limit was reached.",[4]),source_connection_already_canceled:E("unchanged","unchanged",!1,!1,"The source connection was already canceled.",[2,4]),source_connection_completed:E("conflict","conflict",!1,!1,"A completed source connection cannot be canceled.",[4]),source_connection_revoked:E("unchanged","unchanged",!1,!1,"The authorized source connection was revoked.",[0]),source_connection_already_revoked:E("unchanged","unchanged",!1,!1,"The source connection was already revoked.",[0]),source_connection_not_authorized:E("conflict","conflict",!1,!1,"Only an authorized source connection can be revoked.",[4]),reupload_required:E("precondition_required","reupload_required",!1,!0,"The stored artifact is unavailable; upload the bundle again.",[4]),artifact_finalization_failed:E("processing_action_required","partial_success",!0,!1,"The version exists but artifact finalisation is incomplete.",[0]),publication_moderation_failed:E("processing_action_required","partial_success",!1,!1,"The version exists but its moderation transition needs operator inspection.",[0]),source_connection_completion_unverified:E("verification_pending","verification_warning",!0,!0,"Source connection completion could not be verified.",[4,5]),admin_mcp_verification_warning:E("verification_pending","verification_warning",!0,!0,"Administrator MCP verification is pending.",[2,4,5]),admin_mcp_verification_rejected:E("security_verification_failed","rejected",!1,!0,"Administrator MCP verification was rejected.",[4]),authoritative_security_report_pending:E("processing_action_required","already_processing",!0,!0,"The authoritative security report is still processing.",[4]),publication_continuation_scheduled:E("processing_action_required","already_processing",!0,!1,"Publication is continuing through the durable exact-generation workflow.",[2,4]),binary_inspection_pending:E("processing_action_required","already_processing",!0,!0,"Binary asset security inspection is still processing.",[2,4]),binary_inspection_unavailable:E("verification_pending","hold",!0,!0,"Required binary asset security inspection is currently unavailable.",[2,4,5]),binary_asset_blocked:E("policy_blocked","blocked",!1,!0,"A binary asset did not satisfy the platform security policy.",[2,4]),binary_profile_suspended:E("policy_blocked","hold",!0,!0,"The required binary format profile is temporarily suspended.",[2,4]),security_adjudication_pending:E("processing_action_required","already_processing",!0,!0,"Contextual security evidence is still being evaluated.",[2,4]),content_adjudication_insufficient_evidence:E("verification_pending","hold",!0,!0,"The available evidence is insufficient to resolve the security finding.",[2,4]),content_adjudication_confirmed_risk:E("policy_blocked","blocked",!1,!0,"The exact content contains a confirmed security risk.",[2,4]),content_adjudication_source_remediation_required:E("policy_blocked","blocked",!1,!0,"The source must be changed before security review can continue.",[2,4]),content_adjudication_execution_failed:E("verification_pending","hold",!0,!0,"Content security adjudication could not complete and remains held.",[2,4,5]),content_probe_runner_unavailable:E("verification_pending","hold",!0,!0,"The isolated content security evaluator is currently unavailable.",[2,4,5]),binary_inspection_authority_invalid:E("security_verification_failed","hold",!0,!0,"Binary security evidence could not be authenticated.",[2,4,5]),managed_security_pack_stale:E("security_verification_failed","hold",!0,!0,"A required managed security definition pack is not current.",[2,4,5]),workflow_dependency_incomplete:E("precondition_required","waiting_for_dependency",!0,!0,"A required upstream workflow is incomplete.",[4]),creator_processing_sla_breached:E("processing_action_required","action_required",!1,!0,"Creator processing exceeded its platform SLA.",[4,5]),invalid_global_option:E("invalid_input","error",!1,!0,"A global CLI option is invalid.",[4]),invalid_numeric_input:E("invalid_input","error",!1,!0,"A numeric option is invalid.",[4]),unknown_flag:E("invalid_input","error",!1,!0,"The option is not supported.",[4]),unknown_command:E("invalid_input","error",!1,!0,"The command is not supported.",[4]),unknown_subcommand:E("invalid_input","error",!1,!0,"The command is not supported.",[4]),missing_required_argument:E("invalid_input","error",!1,!0,"Required information is missing.",[4]),invalid_json:E("invalid_input","error",!1,!0,"The JSON value is invalid.",[4]),canonical_bundle_rejected:E("invalid_input","error",!1,!0,"The bundle failed canonical validation.",[4]),recovery_code_invalid_or_expired:E("human_action_required","error",!1,!0,"The recovery code is invalid or expired.",[4]),social_provider_not_configured:E("precondition_required","error",!1,!0,"The selected social provider is not configured.",[4,5]),search_selection_not_found:E("not_found","not_found",!1,!0,"The selected skill is not present in these search results.",[4]),best_effort:E("unchanged","low_confidence",!1,!0,"Best-effort candidates need a more specific task for higher confidence.",[2]),unsafe_task:E("policy_blocked","policy_blocked",!1,!0,"This task is outside the recommendation safety policy.",[2]),no_confident_recommendation:E("unchanged","no_confident_recommendation",!1,!0,"No skill met the calibrated recommendation confidence policy.",[2]),clarification_required:E("human_action_required","clarification_required",!1,!0,"One public task constraint is required before a skill can be recommended.",[2]),workspace_required:E("precondition_required","error",!1,!0,"A workspace id is required for this install.",[4]),unsupported_skill_type:E("invalid_input","error",!1,!0,"The requested skill type is unsupported.",[4]),creator_resource_not_found:E("not_found","not_found",!1,!0,"The creator resource was not found.",[4]),creator_access_required:E("permission_denied","access_required",!1,!0,"Creator management access is required for this public skill.",[4]),library_access_required:E("permission_denied","access_required",!1,!0,"Library access is required to inspect issues for this public skill.",[4]),issue_not_found:E("not_found","not_found",!1,!0,"The issue was not found in the managed skill.",[4]),review_not_found:E("not_found","not_found",!1,!0,"The review was not found in the managed skill.",[4]),api_key_not_found:E("not_found","not_found",!1,!0,"The API key was not found.",[4]),approval_request_not_found:E("not_found","not_found",!1,!0,"The approval request was not found.",[4]),available:E("unchanged","available",!1,!1,"The requested capability is available.",[2]),catalog_acquisition_ready:E("unchanged","ready",!1,!1,"The catalog acquisition is ready.",[2]),catalog_artifact_unavailable:E("precondition_required","error",!0,!0,"The exact catalog artifact is temporarily unavailable.",[4,5]),compare_missing_skills:E("not_found","not_found",!1,!0,"One or more skills requested for comparison were not found.",[4]),conflicting_export_output:E("conflict","conflict",!1,!0,"The requested export output options conflict.",[4]),conflicting_mcp_client_selection:E("conflict","conflict",!1,!0,"The MCP client selection is ambiguous.",[4]),conflicting_mcp_migration_mode:E("conflict","conflict",!1,!0,"Choose either a legacy MCP migration preview or an apply operation.",[4]),needs_mcp_client_choice:E("human_action_required","needs_mcp_client_choice",!1,!0,"Choose a verified MCP host before setup can continue.",[4]),mcp_config_symlink_rejected:E("human_action_required","mcp_setup_blocked",!1,!0,"Replace the MCP config symlink with a regular user-owned config file before retrying.",[4]),mcp_registration_ownership_ambiguous:E("human_action_required","mcp_setup_blocked",!1,!0,"Review or rename the existing unowned Skills Layer MCP entry before retrying.",[4]),mcp_client_scope_required:E("human_action_required","needs_mcp_client_scope",!1,!0,"Choose one configured MCP host or explicitly select all hosts.",[4]),mcp_client_inventory_missing:E("precondition_required","mcp_needs_repair",!1,!0,"The local MCP configuration has no canonical host inventory.",[4]),mcp_legacy_project_path_required:E("precondition_required","error",!1,!0,"Choose the exact project root to inspect for legacy MCP registration.",[4]),mcp_multi_client_verify_failed:E("verification_pending","mcp_needs_repair",!0,!0,"One or more configured MCP hosts failed verification.",[4,5]),unknown_mcp_client:E("unsupported_client","error",!1,!0,"The requested MCP host is unsupported.",[4]),creator_listing_not_found_or_not_owned:E("not_found","not_found",!1,!0,"The creator listing is unavailable to this account.",[4]),creator_submission_not_found:E("not_found","not_found",!1,!0,"The creator submission was not found.",[4]),enterprise_resource_not_found:E("not_found","not_found",!1,!0,"The Enterprise resource was not found.",[4]),enterprise_checkout_completion_pending:E("processing_action_required","completion_pending",!0,!0,"Enterprise checkout completion is still being reconciled.",[2,5]),guardian_enabled:E("unchanged","enabled",!1,!1,"Guardian enforcement is enabled.",[2]),feature_already_configured:E("unchanged","unchanged",!1,!1,"The requested feature state is already configured.",[2]),guardian_exact_version_required:E("precondition_required","error",!1,!0,"Guardian requires one exact skill version.",[4]),guardian_unmanaged_atomic_execution_required:E("precondition_required","blocked",!1,!0,"Unmanaged execution cannot be authorized by a diagnostic Guardian check.",[4]),guardian_plan_resolution_failed:E("internal_error","error",!0,!0,"Guardian could not resolve a safe execution plan.",[4,5]),guardian_version_not_current:E("conflict","conflict",!1,!0,"The selected Guardian version is not current.",[4]),human_handoff_required:E("human_action_required","human_action_required",!1,!0,"A human must complete this handoff.",[2,4]),invalid_amount_cents:E("invalid_input","error",!1,!0,"The amount must be a valid non-negative number of cents.",[4]),invalid_enterprise_role:E("invalid_input","error",!1,!0,"The Enterprise role is invalid.",[4]),invalid_expiry:E("invalid_input","error",!1,!0,"The expiry value is invalid.",[4]),invalid_incident_path:E("invalid_input","error",!1,!0,"The incident path is invalid.",[4]),invalid_issue_status:E("invalid_input","error",!1,!0,"The issue status is invalid.",[4]),invalid_price_cents:E("invalid_input","error",!1,!0,"The price must be a valid non-negative number of cents.",[4]),invalid_review_status:E("invalid_input","error",!1,!0,"The review status is invalid.",[4]),invalid_scope:E("invalid_input","error",!1,!0,"The requested scope is invalid.",[4]),invalid_search_filter:E("invalid_input","error",!1,!0,"The search filter is invalid.",[4]),invalid_seats:E("invalid_input","error",!1,!0,"The Enterprise seat count is invalid.",[4]),invalid_sort:E("invalid_input","error",!1,!0,"The requested sort mode is invalid.",[4]),invalid_source:E("invalid_input","error",!1,!0,"The requested source is invalid.",[4]),invalid_version:E("invalid_input","error",!1,!0,"The semantic version is invalid.",[4]),local_install_not_found:E("not_found","not_found",!1,!0,"The local installation was not found.",[4]),local_source_requires_client_files:E("precondition_required","error",!1,!0,"This local source requires client-provided files.",[4]),ownership_claim_not_found:E("not_found","not_found",!1,!0,"The ownership claim was not found.",[4]),ownership_dispute_open:E("human_action_required","manual_review_required",!1,!0,"An ownership dispute requires human resolution.",[2,4]),ownership_already_configured:E("unchanged","unchanged",!1,!1,"The requested ownership assignments are already configured.",[2]),org_dependency_audit_incomplete:E("precondition_required","hold",!0,!0,"The organization dependency audit is incomplete.",[2,4]),purchase_not_found:E("not_found","not_found",!1,!0,"The purchase was not found.",[4]),restore_record_not_found:E("not_found","not_found",!1,!0,"No restorable installation record was found.",[4]),scaffold_overwrite_confirmation_required:E("confirmation_required","human_action_required",!1,!0,"Overwriting the scaffold requires confirmation.",[4]),security_report_requires_review:E("policy_blocked","manual_review_required",!1,!0,"The security report requires human review.",[2,4]),security_report_missing:E("not_found","not_found",!1,!0,"The security report was not found.",[4]),platform_score_subject_missing:E("not_found","not_found",!1,!0,"The exact Platform Score skill generation was not found.",[4]),security_evidence_operation_not_found:E("not_found","not_found",!1,!0,"The security evidence operation was not found.",[4]),skill_not_found:E("not_found","not_found",!1,!0,"The skill was not found.",[4]),social_browser_confirmation_required:E("human_action_required","human_action_required",!1,!0,"Social sign-in requires browser confirmation.",[4]),source_connection_not_found:E("not_found","not_found",!1,!0,"The source connection was not found.",[4]),source_not_verifiable:E("policy_blocked","manual_review_required",!1,!0,"The source cannot be verified automatically.",[2,4]),source_path_not_found:E("not_found","not_found",!1,!0,"The source path was not found.",[4]),source_reference_not_found:E("not_found","not_found",!1,!0,"The source reference was not found.",[4]),submission_not_found:E("not_found","not_found",!1,!0,"The submission was not found.",[2,4]),trust_report_not_found:E("not_found","not_found",!1,!0,"The Platform Score report was not found.",[4]),unknown_agent:E("unsupported_client","error",!1,!0,"The requested agent is unsupported.",[4]),verification_code_invalid:E("human_action_required","error",!1,!0,"The verification code is invalid or expired.",[4]),workspace_not_found_or_forbidden:E("not_found","not_found",!1,!0,"The workspace is unavailable to this account.",[4]),workspace_skill_approval_not_found:E("not_found","not_found",!1,!0,"The workspace skill approval was not found.",[4]),workspace_working_mode_not_found:E("not_found","not_found",!1,!0,"The selected workspace was not found.",[4])};function $ee(e){let t=vN[e];return t?{reasonCode:e,...t}:null}function Og(e,t={}){if(!e)return t.httpStatus===404?Ia("resource_not_found"):t.httpStatus===401?Ia("login_required"):t.httpStatus===403?Ia("permission_denied"):t.httpStatus===409?gt("conflict","conflict"):t.httpStatus===429?Ia("rate_limited"):(t.httpStatus&&t.httpStatus>=500,Ia("command_failed"));let n=$ee(e);return n||(e.includes("not_found")||e==="missing_record"?gt(e,"not_found","not_found"):e.includes("rate_limit")?gt(e,"rate_limited","rate_limited",!0):e.includes("quota")||e.includes("_limit_reached")||e.includes("_limit_exhausted")?gt(e,"quota_exceeded","conflict"):e.includes("human")||e.includes("mfa")||e.includes("browser_confirmation")?gt(e,"human_action_required","human_action_required"):e.includes("already_canceled")||e.includes("unchanged")||e.includes("already_complete")?gt(e,"unchanged","unchanged"):e.includes("dependency")||e.includes("precondition")||e.includes("required")?gt(e,"precondition_required","error"):e.includes("processing")||e.includes("pending")||e.includes("already_processing")?gt(e,"processing_action_required","already_processing",!0):e.includes("conflict")||e.includes("already_final")||e.includes("completed")?gt(e,"conflict","conflict"):e.includes("payment")||e.includes("checkout")||e.includes("purchase")?gt(e,"payment_required","human_action_required"):e.includes("source")?gt(e,"source_required","error"):e.includes("backend")||e.includes("unreachable")||e.includes("network")?gt(e,"backend_unreachable","error",!0):e.includes("agent")||e.includes("client")||e.includes("unsupported")?gt(e,"unsupported_client","error"):e.includes("blocked")||e.includes("policy")||e.includes("guardian")?gt(e,"policy_blocked","blocked"):e.includes("forbidden")||e.includes("permission_denied")?gt(e,"permission_denied","error"):e.includes("not_allowed")||e.includes("invalid_transition")?gt(e,"operation_not_allowed","error"):gt(e,"invalid_input","error"))}function E(e,t,n,r,i,o){return{family:e,defaultStatus:t,retryable:n,nextActionRequired:r,safeSummary:i,allowedHttpStatusClasses:o}}function Ia(e){return{reasonCode:e,...vN[e]}}function gt(e,t,n="error",r=!1){return{reasonCode:e,family:t,defaultStatus:n,retryable:r,nextActionRequired:!1,safeSummary:"The command could not be completed.",allowedHttpStatusClasses:[4,5]}}var kN=[["help","account"],["help","use"],["help","creator"],["help","teams"],["help","security"],["help","mcp"],["help","automation"],["help","troubleshoot"],["help","full"]],wN=[["help"],["help","topic"],["login"],["logout"],["register"],["setup"],["whoami"],["profile"],["profile","update"],["auth"],["auth","status"],["auth","repair"],["auth","verify"],["auth","recover"],["auth","recover","complete"],["auth","connect"],["auth","mfa"],["auth","mfa","status"],["auth","mfa","setup"],["auth","mfa","verify"],["auth","mfa","recovery-codes"],["auth","mfa","disable"],["api-key"],["api-key","create"],["api-key","list"],["api-key","revoke"],["mcp"],["mcp","setup"],["mcp","status"],["mcp","verify"],["mcp","repair"],["mcp","migrate"],["mcp","disconnect"],["backend"],["backend","status"],["backend","cloud"],["backend","local"],["status"],["doctor"],["search"],["find"],["featured"],["trending"],["show"],["trust"],["recommend"],["categories"],["compare"],["install"],["install","status"],["installed"],["owned"],["export"],["add-review"],["show-reviews"],["add-issue"],["show-issues"],["purchases"],["purchases","list"],["purchases","invoice"],["purchases","status"],["purchases","refund-quote"],["purchases","refund"],["purchases","spending"],["validate"],["preview-trigger"],["creator"],["creator","init"],["creator","create"],["creator","sessions"],["creator","resume"],["creator","inspect"],["creator","answer"],["creator","resources"],["creator","resource-decide"],["creator","tool-contract"],["creator","draft"],["creator","validate"],["creator","eval"],["creator","improve"],["creator","revise"],["creator","materialize"],["creator","finalize"],["creator","rules"],["creator","submissions"],["creator","spaces"],["creator","spaces","buy"],["creator","status"],["creator","source"],["creator","source","prepare"],["creator","source","publish-request"],["creator","source","release-status"],["creator","submit"],["creator","submit-version"],["creator","check-slug"],["creator","rename"],["creator","pricing"],["creator","delist"],["creator","relist"],["creator","update-listing"],["creator","visibility"],["creator","security-report"],["creator","rescan-security"],["creator","provenance"],["creator","claim"],["creator","verify"],["creator","dispute"],["creator","issues"],["creator","update-issue"],["creator","reviews"],["creator","moderate-review"],["creator","analytics"],["creator","earnings"],["creator","payout-profile"],["creator","payout-link"],["creator","payouts"],["creator","withdraw"],["source"],["source","connection"],["source","connection","start"],["source","connection","status"],["source","connection","complete"],["source","connection","cancel"],["source","connection","revoke"],["source","reference"],["source","reference","resolve"],["approval"],["approval","request"],["approval","request","status"],["approval","request","complete"],["enterprise"],["enterprise","accept-invite"],["enterprise","checkout"],["enterprise","install-authorize"],["enterprise","list"],["enterprise","member"],["enterprise","member","remove"],["enterprise","member","role"],["enterprise","members"],["enterprise","rename"],["enterprise","primary-admin"],["enterprise","primary-admin","transfer"],["enterprise","primary-admin","status"],["enterprise","primary-admin","accept"],["enterprise","primary-admin","cancel"],["enterprise","seats"],["enterprise","seats","add"],["enterprise","invite"],["enterprise","invites"],["enterprise","revoke-invite"],["enterprise","resend-invite"],["enterprise","workspace-member"],["enterprise","workspace-member","list"],["enterprise","workspace-member","add"],["enterprise","workspace-member","remove"],["enterprise","workspace"],["enterprise","workspace","create"],["enterprise","workspace","rename"],["enterprise","workspace","update"],["enterprise","workspace","archive"],["enterprise","workspaces"],["enterprise","skill"],["enterprise","skill","entitlements"],["enterprise","skill","quote"],["enterprise","skill","buy"],["workspace"],["workspace","list"],["workspace","current"],["workspace","select"],["workspace","request"],["workspace","approve"],["workspace","reject"],["workspace","skills"],["workspace","guide"],["workspaces"],["guardian"],["guardian","check"],["guardian","incident"],["guardian","enable"],["guardian","disable"],["guardian","enable-warnings-only"],["guardian","status"],["guardian","hook"],["guardian","hook","install"],["guardian","hook","status"],["guardian","launch"],["guardian","exec"],["agents"],["agents","list"],["import"],["sync"],["restore"],["check"],["update"],["remove"],["identity"],["identity","providers"],["identity","start"],["identity","continue"],["identity","status"],["identity","complete"],["identity","list"],["identity","unlink"],["library"],["buy"]],Dee=1+kN.length+wN.length;var So="0.2.16";var Tee="skills-layer-cli-event-v1";function _N(e){let t=0,n=e.now??(()=>new Date().toISOString());return(r,i)=>{let o=Ei(i.summary,"summary",512),s=i.redactedDetail===void 0?void 0:Ei(i.redactedDetail,"redacted detail",2048),a=i.next?.map(u=>({id:Ei(u.id,"next-action ID",128),kind:u.kind,label:Ei(u.label,"next-action label",512),...u.command===void 0?{}:{command:{executable:u.command.executable,args:u.command.args.map(d=>Ei(d,"next-action argument",1024))}},...u.url===void 0?{}:{url:bN(u.url)},safeToAutoRun:u.safeToAutoRun,requiresHuman:u.requiresHuman,...u.rationale===void 0?{}:{rationale:Ei(u.rationale,"next-action rationale",1024)},safety:u.safety})),l=i.links?.map(u=>{let d=bN(u.url);return{label:Ei(u.label,"link label",512),url:d}}),c=i.data===void 0?void 0:iI(i.data);return t+=1,{schemaVersion:Tee,operationId:H(e.operationId),sequence:t,timestamp:n(),type:r,command:{name:H(e.command.name)},...i,summary:o,...s===void 0?{}:{redactedDetail:s},...a===void 0?{}:{next:a},...l===void 0?{}:{links:l},...c===void 0?{}:{data:c}}}}function bN(e){let t=Ei(e,"link URL",2048);if(!/^https?:\/\//u.test(t))throw new Error("CLI event links must use http or https URLs.");return t}function Ei(e,t,n){let r=H(e);if(r.length>n)throw new Error(`CLI event ${t} exceeds ${n} characters.`);return r}function iI(e,t=""){return/^(?:accessToken|apiKey|authorization|clientSecret|handoffCode|password|refreshToken|secret)$/iu.test(t)?"[redacted-secret]":typeof e=="string"?H(e):Array.isArray(e)?e.map(n=>iI(n)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,iI(r,n)])):e}var Oee=["human","json","stream-json"],SN=["auto","always","never"],Lee=["auto","modern","classic"],jee=["concise","standard","full"];function xN(e){let t=[],n={},r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(r){t.push(o);continue}if(o==="--"){r=!0,t.push(o);continue}let[s,a]=Nee(o);if(s==="--output-format"){let[l,c]=ku(s,a,e[i+1],Oee);n.outputFormat=l,i+=c}else if(s==="--color"){let[l,c]=ku(s,a,e[i+1],SN);n.color=l,i+=c}else if(s==="--motion"){let[l,c]=ku(s,a,e[i+1],SN);n.motion=l,i+=c}else if(s==="--ui"){let[l,c]=ku(s,a,e[i+1],Lee);n.ui=l,i+=c}else if(s==="--detail"){let[l,c]=ku(s,a,e[i+1],jee);n.detail=l,i+=c}else o==="--no-color"?n.color="never":o==="--no-motion"?n.motion="never":o==="--screen-reader"?n.screenReader=!0:o==="--no-interactive"?n.interactive=!1:o==="--ascii"?n.unicode=!1:t.push(o)}return{args:t,options:n}}function CN(e,t,n){let r=e.outputFormat??"human",i=e.screenReader===!0,o=Lg(t.CI),s=t.TERM==="dumb",a=n.stdinIsTty&&n.stdoutIsTty&&n.stderrIsTty,l=e.ui!=="classic",c=e.ui==="classic",u=e.detail??(r==="human"?"concise":"standard"),d=a&&!o&&!s&&l&&!i&&e.interactive!==!1,p=d&&e.motion!=="never",m=d&&p,h=!i&&e.color!=="never"&&(e.color==="always"||!Lg(t.NO_COLOR)&&!c&&(Lg(t.FORCE_COLOR)||!o&&!s&&n.stdoutIsTty)),g=e.unicode!==!1&&!Lg(t.NO_UNICODE)&&!s;return r==="json"?{kind:"json-final",color:!1,motion:!1,interactive:!1,unicode:!1,screenReader:i,classic:c,detail:u}:r==="stream-json"?{kind:"json-stream",color:!1,motion:!1,interactive:!1,unicode:!1,screenReader:i,classic:c,detail:u}:{kind:m?"human-interactive":"human-static",color:h,motion:p,interactive:m,unicode:g,screenReader:i,classic:c,detail:u}}function Nee(e){let t=e.indexOf("=");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function ku(e,t,n,r){let i=t??n;if(i===void 0||i.startsWith("--")||!r.includes(i))throw new Error(`${e} expects one of: ${r.join(", ")}.`);return[i,t===void 0?1:0]}function Lg(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}var IN=()=>null;var xo=88,Fee=/(?:^|_)(?:blocked|cancelled|canceled|rejected|denied|expired|invalid|not_found|conflict|missing_required_argument)(?:$|_)/u,Bee=/(?:^|_)(?:required|requires_action|warning|unverified|completion_pending)(?:$|_)/u,Mee=/(?:^|_)(?:argument|field|input|parameter|protocol|value)_required(?:$|_)/u,Uee=/(?:^|_)(?:failed|failure|internal_error|network_error|service_unavailable|timed_out|timeout)(?:$|_)/u,zee=/\b(?:required information is missing|unknown (?:command|option|flag)|invalid|already used|not found|blocked|cancelled|canceled|rejected|denied|expired|missing|not supported|could not be read|cannot write)\b/iu,qee=/\b(?:action|approval|authentication|checkout|confirmation|consent|human action|login|mfa|payment|purchase|registration|second factor|secure account connection|sign in|source connection|verification|workspace approval)\b[^.\n]*\b(?:required|needed|must be completed)\b|\b(?:complete|confirm|continue)\b[^.\n]*\b(?:browser|cli|terminal)\b/iu,Vee=/\b(?:failed|failure|service unavailable|server error|network error|timed out|timeout|could not complete)\b/iu;function AN(e){let t=PN(e.status),n=PN(e.reasonCode),r=[t,n].filter(Boolean);return r.some(i=>Fee.test(i))?"stopped":r.some(i=>Bee.test(i)&&!Mee.test(i))?"required":r.some(i=>Uee.test(i))||e.summary&&oI(e.summary)==="failed"?"failed":e.exitCode!==void 0&&e.exitCode!==0?"stopped":"completed"}function oI(e){let t=Gee(e);return zee.test(t)?"stopped":qee.test(t)?"required":Vee.test(t)?"failed":"stopped"}function wu(e,t){let n=t?"\u2014":"-",r=e.slice(0,1).toUpperCase()+e.slice(1);return`Skills Layer ${n} Action ${r}`}function PN(e){return H(e??"").trim().toLowerCase().replace(/[^a-z0-9]+/gu,"_")}function Gee(e){return H(e).split(/\n(?:Unchanged|Why|Next|Reference)(?:\s|$)/u,1)[0]}function Co(e){return ON(sr(e)).reduce((t,n)=>t+LN(n),0)}function RN(e,t){return e.split(`
|
|
2022
|
+
`)):n.options,...yee[e]??[],"--json"])]),inheritedOptions:hee,outputModes:Object.freeze(["human","json","stream-json"]),mutability:Cee(n.sideEffects),humanInLoop:Iee(n),fixturePrerequisites:Object.freeze([...n.requiresLogin?["authenticated_account"]:[],...n.requiresNetwork?["reachable_backend"]:[]]),examples:Object.freeze(n.examples),availability:"public"})})),kee=new Map(vee.map(e=>[e.path,e]));function mN(e){let t=e.map(n=>n.trim().toLowerCase()).filter(Boolean);for(let n=t.length;n>=1;n-=1){let r=kee.get(t.slice(0,n).join(" "));if(r)return r}return null}function wee(e,t){let n=new Set([...e.options,...e.inheritedOptions]),r=t.indexOf("--"),i=r===-1?t:t.slice(0,r);for(let o of i){if(!o.startsWith("--"))continue;let s=o.split("=",1)[0];if(!n.has(s))return s.slice(2)}return null}var gN=wee;function bee(e){return e==="find"?["search"]:e==="workspaces"?["workspace"]:[]}function _ee(e){return[...new Set([...e.matchAll(/<([^>]+)>/gu)].map(t=>t[1]))]}function See(e,t){let n=`skills-layer ${e}`;return t.split(/\r?\n/u).map(r=>r.trim()).filter(r=>r===n||r.startsWith(`${n} `))}function xee(e){return[...new Set([...e.matchAll(/--[a-z][a-z0-9-]*/gu)].map(t=>t[0]))]}function Cee(e){let t=e.some(r=>r.includes("local")||r.includes("credential")),n=e.some(r=>r.includes("cloud_write")||r.includes("payment"));return t&&n?"mixed":n?"cloud_write":t?"local_write":"read_only"}function Iee(e){return e.sideEffects.includes("payment_mutation")?"financial":e.mayOpenBrowser?"browser":e.mayPrompt?"prompt":"none"}import{posix as Pee,win32 as Aee}from"node:path";function hN(e,t){let n=t==="win32"?Aee:Pee;if(t==="win32"){let o=rI(e.APPDATA,e.USERPROFILE,e.HOME);if(!o)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(o,"skills-layer")}let r=rI(e.XDG_CONFIG_HOME);if(r)return n.join(r,"skills-layer");let i=rI(e.HOME);if(!i)throw new Error("Skills Layer CLI needs a writable home directory");return n.join(i,".skills-layer")}function rI(...e){return e.map(t=>t?.trim()).find(t=>!!t)}var Ree=/^[\u00a0\u2007\u202f\ufeff]+|[\u00a0\u2007\u202f\ufeff]+$/gu,Eee=/^\[(https?:\/\/[^\]\r\n]+)\]\((https?:\/\/[^)\r\n]+)\)$/u;function yN(e){let t=e.indexOf("--");return e.map((n,r)=>{if(t!==-1&&r>t)return n;let i=n.replace(Ree,""),o=Eee.exec(i);return o&&o[1]===o[2]?o[1]:i})}var vN={platform_balance_insufficient:A("conflict","conflict",!0,!0,"Platform funds are temporarily insufficient; retry later",[4]),connected_balance_insufficient:A("conflict","conflict",!0,!0,"Creator payout funds are not yet available; retry later",[4]),platform_balance_unavailable:A("backend_unreachable","unavailable",!0,!0,"Platform funds could not be checked; retry later",[5]),payout_provider_refused:A("operation_not_allowed","error",!1,!0,"The payment provider refused the payout; check payout configuration before retrying",[4]),payout_outcome_unknown:A("verification_pending","hold",!1,!0,"Payout outcome needs reconciliation before retrying",[5]),enterprise_member_already_active:A("conflict","conflict",!1,!1,"This person is already an active Enterprise member.",[4]),local_cleanup_incomplete:A("human_action_required","error",!0,!0,"Unlock the OS credential store and retry logout to finish local cleanup.",[4,5]),admin_step_up_invalid:A("security_verification_failed","error",!1,!0,"Verify your administrator step-up key in the private operator checkout.",[4]),verification_code_locked:A("rate_limited","rate_limited",!0,!0,"This code is locked. Request a new code after the retry time.",[4]),conflicting_flags:A("invalid_input","error",!1,!0,"Choose a value or its clear flag, not both.",[4]),flag_value_missing:A("invalid_input","error",!1,!0,"Supply a value for the flag.",[4]),rights_attestation_required:A("precondition_required","error",!1,!0,"Public and unlisted releases require confirmation of distribution rights.",[4]),rights_attestation_invalid:A("invalid_input","error",!1,!0,"Supply a supported rights basis and public distribution scope.",[4]),catalogue_artifact_unavailable:A("backend_unreachable","error",!0,!0,"The catalogue artifact could not be downloaded; retry export.",[4]),admin_mfa_required:A("human_action_required","human_action_required",!1,!0,"Enable MFA with skills-layer auth mfa setup, then retry.",[4]),admin_mfa_unavailable:A("backend_unreachable","unavailable",!0,!0,"Administrator MFA is unavailable; contact the deployment operator.",[5]),source_read_unavailable:A("backend_unreachable","source_unavailable",!1,!0,"The source could not be read completely. Its package has not been assessed.",[5]),command_failed:A("internal_error","error",!1,!1,"The command could not be completed.",[5]),resource_not_found:A("not_found","not_found",!1,!0,"The requested resource was not found.",[4]),permission_denied:A("permission_denied","error",!1,!1,"This credential cannot perform the requested operation.",[4]),login_required:A("login_required","login_required",!1,!0,"Sign in is required.",[4]),unauthorized:A("login_required","login_required",!1,!0,"Sign in is required.",[4]),api_key_invalid_or_expired:A("login_required","login_required",!1,!0,"The saved API key is no longer valid. Sign in again to use account features.",[4]),confirmation_required:A("confirmation_required","human_action_required",!1,!0,"Human confirmation is required.",[4]),mfa_setup_required:A("human_action_required","human_action_required",!1,!0,"MFA setup is required.",[4]),login_mfa_required:A("human_action_required","human_action_required",!1,!0,"A second authentication factor is required.",[4]),login_mfa_input_invalid:A("invalid_input","error",!1,!0,"Provide exactly one supported MFA proof.",[4]),login_mfa_invalid:A("security_verification_failed","error",!1,!0,"The MFA proof was invalid or already used.",[4]),login_security_unavailable:A("security_verification_failed","security_unavailable",!0,!0,"Login security is unavailable.",[5]),mfa_challenge_locked:A("rate_limited","rate_limited",!0,!0,"The MFA challenge is temporarily locked.",[4]),social_secure_continuation_unavailable:A("security_verification_failed","security_unavailable",!1,!0,"Secure social continuation is unavailable.",[4,5]),social_continuation_terminal:A("security_verification_failed","error",!1,!0,"The social continuation ended without authorization.",[4]),verification_code_expired:A("human_action_required","error",!1,!0,"The verification code expired.",[4]),payout_human_confirmation_required:A("human_action_required","human_action_required",!1,!0,"Human payout confirmation is required.",[4]),security_report_requires_action:A("policy_blocked","blocked",!1,!0,"The security report requires action.",[4]),trust_report_not_actionable:A("policy_blocked","blocked",!1,!0,"The trust report does not permit this transition.",[4]),trust_report_authority_mismatch:A("security_verification_failed","blocked",!1,!0,"Trust evidence does not match the exact artifact generation.",[4,5]),trust_report_required_evidence_unavailable:A("verification_pending","action_required",!0,!0,"Required trust evidence is unavailable or incomplete.",[2,4,5]),sarif_source_mapping_required:A("precondition_required","error",!1,!0,"Repository SARIF requires verified repository-relative source locations.",[4]),sarif_security_evidence_required:A("precondition_required","error",!1,!0,"Runtime-audit SARIF requires typed security evidence.",[4]),sarif_rule_mapping_required:A("precondition_required","error",!1,!0,"Runtime-audit SARIF requires an explicit reviewed rule mapping for every actionable event.",[4]),sarif_profile_unsupported:A("invalid_input","error",!1,!0,"The requested SARIF profile is not available for this report audience.",[4]),cloud_trust_ledger_mismatch:A("security_verification_failed","blocked",!1,!0,"This exact public skill generation is temporarily unavailable because its Cloud Trust Ledger attestation does not match. A Skills Layer operator must re-attest the exact generation before install.",[4]),api_key_active_limit_reached:A("quota_exceeded","conflict",!1,!0,"The active API-key limit has been reached.",[4]),rate_limited:A("rate_limited","rate_limited",!0,!0,"The request rate limit was reached.",[4]),source_connection_already_canceled:A("unchanged","unchanged",!1,!1,"The source connection was already canceled.",[2,4]),source_connection_completed:A("conflict","conflict",!1,!1,"A completed source connection cannot be canceled.",[4]),source_connection_revoked:A("unchanged","unchanged",!1,!1,"The authorized source connection was revoked.",[0]),source_connection_already_revoked:A("unchanged","unchanged",!1,!1,"The source connection was already revoked.",[0]),source_connection_not_authorized:A("conflict","conflict",!1,!1,"Only an authorized source connection can be revoked.",[4]),reupload_required:A("precondition_required","reupload_required",!1,!0,"The stored artifact is unavailable; upload the bundle again.",[4]),artifact_finalization_failed:A("processing_action_required","partial_success",!0,!1,"The version exists but artifact finalisation is incomplete.",[0]),publication_moderation_failed:A("processing_action_required","partial_success",!1,!1,"The version exists but its moderation transition needs operator inspection.",[0]),source_connection_completion_unverified:A("verification_pending","verification_warning",!0,!0,"Source connection completion could not be verified.",[4,5]),admin_mcp_verification_warning:A("verification_pending","verification_warning",!0,!0,"Administrator MCP verification is pending.",[2,4,5]),admin_mcp_verification_rejected:A("security_verification_failed","rejected",!1,!0,"Administrator MCP verification was rejected.",[4]),authoritative_security_report_pending:A("processing_action_required","already_processing",!0,!0,"The authoritative security report is still processing.",[4]),publication_continuation_scheduled:A("processing_action_required","already_processing",!0,!1,"Publication is continuing through the durable exact-generation workflow.",[2,4]),binary_inspection_pending:A("processing_action_required","already_processing",!0,!0,"Binary asset security inspection is still processing.",[2,4]),binary_inspection_unavailable:A("verification_pending","hold",!0,!0,"Required binary asset security inspection is currently unavailable.",[2,4,5]),binary_asset_blocked:A("policy_blocked","blocked",!1,!0,"A binary asset did not satisfy the platform security policy.",[2,4]),binary_profile_suspended:A("policy_blocked","hold",!0,!0,"The required binary format profile is temporarily suspended.",[2,4]),security_adjudication_pending:A("processing_action_required","already_processing",!0,!0,"Contextual security evidence is still being evaluated.",[2,4]),content_adjudication_insufficient_evidence:A("verification_pending","hold",!0,!0,"The available evidence is insufficient to resolve the security finding.",[2,4]),content_adjudication_confirmed_risk:A("policy_blocked","blocked",!1,!0,"The exact content contains a confirmed security risk.",[2,4]),content_adjudication_source_remediation_required:A("policy_blocked","blocked",!1,!0,"The source must be changed before security review can continue.",[2,4]),content_adjudication_execution_failed:A("verification_pending","hold",!0,!0,"Content security adjudication could not complete and remains held.",[2,4,5]),content_probe_runner_unavailable:A("verification_pending","hold",!0,!0,"The isolated content security evaluator is currently unavailable.",[2,4,5]),binary_inspection_authority_invalid:A("security_verification_failed","hold",!0,!0,"Binary security evidence could not be authenticated.",[2,4,5]),managed_security_pack_stale:A("security_verification_failed","hold",!0,!0,"A required managed security definition pack is not current.",[2,4,5]),workflow_dependency_incomplete:A("precondition_required","waiting_for_dependency",!0,!0,"A required upstream workflow is incomplete.",[4]),creator_processing_sla_breached:A("processing_action_required","action_required",!1,!0,"Creator processing exceeded its platform SLA.",[4,5]),invalid_global_option:A("invalid_input","error",!1,!0,"A global CLI option is invalid.",[4]),invalid_numeric_input:A("invalid_input","error",!1,!0,"A numeric option is invalid.",[4]),unknown_flag:A("invalid_input","error",!1,!0,"The option is not supported.",[4]),unknown_command:A("invalid_input","error",!1,!0,"The command is not supported.",[4]),unknown_subcommand:A("invalid_input","error",!1,!0,"The command is not supported.",[4]),missing_required_argument:A("invalid_input","error",!1,!0,"Required information is missing.",[4]),invalid_json:A("invalid_input","error",!1,!0,"The JSON value is invalid.",[4]),canonical_bundle_rejected:A("invalid_input","error",!1,!0,"The bundle failed canonical validation.",[4]),recovery_code_invalid_or_expired:A("human_action_required","error",!1,!0,"The recovery code is invalid or expired.",[4]),social_provider_not_configured:A("precondition_required","error",!1,!0,"The selected social provider is not configured.",[4,5]),search_selection_not_found:A("not_found","not_found",!1,!0,"The selected skill is not present in these search results.",[4]),best_effort:A("unchanged","low_confidence",!1,!0,"Best-effort candidates need a more specific task for higher confidence.",[2]),unsafe_task:A("policy_blocked","policy_blocked",!1,!0,"This task is outside the recommendation safety policy.",[2]),no_confident_recommendation:A("unchanged","no_confident_recommendation",!1,!0,"No skill met the calibrated recommendation confidence policy.",[2]),clarification_required:A("human_action_required","clarification_required",!1,!0,"One public task constraint is required before a skill can be recommended.",[2]),workspace_required:A("precondition_required","error",!1,!0,"A workspace id is required for this install.",[4]),unsupported_skill_type:A("invalid_input","error",!1,!0,"The requested skill type is unsupported.",[4]),creator_resource_not_found:A("not_found","not_found",!1,!0,"The creator resource was not found.",[4]),creator_access_required:A("permission_denied","access_required",!1,!0,"Creator management access is required for this public skill.",[4]),library_access_required:A("permission_denied","access_required",!1,!0,"Library access is required to inspect issues for this public skill.",[4]),issue_not_found:A("not_found","not_found",!1,!0,"The issue was not found in the managed skill.",[4]),review_not_found:A("not_found","not_found",!1,!0,"The review was not found in the managed skill.",[4]),api_key_not_found:A("not_found","not_found",!1,!0,"The API key was not found.",[4]),approval_request_not_found:A("not_found","not_found",!1,!0,"The approval request was not found.",[4]),available:A("unchanged","available",!1,!1,"The requested capability is available.",[2]),catalog_acquisition_ready:A("unchanged","ready",!1,!1,"The catalog acquisition is ready.",[2]),catalog_artifact_unavailable:A("precondition_required","error",!0,!0,"The exact catalog artifact is temporarily unavailable.",[4,5]),compare_missing_skills:A("not_found","not_found",!1,!0,"One or more skills requested for comparison were not found.",[4]),conflicting_export_output:A("conflict","conflict",!1,!0,"The requested export output options conflict.",[4]),conflicting_mcp_client_selection:A("conflict","conflict",!1,!0,"The MCP client selection is ambiguous.",[4]),conflicting_mcp_migration_mode:A("conflict","conflict",!1,!0,"Choose either a legacy MCP migration preview or an apply operation.",[4]),needs_mcp_client_choice:A("human_action_required","needs_mcp_client_choice",!1,!0,"Choose a verified MCP host before setup can continue.",[4]),mcp_config_symlink_rejected:A("human_action_required","mcp_setup_blocked",!1,!0,"Replace the MCP config symlink with a regular user-owned config file before retrying.",[4]),mcp_registration_ownership_ambiguous:A("human_action_required","mcp_setup_blocked",!1,!0,"Review or rename the existing unowned Skills Layer MCP entry before retrying.",[4]),mcp_client_scope_required:A("human_action_required","needs_mcp_client_scope",!1,!0,"Choose one configured MCP host or explicitly select all hosts.",[4]),mcp_client_inventory_missing:A("precondition_required","mcp_needs_repair",!1,!0,"The local MCP configuration has no canonical host inventory.",[4]),mcp_legacy_project_path_required:A("precondition_required","error",!1,!0,"Choose the exact project root to inspect for legacy MCP registration.",[4]),mcp_multi_client_verify_failed:A("verification_pending","mcp_needs_repair",!0,!0,"One or more configured MCP hosts failed verification.",[4,5]),unknown_mcp_client:A("unsupported_client","error",!1,!0,"The requested MCP host is unsupported.",[4]),creator_listing_not_found_or_not_owned:A("not_found","not_found",!1,!0,"The creator listing is unavailable to this account.",[4]),creator_submission_not_found:A("not_found","not_found",!1,!0,"The creator submission was not found.",[4]),enterprise_resource_not_found:A("not_found","not_found",!1,!0,"The Enterprise resource was not found.",[4]),enterprise_checkout_completion_pending:A("processing_action_required","completion_pending",!0,!0,"Enterprise checkout completion is still being reconciled.",[2,5]),guardian_enabled:A("unchanged","enabled",!1,!1,"Guardian enforcement is enabled.",[2]),feature_already_configured:A("unchanged","unchanged",!1,!1,"The requested feature state is already configured.",[2]),guardian_exact_version_required:A("precondition_required","error",!1,!0,"Guardian requires one exact skill version.",[4]),guardian_unmanaged_atomic_execution_required:A("precondition_required","blocked",!1,!0,"Unmanaged execution cannot be authorized by a diagnostic Guardian check.",[4]),guardian_plan_resolution_failed:A("internal_error","error",!0,!0,"Guardian could not resolve a safe execution plan.",[4,5]),guardian_version_not_current:A("conflict","conflict",!1,!0,"The selected Guardian version is not current.",[4]),human_handoff_required:A("human_action_required","human_action_required",!1,!0,"A human must complete this handoff.",[2,4]),invalid_amount_cents:A("invalid_input","error",!1,!0,"The amount must be a valid non-negative number of cents.",[4]),invalid_enterprise_role:A("invalid_input","error",!1,!0,"The Enterprise role is invalid.",[4]),invalid_expiry:A("invalid_input","error",!1,!0,"The expiry value is invalid.",[4]),invalid_incident_path:A("invalid_input","error",!1,!0,"The incident path is invalid.",[4]),invalid_issue_status:A("invalid_input","error",!1,!0,"The issue status is invalid.",[4]),invalid_price_cents:A("invalid_input","error",!1,!0,"The price must be a valid non-negative number of cents.",[4]),invalid_review_status:A("invalid_input","error",!1,!0,"The review status is invalid.",[4]),invalid_scope:A("invalid_input","error",!1,!0,"The requested scope is invalid.",[4]),invalid_search_filter:A("invalid_input","error",!1,!0,"The search filter is invalid.",[4]),invalid_seats:A("invalid_input","error",!1,!0,"The Enterprise seat count is invalid.",[4]),invalid_sort:A("invalid_input","error",!1,!0,"The requested sort mode is invalid.",[4]),invalid_source:A("invalid_input","error",!1,!0,"The requested source is invalid.",[4]),invalid_version:A("invalid_input","error",!1,!0,"The semantic version is invalid.",[4]),local_install_not_found:A("not_found","not_found",!1,!0,"The local installation was not found.",[4]),local_source_requires_client_files:A("precondition_required","error",!1,!0,"This local source requires client-provided files.",[4]),ownership_claim_not_found:A("not_found","not_found",!1,!0,"The ownership claim was not found.",[4]),ownership_dispute_open:A("human_action_required","manual_review_required",!1,!0,"An ownership dispute requires human resolution.",[2,4]),ownership_already_configured:A("unchanged","unchanged",!1,!1,"The requested ownership assignments are already configured.",[2]),org_dependency_audit_incomplete:A("precondition_required","hold",!0,!0,"The organization dependency audit is incomplete.",[2,4]),purchase_not_found:A("not_found","not_found",!1,!0,"The purchase was not found.",[4]),restore_record_not_found:A("not_found","not_found",!1,!0,"No restorable installation record was found.",[4]),scaffold_overwrite_confirmation_required:A("confirmation_required","human_action_required",!1,!0,"Overwriting the scaffold requires confirmation.",[4]),security_report_requires_review:A("policy_blocked","manual_review_required",!1,!0,"The security report requires human review.",[2,4]),security_report_missing:A("not_found","not_found",!1,!0,"The security report was not found.",[4]),platform_score_subject_missing:A("not_found","not_found",!1,!0,"The exact Platform Score skill generation was not found.",[4]),security_evidence_operation_not_found:A("not_found","not_found",!1,!0,"The security evidence operation was not found.",[4]),skill_not_found:A("not_found","not_found",!1,!0,"The skill was not found.",[4]),social_browser_confirmation_required:A("human_action_required","human_action_required",!1,!0,"Social sign-in requires browser confirmation.",[4]),source_connection_not_found:A("not_found","not_found",!1,!0,"The source connection was not found.",[4]),source_not_verifiable:A("policy_blocked","manual_review_required",!1,!0,"The source cannot be verified automatically.",[2,4]),source_path_not_found:A("not_found","not_found",!1,!0,"The source path was not found.",[4]),source_reference_not_found:A("not_found","not_found",!1,!0,"The source reference was not found.",[4]),submission_not_found:A("not_found","not_found",!1,!0,"The submission was not found.",[2,4]),trust_report_not_found:A("not_found","not_found",!1,!0,"The Platform Score report was not found.",[4]),unknown_agent:A("unsupported_client","error",!1,!0,"The requested agent is unsupported.",[4]),verification_code_invalid:A("human_action_required","error",!1,!0,"The verification code is invalid or expired.",[4]),workspace_not_found_or_forbidden:A("not_found","not_found",!1,!0,"The workspace is unavailable to this account.",[4]),workspace_skill_approval_not_found:A("not_found","not_found",!1,!0,"The workspace skill approval was not found.",[4]),workspace_working_mode_not_found:A("not_found","not_found",!1,!0,"The selected workspace was not found.",[4])};function $ee(e){let t=vN[e];return t?{reasonCode:e,...t}:null}function Og(e,t={}){if(!e)return t.httpStatus===404?Ia("resource_not_found"):t.httpStatus===401?Ia("login_required"):t.httpStatus===403?Ia("permission_denied"):t.httpStatus===409?gt("conflict","conflict"):t.httpStatus===429?Ia("rate_limited"):(t.httpStatus&&t.httpStatus>=500,Ia("command_failed"));let n=$ee(e);return n||(e.includes("not_found")||e==="missing_record"?gt(e,"not_found","not_found"):e.includes("rate_limit")?gt(e,"rate_limited","rate_limited",!0):e.includes("quota")||e.includes("_limit_reached")||e.includes("_limit_exhausted")?gt(e,"quota_exceeded","conflict"):e.includes("human")||e.includes("mfa")||e.includes("browser_confirmation")?gt(e,"human_action_required","human_action_required"):e.includes("already_canceled")||e.includes("unchanged")||e.includes("already_complete")?gt(e,"unchanged","unchanged"):e.includes("dependency")||e.includes("precondition")||e.includes("required")?gt(e,"precondition_required","error"):e.includes("processing")||e.includes("pending")||e.includes("already_processing")?gt(e,"processing_action_required","already_processing",!0):e.includes("conflict")||e.includes("already_final")||e.includes("completed")?gt(e,"conflict","conflict"):e.includes("payment")||e.includes("checkout")||e.includes("purchase")?gt(e,"payment_required","human_action_required"):e.includes("source")?gt(e,"source_required","error"):e.includes("backend")||e.includes("unreachable")||e.includes("network")?gt(e,"backend_unreachable","error",!0):e.includes("agent")||e.includes("client")||e.includes("unsupported")?gt(e,"unsupported_client","error"):e.includes("blocked")||e.includes("policy")||e.includes("guardian")?gt(e,"policy_blocked","blocked"):e.includes("forbidden")||e.includes("permission_denied")?gt(e,"permission_denied","error"):e.includes("not_allowed")||e.includes("invalid_transition")?gt(e,"operation_not_allowed","error"):gt(e,"invalid_input","error"))}function A(e,t,n,r,i,o){return{family:e,defaultStatus:t,retryable:n,nextActionRequired:r,safeSummary:i,allowedHttpStatusClasses:o}}function Ia(e){return{reasonCode:e,...vN[e]}}function gt(e,t,n="error",r=!1){return{reasonCode:e,family:t,defaultStatus:n,retryable:r,nextActionRequired:!1,safeSummary:"The command could not be completed.",allowedHttpStatusClasses:[4,5]}}var kN=[["help","account"],["help","use"],["help","creator"],["help","teams"],["help","security"],["help","mcp"],["help","automation"],["help","troubleshoot"],["help","full"]],wN=[["help"],["help","topic"],["login"],["logout"],["register"],["setup"],["whoami"],["profile"],["profile","update"],["auth"],["auth","status"],["auth","repair"],["auth","verify"],["auth","recover"],["auth","recover","complete"],["auth","connect"],["auth","mfa"],["auth","mfa","status"],["auth","mfa","setup"],["auth","mfa","verify"],["auth","mfa","recovery-codes"],["auth","mfa","disable"],["api-key"],["api-key","create"],["api-key","list"],["api-key","revoke"],["mcp"],["mcp","setup"],["mcp","status"],["mcp","verify"],["mcp","repair"],["mcp","migrate"],["mcp","disconnect"],["backend"],["backend","status"],["backend","cloud"],["backend","local"],["status"],["doctor"],["search"],["find"],["featured"],["trending"],["show"],["trust"],["recommend"],["categories"],["compare"],["install"],["install","status"],["installed"],["owned"],["export"],["add-review"],["show-reviews"],["add-issue"],["show-issues"],["purchases"],["purchases","list"],["purchases","invoice"],["purchases","status"],["purchases","refund-quote"],["purchases","refund"],["purchases","spending"],["validate"],["preview-trigger"],["creator"],["creator","init"],["creator","create"],["creator","sessions"],["creator","resume"],["creator","inspect"],["creator","answer"],["creator","resources"],["creator","resource-decide"],["creator","tool-contract"],["creator","draft"],["creator","validate"],["creator","eval"],["creator","improve"],["creator","revise"],["creator","materialize"],["creator","finalize"],["creator","rules"],["creator","submissions"],["creator","spaces"],["creator","spaces","buy"],["creator","status"],["creator","source"],["creator","source","prepare"],["creator","source","publish-request"],["creator","source","release-status"],["creator","submit"],["creator","submit-version"],["creator","check-slug"],["creator","rename"],["creator","pricing"],["creator","delist"],["creator","relist"],["creator","update-listing"],["creator","visibility"],["creator","security-report"],["creator","rescan-security"],["creator","provenance"],["creator","claim"],["creator","verify"],["creator","dispute"],["creator","issues"],["creator","update-issue"],["creator","reviews"],["creator","moderate-review"],["creator","analytics"],["creator","earnings"],["creator","payout-profile"],["creator","payout-link"],["creator","payouts"],["creator","withdraw"],["source"],["source","connection"],["source","connection","start"],["source","connection","status"],["source","connection","complete"],["source","connection","cancel"],["source","connection","revoke"],["source","reference"],["source","reference","resolve"],["approval"],["approval","request"],["approval","request","status"],["approval","request","complete"],["enterprise"],["enterprise","accept-invite"],["enterprise","checkout"],["enterprise","install-authorize"],["enterprise","list"],["enterprise","member"],["enterprise","member","remove"],["enterprise","member","role"],["enterprise","members"],["enterprise","rename"],["enterprise","primary-admin"],["enterprise","primary-admin","transfer"],["enterprise","primary-admin","status"],["enterprise","primary-admin","accept"],["enterprise","primary-admin","cancel"],["enterprise","seats"],["enterprise","seats","add"],["enterprise","invite"],["enterprise","invites"],["enterprise","revoke-invite"],["enterprise","resend-invite"],["enterprise","workspace-member"],["enterprise","workspace-member","list"],["enterprise","workspace-member","add"],["enterprise","workspace-member","remove"],["enterprise","workspace"],["enterprise","workspace","create"],["enterprise","workspace","rename"],["enterprise","workspace","update"],["enterprise","workspace","archive"],["enterprise","workspaces"],["enterprise","skill"],["enterprise","skill","entitlements"],["enterprise","skill","quote"],["enterprise","skill","buy"],["workspace"],["workspace","list"],["workspace","current"],["workspace","select"],["workspace","request"],["workspace","approve"],["workspace","reject"],["workspace","skills"],["workspace","guide"],["workspaces"],["guardian"],["guardian","check"],["guardian","incident"],["guardian","enable"],["guardian","disable"],["guardian","enable-warnings-only"],["guardian","status"],["guardian","hook"],["guardian","hook","install"],["guardian","hook","status"],["guardian","launch"],["guardian","exec"],["agents"],["agents","list"],["import"],["sync"],["restore"],["check"],["update"],["remove"],["identity"],["identity","providers"],["identity","start"],["identity","continue"],["identity","status"],["identity","complete"],["identity","list"],["identity","unlink"],["library"],["buy"]],Dee=1+kN.length+wN.length;var So="0.2.17";var Tee="skills-layer-cli-event-v1";function _N(e){let t=0,n=e.now??(()=>new Date().toISOString());return(r,i)=>{let o=Ei(i.summary,"summary",512),s=i.redactedDetail===void 0?void 0:Ei(i.redactedDetail,"redacted detail",2048),a=i.next?.map(u=>({id:Ei(u.id,"next-action ID",128),kind:u.kind,label:Ei(u.label,"next-action label",512),...u.command===void 0?{}:{command:{executable:u.command.executable,args:u.command.args.map(d=>Ei(d,"next-action argument",1024))}},...u.url===void 0?{}:{url:bN(u.url)},safeToAutoRun:u.safeToAutoRun,requiresHuman:u.requiresHuman,...u.rationale===void 0?{}:{rationale:Ei(u.rationale,"next-action rationale",1024)},safety:u.safety})),l=i.links?.map(u=>{let d=bN(u.url);return{label:Ei(u.label,"link label",512),url:d}}),c=i.data===void 0?void 0:iI(i.data);return t+=1,{schemaVersion:Tee,operationId:H(e.operationId),sequence:t,timestamp:n(),type:r,command:{name:H(e.command.name)},...i,summary:o,...s===void 0?{}:{redactedDetail:s},...a===void 0?{}:{next:a},...l===void 0?{}:{links:l},...c===void 0?{}:{data:c}}}}function bN(e){let t=Ei(e,"link URL",2048);if(!/^https?:\/\//u.test(t))throw new Error("CLI event links must use http or https URLs.");return t}function Ei(e,t,n){let r=H(e);if(r.length>n)throw new Error(`CLI event ${t} exceeds ${n} characters.`);return r}function iI(e,t=""){return/^(?:accessToken|apiKey|authorization|clientSecret|handoffCode|password|refreshToken|secret)$/iu.test(t)?"[redacted-secret]":typeof e=="string"?H(e):Array.isArray(e)?e.map(n=>iI(n)):typeof e=="object"&&e!==null?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,iI(r,n)])):e}var Oee=["human","json","stream-json"],SN=["auto","always","never"],Lee=["auto","modern","classic"],jee=["concise","standard","full"];function xN(e){let t=[],n={},r=!1;for(let i=0;i<e.length;i+=1){let o=e[i];if(r){t.push(o);continue}if(o==="--"){r=!0,t.push(o);continue}let[s,a]=Nee(o);if(s==="--output-format"){let[l,c]=ku(s,a,e[i+1],Oee);n.outputFormat=l,i+=c}else if(s==="--color"){let[l,c]=ku(s,a,e[i+1],SN);n.color=l,i+=c}else if(s==="--motion"){let[l,c]=ku(s,a,e[i+1],SN);n.motion=l,i+=c}else if(s==="--ui"){let[l,c]=ku(s,a,e[i+1],Lee);n.ui=l,i+=c}else if(s==="--detail"){let[l,c]=ku(s,a,e[i+1],jee);n.detail=l,i+=c}else o==="--no-color"?n.color="never":o==="--no-motion"?n.motion="never":o==="--screen-reader"?n.screenReader=!0:o==="--no-interactive"?n.interactive=!1:o==="--ascii"?n.unicode=!1:t.push(o)}return{args:t,options:n}}function CN(e,t,n){let r=e.outputFormat??"human",i=e.screenReader===!0,o=Lg(t.CI),s=t.TERM==="dumb",a=n.stdinIsTty&&n.stdoutIsTty&&n.stderrIsTty,l=e.ui!=="classic",c=e.ui==="classic",u=e.detail??(r==="human"?"concise":"standard"),d=a&&!o&&!s&&l&&!i&&e.interactive!==!1,p=d&&e.motion!=="never",m=d&&p,h=!i&&e.color!=="never"&&(e.color==="always"||!Lg(t.NO_COLOR)&&!c&&(Lg(t.FORCE_COLOR)||!o&&!s&&n.stdoutIsTty)),g=e.unicode!==!1&&!Lg(t.NO_UNICODE)&&!s;return r==="json"?{kind:"json-final",color:!1,motion:!1,interactive:!1,unicode:!1,screenReader:i,classic:c,detail:u}:r==="stream-json"?{kind:"json-stream",color:!1,motion:!1,interactive:!1,unicode:!1,screenReader:i,classic:c,detail:u}:{kind:m?"human-interactive":"human-static",color:h,motion:p,interactive:m,unicode:g,screenReader:i,classic:c,detail:u}}function Nee(e){let t=e.indexOf("=");return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function ku(e,t,n,r){let i=t??n;if(i===void 0||i.startsWith("--")||!r.includes(i))throw new Error(`${e} expects one of: ${r.join(", ")}.`);return[i,t===void 0?1:0]}function Lg(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}var IN=()=>null;var xo=88,Fee=/(?:^|_)(?:blocked|cancelled|canceled|rejected|denied|expired|invalid|not_found|conflict|missing_required_argument)(?:$|_)/u,Bee=/(?:^|_)(?:required|requires_action|warning|unverified|completion_pending)(?:$|_)/u,Mee=/(?:^|_)(?:argument|field|input|parameter|protocol|value)_required(?:$|_)/u,Uee=/(?:^|_)(?:failed|failure|internal_error|network_error|service_unavailable|timed_out|timeout)(?:$|_)/u,zee=/\b(?:required information is missing|unknown (?:command|option|flag)|invalid|already used|not found|blocked|cancelled|canceled|rejected|denied|expired|missing|not supported|could not be read|cannot write)\b/iu,qee=/\b(?:action|approval|authentication|checkout|confirmation|consent|human action|login|mfa|payment|purchase|registration|second factor|secure account connection|sign in|source connection|verification|workspace approval)\b[^.\n]*\b(?:required|needed|must be completed)\b|\b(?:complete|confirm|continue)\b[^.\n]*\b(?:browser|cli|terminal)\b/iu,Vee=/\b(?:failed|failure|service unavailable|server error|network error|timed out|timeout|could not complete)\b/iu;function AN(e){let t=PN(e.status),n=PN(e.reasonCode),r=[t,n].filter(Boolean);return r.some(i=>Fee.test(i))?"stopped":r.some(i=>Bee.test(i)&&!Mee.test(i))?"required":r.some(i=>Uee.test(i))||e.summary&&oI(e.summary)==="failed"?"failed":e.exitCode!==void 0&&e.exitCode!==0?"stopped":"completed"}function oI(e){let t=Gee(e);return zee.test(t)?"stopped":qee.test(t)?"required":Vee.test(t)?"failed":"stopped"}function wu(e,t){let n=t?"\u2014":"-",r=e.slice(0,1).toUpperCase()+e.slice(1);return`Skills Layer ${n} Action ${r}`}function PN(e){return H(e??"").trim().toLowerCase().replace(/[^a-z0-9]+/gu,"_")}function Gee(e){return H(e).split(/\n(?:Unchanged|Why|Next|Reference)(?:\s|$)/u,1)[0]}function Co(e){return ON(sr(e)).reduce((t,n)=>t+LN(n),0)}function RN(e,t){return e.split(`
|
|
2023
2023
|
`).flatMap(n=>Kee(n,t))}function jg(e,t,n){let r=H(e),i=H(t),o=n.width-2;if(n.width<12||Co(r)+4>o)return i;let s=n.unicode?{topLeft:"\u250C",topRight:"\u2510",bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",vertical:"\u2502"}:{topLeft:"+",topRight:"+",bottomLeft:"+",bottomRight:"+",horizontal:"-",vertical:"|"},a=`${s.horizontal} ${r} `,l=n.border??(m=>m),c=l(`${s.topLeft}${a}${s.horizontal.repeat(o-Co(a))}${s.topRight}`),u=o-2,d=RN(i,u).map(m=>`${l(s.vertical)} ${aI(m,u)} ${l(s.vertical)}`),p=l(`${s.bottomLeft}${s.horizontal.repeat(o)}${s.bottomRight}`);return[c,...d,p].join(`
|
|
2024
2024
|
`)}function Xe(e,t){return`${H(e)}
|
|
2025
2025
|
${H(t)}`}function Ng(e,t){let n=t?"\u2022":"-";return e.map(r=>`${n} ${H(r)}`).join(`
|
|
@@ -2078,10 +2078,10 @@ ${t}`,yne=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),vne=Obj
|
|
|
2078
2078
|
`)}this.#u(()=>this.#n.write(r))===!1&&this.#n.isTTY&&(this.#c=()=>{this.#c=void 0,this.#g()},this.#n.once("drain",this.#c)),this.#i=this.#m(r,i)}finally{n&&this.#u(()=>this.#n.write(Xne))}return this}start(t){if(t!==void 0&&(this.text=t),this.isSilent)return this;if(!this.isEnabled){let n=this.text?"-":"",r=" ".repeat(this.#e.indent)+this.#y(n,this.text,this.#e.prefixText,this.#e.suffixText);return r.trim()!==""&&this.#u(()=>this.#n.write(r+`
|
|
2079
2079
|
`)),this}return this.isSpinning?this:(this.#e.hideCursor&&HI.hide(this.#n),this.#e.discardStdin&&Du.stdin.isTTY&&(eP.start(),this.#f=!0),this.#C(),this.render(),this.#s=setInterval(this.render.bind(this),this.interval),this)}stop(){return clearInterval(this.#s),this.#s=void 0,this.#r=-1,this.#t=0,this.#h(),this.#I(),this.#c&&(this.#n.removeListener("drain",this.#c),this.#c=void 0),this.isEnabled&&(this.clear(),this.#e.hideCursor&&HI.show(this.#n)),this.#f&&(this.#f=!1,eP.stop()),this}succeed(t){return this.stopAndPersist({symbol:Do.success,text:t})}fail(t){return this.stopAndPersist({symbol:Do.error,text:t})}warn(t){return this.stopAndPersist({symbol:Do.warning,text:t})}info(t){return this.stopAndPersist({symbol:Do.info,text:t})}stopAndPersist(t={}){if(this.isSilent)return this;let n=t.symbol??" ",r=t.text??this.text,i=t.prefixText??this.#e.prefixText,o=t.suffixText??this.#e.suffixText,s=this.#y(n,r,i,o)+`
|
|
2080
2080
|
`;return this.stop(),this.#u(()=>this.#n.write(s)),this}};function nP(e){return new tP(e)}function ere(e){let t=e.mode.kind==="human-interactive"&&e.mode.motion,n=e.stream,r=t&&Number(n.columns)>0&&Number(n.rows)>0,i=e.mode.kind==="human-static"||t&&!r,o=H(e.commandName)||"command",s=e.spinnerFactory??(g=>nP(g)),a=e.setTimer??((g,y)=>setTimeout(g,y)),l=e.clearTimer??(g=>clearTimeout(g)),c=`Working on ${o}\u2026`,u,d,p=!1,m=!1,h=()=>{r&&d===void 0&&u===void 0&&(d=a(()=>{d=void 0,!p&&(m||(u=s({text:c,stream:e.stream,isEnabled:!0,discardStdin:!1,color:e.mode.color?"cyan":!1}).start()))},e.delayMs??80))};return h(),{info(g){c=H(g),u?u.text=c:i&&e.stream.write(`${c}
|
|
2081
|
-
`)},pause(){p=!0,d!==void 0&&(l(d),d=void 0),u?.stop?.(),u=void 0},resume(){m||(p=!1,h())},finish(g){m||(m=!0,d!==void 0&&(l(d),d=void 0),u&&(g.exitCode===0?u.succeed(tre(g.stdout,o)):u.fail(`Stopped ${o}`),u=void 0))}}}function tre(e,t){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n)){let r=String(n.status??"").toLowerCase();if(r==="install_pending_review"||r==="source_submitted"||r.includes("pending"))return`Submitted ${t}`;if(r==="installed_unverified")return"Installed unverified source"}}catch{}return`Completed ${t}`}var Z=class extends Error{status;details;constructor(t,n,r){super(n),this.name="ApiError",this.status=t,this.details=r}},are=1,JP=1,hh=2,VM="skills-layer-public-cli-v1",$t="skills-layer-security-hook",xt="Skills Layer Security Hook",YP="https://api.skills-layer.com",lre="http://127.0.0.1:8787",EB=new Set(["json","dry-run","skip-probe","clear-display-name","clear-company","clear-bio","help","list","all","deep","verbose","show-url","no-open","confirm","confirmed","create-account","yes","with-mcp","no-mcp","allow-unmanaged-once","disclose-source","new-enterprise","leave-enterprise","skip-license","replace-unpublished","accept-unverified-source","local-only","replace-unverified-source","quick","apply","attest-rights","confirm-free","forget"]),rP=new Set(["accept-capability","approval-request-id","grant-json","paraphrase","secret-env","should-not-trigger","should-trigger"]),$B=new Set(["bio","company","description","display-name","feedback","message","note","reason","search","summary"]),DB=new Set(["country","cursor","publisher","price","minimum-score","minimum-stars","badge","action","action-json","agent","amount-cents","api-key","base-url","capability","category","claim-id","client","cloud-trust-ledger","code","commit-sha","created-after","created-before","decision","decision-evidence-json","dependency-audit-status","dir","email","environment","eval-summary","evidence-json","expires","expires-after","expires-before","external-reference","idempotency-key","fixed-version","format","host-version","install","issue-id","issue-type","key-id","kind","license","license-file","limit","listing-status","max-characters","method","mfa-code","mode","name","output","path","payment-method","pack","pin","price-cents","provider","purpose","provider-installation-id","provider-owner-id","provider-project-id","provider-repo-id","provenance-intent","publication-status","rating","reference","recovery-code","requested-role","review-id","role","runtime-risk","scope","security-capability","skill","skill-type","sort","source","source-intake-context","space-pack","state","status","seats","text","telemetry-mode","telemetry-policy","guardian-policy","trust","type","unmanaged-policy","version","version-id","visibility","workspace","workspace-name","enterprise-name","answers","answer-json","question-id","decisions-json","patch-json","expected-revision","plan-digest","report-digest","caller-capabilities-json","challenge-digest","observations-json","supplied-resources-json","additional-evidence-json","tags-json","outcome","session-id","creator-session-id","imported-candidate-id","rights-basis","distribution-scope","source-reference"]),yh=new Set(nI),cre=new Set(["standards","marketplace-status","capabilities","schema-plan","optimize-tokens"]);async function yCe(e,t={}){e=yN(e);let n=t.env??process.env,r=ure(e),i;try{i=Aa(e,n,{stdinIsTty:t.stdinIsTty??!!(t.selectInput?.isTTY??process.stdin.isTTY),stdoutIsTty:t.stdoutIsTty??!!(t.selectOutput?.isTTY??process.stdout.isTTY),stderrIsTty:t.stderrIsTty??!!process.stderr.isTTY})}catch(w){return dre(e,ve(w),r,t)}let o=[],s=i.mode.kind==="json-final"||i.mode.kind==="json-stream",a=i.options.interactive===!1||i.options.screenReader===!0||i.options.motion==="never"||i.options.ui==="classic",l=fre(n.CI)||n.TERM==="dumb",u=t.stdinIsTty===void 0&&t.stderrIsTty===void 0&&t.stdoutIsTty!==!1&&!!(t.promptText||t.promptSecret||t.promptSelect||t.selectInput||t.openUrl||t.emitInfo),d=t.stdoutIsTty===!0&&t.stdinIsTty===void 0&&t.stderrIsTty===void 0,p=a||l&&!u||s&&!u||!i.mode.interactive&&!u&&!d,m=t.emitInfo,h=i.args.find(w=>!w.startsWith("-"))??"skills-layer",g=i.mode.kind==="json-stream"?pI({operationId:t.operationId??`op_${Ge(8).toString("hex")}`,command:{name:h},now:t.now},t.emitCliEvent,i.mode.detail):void 0,y={...t,renderMode:i.mode,nonInteractive:i.options.interactive===!1,...p?{stdoutIsTty:!1,openUrl:async()=>!1,promptText:async()=>{throw new Error("Interactive prompts are disabled for this presentation mode.")},promptSecret:async()=>{throw new Error("Interactive prompts are disabled for this presentation mode.")},promptSelect:async()=>{throw new Error("Interactive prompts are disabled for this presentation mode.")}}:{},...s?{emitInfo:g?GN(g,m):VN(i.mode,o,m)}:{}},v=g?HN({session:g,commandName:h}):void 0,b;try{b=await mre(i.args,y)}finally{v?.()}return i.mode.kind!=="json-stream"?b:(g.finish(b),{exitCode:b.exitCode,stdout:t.emitCliEvent?"":fI(g.events),stderr:""})}function ure(e){let t=e.indexOf("--"),n=t===-1?e:e.slice(0,t),r=n.includes("--json"),i=!1;for(let o=0;o<n.length;o+=1){let s=n[o],a=s.startsWith("--output-format=")?s.slice(16):null,l=a??(s==="--output-format"?n[o+1]:void 0);l==="stream-json"?i=!0:l==="json"&&(r=!0),a===null&&s==="--output-format"&&(o+=1)}return i?"stream-json":r?"json":null}function dre(e,t,n,r){let i=/^--(?<option>[a-z0-9-]+) expects one of: (?<accepted>.+)\.$/iu.exec(t);if(!n||!i?.groups)return
|
|
2081
|
+
`)},pause(){p=!0,d!==void 0&&(l(d),d=void 0),u?.stop?.(),u=void 0},resume(){m||(p=!1,h())},finish(g){m||(m=!0,d!==void 0&&(l(d),d=void 0),u&&(g.exitCode===0?u.succeed(tre(g.stdout,o)):u.fail(`Stopped ${o}`),u=void 0))}}}function tre(e,t){try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n)){let r=String(n.status??"").toLowerCase();if(r==="install_pending_review"||r==="source_submitted"||r.includes("pending"))return`Submitted ${t}`;if(r==="installed_unverified")return"Installed unverified source"}}catch{}return`Completed ${t}`}var Z=class extends Error{status;details;constructor(t,n,r){super(n),this.name="ApiError",this.status=t,this.details=r}},are=1,JP=1,hh=2,VM="skills-layer-public-cli-v1",$t="skills-layer-security-hook",xt="Skills Layer Security Hook",YP="https://api.skills-layer.com",lre="http://127.0.0.1:8787",EB=new Set(["json","dry-run","skip-probe","clear-display-name","clear-company","clear-bio","help","list","all","deep","verbose","show-url","no-open","confirm","confirmed","create-account","yes","with-mcp","no-mcp","allow-unmanaged-once","disclose-source","new-enterprise","leave-enterprise","skip-license","replace-unpublished","accept-unverified-source","local-only","replace-unverified-source","quick","apply","attest-rights","confirm-free","forget"]),rP=new Set(["accept-capability","approval-request-id","grant-json","paraphrase","secret-env","should-not-trigger","should-trigger"]),$B=new Set(["bio","company","description","display-name","feedback","message","note","reason","search","summary"]),DB=new Set(["country","cursor","publisher","price","minimum-score","minimum-stars","badge","action","action-json","agent","amount-cents","api-key","base-url","capability","category","claim-id","client","cloud-trust-ledger","code","commit-sha","created-after","created-before","decision","decision-evidence-json","dependency-audit-status","dir","email","environment","eval-summary","evidence-json","expires","expires-after","expires-before","external-reference","idempotency-key","fixed-version","format","host-version","install","issue-id","issue-type","key-id","kind","license","license-file","limit","listing-status","max-characters","method","mfa-code","mode","name","output","path","payment-method","pack","pin","price-cents","provider","purpose","provider-installation-id","provider-owner-id","provider-project-id","provider-repo-id","provenance-intent","publication-status","rating","reference","recovery-code","requested-role","review-id","role","runtime-risk","scope","security-capability","skill","skill-type","sort","source","source-intake-context","space-pack","state","status","seats","text","telemetry-mode","telemetry-policy","guardian-policy","trust","type","unmanaged-policy","version","version-id","visibility","workspace","workspace-name","enterprise-name","answers","answer-json","question-id","decisions-json","patch-json","expected-revision","plan-digest","report-digest","caller-capabilities-json","challenge-digest","observations-json","supplied-resources-json","additional-evidence-json","tags-json","outcome","session-id","creator-session-id","imported-candidate-id","rights-basis","distribution-scope","source-reference"]),yh=new Set(nI),cre=new Set(["standards","marketplace-status","capabilities","schema-plan","optimize-tokens"]);async function yCe(e,t={}){e=yN(e);let n=t.env??process.env,r=ure(e),i;try{i=Aa(e,n,{stdinIsTty:t.stdinIsTty??!!(t.selectInput?.isTTY??process.stdin.isTTY),stdoutIsTty:t.stdoutIsTty??!!(t.selectOutput?.isTTY??process.stdout.isTTY),stderrIsTty:t.stderrIsTty??!!process.stderr.isTTY})}catch(w){return dre(e,ve(w),r,t)}let o=[],s=i.mode.kind==="json-final"||i.mode.kind==="json-stream",a=i.options.interactive===!1||i.options.screenReader===!0||i.options.motion==="never"||i.options.ui==="classic",l=fre(n.CI)||n.TERM==="dumb",u=t.stdinIsTty===void 0&&t.stderrIsTty===void 0&&t.stdoutIsTty!==!1&&!!(t.promptText||t.promptSecret||t.promptSelect||t.selectInput||t.openUrl||t.emitInfo),d=t.stdoutIsTty===!0&&t.stdinIsTty===void 0&&t.stderrIsTty===void 0,p=a||l&&!u||s&&!u||!i.mode.interactive&&!u&&!d,m=t.emitInfo,h=i.args.find(w=>!w.startsWith("-"))??"skills-layer",g=i.mode.kind==="json-stream"?pI({operationId:t.operationId??`op_${Ge(8).toString("hex")}`,command:{name:h},now:t.now},t.emitCliEvent,i.mode.detail):void 0,y={...t,renderMode:i.mode,nonInteractive:i.options.interactive===!1,...p?{stdoutIsTty:!1,openUrl:async()=>!1,promptText:async()=>{throw new Error("Interactive prompts are disabled for this presentation mode.")},promptSecret:async()=>{throw new Error("Interactive prompts are disabled for this presentation mode.")},promptSelect:async()=>{throw new Error("Interactive prompts are disabled for this presentation mode.")}}:{},...s?{emitInfo:g?GN(g,m):VN(i.mode,o,m)}:{}},v=g?HN({session:g,commandName:h}):void 0,b;try{b=await mre(i.args,y)}finally{v?.()}return i.mode.kind!=="json-stream"?b:(g.finish(b),{exitCode:b.exitCode,stdout:t.emitCliEvent?"":fI(g.events),stderr:""})}function ure(e){let t=e.indexOf("--"),n=t===-1?e:e.slice(0,t),r=n.includes("--json"),i=!1;for(let o=0;o<n.length;o+=1){let s=n[o],a=s.startsWith("--output-format=")?s.slice(16):null,l=a??(s==="--output-format"?n[o+1]:void 0);l==="stream-json"?i=!0:l==="json"&&(r=!0),a===null&&s==="--output-format"&&(o+=1)}return i?"stream-json":r?"json":null}function dre(e,t,n,r){let i=/^--(?<option>[a-z0-9-]+) expects one of: (?<accepted>.+)\.$/iu.exec(t);if(!n||!i?.groups)return E(`${t}
|
|
2082
2082
|
Next: run skills-layer --help`,n==="json");let o=i.groups.option,s=pre(e,o),a={status:"error",reasonCode:"invalid_global_option",option:o,providedValue:H((s??"<missing>").slice(0,128)),acceptedValues:i.groups.accepted.split(",").map(d=>d.trim()).filter(Boolean),nextAction:"help",nextStep:"Run `skills-layer --help` and provide one accepted global option value."},l=x(a,`Invalid global option --${o}.`,!0,"invalid_global_option");if(n==="json")return l;let c=e.find(d=>!d.startsWith("-"))??"skills-layer",u=pI({operationId:r.operationId??`op_${Ge(8).toString("hex")}`,command:{name:c},now:r.now},r.emitCliEvent);return u.finish(l),{exitCode:1,stdout:r.emitCliEvent?"":fI(u.events),stderr:""}}function pre(e,t){let n=`--${t}`,r=`${n}=`,i=e.indexOf("--"),o=i===-1?e:e.slice(0,i);for(let s=0;s<o.length;s+=1){let a=o[s];if(a.startsWith(r))return a.slice(r.length);if(a===n)return o[s+1]}}function fre(e){return e!==void 0&&e!==""&&e!=="0"&&e.toLowerCase()!=="false"}async function mre(e,t){let n={env:t.env??process.env,platform:t.platform??process.platform,cwd:t.cwd??process.cwd(),now:t.now??(()=>new Date().toISOString()),fetchFn:t.fetch??globalThis.fetch,openUrl:t.openUrl??_ce(t.platform??process.platform),stdoutIsTty:t.stdoutIsTty??!!process.stdout.isTTY,helpInteractive:t.stdoutIsTty??!!(t.selectInput?.isTTY&&t.selectOutput?.isTTY),renderMode:t.renderMode??Aa([],t.env??process.env,{stdinIsTty:!1,stdoutIsTty:t.stdoutIsTty??!!process.stdout.isTTY,stderrIsTty:!1}).mode,promptText:Qg(t.promptText??kce(),{start:t.onPromptStart,end:t.onPromptEnd}),promptSecret:Qg(t.promptSecret??wce(),{start:t.onPromptStart,end:t.onPromptEnd}),promptSelect:Qg(t.promptSelect??bce(t.selectInput??process.stdin,t.selectOutput??process.stdout),{start:t.onPromptStart,end:t.onPromptEnd}),sleep:t.sleep??(u=>new Promise(d=>setTimeout(d,u))),emitInfo:t.emitInfo??(u=>process.stdout.write(`${u}
|
|
2083
|
-
`)),credentialStore:t.credentialStore!==void 0?t.credentialStore:FC(t.platform??process.platform,t.env??process.env),nonInteractive:t.nonInteractive===!0,pathExists:t.pathExists??pr},r=e[0];if(!r){let u=iP([]),d=await Tu(u.flags,n);return await pae(u.flags,d)}if(r==="--help"||r==="-h"){let u=iP(e.slice(1));if(u.flags.json||n.renderMode.kind==="json-final"){let d=await Tu(u.flags,n),p=_o();return
|
|
2084
|
-
`,stderr:""};let i=iP(e.slice(1));if(i.error)return
|
|
2083
|
+
`)),credentialStore:t.credentialStore!==void 0?t.credentialStore:FC(t.platform??process.platform,t.env??process.env),nonInteractive:t.nonInteractive===!0,pathExists:t.pathExists??pr},r=e[0];if(!r){let u=iP([]),d=await Tu(u.flags,n);return await pae(u.flags,d)}if(r==="--help"||r==="-h"){let u=iP(e.slice(1));if(u.flags.json||n.renderMode.kind==="json-final"){let d=await Tu(u.flags,n),p=_o();return R(p,"Help loaded.",!0,d)}return{exitCode:0,stdout:Lo(n.renderMode),stderr:""}}if(r==="--version"||r==="-v")return{exitCode:0,stdout:`skills-layer ${So}
|
|
2084
|
+
`,stderr:""};let i=iP(e.slice(1));if(i.error)return E(i.error,i.flags.json);let{flags:o,positionals:s}=i;if(r==="admin")return E("The public skills-layer package does not include internal commands.",o.json);if(r==="version"){let u=await Tu(o,n);return R({status:"ok",name:"skills-layer",version:So},`skills-layer ${So}`,o.json,u)}if(!yh.has(r))return TB(r,o.json);let a=mN([r,...s]),l=a?gN(a,e.slice(1)):null,c=a?.path==="guardian exec"&&(l==="action-json"||l==="grant-json")||a?.path==="guardian check"&&l==="allow-unmanaged-once"?null:l;if(a?.kind==="command"&&c)return x({status:"error",reasonCode:"unknown_flag",command:a.path,flag:c,nextAction:`${a.path.replace(/\s+/gu,".")}.help`,nextStep:`Run \`skills-layer ${a.path} --help\` to see the options owned by this command.`},`Unknown flag --${c} for skills-layer ${a.path}.`,o.json,"unknown_flag");if(o.help){if(o.json){let d=await Tu(o,n),p=_o(r,s);return p?R(p,"Help loaded.",!0,d):yh.has(r)?IP([r,...s],!0):E(bP(r),!0)}let u=vu(r,s);return u?{exitCode:0,stdout:u,stderr:""}:yh.has(r)?IP([r,...s],o.json):E(bP(r),o.json)}try{let u=await Tu(o,n);switch(r){case"agents":return await wre(s,o,u);case"backend":return await bre(s,o,u);case"register":return await GM(o,u);case"login":return await HM(o,u);case"logout":return await KM(o,u);case"whoami":return await me("/api/v1/whoami",o,u,"Account loaded.",{authenticated:!0});case"profile":return await Ire(s,o,u);case"auth":return await Are(s,o,u);case"identity":return await Ore(s,o,u);case"api-key":return await Nre(s,o,u);case"mcp":return await zre(s,o,u);case"enterprise":return await Vre(s,o,u);case"search":case"find":return await hie(s,o,u);case"featured":case"trending":return await Mie(r,o,u);case"categories":return s.length>0?ZB("categories",s[0],o):await me("/api/v1/categories",o,u,"Categories loaded.");case"recommend":return await Uie(s,o,u);case"compare":return await zie(s,o,u);case"show":return await qie(s,o,u);case"trust":return await Vie(s,o,u);case"help":return await Gie(s,o,u);case"status":return s.length>0?ZB("status",s[0],o):await nle(o,u);case"doctor":return await rle(o,u);case"setup":return await HU(o,u);case"validate":return await Hie(s,o,u);case"preview-trigger":return await Yie(s,o,u);case"creator":return await Xie(s,o,u);case"install":return await Wa(s,o,u);case"installed":return await nse(o,u);case"remove":return await rse(s,o,u);case"update":return await sse(s,o,u);case"sync":return await lse(o,u);case"restore":return await yse(s,o,u);case"check":return await kse(s,o,u);case"import":return await wse(s,o,u);case"source":return await Sse(s,o,u);case"approval":return await Ise(s,o,u);case"workspace":case"workspaces":return await Pse(s,o,u);case"buy":return await Dse(s,o,u);case"purchases":return await Tse(s,o,u);case"owned":return await me("/api/v1/me/library",o,u,"Owned skills loaded.",{authenticated:!0});case"export":return await Lse(s,o,u);case"library":return await Ose(s,o,u);case"add-review":return await wM("add",s,o,u);case"show-reviews":return await wM("show",s,o,u);case"add-issue":return await bM("add",s,o,u);case"show-issues":return await bM("show",s,o,u);case"guardian":return await jse(s,o,u);default:return TB(r,o.json)}}catch(u){return u instanceof Z?Go(u,o.json):u instanceof pe?gre(u,o.json):E(ve(u),o.json)}}function gre(e,t){return x({status:"error",reasonCode:e.code,why:e.code==="canonical_bundle_rejected"?"One or more bundle files failed canonical intake.":"The local bundle could not be collected safely.",issues:e.issues,blockingFindings:e.issues.map(n=>({code:n.code,...n.path?{path:n.path}:{}})),...e.preview?{preview:e.preview}:{},nextAction:"bundle.fix",nextStep:"Correct the listed files and run `skills-layer validate <path>`."},e.code==="canonical_bundle_rejected"?"The local bundle failed canonical intake. Correct the listed files and validate again.":e.message,t,e.code)}function bP(e){let t=e.trim().toLowerCase();return t==="purchase"?`Unknown command "${e}".
|
|
2085
2085
|
|
|
2086
2086
|
Did you mean:
|
|
2087
2087
|
skills-layer buy <skill-slug>
|
|
@@ -2098,10 +2098,10 @@ Did you mean:
|
|
|
2098
2098
|
|
|
2099
2099
|
Next: ${r.replace(/^Run /u,"run ")}`,t,"unknown_command")}function hre(e){let t=e.trim().toLowerCase(),n={purchase:"buy",validation:"validate",details:"show","security-report":"trust"};if(n[t])return n[t];let r=[...yh].filter(s=>!s.includes(" ")).map(s=>({candidate:s,distance:yre(t,s)})).sort((s,a)=>s.distance-a.distance||s.candidate.localeCompare(a.candidate)),i=r[0],o=r[1];return i&&i.distance<=2&&i.distance<(o?.distance??Number.POSITIVE_INFINITY)?i.candidate:void 0}function yre(e,t){let n=Array.from({length:t.length+1},(r,i)=>i);for(let r=1;r<=e.length;r+=1){let i=[r];for(let o=1;o<=t.length;o+=1)i[o]=Math.min((i[o-1]??0)+1,(n[o]??0)+1,(n[o-1]??0)+(e[r-1]===t[o-1]?0:1));n.splice(0,n.length,...i)}return n[t.length]??t.length}function Lo(e,t=!1){let n=t?yu:Eg;return`${Ag(e)}
|
|
2100
2100
|
|
|
2101
|
-
${n}`}function iP(e){let t={json:e.includes("--json"),help:!1,dryRun:!1,list:!1,all:!1,deep:!1,verbose:!1,showUrl:!1,noOpen:!1,confirmed:!1,allowUnmanagedOnce:!1,discloseSource:!1,shouldTrigger:[],shouldNotTrigger:[],paraphrase:[],grantJson:[],findingCode:[],acceptCapability:[],approvalRequestId:[]},n=[];for(let r=0;r<e.length;r+=1){let i=e[r];if(!i)continue;if(i==="--"){n.push(...e.slice(r+1));break}if(i==="-h"){t.help=!0;continue}if(!i.startsWith("--")){n.push(i);continue}let o=i.slice(2);if(o!=="install"&&!EB.has(o)&&!$B.has(o)&&!DB.has(o)&&!rP.has(o))return{flags:t,positionals:n,error:`Unknown flag --${o}.`};if(EB.has(o)){let a=oP(o);o==="confirm"||o==="yes"?t.confirmed=!0:t[a]=!0;continue}let s=e[r+1];if(!s||s.startsWith("--")){if(o==="install"){t.install="";continue}return{flags:t,positionals:n,error:`Flag --${o} requires a value.`}}if($B.has(o)){let a=vre(e,r);if(!a.value)return{flags:t,positionals:n,error:`Flag --${o} requires a value.`};t[oP(o)]=a.value,r=a.nextIndex;continue}if(DB.has(o)||rP.has(o)){let a=oP(o);if(o==="scope"){let l=Array.isArray(t.scopeValues)?t.scopeValues:[];l.push(s),t.scopeValues=l,t.scope=s}else if(rP.has(o)){let l=Array.isArray(t[a])?t[a]:[];l.push(s),t[a]=l}else t[a]=s;r+=1;continue}return{flags:t,positionals:n,error:`Unknown flag --${o}.`}}return{flags:t,positionals:n}}function vre(e,t){let n=[],r=t;for(let i=t+1;i<e.length;i+=1){let o=e[i];if(!o||o.startsWith("--"))break;n.push(o),r=i}return{value:n.length>0?n.join(" "):null,nextIndex:r}}function oP(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function Tu(e,t){let n=kre(t.env,t.platform),[r,i]=await Promise.all([vce(n.configPath,t),ke(n.backendPreferencePath)]),o=dr(k(e.baseUrl)??Re(t.env.SKILLS_LAYER_BASE_URL)??Re(i?.preferredBaseUrl)??Re(r?.baseUrl)??YP);try{tl(o)}catch{throw new Z(400,"Invalid backend URL. Use HTTPS, or HTTP for loopback development only.",{reasonCode:"invalid_base_url",baseUrl:o.replace(/(\/\/)[^/]*@/u,"$1<redacted>@"),nextAction:"backend",nextStep:"Use an HTTPS backend URL without credentials, query parameters, or fragments."})}let s=k(e.apiKey)??Re(t.env.SKILLS_LAYER_API_KEY),a=Re(r?.apiKey),l=Re(r?.baseUrl),c=!l||Yu(l,o),u=s??(c?a:void 0),d=!s&&a&&l&&!c?`Your saved login belongs to ${dr(l)}, but the selected backend is ${o}. Run \`skills-layer backend --base-url ${dr(l)}\` to use that login, or run \`skills-layer login\` for ${o}.`:void 0;return{...t,paths:n,config:r,baseUrl:o,apiKey:u,authBlockedMessage:d}}function kre(e,t){let n=t==="win32"?st:Lt,r=hN(e,t);return{stateDir:r,configPath:n.join(r,"config.json"),backendPreferencePath:n.join(r,"backend-preference.json"),installTargetPreferencePath:n.join(r,"install-target-preference.json"),installsPath:n.join(r,"installs.json"),importsPath:n.join(r,"imports.json"),mcpConfigPath:n.join(r,"mcp.json"),mcpPreferencePath:n.join(r,"mcp-preference.json"),pendingRevocationsPath:n.join(r,"pending-revocations.json"),bundlesDir:n.join(r,"bundles"),incidentsDir:n.join(r,"incidents")}}async function wre(e,t,n){if(e[0]!=="list")return R(`Unknown agents command "${e[0]??""}".`,t.json);let r=et(n.env,n.platform,n.cwd).map(i=>({id:i.id,displayName:i.displayName,capabilities:i.capabilities,projectSkillsPath:i.targets.projectSkillsPath,globalSkillsPath:i.targets.globalSkillsPath}));return A({status:"ok",results:r},`Found ${r.length} supported agent targets.`,t.json,n)}async function bre(e,t,n){let r=e[0],i=k(t.baseUrl);if(!r&&i||r==="cloud"||r==="local"){let l=dr(i??(r==="local"?lre:YP)),c=jie(l,t);if(c)return c;if(!t.skipProbe){let m=await zA(l,n.fetchFn);if(m!=="ok")return x({status:"error",reasonCode:m,unchanged:!0,nextStep:"Check the backend address, or use --skip-probe for offline configuration."},m==="backend_unreachable"?"Backend could not be reached.":"The address did not identify a Skills Layer API.",t.json,m)}let u=Dt(l),d=n.config?.baseUrl??null,p=!n.config?.baseUrl||Yu(n.config.baseUrl,l);return await Ve(n.paths.backendPreferencePath,{version:JP,preferredBaseUrl:l,savedAt:n.now()}),A({status:"updated",selectedBackend:u,selectedBaseUrl:l,savedLoginBaseUrl:d,loginMatchesSelectedBackend:p,loggedIn:!!n.apiKey&&p,...p?{}:{warning:`Saved login belongs to ${d}; selected backend is ${l}.`}},p?`Backend set to ${u}.`:`Backend set to ${u}. Saved login is for ${d}.`,t.json,n)}if(r&&r!=="status")return R(`Unknown backend command "${r}".`,t.json);let o=Dt(n.baseUrl),s=!n.config?.baseUrl||Yu(n.config.baseUrl,n.baseUrl),a=!!n.apiKey&&s;return A({status:"ok",selectedBackend:o,selectedBaseUrl:n.baseUrl,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:s,loggedIn:a,email:a?n.config?.email??null:null,role:a?n.config?.role??null:null,identitySource:"cached_at_login"},`Backend: ${n.baseUrl}. Account details are cached from login; run skills-layer whoami to check current access.`,t.json,n)}var $h=[{value:"google",label:"Google",description:"Open browser sign-in and return here"},{value:"github",label:"GitHub",description:"Open browser sign-in and return here"},{value:"gitlab",label:"GitLab",description:"Open browser sign-in and return here"},{value:"microsoft",label:"Microsoft",description:"Open browser sign-in and return here"}];async function Dh(e,t){if(t.nonInteractive||!t.stdoutIsTty)return e.filter(n=>n.value!=="microsoft");try{let n=await D(t,"/api/v1/identity/social/providers");return Array.isArray(n.providers)?e.filter(r=>!Ko(r.value)||n.providers.includes(r.value)):e.filter(r=>r.value!=="microsoft")}catch{return e.filter(n=>n.value!=="microsoft")}}var _re=[...$h,{value:"email",label:"Continue with email",description:"Sign in or create an account with an emailed one-time code"},{value:"api_key",label:"API key (advanced)",description:"Paste an existing Skills Layer login key"}],Sre=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...$h],xre=[{value:"email",label:"Email code",description:"Verify account ownership with an emailed one-time code"}];async function GM(e,t){let n=k(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",await Dh(Sre,t))}catch{return R("register requires --method when interactive selection is unavailable. Try `skills-layer register --method email --email you@example.com`, `skills-layer register --method google`, `skills-layer register --method github` or `skills-layer register --method gitlab`.",!1)}let r=Mn("register","method",n,Cie,e,"invalid_method");if(r)return r;if(n==="email"){let a=k(e.email);if(!a&&!e.json)try{a=await t.promptText("Enter your email address: ")}catch{return R("register --method email requires --email when interactive prompts are unavailable.",!1)}a=O(a,"register requires --email.");let l=await D(t,"/api/v1/register",{method:"POST",headers:V(),body:JSON.stringify({method:n,email:a})});if(e.json){let u=l.status==="already_registered"?WP(l):Nt({...l,nextCommand:`skills-layer auth verify --email ${a} --code <code> --json`,nextAction:"auth.verify"}),d=l.status==="already_registered"?`${a} is already registered.`:`Registration started for ${a}.`;return A(u,d,e.json,t)}if(l.status==="already_registered")return A(WP(l),`${a} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,!1,t);let c;try{c=await t.promptText(`Enter the verification code sent to ${a} (check spam/junk folder if missing): `)}catch{return A(Nt(l),`Registration started for ${a}. Check your email (including spam/junk folder) for the verification code, then run \`skills-layer auth verify --email ${a} --code <code>\`.`,!1,t)}return await vA(a,c,e,t,`Verified ${a}.`)}if(!Ko(n))return R("register --method must be email, google, github, or gitlab.",e.json);let i=Ho(),o=await wA({flags:e,backend:t,provider:n,mode:"register",credentialHandoff:i});if(fe(o))return o;let s=await D(t,"/api/v1/identity/social/start",{method:"POST",headers:V(),body:JSON.stringify({provider:n,mode:"register",createAccount:e.createAccount===!0,handoffCodeHash:i.authorizationCodeHash,handoffCodeChallenge:i.codeChallenge})});return await jh(n,s,i,e,t,"register",void 0,o)}async function HM(e,t){if(e.withMcp&&e.noMcp)return R("login cannot combine --with-mcp and --no-mcp.",e.json);let n=k(e.apiKey);if(n){let l=await Vu(t,n,{notifyLogin:!0}),c=await wh(e,{...t,config:l,apiKey:n});if(fe(c))return c;let u=await xP(e,{...t,config:l,apiKey:n});if(fe(u))return u;let d=u.data?.status==="mcp_not_configured";return A(Nt(CP({status:d?"partial_success":"verified",...l,loggedIn:!0,...c.data?{workingMode:c.data}:{},...u.data?{mcp:u.data}:{},...d?{warnings:[u.data]}:{}},u.data)),[`Logged in as ${l.email}.`,c.message??"",u.message??""].filter(Boolean).join(" "),e.json,t)}let r=k(e.method);if(!r&&!e.json)try{let l=await t.promptSelect("Choose how to sign in:",await Dh(_re,t));r=l==="api_key"?void 0:l}catch{return R("login requires --api-key or --method <email|google|github|gitlab> when interactive selection is unavailable.",!1)}let i=Mn("login","method",r,xie,e,"invalid_method");if(i)return i;if(r){if(r==="email"){let d=k(e.email);!d&&!e.json&&(d=(await t.promptText("Enter your email address: ")).trim()),d=O(d,"login --method email requires --email.");let p=await D(t,"/api/v1/register",{method:"POST",headers:V(),body:JSON.stringify({email:d})}),m=Nt({...p,nextAction:"auth.verify",nextCommand:`skills-layer auth verify --email ${d} --code <code> --json`});if(f(p,"emailDelivery")==="failed")return x({...m,status:"email_delivery_failed",reasonCode:"email_delivery_failed",nextAction:"login.retry",nextStep:"Retry email sign-in after the delivery service recovers, or choose a connected social provider."},"The email code could not be delivered. Retry later or choose another sign-in method.",e.json,"email_delivery_failed");if(f(p,"status")==="already_registered")return R("The backend did not prepare an email sign-in code. Retry later or choose another sign-in method.",e.json);if(e.json)return A(m,`Email sign-in started for ${d}.`,!0,t);let h="";try{h=(await t.promptText("Enter the email code if you received one, or press Enter to stop: ")).trim()}catch{return A(m,`Email sign-in started for ${d}. Check your email (including spam/junk folder), then run \`skills-layer auth verify --email ${d} --code <code>\` when the code arrives.`,!1,t)}return h?await vA(d,h,e,t,`Verified ${d}.`):A(m,`Email sign-in started for ${d}. No code was entered, so nothing else was changed. Run \`skills-layer auth verify --email ${d} --code <code>\` when ready.`,!1,t)}if(!Ko(r))return R("login --method must be email, google, github, or gitlab.",e.json);let l=Ho(),c=await wA({flags:e,backend:t,provider:r,mode:"login",credentialHandoff:l});if(fe(c))return c;let u=await D(t,"/api/v1/identity/social/start",{method:"POST",headers:V(),body:JSON.stringify({provider:r,mode:"login",handoffCodeHash:l.authorizationCodeHash,handoffCodeChallenge:l.codeChallenge})});return await jh(r,u,l,e,t,"login",void 0,c)}if(!e.json)try{n=(await t.promptSecret("Enter your Skills Layer API key: ")).trim()}catch{return R("login requires an API key.",e.json)}if(!n)return R("login requires --api-key or --method <email|google|github|gitlab>.",e.json);let o=await Vu(t,n,{notifyLogin:!0}),s=await wh(e,{...t,config:o,apiKey:n});if(fe(s))return s;let a=await xP(e,{...t,config:o,apiKey:n});return fe(a)?a:A(Nt(CP({status:"verified",...o,...s.data?{workingMode:s.data}:{},...a.data?{mcp:a.data}:{}},a.data)),[`Logged in as ${o.email}.`,s.message??"",a.message??""].filter(Boolean).join(" "),e.json,t)}async function KM(e,t){let n=!1,r=!1,i=await ke(t.paths.mcpConfigPath),o=i?f(i,"keyId"):void 0,s=Re(t.config?.apiKey)??t.apiKey,a=dr(Re(t.config?.baseUrl)??t.baseUrl);if(s){try{await D({...t,baseUrl:a,apiKey:s},"/api/v1/me/working-mode",{method:"DELETE",headers:re(s)}),n=!0}catch{n=!1}try{await D({...t,baseUrl:a,apiKey:s},"/api/v1/me/session/revoke",{method:"POST",headers:V(s),body:JSON.stringify({includeCurrent:!0,revokeAllMcp:!0,humanKeyIds:[],mcpKeyIds:o?[o]:[]})}),r=!0}catch{r=!1}}let l=F2(t.config,{env:t.env,platform:t.platform,store:t.credentialStore}),c=await Promise.allSettled([l,Cre(t),l.then(()=>We(t.paths.configPath,{force:!0}))]),u=c.every(m=>m.status==="fulfilled");if(!u)return x({status:"logout_incomplete",reasonCode:"local_cleanup_incomplete",serverCredentialsRevoked:r,localCleanupComplete:!1,nextAction:"logout",nextStep:"Unlock the OS credential store and retry logout. Local references were retained for cleanup."},"Server revocation was attempted, but local cleanup is incomplete.",e.json,"local_cleanup_incomplete");let d=!!s&&!r,p=d&&(t.config?.userId&&(t.config.sessionCredentialId||o))?await xA(t,{baseUrl:a,userId:t.config.userId,humanKeyIds:t.config.sessionCredentialId?[t.config.sessionCredentialId]:[],mcpKeyIds:o?[o]:[],revokeAllMcp:!0,revokeAdminMcp:!0,createdAt:t.now()}):!1;return A({status:s?"logged_out":"not_logged_in",serverWorkingModeCleared:n,serverCredentialsRevoked:r,revocationPending:d,...d?{pendingRecorded:p}:{},localCleanupComplete:u,warnings:u?[]:["Some local cleanup failed. Retry logout to finish clearing local state."],mcpAuthCleared:c[1].status==="fulfilled"},d?p?"Logged out locally. Server revocation is pending and will retry after the same account authenticates again.":"Logged out locally, but server revocation could not be recorded. Reconnect promptly; credentials remain bounded by expiry.":r?"Logged out. Human and MCP credentials were revoked.":"No saved login; local state cleared.",e.json,t)}async function Cre(e){let t=await ke(e.paths.mcpConfigPath);if(!t){await SP(null,e),await We(e.paths.mcpPreferencePath,{force:!0});return}let n=t?f(t,"baseUrl")??e.baseUrl:e.baseUrl,r=t?f(t,"clientId")??"codex":"codex",i=es({baseUrl:n,mcpUrl:t?f(t,"mcpUrl")??`${n}/mcp`:`${n}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:t?f(t,"environment")??Dt(n):Dt(n),now:e.now(),env:e.env,platform:e.platform,cwd:e.cwd,stateDir:e.paths.stateDir,mcpConfigPath:e.paths.mcpConfigPath,nodePath:process.execPath}),o=t&&Array.isArray(t.clientIds)?t.clientIds.filter(a=>typeof a=="string"):t?[r]:[];if((await Promise.allSettled([SP(t,e),...i.targets.filter(a=>o.includes(a.agentId)).map(a=>a.disconnect?.()),ay(i.bridgePath),ly(i.brokerPath,i.brokerSocketPath,i.brokerLockPath),We(e.paths.mcpPreferencePath,{force:!0})])).some(a=>a.status==="rejected"))throw new Error("MCP local cleanup is incomplete; retry logout.");await We(e.paths.mcpConfigPath,{force:!0})}async function Ire(e,t,n){let r=e[0]??"show";if(r==="show")return await me("/api/v1/profile",t,n,"Editable profile loaded.",{authenticated:!0});if(r==="update"){let i=await Pre(t,n);if(fe(i))return i;let o=await D(n,"/api/v1/profile",{method:"PATCH",headers:V(n.apiKey),body:JSON.stringify(i)});return A(o,"Profile updated.",t.json,n)}return R(`Unknown profile command "${r}".`,t.json)}async function Pre(e,t){let n=Ft(e,["displayName","bio","company"]);for(let r of["displayName","bio","company"])if(e[`clear${r[0].toUpperCase()}${r.slice(1)}`]){let i=r.replace(/[A-Z]/gu,o=>`-${o.toLowerCase()}`);if(n[r]!==void 0)return x({reasonCode:"conflicting_flags",unchanged:!0},`Choose either --${i} or --clear-${i}.`,e.json,"conflicting_flags");n[r]=null}if(Object.keys(n).length>0)return n;if(e.json)return R("profile update requires at least one of --display-name, --bio, or --company.",!0);try{let r=await t.promptText("Display name (leave blank to keep unchanged): "),i=await t.promptText("Bio (leave blank to keep unchanged): "),o=await t.promptText("Company (leave blank to keep unchanged): "),s=ie({displayName:r||void 0,bio:i||void 0,company:o||void 0});return Object.keys(s).length===0?R("No profile changes entered.",!1):s}catch{return R("profile update requires at least one of --display-name, --bio, or --company.",!1)}}async function Are(e,t,n){let r=e[0];if(r==="register")return await GM({...t,method:"email"},n);if(r==="verify"){let i=O(t.email,"auth verify requires --email."),o=O(t.code,"auth verify requires --code.");return await vA(i,o,t,n,`Verified ${i}.`)}return r==="recover"?await $re(e.slice(1),t,n):r==="connect"?await Dre(t,n):r==="mfa"?await Tre(e.slice(1),t,n):r==="login"?await HM(t,n):r==="logout"?await KM(t,n):r==="status"?Rre(t,n):r==="repair"?await Ere(t,n):R(`Unknown auth command "${r??""}".`,t.json)}function Rre(e,t){let n=t.config?.baseUrl?dr(t.config.baseUrl):null,r=!!(t.apiKey&&n&&Yu(n,t.baseUrl));return A({status:"auth_status",selectedBackend:Dt(t.baseUrl),selectedBaseUrl:t.baseUrl,loggedIn:r,requiresLogin:!r,...t.config?.email?{savedLogin:{baseUrl:n,email:t.config.email,role:t.config.role??null,roles:t.config.roles??[],savedAt:t.config.savedAt??null,...t.config.credentialStorage?{credentialStorage:t.config.credentialStorage}:{},matchesSelectedBackend:r}}:{}},r&&t.config?.email?`Logged in as ${t.config.email}.`:t.config?.baseUrl?`Saved login targets ${n}; selected backend is ${t.baseUrl}. Run \`skills-layer auth repair\` or \`skills-layer login\`.`:"Not logged in. Run `skills-layer login`.",e.json,t)}async function Ere(e,t){if(!t.config?.baseUrl||!t.config.apiKey||!t.config.email||!t.config.role||!t.config.savedAt)return x({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login` to create a saved session, then use `skills-layer auth repair` only if backend/session metadata drifts."},"No saved Skills Layer login was found to repair. Run `skills-layer login`.",e.json,"login_required");let n=dr(t.config.baseUrl);return await Ve(t.paths.backendPreferencePath,{version:JP,preferredBaseUrl:n,savedAt:t.now()}),await CA(t.paths.configPath,{...t.config,baseUrl:n,savedAt:t.now()},t),A({status:"auth_repaired",baseUrl:n,loggedIn:!0,email:t.config.email,role:t.config.role,credentialStorage:t.config.credentialStorage??"local_file_locked"},`Auth repaired for ${t.config.email}. Backend preference now matches ${n}.`,e.json,t)}async function $re(e,t,n){let r=e[0]??k(t.method);if(!r&&!t.json)try{r=await n.promptSelect("Choose how to recover access:",xre)}catch{return R("auth recover requires --method email when interactive selection is unavailable.",!1)}if(r??="email",Ko(r))return x({status:"unsupported_auth_journey",reasonCode:"unsupported_auth_journey",provider:r,nextAction:"account.connect",nextStep:`Run \`skills-layer auth connect --provider ${r}\` after signing in.`},`Social identities are connected, not used for account recovery. Sign in, then run \`skills-layer auth connect --provider ${r}\`.`,t.json,"unsupported_auth_journey");if(r!=="complete"&&r!=="email")return R("auth recover --method must be email.",t.json);let i=k(t.email);if(r==="complete"){if(!i&&!t.json)try{i=await n.promptText("Enter your email address: ")}catch{return R("auth recover complete requires --email when interactive prompts are unavailable.",!1)}i=O(i,"auth recover complete requires --email.");let l=k(t.code);if(!l&&!t.json)try{l=await n.promptText("Enter the recovery code: ")}catch{return R("auth recover complete requires --code when interactive prompts are unavailable.",!1)}return l=O(l,"auth recover complete requires --code."),await OB(i,l,t,n)}if(!i&&!t.json)try{i=await n.promptText("Enter your email address: ")}catch{return R("auth recover --method email requires --email when interactive prompts are unavailable.",!1)}i=O(i,"auth recover --method email requires --email.");let o=await D(n,"/api/v1/identity/recover/start",{method:"POST",headers:V(),body:JSON.stringify({email:i,method:r})}),s=WP(o);if(t.json)return A({...s,nextCommand:`skills-layer auth recover complete --email ${i} --code <code>`,nextAction:"auth.recover.complete",nextStep:"Check your email and complete recovery with the emailed code."},"Recovery started.",!0,n);let a="";try{a=(await n.promptText("Enter the recovery code if you received one, or press Enter to stop: ")).trim()}catch{return A(s,`If this email can continue, instructions have been sent. Check your inbox and spam folder. When you have a code, run \`skills-layer auth recover complete --email ${i} --code <code>\`.`,!1,n)}return a?await OB(i,a,t,n):A(s,`If this email can continue, instructions have been sent. When you have a code, run \`skills-layer auth recover complete --email ${i} --code <code>\`.`,!1,n)}async function Dre(e,t){let n=k(e.provider);if(!n&&!e.json)try{n=await t.promptSelect("Choose an identity to connect:",await Dh($h,t))}catch{return R("auth connect requires --provider when interactive selection is unavailable.",!1)}if(n=O(n,"auth connect requires --provider."),!Ko(n))return R("auth connect --provider must be google, github, or gitlab.",e.json);if(!t.apiKey||t.authBlockedMessage)return x({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login`, then retry the connection."},"Sign in before connecting another login method.",e.json,"login_required");if((await D(t,"/api/v1/identity/mfa/status",{headers:V(t.apiKey,t.authBlockedMessage)})).enabled!==!0){let l=await WM(e,t);return fe(l)?l:A(l,"MFA setup is required before connecting a sign-in method. Complete setup in the browser, then run this command again.",e.json,t)}let i=k(e.mfaCode);if(!i&&!e.json)try{i=await t.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return R("auth connect requires MFA verification. Retry with an interactive terminal.",!1)}if(!i||!/^\d{6}$/u.test(i))return R("auth connect requires a 6-digit --mfa-code when interactive prompts are unavailable.",e.json);let o=await D(t,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({purpose:"identity.connect",code:i})}),s=O(f(o,"stepUpGrant"),"MFA verification did not return a step-up grant."),a=await D(t,"/api/v1/identity/connect/start",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({provider:n,stepUpGrant:s})});return await jh(n,a,void 0,e,t,"connect","/api/v1/identity/connect/status")}async function Tre(e,t,n){let r=e[0]??"status";if(!n.apiKey||n.authBlockedMessage)return x({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login`, then retry the MFA command."},"Sign in before managing MFA.",t.json,"login_required");if(r==="status"){let i=await D(n,"/api/v1/identity/mfa/status",{headers:re(n.apiKey,n.authBlockedMessage)}),o=i.enabled===!1?{...i,nextAction:"account.mfa.setup",nextStep:"Protect this account by running `skills-layer auth mfa setup`."}:i;return A(o,"MFA status loaded.",t.json,n)}if(r==="setup"){let i=await WM(t,n);return fe(i)?i:A(i,"MFA setup started. Complete it in your browser; recovery codes are shown there once.",t.json,n)}if(r==="verify"){let i=O(k(t.purpose),"auth mfa verify requires --purpose."),o=k(t.mfaCode)??k(t.code);if(!o&&!t.json)try{o=await n.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return R("auth mfa verify requires an interactive code or --mfa-code.",!1)}if(!o||!/^\d{6}$/u.test(o))return R("auth mfa verify requires a 6-digit --mfa-code.",t.json);let s=await D(n,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({purpose:i,code:o})});return A(s,`MFA verified for ${i}.`,t.json,n)}if(r==="recovery-codes"){if(k(t.mfaCode)||k(t.code))return R("Do not pass an authenticator code on the command line. Recovery-code regeneration now requires protected browser verification.",t.json);if(t.json)return A({status:"human_action_required",reasonCode:"human_handoff_required",nextAction:"mfa.recovery_codes.browser",nextStep:"Run `skills-layer auth mfa recovery-codes` in an interactive human terminal to open the protected browser flow.",delivery:"browser_only"},"Recovery-code regeneration requires a protected human browser session.",!0,n);let i=await D(n,"/api/v1/identity/mfa/recovery-codes/regenerate",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({})}),o=O(f(i,"recoveryCodesUrl"),"Recovery-code regeneration did not return a secure browser handoff."),s=O(f(i,"operationId"),"Recovery-code regeneration did not return a secure operation identifier.");!t.noOpen&&await n.openUrl(o)||n.emitInfo(`Open this secure recovery-code link in your browser:
|
|
2102
|
-
${o}`),n.emitInfo("Waiting for recovery-code verification to finish in your browser...");let l=await Yae(s,n);return fe(l)?l:
|
|
2103
|
-
${r}`),{...n,status:"human_action_required",nextAction:"mfa.setup.browser",nextStep:"Complete authenticator setup in the browser, save the one-time recovery codes, then return to the CLI."}}async function OB(e,t,n,r){let i=Ho(),o=async(l,c)=>D(r,"/api/v1/identity/recover/complete",{method:"POST",headers:V(),body:JSON.stringify({email:e,code:t,...l?{mfaCode:l}:{},...c?{recoveryCode:c}:{},handoffCodeHash:i.authorizationCodeHash,handoffCodeChallenge:i.codeChallenge})}),s;try{s=await o(k(n.mfaCode),k(n.recoveryCode))}catch(l){if(!(l instanceof Z)||l.status!==428)throw l;if(n.json)return x({status:"human_action_required",reasonCode:"recovery_mfa_required",nextAction:"account.recover.verify_mfa",nextStep:"Retry with --mfa-code <6-digits> or --recovery-code <one-time-code>."},"Recovery needs your second factor.",!0,"recovery_mfa_required");let c=await r.promptSelect("Choose your recovery second factor:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one saved one-time recovery code"}]),u=(await r.promptSecret(c==="authenticator"?"Enter the 6-digit authenticator code: ":"Enter one unused recovery code: ")).trim();s=c==="authenticator"?await o(u,void 0):await o(void 0,u)}if(f(s,"status")!=="recovered")return R("Email recovery did not prepare a secure credential handoff. Start recovery again.",n.json);let a=await D(r,"/api/v1/identity/credential-handoff/exchange",{method:"POST",headers:V(),body:JSON.stringify({authorizationCode:i.authorizationCode,codeVerifier:i.codeVerifier})});if(f(a,"status")!=="exchanged"||!f(a,"email")||!f(a,"role")||!f(a,"apiKey"))return R("Email recovery credential handoff failed closed. Start recovery again.",n.json);if(n.json){let l=f(a,"apiKey");return l?(await Vu(r,l,{expectedEmail:e,knownEmail:f(a,"email")??e,knownRole:f(a,"role")??"user",knownRoles:Un(a,"roles"),knownUserId:f(a,"userId"),knownSessionCredentialId:f(a,"id")}),A(Nt({...a,holdUntil:s.holdUntil,blockedActions:s.blockedActions,loggedIn:!0}),`Recovery complete. Sensitive actions are held until ${String(s.holdUntil)}.`,!0,r)):A(Nt({...a,holdUntil:s.holdUntil,blockedActions:s.blockedActions,email:e,loggedIn:!1}),`Recovery complete. Sensitive actions are held until ${String(s.holdUntil)}.`,!0,r)}return await kA(e,{...a,holdUntil:s.holdUntil,blockedActions:s.blockedActions},n,r,`Recovered access for ${e}. Sensitive actions are held until ${String(s.holdUntil)}.`)}async function Ore(e,t,n){let r=e[0],i=1;if(r==="providers")return await me("/api/v1/identity/social/providers",t,n,"Identity providers loaded.");if(r==="start"){let o=k(t.provider);if(!o&&!t.json)try{o=await n.promptSelect("Choose identity provider:",await Dh($h,n))}catch{return R("identity start requires --provider when interactive selection is unavailable.",!1)}if(o=O(o,"identity start requires --provider."),!Ko(o))return R("identity start --provider must be google, github, or gitlab.",t.json);let s=k(t.mode)??"login";if(s!=="login"&&s!=="register")return x({status:"dedicated_auth_journey_required",reasonCode:"dedicated_auth_journey_required",nextStep:s==="recovery"?"Run `skills-layer auth recover`.":"Run `skills-layer auth connect --provider <provider>`."},"Use the dedicated recover or connect command for this account journey.",t.json,"dedicated_auth_journey_required");let a=Ho(),l=await wA({flags:t,backend:n,provider:o,mode:s,credentialHandoff:a});if(fe(l))return l;let c=await D(n,"/api/v1/identity/social/start",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({provider:o,mode:s,handoffCodeHash:a.authorizationCodeHash,handoffCodeChallenge:a.codeChallenge})});return await jh(o,c,a,t,n,s,void 0,l)}if(r==="status"){let o=k(t.state)??e[i];return o?await me(`/api/v1/identity/social/status/${encodeURIComponent(o)}`,t,n,"Social auth status loaded."):R("identity status requires --state.",t.json)}if(r==="continue"){let o=k(t.reference)??e[i];return await Lre(o,t,n)}if(r==="complete"){let o=O(t.provider,"identity complete requires --provider."),s=O(t.state,"identity complete requires --state."),a=O(t.code,"identity complete requires --code."),l=await D(n,"/api/v1/identity/social/complete",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({provider:o,state:s,code:a})});return A(Nt(l),"Social auth complete.",t.json,n)}if(r==="list")return await me("/api/v1/me/linked-identities",t,n,"Linked identities loaded.",{authenticated:!0});if(r==="unlink"){let o=O(t.provider??e[i],"identity unlink requires a provider."),s=l=>D(n,`/api/v1/me/linked-identities/${encodeURIComponent(o)}`,{method:"DELETE",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({mfaCode:l})}),a;try{a=await s(k(t.mfaCode))}catch(l){if(!(l instanceof Z)||l.details?.reasonCode!=="mfa_step_up_required"||t.json||n.nonInteractive||k(t.mfaCode))throw l;a=await s((await n.promptSecret("Enter a fresh authenticator code to unlink this identity: ")).trim())}return A(a,"Identity unlinked.",t.json,n)}return R(`Unknown identity command "${r??""}".`,t.json)}async function Lre(e,t,n){let r=O(e,"identity continue requires --reference <reference>.");if(!/^social_[A-Za-z0-9_-]{20,80}$/u.test(r)||!n.credentialStore)return No(t,n);let i=`skills-layer-social-continuation:${r}`,o;try{o=await n.credentialStore.get(je,i)}catch{o=null}let s=jre(o,r,n.baseUrl);if(!s)return await n.credentialStore.delete(je,i).catch(()=>{}),No(t,n);if(Date.parse(n.now())>=Date.parse(s.expiresAt))return await n.credentialStore.delete(je,i).catch(()=>{}),No(t,n);let a=await D(n,`/api/v1/identity/social/status/${encodeURIComponent(s.state)}`),l=f(a,"status");if(l==="pending")return A({status:"already_processing",reasonCode:"social_auth_pending",reference:r,expiresAt:s.expiresAt,nextAction:"identity.continue",nextStep:`Complete browser sign-in, then rerun \`skills-layer identity continue --reference ${r}\`.`},"Browser sign-in is still pending.",t.json,n);if(l==="mfa_required"){let c=k(t.mfaCode),u=k(t.recoveryCode);if(!c&&!u&&!t.json&&!n.nonInteractive&&n.stdoutIsTty){let p=await n.promptSelect("Complete MFA to finish login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),m=(await n.promptSecret(p==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();p==="recovery_code"?u=m:c=m}if(!c&&!u)return x({status:"human_action_required",reasonCode:"login_mfa_required",methods:["authenticator","recovery_code"],reference:r,nextAction:"identity.continue",nextStep:`Run \`skills-layer identity continue --reference ${r} --mfa-code <6-digits>\` in a human-controlled terminal.`},"MFA is required to finish the social login.",t.json,"login_mfa_required");let d=await D(n,"/api/v1/identity/login/mfa/verify",{method:"POST",headers:V(),body:JSON.stringify({state:s.state,authorizationCode:s.authorizationCode,codeVerifier:s.codeVerifier,...c?{mfaCode:c}:{},...u?{recoveryCode:u}:{}})});if(f(d,"status")!=="verified"||f(d,"credentialHandoff")!=="ready")return R("MFA verification did not authorize the stored login.",t.json)}else if(l!=="verified"&&l!=="recovered")return await n.credentialStore.delete(je,i).catch(()=>{}),x({status:l??"failed",reasonCode:"social_continuation_terminal",unchanged:!0,nextAction:"login",nextStep:"Start a fresh social login."},"The social login cannot be continued.",t.json,"social_continuation_terminal");try{return await kh(Cz(s.provider),{authorizationCode:s.authorizationCode,codeVerifier:s.codeVerifier,authorizationCodeHash:s.authorizationCodeHash,codeChallenge:s.codeChallenge},t,n,s.mode)}finally{await n.credentialStore.delete(je,i).catch(()=>{})}}function jre(e,t,n){if(!e)return null;try{let r=JSON.parse(e),i=f(r,"provider"),o=f(r,"mode"),s=f(r,"state"),a=f(r,"expiresAt"),l=f(r,"authorizationCode"),c=f(r,"codeVerifier"),u=f(r,"authorizationCodeHash"),d=f(r,"codeChallenge"),p=f(r,"integrityDigest"),m=f(r,"createdAt")??"";return r.version!==1||f(r,"reference")!==t||f(r,"baseUrl")!==n||!i||!Ko(i)||o!=="login"&&o!=="register"||!s||!a||!Number.isFinite(Date.parse(a))||!l?.startsWith("social_handoff_")||!c||!u||!d||!p||Ue("sha256").update(l).digest("base64url")!==u||Ue("sha256").update(c).digest("base64url")!==d||bA({version:1,reference:t,baseUrl:n,provider:i,mode:o,authorizationCode:l,codeVerifier:c,authorizationCodeHash:u,codeChallenge:d,createdAt:m,state:s,expiresAt:a})!==p?null:{version:1,reference:t,baseUrl:n,provider:i,mode:o,authorizationCode:l,codeVerifier:c,authorizationCodeHash:u,codeChallenge:d,integrityDigest:p,createdAt:m,state:s,expiresAt:a}}catch{return null}}async function Nre(e,t,n){let r=e[0];if(!r)return R("api-key requires create, list, or revoke.",t.json);if(r==="list"){let i=Fre(t);if(i.failure)return i.failure;let o=await D(n,"/api/v1/me/api-keys",{headers:re(n.apiKey,n.authBlockedMessage)}),s=Bre(ZM(o),i.filters,Date.parse(n.now()));return A({...o,filters:ie({...i.filters}),results:s},"API keys loaded.",t.json,n)}if(r==="create"){let i=k(t.name),o=Pce(Array.isArray(t.scopeValues)&&t.scopeValues.length>1?t.scopeValues:t.scope);if(!i)return R("api-key create requires --name.",t.json);if(o.length===0)return R("api-key create requires at least one --scope.",t.json);let s=o.find(p=>!GB.includes(p));if(s)return Nr("api-key.create","scope",s,GB,t,"invalid_scope");let a=Fie("api-key.create",t.expires,t);if(a)return a;if(t.dryRun){let p=await D(n,"/api/v1/me/api-keys",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({name:i,scopes:o,expiresIn:k(t.expires),dryRun:!0})});return A(p,"API key create dry run passed.",t.json,n)}let l=Ho(),c=await D(n,"/api/v1/me/api-keys",{method:"POST",headers:{"content-type":"application/json",...re(n.apiKey,n.authBlockedMessage)},body:JSON.stringify({name:i,scopes:o,...k(t.expires)?{expiresIn:k(t.expires)}:{},handoffCodeHash:l.authorizationCodeHash,handoffCodeChallenge:l.codeChallenge})});if(f(c,"credentialHandoff")!=="ready")return R("API key creation did not prepare a secure credential handoff.",t.json);let u=await D(n,"/api/v1/credential-handoffs/exchange",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({authorizationCode:l.authorizationCode,codeVerifier:l.codeVerifier})}),d=f(u,"apiKey");return f(u,"status")!=="exchanged"||!d?R("API key credential exchange failed closed; prepare the key again.",t.json):A({...u,secretReturned:!0,secretDelivery:"one_time_client_bound_exchange"},`Automation API key created. Copy this one-time secret now: ${d}
|
|
2104
|
-
Run \`skills-layer api-key list\` to manage keys.`,t.json,n)}if(r==="rotate")return
|
|
2101
|
+
${n}`}function iP(e){let t={json:e.includes("--json"),help:!1,dryRun:!1,list:!1,all:!1,deep:!1,verbose:!1,showUrl:!1,noOpen:!1,confirmed:!1,allowUnmanagedOnce:!1,discloseSource:!1,shouldTrigger:[],shouldNotTrigger:[],paraphrase:[],grantJson:[],findingCode:[],acceptCapability:[],approvalRequestId:[]},n=[];for(let r=0;r<e.length;r+=1){let i=e[r];if(!i)continue;if(i==="--"){n.push(...e.slice(r+1));break}if(i==="-h"){t.help=!0;continue}if(!i.startsWith("--")){n.push(i);continue}let o=i.slice(2);if(o!=="install"&&!EB.has(o)&&!$B.has(o)&&!DB.has(o)&&!rP.has(o))return{flags:t,positionals:n,error:`Unknown flag --${o}.`};if(EB.has(o)){let a=oP(o);o==="confirm"||o==="yes"?t.confirmed=!0:t[a]=!0;continue}let s=e[r+1];if(!s||s.startsWith("--")){if(o==="install"){t.install="";continue}return{flags:t,positionals:n,error:`Flag --${o} requires a value.`}}if($B.has(o)){let a=vre(e,r);if(!a.value)return{flags:t,positionals:n,error:`Flag --${o} requires a value.`};t[oP(o)]=a.value,r=a.nextIndex;continue}if(DB.has(o)||rP.has(o)){let a=oP(o);if(o==="scope"){let l=Array.isArray(t.scopeValues)?t.scopeValues:[];l.push(s),t.scopeValues=l,t.scope=s}else if(rP.has(o)){let l=Array.isArray(t[a])?t[a]:[];l.push(s),t[a]=l}else t[a]=s;r+=1;continue}return{flags:t,positionals:n,error:`Unknown flag --${o}.`}}return{flags:t,positionals:n}}function vre(e,t){let n=[],r=t;for(let i=t+1;i<e.length;i+=1){let o=e[i];if(!o||o.startsWith("--"))break;n.push(o),r=i}return{value:n.length>0?n.join(" "):null,nextIndex:r}}function oP(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}async function Tu(e,t){let n=kre(t.env,t.platform),[r,i]=await Promise.all([vce(n.configPath,t),ke(n.backendPreferencePath)]),o=dr(k(e.baseUrl)??Re(t.env.SKILLS_LAYER_BASE_URL)??Re(i?.preferredBaseUrl)??Re(r?.baseUrl)??YP);try{tl(o)}catch{throw new Z(400,"Invalid backend URL. Use HTTPS, or HTTP for loopback development only.",{reasonCode:"invalid_base_url",baseUrl:o.replace(/(\/\/)[^/]*@/u,"$1<redacted>@"),nextAction:"backend",nextStep:"Use an HTTPS backend URL without credentials, query parameters, or fragments."})}let s=k(e.apiKey)??Re(t.env.SKILLS_LAYER_API_KEY),a=Re(r?.apiKey),l=Re(r?.baseUrl),c=!l||Yu(l,o),u=s??(c?a:void 0),d=!s&&a&&l&&!c?`Your saved login belongs to ${dr(l)}, but the selected backend is ${o}. Run \`skills-layer backend --base-url ${dr(l)}\` to use that login, or run \`skills-layer login\` for ${o}.`:void 0;return{...t,paths:n,config:r,baseUrl:o,apiKey:u,authBlockedMessage:d}}function kre(e,t){let n=t==="win32"?st:Lt,r=hN(e,t);return{stateDir:r,configPath:n.join(r,"config.json"),backendPreferencePath:n.join(r,"backend-preference.json"),installTargetPreferencePath:n.join(r,"install-target-preference.json"),installsPath:n.join(r,"installs.json"),importsPath:n.join(r,"imports.json"),mcpConfigPath:n.join(r,"mcp.json"),mcpPreferencePath:n.join(r,"mcp-preference.json"),pendingRevocationsPath:n.join(r,"pending-revocations.json"),bundlesDir:n.join(r,"bundles"),incidentsDir:n.join(r,"incidents")}}async function wre(e,t,n){if(e[0]!=="list")return E(`Unknown agents command "${e[0]??""}".`,t.json);let r=et(n.env,n.platform,n.cwd).map(i=>({id:i.id,displayName:i.displayName,capabilities:i.capabilities,projectSkillsPath:i.targets.projectSkillsPath,globalSkillsPath:i.targets.globalSkillsPath}));return R({status:"ok",results:r},`Found ${r.length} supported agent targets.`,t.json,n)}async function bre(e,t,n){let r=e[0],i=k(t.baseUrl);if(!r&&i||r==="cloud"||r==="local"){let l=dr(i??(r==="local"?lre:YP)),c=jie(l,t);if(c)return c;if(!t.skipProbe){let m=await zA(l,n.fetchFn);if(m!=="ok")return x({status:"error",reasonCode:m,unchanged:!0,nextStep:"Check the backend address, or use --skip-probe for offline configuration."},m==="backend_unreachable"?"Backend could not be reached.":"The address did not identify a Skills Layer API.",t.json,m)}let u=Dt(l),d=n.config?.baseUrl??null,p=!n.config?.baseUrl||Yu(n.config.baseUrl,l);return await Ve(n.paths.backendPreferencePath,{version:JP,preferredBaseUrl:l,savedAt:n.now()}),R({status:"updated",selectedBackend:u,selectedBaseUrl:l,savedLoginBaseUrl:d,loginMatchesSelectedBackend:p,loggedIn:!!n.apiKey&&p,...p?{}:{warning:`Saved login belongs to ${d}; selected backend is ${l}.`}},p?`Backend set to ${u}.`:`Backend set to ${u}. Saved login is for ${d}.`,t.json,n)}if(r&&r!=="status")return E(`Unknown backend command "${r}".`,t.json);let o=Dt(n.baseUrl),s=!n.config?.baseUrl||Yu(n.config.baseUrl,n.baseUrl),a=!!n.apiKey&&s;return R({status:"ok",selectedBackend:o,selectedBaseUrl:n.baseUrl,savedLoginBaseUrl:n.config?.baseUrl??null,loginMatchesSelectedBackend:s,loggedIn:a,email:a?n.config?.email??null:null,role:a?n.config?.role??null:null,identitySource:"cached_at_login"},`Backend: ${n.baseUrl}. Account details are cached from login; run skills-layer whoami to check current access.`,t.json,n)}var $h=[{value:"google",label:"Google",description:"Open browser sign-in and return here"},{value:"github",label:"GitHub",description:"Open browser sign-in and return here"},{value:"gitlab",label:"GitLab",description:"Open browser sign-in and return here"},{value:"microsoft",label:"Microsoft",description:"Open browser sign-in and return here"}];async function Dh(e,t){if(t.nonInteractive||!t.stdoutIsTty)return e.filter(n=>n.value!=="microsoft");try{let n=await D(t,"/api/v1/identity/social/providers");return Array.isArray(n.providers)?e.filter(r=>!Ko(r.value)||n.providers.includes(r.value)):e.filter(r=>r.value!=="microsoft")}catch{return e.filter(n=>n.value!=="microsoft")}}var _re=[...$h,{value:"email",label:"Continue with email",description:"Sign in or create an account with an emailed one-time code"},{value:"api_key",label:"API key (advanced)",description:"Paste an existing Skills Layer login key"}],Sre=[{value:"email",label:"Email",description:"Use an emailed verification code and API key"},...$h],xre=[{value:"email",label:"Email code",description:"Verify account ownership with an emailed one-time code"}];async function GM(e,t){let n=k(e.method);if(!n)if(e.json)n="email";else try{n=await t.promptSelect("Choose how to register:",await Dh(Sre,t))}catch{return E("register requires --method when interactive selection is unavailable. Try `skills-layer register --method email --email you@example.com`, `skills-layer register --method google`, `skills-layer register --method github` or `skills-layer register --method gitlab`.",!1)}let r=Mn("register","method",n,Cie,e,"invalid_method");if(r)return r;if(n==="email"){let a=k(e.email);if(!a&&!e.json)try{a=await t.promptText("Enter your email address: ")}catch{return E("register --method email requires --email when interactive prompts are unavailable.",!1)}a=O(a,"register requires --email.");let l=await D(t,"/api/v1/register",{method:"POST",headers:V(),body:JSON.stringify({method:n,email:a})});if(e.json){let u=l.status==="already_registered"?WP(l):Nt({...l,nextCommand:`skills-layer auth verify --email ${a} --code <code> --json`,nextAction:"auth.verify"}),d=l.status==="already_registered"?`${a} is already registered.`:`Registration started for ${a}.`;return R(u,d,e.json,t)}if(l.status==="already_registered")return R(WP(l),`${a} is already registered. Run \`skills-layer login\` to sign in, or \`skills-layer auth recover\` if you need account recovery.`,!1,t);let c;try{c=await t.promptText(`Enter the verification code sent to ${a} (check spam/junk folder if missing): `)}catch{return R(Nt(l),`Registration started for ${a}. Check your email (including spam/junk folder) for the verification code, then run \`skills-layer auth verify --email ${a} --code <code>\`.`,!1,t)}return await vA(a,c,e,t,`Verified ${a}.`)}if(!Ko(n))return E("register --method must be email, google, github, or gitlab.",e.json);let i=Ho(),o=await wA({flags:e,backend:t,provider:n,mode:"register",credentialHandoff:i});if(fe(o))return o;let s=await D(t,"/api/v1/identity/social/start",{method:"POST",headers:V(),body:JSON.stringify({provider:n,mode:"register",createAccount:e.createAccount===!0,handoffCodeHash:i.authorizationCodeHash,handoffCodeChallenge:i.codeChallenge})});return await jh(n,s,i,e,t,"register",void 0,o)}async function HM(e,t){if(e.withMcp&&e.noMcp)return E("login cannot combine --with-mcp and --no-mcp.",e.json);let n=k(e.apiKey);if(n){let l=await Vu(t,n,{notifyLogin:!0}),c=await wh(e,{...t,config:l,apiKey:n});if(fe(c))return c;let u=await xP(e,{...t,config:l,apiKey:n});if(fe(u))return u;let d=u.data?.status==="mcp_not_configured";return R(Nt(CP({status:d?"partial_success":"verified",...l,loggedIn:!0,...c.data?{workingMode:c.data}:{},...u.data?{mcp:u.data}:{},...d?{warnings:[u.data]}:{}},u.data)),[`Logged in as ${l.email}.`,c.message??"",u.message??""].filter(Boolean).join(" "),e.json,t)}let r=k(e.method);if(!r&&!e.json)try{let l=await t.promptSelect("Choose how to sign in:",await Dh(_re,t));r=l==="api_key"?void 0:l}catch{return E("login requires --api-key or --method <email|google|github|gitlab> when interactive selection is unavailable.",!1)}let i=Mn("login","method",r,xie,e,"invalid_method");if(i)return i;if(r){if(r==="email"){let d=k(e.email);!d&&!e.json&&(d=(await t.promptText("Enter your email address: ")).trim()),d=O(d,"login --method email requires --email.");let p=await D(t,"/api/v1/register",{method:"POST",headers:V(),body:JSON.stringify({email:d})}),m=Nt({...p,nextAction:"auth.verify",nextCommand:`skills-layer auth verify --email ${d} --code <code> --json`});if(f(p,"emailDelivery")==="failed")return x({...m,status:"email_delivery_failed",reasonCode:"email_delivery_failed",nextAction:"login.retry",nextStep:"Retry email sign-in after the delivery service recovers, or choose a connected social provider."},"The email code could not be delivered. Retry later or choose another sign-in method.",e.json,"email_delivery_failed");if(f(p,"status")==="already_registered")return E("The backend did not prepare an email sign-in code. Retry later or choose another sign-in method.",e.json);if(e.json)return R(m,`Email sign-in started for ${d}.`,!0,t);let h="";try{h=(await t.promptText("Enter the email code if you received one, or press Enter to stop: ")).trim()}catch{return R(m,`Email sign-in started for ${d}. Check your email (including spam/junk folder), then run \`skills-layer auth verify --email ${d} --code <code>\` when the code arrives.`,!1,t)}return h?await vA(d,h,e,t,`Verified ${d}.`):R(m,`Email sign-in started for ${d}. No code was entered, so nothing else was changed. Run \`skills-layer auth verify --email ${d} --code <code>\` when ready.`,!1,t)}if(!Ko(r))return E("login --method must be email, google, github, or gitlab.",e.json);let l=Ho(),c=await wA({flags:e,backend:t,provider:r,mode:"login",credentialHandoff:l});if(fe(c))return c;let u=await D(t,"/api/v1/identity/social/start",{method:"POST",headers:V(),body:JSON.stringify({provider:r,mode:"login",handoffCodeHash:l.authorizationCodeHash,handoffCodeChallenge:l.codeChallenge})});return await jh(r,u,l,e,t,"login",void 0,c)}if(!e.json)try{n=(await t.promptSecret("Enter your Skills Layer API key: ")).trim()}catch{return E("login requires an API key.",e.json)}if(!n)return E("login requires --api-key or --method <email|google|github|gitlab>.",e.json);let o=await Vu(t,n,{notifyLogin:!0}),s=await wh(e,{...t,config:o,apiKey:n});if(fe(s))return s;let a=await xP(e,{...t,config:o,apiKey:n});return fe(a)?a:R(Nt(CP({status:"verified",...o,...s.data?{workingMode:s.data}:{},...a.data?{mcp:a.data}:{}},a.data)),[`Logged in as ${o.email}.`,s.message??"",a.message??""].filter(Boolean).join(" "),e.json,t)}async function KM(e,t){let n=!1,r=!1,i=await ke(t.paths.mcpConfigPath),o=i?f(i,"keyId"):void 0,s=Re(t.config?.apiKey)??t.apiKey,a=dr(Re(t.config?.baseUrl)??t.baseUrl);if(s){try{await D({...t,baseUrl:a,apiKey:s},"/api/v1/me/working-mode",{method:"DELETE",headers:re(s)}),n=!0}catch{n=!1}try{await D({...t,baseUrl:a,apiKey:s},"/api/v1/me/session/revoke",{method:"POST",headers:V(s),body:JSON.stringify({includeCurrent:!0,revokeAllMcp:!0,humanKeyIds:[],mcpKeyIds:o?[o]:[]})}),r=!0}catch{r=!1}}let l=F2(t.config,{env:t.env,platform:t.platform,store:t.credentialStore}),c=await Promise.allSettled([l,Cre(t),l.then(()=>We(t.paths.configPath,{force:!0}))]),u=c.every(m=>m.status==="fulfilled");if(!u)return x({status:"logout_incomplete",reasonCode:"local_cleanup_incomplete",serverCredentialsRevoked:r,localCleanupComplete:!1,nextAction:"logout",nextStep:"Unlock the OS credential store and retry logout. Local references were retained for cleanup."},"Server revocation was attempted, but local cleanup is incomplete.",e.json,"local_cleanup_incomplete");let d=!!s&&!r,p=d&&(t.config?.userId&&(t.config.sessionCredentialId||o))?await xA(t,{baseUrl:a,userId:t.config.userId,humanKeyIds:t.config.sessionCredentialId?[t.config.sessionCredentialId]:[],mcpKeyIds:o?[o]:[],revokeAllMcp:!0,revokeAdminMcp:!0,createdAt:t.now()}):!1;return R({status:s?"logged_out":"not_logged_in",serverWorkingModeCleared:n,serverCredentialsRevoked:r,revocationPending:d,...d?{pendingRecorded:p}:{},localCleanupComplete:u,warnings:u?[]:["Some local cleanup failed. Retry logout to finish clearing local state."],mcpAuthCleared:c[1].status==="fulfilled"},d?p?"Logged out locally. Server revocation is pending and will retry after the same account authenticates again.":"Logged out locally, but server revocation could not be recorded. Reconnect promptly; credentials remain bounded by expiry.":r?"Logged out. Human and MCP credentials were revoked.":"No saved login; local state cleared.",e.json,t)}async function Cre(e){let t=await ke(e.paths.mcpConfigPath);if(!t){await SP(null,e),await We(e.paths.mcpPreferencePath,{force:!0});return}let n=t?f(t,"baseUrl")??e.baseUrl:e.baseUrl,r=t?f(t,"clientId")??"codex":"codex",i=es({baseUrl:n,mcpUrl:t?f(t,"mcpUrl")??`${n}/mcp`:`${n}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:r,environment:t?f(t,"environment")??Dt(n):Dt(n),now:e.now(),env:e.env,platform:e.platform,cwd:e.cwd,stateDir:e.paths.stateDir,mcpConfigPath:e.paths.mcpConfigPath,nodePath:process.execPath}),o=t&&Array.isArray(t.clientIds)?t.clientIds.filter(a=>typeof a=="string"):t?[r]:[];if((await Promise.allSettled([SP(t,e),...i.targets.filter(a=>o.includes(a.agentId)).map(a=>a.disconnect?.()),ay(i.bridgePath),ly(i.brokerPath,i.brokerSocketPath,i.brokerLockPath),We(e.paths.mcpPreferencePath,{force:!0})])).some(a=>a.status==="rejected"))throw new Error("MCP local cleanup is incomplete; retry logout.");await We(e.paths.mcpConfigPath,{force:!0})}async function Ire(e,t,n){let r=e[0]??"show";if(r==="show")return await me("/api/v1/profile",t,n,"Editable profile loaded.",{authenticated:!0});if(r==="update"){let i=await Pre(t,n);if(fe(i))return i;let o=await D(n,"/api/v1/profile",{method:"PATCH",headers:V(n.apiKey),body:JSON.stringify(i)});return R(o,"Profile updated.",t.json,n)}return E(`Unknown profile command "${r}".`,t.json)}async function Pre(e,t){let n=Ft(e,["displayName","bio","company"]);for(let r of["displayName","bio","company"])if(e[`clear${r[0].toUpperCase()}${r.slice(1)}`]){let i=r.replace(/[A-Z]/gu,o=>`-${o.toLowerCase()}`);if(n[r]!==void 0)return x({reasonCode:"conflicting_flags",unchanged:!0},`Choose either --${i} or --clear-${i}.`,e.json,"conflicting_flags");n[r]=null}if(Object.keys(n).length>0)return n;if(e.json)return E("profile update requires at least one of --display-name, --bio, or --company.",!0);try{let r=await t.promptText("Display name (leave blank to keep unchanged): "),i=await t.promptText("Bio (leave blank to keep unchanged): "),o=await t.promptText("Company (leave blank to keep unchanged): "),s=ie({displayName:r||void 0,bio:i||void 0,company:o||void 0});return Object.keys(s).length===0?E("No profile changes entered.",!1):s}catch{return E("profile update requires at least one of --display-name, --bio, or --company.",!1)}}async function Are(e,t,n){let r=e[0];if(r==="register")return await GM({...t,method:"email"},n);if(r==="verify"){let i=O(t.email,"auth verify requires --email."),o=O(t.code,"auth verify requires --code.");return await vA(i,o,t,n,`Verified ${i}.`)}return r==="recover"?await $re(e.slice(1),t,n):r==="connect"?await Dre(t,n):r==="mfa"?await Tre(e.slice(1),t,n):r==="login"?await HM(t,n):r==="logout"?await KM(t,n):r==="status"?Rre(t,n):r==="repair"?await Ere(t,n):E(`Unknown auth command "${r??""}".`,t.json)}function Rre(e,t){let n=t.config?.baseUrl?dr(t.config.baseUrl):null,r=!!(t.apiKey&&n&&Yu(n,t.baseUrl));return R({status:"auth_status",selectedBackend:Dt(t.baseUrl),selectedBaseUrl:t.baseUrl,loggedIn:r,requiresLogin:!r,...t.config?.email?{savedLogin:{baseUrl:n,email:t.config.email,role:t.config.role??null,roles:t.config.roles??[],savedAt:t.config.savedAt??null,...t.config.credentialStorage?{credentialStorage:t.config.credentialStorage}:{},matchesSelectedBackend:r}}:{}},r&&t.config?.email?`Logged in as ${t.config.email}.`:t.config?.baseUrl?`Saved login targets ${n}; selected backend is ${t.baseUrl}. Run \`skills-layer auth repair\` or \`skills-layer login\`.`:"Not logged in. Run `skills-layer login`.",e.json,t)}async function Ere(e,t){if(!t.config?.baseUrl||!t.config.apiKey||!t.config.email||!t.config.role||!t.config.savedAt)return x({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login` to create a saved session, then use `skills-layer auth repair` only if backend/session metadata drifts."},"No saved Skills Layer login was found to repair. Run `skills-layer login`.",e.json,"login_required");let n=dr(t.config.baseUrl);return await Ve(t.paths.backendPreferencePath,{version:JP,preferredBaseUrl:n,savedAt:t.now()}),await CA(t.paths.configPath,{...t.config,baseUrl:n,savedAt:t.now()},t),R({status:"auth_repaired",baseUrl:n,loggedIn:!0,email:t.config.email,role:t.config.role,credentialStorage:t.config.credentialStorage??"local_file_locked"},`Auth repaired for ${t.config.email}. Backend preference now matches ${n}.`,e.json,t)}async function $re(e,t,n){let r=e[0]??k(t.method);if(!r&&!t.json)try{r=await n.promptSelect("Choose how to recover access:",xre)}catch{return E("auth recover requires --method email when interactive selection is unavailable.",!1)}if(r??="email",Ko(r))return x({status:"unsupported_auth_journey",reasonCode:"unsupported_auth_journey",provider:r,nextAction:"account.connect",nextStep:`Run \`skills-layer auth connect --provider ${r}\` after signing in.`},`Social identities are connected, not used for account recovery. Sign in, then run \`skills-layer auth connect --provider ${r}\`.`,t.json,"unsupported_auth_journey");if(r!=="complete"&&r!=="email")return E("auth recover --method must be email.",t.json);let i=k(t.email);if(r==="complete"){if(!i&&!t.json)try{i=await n.promptText("Enter your email address: ")}catch{return E("auth recover complete requires --email when interactive prompts are unavailable.",!1)}i=O(i,"auth recover complete requires --email.");let l=k(t.code);if(!l&&!t.json)try{l=await n.promptText("Enter the recovery code: ")}catch{return E("auth recover complete requires --code when interactive prompts are unavailable.",!1)}return l=O(l,"auth recover complete requires --code."),await OB(i,l,t,n)}if(!i&&!t.json)try{i=await n.promptText("Enter your email address: ")}catch{return E("auth recover --method email requires --email when interactive prompts are unavailable.",!1)}i=O(i,"auth recover --method email requires --email.");let o=await D(n,"/api/v1/identity/recover/start",{method:"POST",headers:V(),body:JSON.stringify({email:i,method:r})}),s=WP(o);if(t.json)return R({...s,nextCommand:`skills-layer auth recover complete --email ${i} --code <code>`,nextAction:"auth.recover.complete",nextStep:"Check your email and complete recovery with the emailed code."},"Recovery started.",!0,n);let a="";try{a=(await n.promptText("Enter the recovery code if you received one, or press Enter to stop: ")).trim()}catch{return R(s,`If this email can continue, instructions have been sent. Check your inbox and spam folder. When you have a code, run \`skills-layer auth recover complete --email ${i} --code <code>\`.`,!1,n)}return a?await OB(i,a,t,n):R(s,`If this email can continue, instructions have been sent. When you have a code, run \`skills-layer auth recover complete --email ${i} --code <code>\`.`,!1,n)}async function Dre(e,t){let n=k(e.provider);if(!n&&!e.json)try{n=await t.promptSelect("Choose an identity to connect:",await Dh($h,t))}catch{return E("auth connect requires --provider when interactive selection is unavailable.",!1)}if(n=O(n,"auth connect requires --provider."),!Ko(n))return E("auth connect --provider must be google, github, or gitlab.",e.json);if(!t.apiKey||t.authBlockedMessage)return x({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login`, then retry the connection."},"Sign in before connecting another login method.",e.json,"login_required");if((await D(t,"/api/v1/identity/mfa/status",{headers:V(t.apiKey,t.authBlockedMessage)})).enabled!==!0){let l=await WM(e,t);return fe(l)?l:R(l,"MFA setup is required before connecting a sign-in method. Complete setup in the browser, then run this command again.",e.json,t)}let i=k(e.mfaCode);if(!i&&!e.json)try{i=await t.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return E("auth connect requires MFA verification. Retry with an interactive terminal.",!1)}if(!i||!/^\d{6}$/u.test(i))return E("auth connect requires a 6-digit --mfa-code when interactive prompts are unavailable.",e.json);let o=await D(t,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({purpose:"identity.connect",code:i})}),s=O(f(o,"stepUpGrant"),"MFA verification did not return a step-up grant."),a=await D(t,"/api/v1/identity/connect/start",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({provider:n,stepUpGrant:s})});return await jh(n,a,void 0,e,t,"connect","/api/v1/identity/connect/status")}async function Tre(e,t,n){let r=e[0]??"status";if(!n.apiKey||n.authBlockedMessage)return x({status:"login_required",reasonCode:"login_required",nextAction:"login",nextStep:"Run `skills-layer login`, then retry the MFA command."},"Sign in before managing MFA.",t.json,"login_required");if(r==="status"){let i=await D(n,"/api/v1/identity/mfa/status",{headers:re(n.apiKey,n.authBlockedMessage)}),o=i.enabled===!1?{...i,nextAction:"account.mfa.setup",nextStep:"Protect this account by running `skills-layer auth mfa setup`."}:i;return R(o,"MFA status loaded.",t.json,n)}if(r==="setup"){let i=await WM(t,n);return fe(i)?i:R(i,"MFA setup started. Complete it in your browser; recovery codes are shown there once.",t.json,n)}if(r==="verify"){let i=O(k(t.purpose),"auth mfa verify requires --purpose."),o=k(t.mfaCode)??k(t.code);if(!o&&!t.json)try{o=await n.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return E("auth mfa verify requires an interactive code or --mfa-code.",!1)}if(!o||!/^\d{6}$/u.test(o))return E("auth mfa verify requires a 6-digit --mfa-code.",t.json);let s=await D(n,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({purpose:i,code:o})});return R(s,`MFA verified for ${i}.`,t.json,n)}if(r==="recovery-codes"){if(k(t.mfaCode)||k(t.code))return E("Do not pass an authenticator code on the command line. Recovery-code regeneration now requires protected browser verification.",t.json);if(t.json)return R({status:"human_action_required",reasonCode:"human_handoff_required",nextAction:"mfa.recovery_codes.browser",nextStep:"Run `skills-layer auth mfa recovery-codes` in an interactive human terminal to open the protected browser flow.",delivery:"browser_only"},"Recovery-code regeneration requires a protected human browser session.",!0,n);let i=await D(n,"/api/v1/identity/mfa/recovery-codes/regenerate",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({})}),o=O(f(i,"recoveryCodesUrl"),"Recovery-code regeneration did not return a secure browser handoff."),s=O(f(i,"operationId"),"Recovery-code regeneration did not return a secure operation identifier.");!t.noOpen&&await n.openUrl(o)||n.emitInfo(`Open this secure recovery-code link in your browser:
|
|
2102
|
+
${o}`),n.emitInfo("Waiting for recovery-code verification to finish in your browser...");let l=await Yae(s,n);return fe(l)?l:R({status:"regenerated",action:"mfa.recovery_codes.completed",completedAt:f(l,"completedAt"),delivery:"browser_only",nextAction:"store_recovery_codes",nextStep:"Confirm the replacement recovery codes are saved in your password manager or secure offline location."},"Recovery codes were replaced in your browser.",!1,n)}if(r==="disable"){let i="identity.mfa.disable",o=k(t.mfaCode)??k(t.code);if(!o&&!t.json)try{o=await n.promptSecret("Enter the 6-digit code from your authenticator app: ")}catch{return E(`auth mfa ${r} requires an interactive code or --mfa-code.`,!1)}if(!o||!/^\d{6}$/u.test(o))return E(`auth mfa ${r} requires a 6-digit --mfa-code.`,t.json);let s=await D(n,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({purpose:i,code:o})}),a=O(f(s,"stepUpGrant"),"MFA verification did not return a step-up grant."),l=await D(n,"/api/v1/identity/mfa/disable",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({stepUpGrant:a})});return R(l,"MFA disabled.",t.json,n)}return E(`Unknown auth mfa command "${r}".`,t.json)}async function WM(e,t){let n=await D(t,"/api/v1/identity/mfa/setup/start",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage)}),r=O(f(n,"setupUrl"),"MFA setup did not return a browser handoff."),i=e.noOpen||e.json?!1:await t.openUrl(r);return!e.json&&!i&&t.emitInfo(`Open this secure MFA setup link in your browser:
|
|
2103
|
+
${r}`),{...n,status:"human_action_required",nextAction:"mfa.setup.browser",nextStep:"Complete authenticator setup in the browser, save the one-time recovery codes, then return to the CLI."}}async function OB(e,t,n,r){let i=Ho(),o=async(l,c)=>D(r,"/api/v1/identity/recover/complete",{method:"POST",headers:V(),body:JSON.stringify({email:e,code:t,...l?{mfaCode:l}:{},...c?{recoveryCode:c}:{},handoffCodeHash:i.authorizationCodeHash,handoffCodeChallenge:i.codeChallenge})}),s;try{s=await o(k(n.mfaCode),k(n.recoveryCode))}catch(l){if(!(l instanceof Z)||l.status!==428)throw l;if(n.json)return x({status:"human_action_required",reasonCode:"recovery_mfa_required",nextAction:"account.recover.verify_mfa",nextStep:"Retry with --mfa-code <6-digits> or --recovery-code <one-time-code>."},"Recovery needs your second factor.",!0,"recovery_mfa_required");let c=await r.promptSelect("Choose your recovery second factor:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one saved one-time recovery code"}]),u=(await r.promptSecret(c==="authenticator"?"Enter the 6-digit authenticator code: ":"Enter one unused recovery code: ")).trim();s=c==="authenticator"?await o(u,void 0):await o(void 0,u)}if(f(s,"status")!=="recovered")return E("Email recovery did not prepare a secure credential handoff. Start recovery again.",n.json);let a=await D(r,"/api/v1/identity/credential-handoff/exchange",{method:"POST",headers:V(),body:JSON.stringify({authorizationCode:i.authorizationCode,codeVerifier:i.codeVerifier})});if(f(a,"status")!=="exchanged"||!f(a,"email")||!f(a,"role")||!f(a,"apiKey"))return E("Email recovery credential handoff failed closed. Start recovery again.",n.json);if(n.json){let l=f(a,"apiKey");return l?(await Vu(r,l,{expectedEmail:e,knownEmail:f(a,"email")??e,knownRole:f(a,"role")??"user",knownRoles:Un(a,"roles"),knownUserId:f(a,"userId"),knownSessionCredentialId:f(a,"id")}),R(Nt({...a,holdUntil:s.holdUntil,blockedActions:s.blockedActions,loggedIn:!0}),`Recovery complete. Sensitive actions are held until ${String(s.holdUntil)}.`,!0,r)):R(Nt({...a,holdUntil:s.holdUntil,blockedActions:s.blockedActions,email:e,loggedIn:!1}),`Recovery complete. Sensitive actions are held until ${String(s.holdUntil)}.`,!0,r)}return await kA(e,{...a,holdUntil:s.holdUntil,blockedActions:s.blockedActions},n,r,`Recovered access for ${e}. Sensitive actions are held until ${String(s.holdUntil)}.`)}async function Ore(e,t,n){let r=e[0],i=1;if(r==="providers")return await me("/api/v1/identity/social/providers",t,n,"Identity providers loaded.");if(r==="start"){let o=k(t.provider);if(!o&&!t.json)try{o=await n.promptSelect("Choose identity provider:",await Dh($h,n))}catch{return E("identity start requires --provider when interactive selection is unavailable.",!1)}if(o=O(o,"identity start requires --provider."),!Ko(o))return E("identity start --provider must be google, github, or gitlab.",t.json);let s=k(t.mode)??"login";if(s!=="login"&&s!=="register")return x({status:"dedicated_auth_journey_required",reasonCode:"dedicated_auth_journey_required",nextStep:s==="recovery"?"Run `skills-layer auth recover`.":"Run `skills-layer auth connect --provider <provider>`."},"Use the dedicated recover or connect command for this account journey.",t.json,"dedicated_auth_journey_required");let a=Ho(),l=await wA({flags:t,backend:n,provider:o,mode:s,credentialHandoff:a});if(fe(l))return l;let c=await D(n,"/api/v1/identity/social/start",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({provider:o,mode:s,handoffCodeHash:a.authorizationCodeHash,handoffCodeChallenge:a.codeChallenge})});return await jh(o,c,a,t,n,s,void 0,l)}if(r==="status"){let o=k(t.state)??e[i];return o?await me(`/api/v1/identity/social/status/${encodeURIComponent(o)}`,t,n,"Social auth status loaded."):E("identity status requires --state.",t.json)}if(r==="continue"){let o=k(t.reference)??e[i];return await Lre(o,t,n)}if(r==="complete"){let o=O(t.provider,"identity complete requires --provider."),s=O(t.state,"identity complete requires --state."),a=O(t.code,"identity complete requires --code."),l=await D(n,"/api/v1/identity/social/complete",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({provider:o,state:s,code:a})});return R(Nt(l),"Social auth complete.",t.json,n)}if(r==="list")return await me("/api/v1/me/linked-identities",t,n,"Linked identities loaded.",{authenticated:!0});if(r==="unlink"){let o=O(t.provider??e[i],"identity unlink requires a provider."),s=l=>D(n,`/api/v1/me/linked-identities/${encodeURIComponent(o)}`,{method:"DELETE",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({mfaCode:l})}),a;try{a=await s(k(t.mfaCode))}catch(l){if(!(l instanceof Z)||l.details?.reasonCode!=="mfa_step_up_required"||t.json||n.nonInteractive||k(t.mfaCode))throw l;a=await s((await n.promptSecret("Enter a fresh authenticator code to unlink this identity: ")).trim())}return R(a,"Identity unlinked.",t.json,n)}return E(`Unknown identity command "${r??""}".`,t.json)}async function Lre(e,t,n){let r=O(e,"identity continue requires --reference <reference>.");if(!/^social_[A-Za-z0-9_-]{20,80}$/u.test(r)||!n.credentialStore)return No(t,n);let i=`skills-layer-social-continuation:${r}`,o;try{o=await n.credentialStore.get(je,i)}catch{o=null}let s=jre(o,r,n.baseUrl);if(!s)return await n.credentialStore.delete(je,i).catch(()=>{}),No(t,n);if(Date.parse(n.now())>=Date.parse(s.expiresAt))return await n.credentialStore.delete(je,i).catch(()=>{}),No(t,n);let a=await D(n,`/api/v1/identity/social/status/${encodeURIComponent(s.state)}`),l=f(a,"status");if(l==="pending")return R({status:"already_processing",reasonCode:"social_auth_pending",reference:r,expiresAt:s.expiresAt,nextAction:"identity.continue",nextStep:`Complete browser sign-in, then rerun \`skills-layer identity continue --reference ${r}\`.`},"Browser sign-in is still pending.",t.json,n);if(l==="mfa_required"){let c=k(t.mfaCode),u=k(t.recoveryCode);if(!c&&!u&&!t.json&&!n.nonInteractive&&n.stdoutIsTty){let p=await n.promptSelect("Complete MFA to finish login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),m=(await n.promptSecret(p==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();p==="recovery_code"?u=m:c=m}if(!c&&!u)return x({status:"human_action_required",reasonCode:"login_mfa_required",methods:["authenticator","recovery_code"],reference:r,nextAction:"identity.continue",nextStep:`Run \`skills-layer identity continue --reference ${r} --mfa-code <6-digits>\` in a human-controlled terminal.`},"MFA is required to finish the social login.",t.json,"login_mfa_required");let d=await D(n,"/api/v1/identity/login/mfa/verify",{method:"POST",headers:V(),body:JSON.stringify({state:s.state,authorizationCode:s.authorizationCode,codeVerifier:s.codeVerifier,...c?{mfaCode:c}:{},...u?{recoveryCode:u}:{}})});if(f(d,"status")!=="verified"||f(d,"credentialHandoff")!=="ready")return E("MFA verification did not authorize the stored login.",t.json)}else if(l!=="verified"&&l!=="recovered")return await n.credentialStore.delete(je,i).catch(()=>{}),x({status:l??"failed",reasonCode:"social_continuation_terminal",unchanged:!0,nextAction:"login",nextStep:"Start a fresh social login."},"The social login cannot be continued.",t.json,"social_continuation_terminal");try{return await kh(Cz(s.provider),{authorizationCode:s.authorizationCode,codeVerifier:s.codeVerifier,authorizationCodeHash:s.authorizationCodeHash,codeChallenge:s.codeChallenge},t,n,s.mode)}finally{await n.credentialStore.delete(je,i).catch(()=>{})}}function jre(e,t,n){if(!e)return null;try{let r=JSON.parse(e),i=f(r,"provider"),o=f(r,"mode"),s=f(r,"state"),a=f(r,"expiresAt"),l=f(r,"authorizationCode"),c=f(r,"codeVerifier"),u=f(r,"authorizationCodeHash"),d=f(r,"codeChallenge"),p=f(r,"integrityDigest"),m=f(r,"createdAt")??"";return r.version!==1||f(r,"reference")!==t||f(r,"baseUrl")!==n||!i||!Ko(i)||o!=="login"&&o!=="register"||!s||!a||!Number.isFinite(Date.parse(a))||!l?.startsWith("social_handoff_")||!c||!u||!d||!p||Ue("sha256").update(l).digest("base64url")!==u||Ue("sha256").update(c).digest("base64url")!==d||bA({version:1,reference:t,baseUrl:n,provider:i,mode:o,authorizationCode:l,codeVerifier:c,authorizationCodeHash:u,codeChallenge:d,createdAt:m,state:s,expiresAt:a})!==p?null:{version:1,reference:t,baseUrl:n,provider:i,mode:o,authorizationCode:l,codeVerifier:c,authorizationCodeHash:u,codeChallenge:d,integrityDigest:p,createdAt:m,state:s,expiresAt:a}}catch{return null}}async function Nre(e,t,n){let r=e[0];if(!r)return E("api-key requires create, list, or revoke.",t.json);if(r==="list"){let i=Fre(t);if(i.failure)return i.failure;let o=await D(n,"/api/v1/me/api-keys",{headers:re(n.apiKey,n.authBlockedMessage)}),s=Bre(ZM(o),i.filters,Date.parse(n.now()));return R({...o,filters:ie({...i.filters}),results:s},"API keys loaded.",t.json,n)}if(r==="create"){let i=k(t.name),o=Pce(Array.isArray(t.scopeValues)&&t.scopeValues.length>1?t.scopeValues:t.scope);if(!i)return E("api-key create requires --name.",t.json);if(o.length===0)return E("api-key create requires at least one --scope.",t.json);let s=o.find(p=>!GB.includes(p));if(s)return Nr("api-key.create","scope",s,GB,t,"invalid_scope");let a=Fie("api-key.create",t.expires,t);if(a)return a;if(t.dryRun){let p=await D(n,"/api/v1/me/api-keys",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({name:i,scopes:o,expiresIn:k(t.expires),dryRun:!0})});return R(p,"API key create dry run passed.",t.json,n)}let l=Ho(),c=await D(n,"/api/v1/me/api-keys",{method:"POST",headers:{"content-type":"application/json",...re(n.apiKey,n.authBlockedMessage)},body:JSON.stringify({name:i,scopes:o,...k(t.expires)?{expiresIn:k(t.expires)}:{},handoffCodeHash:l.authorizationCodeHash,handoffCodeChallenge:l.codeChallenge})});if(f(c,"credentialHandoff")!=="ready")return E("API key creation did not prepare a secure credential handoff.",t.json);let u=await D(n,"/api/v1/credential-handoffs/exchange",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({authorizationCode:l.authorizationCode,codeVerifier:l.codeVerifier})}),d=f(u,"apiKey");return f(u,"status")!=="exchanged"||!d?E("API key credential exchange failed closed; prepare the key again.",t.json):R({...u,secretReturned:!0,secretDelivery:"one_time_client_bound_exchange"},`Automation API key created. Copy this one-time secret now: ${d}
|
|
2104
|
+
Run \`skills-layer api-key list\` to manage keys.`,t.json,n)}if(r==="rotate")return E(`api-key rotate is not part of normal login.
|
|
2105
2105
|
|
|
2106
2106
|
For CLI access:
|
|
2107
2107
|
skills-layer login
|
|
@@ -2115,7 +2115,7 @@ To remove an old key:
|
|
|
2115
2115
|
|
|
2116
2116
|
Run:
|
|
2117
2117
|
skills-layer api-key list
|
|
2118
|
-
skills-layer api-key revoke --key-id <key-id>`,t.json,"missing_required_argument");let o=String(i);if(t.dryRun){let a=await jB(o,n);return a?A(ie({status:"pass",wouldRevoke:!0,keyId:o,keyPrefix:f(a,"keyPrefix"),type:f(a,"type"),name:f(a,"name"),scopes:Un(a,"scopes")??[],revokedAt:a.revokedAt??null,nextAction:"api-key.revoke",nextStep:`Run \`skills-layer api-key revoke --key-id ${o} --yes\` to revoke this key.`}),"API key revoke dry run passed.",t.json,n):NB(o,t)}if(!t.confirmed){let a=await jB(o,n);if(!a)return NB(o,t);let l=ie({status:"confirmation_required",reasonCode:"confirmation_required",keyId:o,keyPrefix:f(a,"keyPrefix"),type:f(a,"type"),name:f(a,"name"),nextAction:"api-key.revoke",nextStep:`Re-run with \`skills-layer api-key revoke --key-id ${o} --yes\` after confirming this is the key to revoke.`});if(t.json||!n.stdoutIsTty)return x(l,"API key revoke needs confirmation. Re-run with --yes after checking the key id.",t.json,"confirmation_required");if(await n.promptSelect(`Revoke API key ${o}?`,[{value:"cancel",label:"Cancel",description:"Leave this API key active"},{value:"confirm",label:"Revoke",description:"Permanently revoke this API key"}])!=="confirm")return A({status:"canceled",keyId:o},"API key revoke canceled.",t.json,n)}let s=await D(n,`/api/v1/me/api-keys/${encodeURIComponent(o)}/revoke`,{method:"POST",headers:re(n.apiKey,n.authBlockedMessage)});return A(s,s.status==="already_revoked"?"API key was already revoked.":"API key revoked.",t.json,n)}return R(`Unknown api-key command "${r}".`,t.json)}function Fre(e){let t=k(e.type);if(t&&!HB.includes(t))return{failure:Nr("api-key.list","type",t,HB,e,"invalid_api_key_filter","type")};let n=k(e.status)??"active";if(!KB.includes(n))return{failure:Nr("api-key.list","status",n,KB,e,"invalid_api_key_filter","status")};let r=k(e.sort)??"created-desc";if(!WB.includes(r))return{failure:Nr("api-key.list","sort",r,WB,e,"invalid_api_key_filter","sort")};let i=[["createdAfter","created-after",e.createdAfter],["createdBefore","created-before",e.createdBefore],["expiresAfter","expires-after",e.expiresAfter],["expiresBefore","expires-before",e.expiresBefore]],o={status:n,sort:r};for(let[s,a,l]of i){let c=k(l);if(c){if(Number.isNaN(Date.parse(c)))return{failure:x({status:"error",reasonCode:"invalid_api_key_filter",field:a,value:c,nextAction:"api-key.list",nextStep:`Use --${a} with an ISO date or timestamp.`},`Invalid api-key list --${a} "${c}". Use an ISO date or timestamp.`,e.json,"invalid_api_key_filter")};o[s]=c}}return{filters:ie({...o,...t?{type:t}:{},...k(e.name)?{name:k(e.name)}:{}})}}function ZM(e){return(Be(e,"results")??[]).filter(t=>j(t))}function Bre(e,t,n){let r=t.name?.toLowerCase();return e.filter(i=>!t.type||f(i,"type")===t.type).filter(i=>t.status==="all"||Mre(i,n)===t.status).filter(i=>!r||(f(i,"name")??f(i,"id")??"").toLowerCase().includes(r)).filter(i=>lh(i,"createdAt",t.createdAfter,"after")).filter(i=>lh(i,"createdAt",t.createdBefore,"before")).filter(i=>lh(i,"expiresAt",t.expiresAfter,"after")).filter(i=>lh(i,"expiresAt",t.expiresBefore,"before")).sort((i,o)=>Ure(i,o,t.sort))}function Mre(e,t=Date.now()){if(e.revokedAt!==null&&e.revokedAt!==void 0)return"revoked";let n=f(e,"expiresAt");if(!n)return"active";let r=Date.parse(n);return Number.isNaN(r)||r>t?"active":"expired"}function lh(e,t,n,r){if(!n)return!0;let i=f(e,t);if(!i)return!1;let o=Date.parse(i),s=Date.parse(n);return Number.isNaN(o)||Number.isNaN(s)?!1:r==="after"?o>=s:o<=s}function Ure(e,t,n){if(n==="name-asc"||n==="name-desc")return(n==="name-asc"?1:-1)*(f(e,"name")??f(e,"id")??"").localeCompare(f(t,"name")??f(t,"id")??"");let r=n.endsWith("-asc")?1:-1,i=n.startsWith("expires-")?"expiresAt":n.startsWith("last-used-")?"lastUsedAt":"createdAt";return r*(LB(e,i)-LB(t,i))}function LB(e,t){let n=f(e,t);if(!n)return 0;let r=Date.parse(n);return Number.isNaN(r)?0:r}async function jB(e,t){let n=await D(t,"/api/v1/me/api-keys",{headers:re(t.apiKey,t.authBlockedMessage)});return ZM(n).find(r=>f(r,"id")===e)}function NB(e,t){return x({status:"not_found",reasonCode:"api_key_not_found",keyId:e,nextAction:"api-key.list",nextStep:"Run `skills-layer api-key list` to find an active key id, then retry revoke."},`API key ${e} was not found.`,t.json,"api_key_not_found")}async function zre(e,t,n){let r=e[0]??"status";if(r==="migrate")return await qre(t,n);if(r==="setup"||r==="repair"){let i=await ke(n.paths.mcpConfigPath);if(i&&f(i,"brokerIntegrityProfile")==="extended_v1"){let a=f(i,"clientId")??"codex";return x({status:"unchanged",reasonCode:"mcp_extended_broker_requires_private_cli",nextAction:"mcp.repair.private",nextStep:`Run \`npm run skills-layer -- mcp repair --client ${a}\` from the private checkout.`},"This MCP broker is managed by the private checkout and was left unchanged.",t.json,"mcp_extended_broker_requires_private_cli")}let o=k(t.client);if(o&&t.all)return x({status:"error",reasonCode:"conflicting_mcp_client_selection",client:o,all:!0,nextAction:`mcp.${r}`,nextStep:"Use either --client <agent-id> for one agent or --all for every detected MCP-capable agent."},`mcp ${r} cannot use --client and --all together.`,t.json,"conflicting_mcp_client_selection");if(o&&!aie(o))return sP(o,t);if(o){let a=await ke(n.paths.mcpConfigPath),l=a?f(a,"baseUrl")??n.baseUrl:n.baseUrl,c=await qi({baseUrl:l,mcpUrl:a?f(a,"mcpUrl")??`${l}/mcp`:`${l}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:Ot(o),environment:a?f(a,"environment")??Dt(l):Dt(l),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:a});if(c.target.status==="skills_only"){let u=ch(c);return A(u,`${c.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}}let s=await XP(t,n);return fe(s)?s:A({...s},`MCP configuration written for ${s.clientId}. Open a fresh agent session to load Skills Layer tools, then run \`skills-layer mcp verify --client ${s.clientId}\` if they are not visible.`,t.json,n)}if(r==="status"||r==="verify"){let i=k(t.client),o=i?Ot(i):null;if(i&&!o)return sP(i,t);let s=await Nh(n),a=s.config;if(!a){if(o){let m=await qi({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:o,environment:Dt(n.baseUrl),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:null});if(m.target.status==="skills_only"){let h=ch(m);return A(h,`${m.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}}return A(s.publicState,s.summary,t.json,n)}let l=Array.isArray(a.clientIds)?a.clientIds.filter(m=>typeof m=="string"&&Ot(m)!==null):f(a,"clientId")?[f(a,"clientId")]:[];if(!o&&l.length>1){let m=f(a,"baseUrl")??n.baseUrl,h=[];for(let b of l){let w=await qi({baseUrl:m,mcpUrl:f(a,"mcpUrl")??`${m}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:b,environment:f(a,"environment")??Dt(m),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:a}),_=r==="verify"&&w.configured?await ty({nodePath:process.execPath,bridgePath:w.bridge.path}):w.liveProbe;h.push({...w,liveProbe:_,verified:r==="verify"?_.status==="ok":void 0})}let g=h.every(b=>b.configured),y=r==="verify"?h.every(b=>b.verified===!0):void 0,v={status:r==="verify"&&!y?"mcp_needs_repair":g?"mcp_configured":"mcp_needs_repair",configured:g,verified:y,clientIds:l,clients:h,sharedBroker:{path:f(a,"brokerPath"),socketPath:f(a,"brokerSocketPath")},nextAction:r==="verify"?"mcp.repair":"mcp.verify"};return r==="verify"&&!y?x(v,"One or more configured MCP hosts failed verification.",t.json,"mcp_multi_client_verify_failed"):A(v,`MCP ${r} completed for ${l.length} configured hosts.`,t.json,n)}if(!o&&l.length===0)return x({status:"mcp_needs_repair",reasonCode:"mcp_client_inventory_missing",configured:!1,nextAction:"mcp.repair",nextStep:"Run `skills-layer mcp repair --client <host-id>` or `skills-layer mcp repair --all`."},"The MCP config has no canonical host inventory and was not assigned to Codex implicitly.",t.json,"mcp_client_inventory_missing");let c=o??f(a,"clientId")??(Array.isArray(a.clientIds)&&typeof a.clientIds[0]=="string"?a.clientIds[0]:"codex"),u=f(a,"baseUrl")??n.baseUrl,d=await qi({baseUrl:u,mcpUrl:f(a,"mcpUrl")??`${u}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:c,environment:f(a,"environment")??Dt(u),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:a});if(d.target.status==="skills_only"){let m=ch(d);return A(m,`${d.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}if(d.status==="mcp_extension_verification_required")return r==="verify"?x({...d,nextAction:"mcp.verify.private",nextStep:`Run \`${d.nextCommand}\` from the private checkout.`},`MCP for ${d.clientId} uses a broker managed by the private checkout. Verify it there; the public CLI left it unchanged.`,t.json,"mcp_extended_broker_requires_private_cli"):A({...d,nextAction:"mcp.verify.private",nextStep:`Run \`${d.nextCommand}\` from the private checkout.`},`MCP for ${d.clientId} uses a broker managed by the private checkout. Run \`${d.nextCommand}\` for its authoritative integrity and live check.`,t.json,n);if(r==="verify"&&d.configured){let m=await ty({nodePath:process.execPath,bridgePath:d.bridge.path}),h={...d,verified:m.status==="ok",liveProbe:m};return m.status!=="ok"?x({...h,nextAction:"mcp.verify",nextStep:`Run \`skills-layer mcp verify --client ${d.clientId}\` again after checking local broker and network availability.`},`MCP config exists for ${d.clientId}, but live bridge verification failed: ${m.message}`,t.json,m.reasonCode??void 0):A({...h,nextAction:"agent.restart",nextStep:"Open a fresh agent session or restart the agent so it reloads the verified Skills Layer MCP connection."},`MCP verified for ${d.clientId}. ${m.message} Open a fresh agent session or restart the agent if tools are not visible yet.`,t.json,n)}let p=d.configured?{...d,nextAction:"mcp.verify",nextStep:`Run \`skills-layer mcp verify --client ${d.clientId}\` for a live tools/list check.`}:{...d,nextAction:"mcp.repair",nextStep:`Run \`${d.nextCommand}\`, then verify again.`};return A(p,d.configured?`MCP configuration is present for ${d.clientId}. Open a fresh agent session if tools are not visible, or run \`skills-layer mcp verify --client ${d.clientId}\` for a live check.`:`MCP needs repair for ${d.clientId}. Run \`${d.nextCommand}\`.`,t.json,n)}if(r==="disconnect"||r==="logout"){let i=await ke(n.paths.mcpConfigPath),o=k(t.client),s=o?Ot(o):null;if(o&&!s)return sP(o,t);let a=i&&Array.isArray(i.clientIds)?i.clientIds.filter(_=>typeof _=="string"):i&&f(i,"clientId")?[f(i,"clientId")]:[];if(!s&&a.length===0)return A({status:"mcp_not_configured",configured:!1,clientIds:[]},"MCP is not configured on this machine.",t.json,n);if(!s&&!t.all&&a.length>1)return x({status:"needs_mcp_client_scope",reasonCode:"mcp_client_scope_required",configuredClientIds:a,nextAction:`mcp.${r}`,nextStep:`Run \`skills-layer mcp ${r} --client <host-id>\` or add \`--all\`.`},`MCP ${r} requires --client or --all because multiple hosts are configured.`,t.json,"mcp_client_scope_required");let l=t.all?a:[s??a[0]],c=l[0],u=i?f(i,"baseUrl")??n.baseUrl:n.baseUrl,d=await qi({baseUrl:u,mcpUrl:i?f(i,"mcpUrl")??`${u}/mcp`:`${u}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:c,environment:i?f(i,"environment")??Dt(u):Dt(u),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:i});if(d.target.status==="skills_only"){let _=ch(d);return A(_,`${d.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}let p=es({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:c,environment:Dt(n.baseUrl),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath}),m=p.targets.filter(_=>l.includes(_.agentId)),h=a.filter(_=>!l.includes(_)),g=h.length>0,y=!1,v=i?f(i,"keyId"):void 0;if(!g&&n.apiKey&&(!i||v))try{await D(n,"/api/v1/me/session/revoke",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({includeCurrent:!1,revokeAllMcp:!1,humanKeyIds:[],mcpKeyIds:v?[v]:[]})}),y=!0}catch{y=!1}for(let _ of m)await _.disconnect?.();g&&i?await Ve(n.paths.mcpConfigPath,{...i,clientId:h[0],clientIds:h,savedAt:n.now()}):(await SP(i,n),await ay(p.bridgePath),await ly(p.brokerPath,p.brokerSocketPath,p.brokerLockPath),await We(n.paths.mcpConfigPath,{force:!0}),await We(n.paths.mcpPreferencePath,{force:!0}));let b=!g&&!!(n.apiKey&&i)&&!y,w=b&&(n.config?.userId&&v)?await xA(n,{baseUrl:u,userId:n.config.userId,humanKeyIds:[],mcpKeyIds:[v],revokeAllMcp:!1,revokeAdminMcp:!0,createdAt:n.now()}):!1;return A({status:b?"mcp_revocation_pending":"mcp_disconnected",configured:g,clientId:c,clientIds:l,remainingClientIds:h,serverCredentialsRevoked:y,revocationPending:b,pendingRecorded:w},b?w?"MCP disconnected locally. Server revocation is pending and will retry after this account authenticates again.":"MCP disconnected locally, but server revocation could not be recorded. Reconnect promptly; the machine credential remains bounded by expiry.":"MCP disconnected and its server credential was revoked.",t.json,n)}return R(`Unknown mcp command "${r}". Use setup, status, verify, repair, migrate, or disconnect.`,t.json)}async function qre(e,t){if(e.dryRun&&e.apply)return x({status:"error",reasonCode:"conflicting_mcp_migration_mode",nextAction:"mcp.migrate",nextStep:"Use --dry-run to preview or --apply to remove verified owned entries, but not both."},"Legacy MCP migration cannot use --dry-run and --apply together.",e.json,"conflicting_mcp_migration_mode");let n=k(e.path);if(!n)return x({status:"error",reasonCode:"mcp_legacy_project_path_required",nextAction:"mcp.migrate",nextStep:"Run `skills-layer mcp migrate --path <project-root> --dry-run --json`."},"Legacy MCP migration requires an explicit project root.",e.json,"mcp_legacy_project_path_required");let r=qo(t.cwd,n),i=await xR({projectRoot:r,stateDir:t.paths.stateDir,nodePath:process.execPath}),o=await ke(t.paths.mcpConfigPath),s=o&&Array.isArray(o.clientIds)?o.clientIds.filter(c=>typeof c=="string"&&Ot(c)!==null):o&&f(o,"clientId")&&Ot(f(o,"clientId"))?[f(o,"clientId")]:[],a=[];for(let c of s){let u=Ot(c);if(!u||!o)continue;let d=f(o,"baseUrl")??t.baseUrl;(await qi({baseUrl:d,mcpUrl:f(o,"mcpUrl")??`${d}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:u,environment:f(o,"environment")??Dt(d),now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:o})).configured&&a.push(u)}let l=await CR({discovery:i,verifiedGlobalHostIds:a,apply:!!e.apply});return l.plannedPaths.length===0?A({status:"mcp_legacy_migration_not_required",projectRoot:r,discovery:i,...l,nextAction:"none",nextStep:"No legacy project MCP registration requires migration."},"No legacy project MCP registration requires migration.",e.json,t):A({status:e.apply?"mcp_legacy_migration_applied":"mcp_legacy_migration_dry_run",projectRoot:r,discovery:i,...l,nextAction:e.apply?"mcp.status":"mcp.migrate",nextStep:e.apply?"Run `skills-layer mcp status --json` and restart affected hosts.":"Verify the replacement global registration, then rerun with `--apply`."},e.apply?`Removed ${l.cleanedPaths.length} verified legacy project registration(s).`:`Legacy MCP migration dry-run found ${l.plannedPaths.length} removable registration(s).`,e.json,t)}async function Vre(e,t,n){let r=e[0];if(!r)return x({status:"error",reasonCode:"missing_required_argument",command:"enterprise",argument:"command",nextAction:"enterprise.help",nextStep:"Run `skills-layer enterprise --help` to see available commands."},"enterprise requires a command. Run `skills-layer enterprise --help` to see available commands.",t.json,"missing_required_argument");if(r==="list"){let i;try{i=await D(n,"/api/v1/me/enterprises",{headers:re(n.apiKey,n.authBlockedMessage)})}catch(o){if(o instanceof Z&&o.status===404)return x({status:"not_supported",reasonCode:"enterprise_list_not_supported",nextAction:"operator.deploy",nextStep:"Ask an operator to deploy the current Enterprise API, then retry skills-layer enterprise list."},"This backend does not support Enterprise membership listing.",t.json,"enterprise_list_not_supported");throw o}return cn(i,Kre(i,n),"Enterprise memberships loaded.",t.json,n)}if(r==="checkout"){let i=JB(t.seats,"--seats","seats","enterprise checkout",t,{minimum:2});if(fe(i))return i;let o=O(t.enterpriseName??t.name,"enterprise checkout requires --enterprise-name <name>."),s=O(t.workspaceName??t.workspace,"enterprise checkout requires --workspace-name <name>."),a=tie(),l=await D(n,"/api/v1/enterprise/checkout",{method:"POST",headers:{...V(n.apiKey,n.authBlockedMessage),"idempotency-key":a},body:JSON.stringify({seatCount:i,enterpriseName:o,firstWorkspaceName:s,creationIntentId:a,createNewEnterprise:t.newEnterprise===!0})});return f(l,"status")==="enterprise_exists"?cn(l,Hre(l,n),"Existing Enterprise found.",t.json,n):await _P(l,t,n,"Enterprise checkout prepared.","Opening Enterprise checkout. Complete payment in your browser, then come back here.",{kind:"enterprise",statusPathForCheckoutId:c=>`/api/v1/enterprise/checkout/${encodeURIComponent(c)}`,waitingMessage:"Waiting for Enterprise checkout completion...",completedMessage:"Enterprise checkout completed."})}if(r==="rename"){let i=O(e[1],"enterprise rename requires <enterprise-id>."),o=O(t.enterpriseName??t.name??e[2],"enterprise rename requires --name <enterprise-name>.");return await Li(`/api/v1/enterprises/${encodeURIComponent(i)}`,{name:o},t,n,"Enterprise updated.")}if(r==="primary-admin"){let i=O(e[1],"enterprise primary-admin requires transfer, status, accept, or cancel.");if(i==="transfer"){let a=O(e[2],"enterprise primary-admin transfer requires <enterprise-id>."),l=O(e[3],"enterprise primary-admin transfer requires <target-user-id>.");return await Oe(`/api/v1/enterprises/${encodeURIComponent(a)}/primary-admin-transfers`,{targetUserId:l,outgoingAction:t.leaveEnterprise===!0?"leave_enterprise":"remain_admin"},t,n,"Primary Admin transfer started.")}let o=O(e[2],`enterprise primary-admin ${i} requires <transfer-id>.`),s=`/api/v1/enterprise/primary-admin-transfers/${encodeURIComponent(o)}`;return i==="status"?await me(s,t,n,"Primary Admin transfer loaded.",{authenticated:!0}):i==="accept"?await Oe(`${s}/accept`,{},t,n,"Primary Admin responsibility transferred."):i==="cancel"?await Oe(`${s}/cancel`,{},t,n,"Primary Admin transfer cancelled."):R(`Unknown enterprise primary-admin command "${i}". Use transfer, status, accept, or cancel.`,t.json)}if(r==="seats"){if(e[1]&&e[1]!=="add")return R(`Unknown enterprise seats command "${e[1]}".`,t.json);if(e[1]==="add"){let o=O(e[2],"enterprise seats add requires <enterprise-id>."),s=JB(t.seats,"--seats","seats","enterprise seats add",t,{minimum:1});if(fe(s))return s;let a=await D(n,"/api/v1/enterprise/seats/add",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({enterpriseId:o,additionalSeats:s})});return await _P(a,t,n,"Enterprise seat checkout prepared.",`Opening checkout for ${s} additional Enterprise seat${s===1?"":"s"}. Complete payment in your browser, then come back here.`,{kind:"enterprise_seats",statusPathForCheckoutId:l=>`/api/v1/enterprise/seats/checkout/${encodeURIComponent(l)}`,waitingMessage:"Waiting for Enterprise seat checkout completion...",completedMessage:"Enterprise seats added."})}let i=await D(n,"/api/v1/enterprise/seats",{headers:re(n.apiKey,n.authBlockedMessage)});return cn(i,Qre(i,n),"Enterprise seats loaded.",t.json,n)}if(r==="members"){let i=O(e[1],"enterprise members requires <enterprise-id>."),o=await D(n,`/api/v1/enterprises/${encodeURIComponent(i)}/members`,{headers:re(n.apiKey,n.authBlockedMessage)});return cn(o,Wre(o,n),"Enterprise members loaded.",t.json,n)}if(r==="invites"){let i=O(e[1],"enterprise invites requires <enterprise-id>."),o=await D(n,`/api/v1/enterprises/${encodeURIComponent(i)}/invites`,{headers:re(n.apiKey,n.authBlockedMessage)});return cn(o,Zre(o,n),"Enterprise invites loaded.",t.json,n)}if(r==="invite"){let i=O(e[1],"enterprise invite requires <enterprise-id>."),o=O(t.email??e[2],"enterprise invite requires --email <email>."),s=O(k(t.workspace),"enterprise invite requires --workspace <workspace-id|all|none>.");return await Oe(`/api/v1/enterprises/${encodeURIComponent(i)}/invites`,{email:o,role:k(t.role)??k(t.requestedRole)??"workspace_user",workspaceIds:gie(s)},t,n,"Enterprise invite created.")}if(r==="accept-invite"){let i=O(e[1],"enterprise accept-invite requires <invite-id>."),o=await D(n,`/api/v1/enterprise-invites/${encodeURIComponent(i)}/accept`,{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({})});return await ji(n,o),A(o,"Enterprise invite accepted.",t.json,n)}if(r==="revoke-invite"||r==="resend-invite"){let i=O(e[1],`enterprise ${r} requires <enterprise-id> and <invite-id>.`),o=O(e[2],`enterprise ${r} requires <enterprise-id> and <invite-id>.`),s=r==="revoke-invite"?"revoke":"resend";return await Oe(`/api/v1/enterprises/${encodeURIComponent(i)}/invites/${encodeURIComponent(o)}/${s}`,{},t,n,r==="revoke-invite"?"Enterprise invite revoked.":"Enterprise invite resent.")}if(r==="member"){let i=e[1];if(i!=="role"&&i!=="remove")return R(`Unknown enterprise member command "${i??""}".`,t.json);let o=O(e[2],"enterprise member <role|remove> requires <enterprise-id> and <user-id>."),s=O(e[3],"enterprise member <role|remove> requires <enterprise-id> and <user-id>.");if(i==="role"){let a=O(t.role??t.requestedRole,"enterprise member role requires --role <enterprise_admin|workspace_manager|workspace_user>.");return await Li(`/api/v1/enterprises/${encodeURIComponent(o)}/members/${encodeURIComponent(s)}`,{role:a},t,n,"Enterprise member role updated.")}if(i==="remove")return await Gu(`/api/v1/enterprises/${encodeURIComponent(o)}/members/${encodeURIComponent(s)}`,{method:"DELETE",headers:re(n.apiKey,n.authBlockedMessage)},t,n,"Enterprise member removed.")}if(r==="workspaces"){let i=O(e[1],"enterprise workspaces requires <enterprise-id>."),o=await D(n,`/api/v1/enterprises/${encodeURIComponent(i)}/workspaces`,{headers:re(n.apiKey,n.authBlockedMessage)});return cn(o,Jre(o,n),"Enterprise workspaces loaded.",t.json,n)}if(r==="workspace"){let i=e[1],o=O(e[2],"enterprise workspace <create|rename|archive> requires <enterprise-id>.");if(i==="create"){let a=O(t.workspaceName??t.name??e[3],"enterprise workspace create requires --name <workspace-name>.");return await Oe(`/api/v1/enterprises/${encodeURIComponent(o)}/workspaces`,{name:a},t,n,"Enterprise workspace created.")}let s=O(e[3],"enterprise workspace <rename|archive> requires <workspace-id>.");if(i==="rename"||i==="update"){let a=k(t.workspaceName)??k(t.name)??e[4],l=k(t.telemetryPolicy),c=k(t.guardianPolicy);return c&&c!=="standard"&&c!=="strict"?R("--guardian-policy must be standard or strict.",t.json):i==="rename"&&!a?R("enterprise workspace rename requires --name <workspace-name>.",t.json):!a&&!l&&!c?R("enterprise workspace update requires --name <workspace-name>, --telemetry-policy <best_effort|required> or --guardian-policy <standard|strict>.",t.json):l&&l!=="best_effort"&&l!=="required"?R("--telemetry-policy must be best_effort or required.",t.json):await Li(`/api/v1/workspaces/${encodeURIComponent(s)}`,{enterpriseId:o,...a?{name:a}:{},...l?{telemetryPolicy:l}:{},...c?{guardianPolicy:c}:{}},t,n,"Enterprise workspace updated.")}return i==="archive"?await Oe(`/api/v1/workspaces/${encodeURIComponent(s)}/archive`,{enterpriseId:o},t,n,"Enterprise workspace archived."):R(`Unknown enterprise workspace command "${i??""}".`,t.json)}if(r==="workspace-member"){let i=e[1];if(i!=="list"&&i!=="add"&&i!=="remove")return R(`Unknown enterprise workspace-member command "${i??""}".`,t.json);let o=O(e[2],"enterprise workspace-member <list|add|remove> requires <enterprise-id> <workspace-id>."),s=O(e[3],"enterprise workspace-member <list|add|remove> requires <enterprise-id> <workspace-id>.");if(i==="list"){let l=await D(n,`/api/v1/workspaces/${encodeURIComponent(s)}/members?enterpriseId=${encodeURIComponent(o)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return cn(l,Xre(l,n),"Workspace members loaded.",t.json,n)}let a=O(e[4],`enterprise workspace-member ${i} requires <user-id>.`);if(i==="add")return await Oe(`/api/v1/workspaces/${encodeURIComponent(s)}/members`,{enterpriseId:o,userId:a,role:k(t.role)??k(t.requestedRole)??"workspace_user"},t,n,"Workspace member added.");if(i==="remove")return await Gu(`/api/v1/workspaces/${encodeURIComponent(s)}/members/${encodeURIComponent(a)}`,{method:"DELETE",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({enterpriseId:o})},t,n,"Workspace member removed.")}if(r==="skill")return await Gre(e.slice(1),t,n);if(r==="install-authorize"){let i=O(e[1],"enterprise install-authorize requires <skill-slug>.");return await Oe(`/api/v1/skills/${encodeURIComponent(i)}/install-authorize`,{},t,n,"Install authorization evaluated.")}return R(`Unknown enterprise command "${r}".`,t.json)}async function Gre(e,t,n){let r=e[0];if(r==="quote"||r==="buy"){let i=O(e[1],`enterprise skill ${r} requires <enterprise-id> and <skill-slug>.`),o=O(e[2],`enterprise skill ${r} requires <enterprise-id> and <skill-slug>.`),s=await D(n,`/api/v1/enterprises/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/${r==="quote"?"quote":"checkout"}`,{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({})});return r==="quote"?cn(s,eie(s,i,o,n),"Enterprise skill quote loaded.",t.json,n):await _P(s,t,n,"Enterprise skill checkout prepared.",`Opening Enterprise skill checkout for ${o}. Complete payment in your browser, then come back here.`,{kind:"enterprise_skill",statusPathForCheckoutId:a=>`/api/v1/enterprises/_/skills/_/checkout/${encodeURIComponent(a)}`,waitingMessage:"Waiting for Enterprise skill checkout completion...",completedMessage:"Enterprise skill checkout completed."})}if(r==="entitlements"){let i=O(e[1],"enterprise skill entitlements requires <enterprise-id>."),o=await D(n,`/api/v1/enterprises/${encodeURIComponent(i)}/skill-entitlements`,{headers:re(n.apiKey,n.authBlockedMessage)});return cn(o,Yre(o,n),"Enterprise skill entitlements loaded.",t.json,n)}return R(`Unknown enterprise skill command "${r??""}".`,t.json)}async function _P(e,t,n,r,i,o){let s=f(e,"checkoutUrl"),a=f(e,"checkoutId"),l=f(e,"status");if(!t.json&&!t.noOpen&&(l==="checkout_required"&&s&&(n.emitInfo(i),await n.openUrl(s)||n.emitInfo(`Open this checkout URL manually to continue: ${s}`)),o&&a&&(l==="checkout_required"||l==="finalizing"))){n.emitInfo(o.waitingMessage);let c=o.statusPathForCheckoutId(a),u=await Qae(c,a,n);if(fe(u))return u;let d=f(u,"status");return d==="completion_pending"?cn(u,sie(u,o.kind,n),"Enterprise checkout completion is still pending.",t.json,n):d!=="completed"&&d!=="already_completed"?R(oie(d,o.kind),t.json):(n.emitInfo(o.completedMessage),cn(u,o.kind==="enterprise"?nie(u,n):o.kind==="enterprise_seats"?iie(u,n):rie(u,n),o.completedMessage,t.json,n))}return A(e,r,t.json,n)}function Hre(e,t){let n=Pe(t),r=L(e,"enterprise"),i=L(e,"membership"),o=Array.isArray(e.workspaces)?e.workspaces.filter(j):[],s=[`${n.ok("OK")} Existing Enterprise found. No payment was started.`,"",n.section("Enterprise")];if(s.push(` ${n.label("Name")}: ${r?f(r,"name")??"unknown":"unknown"}`),s.push(` ${n.label("ID")}: ${r?f(r,"enterpriseId")??"unknown":"unknown"}`),s.push(` ${n.label("Your role")}: ${jt(i?f(i,"role")??"unknown":"unknown")}`),o.length>0){s.push("",n.section("Workspaces"));for(let l of o)s.push(` ${n.arrow} ${f(l,"name")??"Unnamed"} (${f(l,"workspaceId")??"unknown"})`)}let a=f(e,"nextStep");return a&&s.push("",n.section("Next"),` ${n.arrow} ${a}`),s.join(`
|
|
2118
|
+
skills-layer api-key revoke --key-id <key-id>`,t.json,"missing_required_argument");let o=String(i);if(t.dryRun){let a=await jB(o,n);return a?R(ie({status:"pass",wouldRevoke:!0,keyId:o,keyPrefix:f(a,"keyPrefix"),type:f(a,"type"),name:f(a,"name"),scopes:Un(a,"scopes")??[],revokedAt:a.revokedAt??null,nextAction:"api-key.revoke",nextStep:`Run \`skills-layer api-key revoke --key-id ${o} --yes\` to revoke this key.`}),"API key revoke dry run passed.",t.json,n):NB(o,t)}if(!t.confirmed){let a=await jB(o,n);if(!a)return NB(o,t);let l=ie({status:"confirmation_required",reasonCode:"confirmation_required",keyId:o,keyPrefix:f(a,"keyPrefix"),type:f(a,"type"),name:f(a,"name"),nextAction:"api-key.revoke",nextStep:`Re-run with \`skills-layer api-key revoke --key-id ${o} --yes\` after confirming this is the key to revoke.`});if(t.json||!n.stdoutIsTty)return x(l,"API key revoke needs confirmation. Re-run with --yes after checking the key id.",t.json,"confirmation_required");if(await n.promptSelect(`Revoke API key ${o}?`,[{value:"cancel",label:"Cancel",description:"Leave this API key active"},{value:"confirm",label:"Revoke",description:"Permanently revoke this API key"}])!=="confirm")return R({status:"canceled",keyId:o},"API key revoke canceled.",t.json,n)}let s=await D(n,`/api/v1/me/api-keys/${encodeURIComponent(o)}/revoke`,{method:"POST",headers:re(n.apiKey,n.authBlockedMessage)});return R(s,s.status==="already_revoked"?"API key was already revoked.":"API key revoked.",t.json,n)}return E(`Unknown api-key command "${r}".`,t.json)}function Fre(e){let t=k(e.type);if(t&&!HB.includes(t))return{failure:Nr("api-key.list","type",t,HB,e,"invalid_api_key_filter","type")};let n=k(e.status)??"active";if(!KB.includes(n))return{failure:Nr("api-key.list","status",n,KB,e,"invalid_api_key_filter","status")};let r=k(e.sort)??"created-desc";if(!WB.includes(r))return{failure:Nr("api-key.list","sort",r,WB,e,"invalid_api_key_filter","sort")};let i=[["createdAfter","created-after",e.createdAfter],["createdBefore","created-before",e.createdBefore],["expiresAfter","expires-after",e.expiresAfter],["expiresBefore","expires-before",e.expiresBefore]],o={status:n,sort:r};for(let[s,a,l]of i){let c=k(l);if(c){if(Number.isNaN(Date.parse(c)))return{failure:x({status:"error",reasonCode:"invalid_api_key_filter",field:a,value:c,nextAction:"api-key.list",nextStep:`Use --${a} with an ISO date or timestamp.`},`Invalid api-key list --${a} "${c}". Use an ISO date or timestamp.`,e.json,"invalid_api_key_filter")};o[s]=c}}return{filters:ie({...o,...t?{type:t}:{},...k(e.name)?{name:k(e.name)}:{}})}}function ZM(e){return(Be(e,"results")??[]).filter(t=>j(t))}function Bre(e,t,n){let r=t.name?.toLowerCase();return e.filter(i=>!t.type||f(i,"type")===t.type).filter(i=>t.status==="all"||Mre(i,n)===t.status).filter(i=>!r||(f(i,"name")??f(i,"id")??"").toLowerCase().includes(r)).filter(i=>lh(i,"createdAt",t.createdAfter,"after")).filter(i=>lh(i,"createdAt",t.createdBefore,"before")).filter(i=>lh(i,"expiresAt",t.expiresAfter,"after")).filter(i=>lh(i,"expiresAt",t.expiresBefore,"before")).sort((i,o)=>Ure(i,o,t.sort))}function Mre(e,t=Date.now()){if(e.revokedAt!==null&&e.revokedAt!==void 0)return"revoked";let n=f(e,"expiresAt");if(!n)return"active";let r=Date.parse(n);return Number.isNaN(r)||r>t?"active":"expired"}function lh(e,t,n,r){if(!n)return!0;let i=f(e,t);if(!i)return!1;let o=Date.parse(i),s=Date.parse(n);return Number.isNaN(o)||Number.isNaN(s)?!1:r==="after"?o>=s:o<=s}function Ure(e,t,n){if(n==="name-asc"||n==="name-desc")return(n==="name-asc"?1:-1)*(f(e,"name")??f(e,"id")??"").localeCompare(f(t,"name")??f(t,"id")??"");let r=n.endsWith("-asc")?1:-1,i=n.startsWith("expires-")?"expiresAt":n.startsWith("last-used-")?"lastUsedAt":"createdAt";return r*(LB(e,i)-LB(t,i))}function LB(e,t){let n=f(e,t);if(!n)return 0;let r=Date.parse(n);return Number.isNaN(r)?0:r}async function jB(e,t){let n=await D(t,"/api/v1/me/api-keys",{headers:re(t.apiKey,t.authBlockedMessage)});return ZM(n).find(r=>f(r,"id")===e)}function NB(e,t){return x({status:"not_found",reasonCode:"api_key_not_found",keyId:e,nextAction:"api-key.list",nextStep:"Run `skills-layer api-key list` to find an active key id, then retry revoke."},`API key ${e} was not found.`,t.json,"api_key_not_found")}async function zre(e,t,n){let r=e[0]??"status";if(r==="migrate")return await qre(t,n);if(r==="setup"||r==="repair"){let i=await ke(n.paths.mcpConfigPath);if(i&&f(i,"brokerIntegrityProfile")==="extended_v1"){let a=f(i,"clientId")??"codex";return x({status:"unchanged",reasonCode:"mcp_extended_broker_requires_private_cli",nextAction:"mcp.repair.private",nextStep:`Run \`npm run skills-layer -- mcp repair --client ${a}\` from the private checkout.`},"This MCP broker is managed by the private checkout and was left unchanged.",t.json,"mcp_extended_broker_requires_private_cli")}let o=k(t.client);if(o&&t.all)return x({status:"error",reasonCode:"conflicting_mcp_client_selection",client:o,all:!0,nextAction:`mcp.${r}`,nextStep:"Use either --client <agent-id> for one agent or --all for every detected MCP-capable agent."},`mcp ${r} cannot use --client and --all together.`,t.json,"conflicting_mcp_client_selection");if(o&&!aie(o))return sP(o,t);if(o){let a=await ke(n.paths.mcpConfigPath),l=a?f(a,"baseUrl")??n.baseUrl:n.baseUrl,c=await qi({baseUrl:l,mcpUrl:a?f(a,"mcpUrl")??`${l}/mcp`:`${l}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:Ot(o),environment:a?f(a,"environment")??Dt(l):Dt(l),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:a});if(c.target.status==="skills_only"){let u=ch(c);return R(u,`${c.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}}let s=await XP(t,n);return fe(s)?s:R({...s},`MCP configuration written for ${s.clientId}. Open a fresh agent session to load Skills Layer tools, then run \`skills-layer mcp verify --client ${s.clientId}\` if they are not visible.`,t.json,n)}if(r==="status"||r==="verify"){let i=k(t.client),o=i?Ot(i):null;if(i&&!o)return sP(i,t);let s=await Nh(n),a=s.config;if(!a){if(o){let m=await qi({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:o,environment:Dt(n.baseUrl),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:null});if(m.target.status==="skills_only"){let h=ch(m);return R(h,`${m.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}}return R(s.publicState,s.summary,t.json,n)}let l=Array.isArray(a.clientIds)?a.clientIds.filter(m=>typeof m=="string"&&Ot(m)!==null):f(a,"clientId")?[f(a,"clientId")]:[];if(!o&&l.length>1){let m=f(a,"baseUrl")??n.baseUrl,h=[];for(let b of l){let w=await qi({baseUrl:m,mcpUrl:f(a,"mcpUrl")??`${m}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:b,environment:f(a,"environment")??Dt(m),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:a}),_=r==="verify"&&w.configured?await ty({nodePath:process.execPath,bridgePath:w.bridge.path}):w.liveProbe;h.push({...w,liveProbe:_,verified:r==="verify"?_.status==="ok":void 0})}let g=h.every(b=>b.configured),y=r==="verify"?h.every(b=>b.verified===!0):void 0,v={status:r==="verify"&&!y?"mcp_needs_repair":g?"mcp_configured":"mcp_needs_repair",configured:g,verified:y,clientIds:l,clients:h,sharedBroker:{path:f(a,"brokerPath"),socketPath:f(a,"brokerSocketPath")},nextAction:r==="verify"?"mcp.repair":"mcp.verify"};return r==="verify"&&!y?x(v,"One or more configured MCP hosts failed verification.",t.json,"mcp_multi_client_verify_failed"):R(v,`MCP ${r} completed for ${l.length} configured hosts.`,t.json,n)}if(!o&&l.length===0)return x({status:"mcp_needs_repair",reasonCode:"mcp_client_inventory_missing",configured:!1,nextAction:"mcp.repair",nextStep:"Run `skills-layer mcp repair --client <host-id>` or `skills-layer mcp repair --all`."},"The MCP config has no canonical host inventory and was not assigned to Codex implicitly.",t.json,"mcp_client_inventory_missing");let c=o??f(a,"clientId")??(Array.isArray(a.clientIds)&&typeof a.clientIds[0]=="string"?a.clientIds[0]:"codex"),u=f(a,"baseUrl")??n.baseUrl,d=await qi({baseUrl:u,mcpUrl:f(a,"mcpUrl")??`${u}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:c,environment:f(a,"environment")??Dt(u),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:a});if(d.target.status==="skills_only"){let m=ch(d);return R(m,`${d.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}if(d.status==="mcp_extension_verification_required")return r==="verify"?x({...d,nextAction:"mcp.verify.private",nextStep:`Run \`${d.nextCommand}\` from the private checkout.`},`MCP for ${d.clientId} uses a broker managed by the private checkout. Verify it there; the public CLI left it unchanged.`,t.json,"mcp_extended_broker_requires_private_cli"):R({...d,nextAction:"mcp.verify.private",nextStep:`Run \`${d.nextCommand}\` from the private checkout.`},`MCP for ${d.clientId} uses a broker managed by the private checkout. Run \`${d.nextCommand}\` for its authoritative integrity and live check.`,t.json,n);if(r==="verify"&&d.configured){let m=await ty({nodePath:process.execPath,bridgePath:d.bridge.path}),h={...d,verified:m.status==="ok",liveProbe:m};return m.status!=="ok"?x({...h,nextAction:"mcp.verify",nextStep:`Run \`skills-layer mcp verify --client ${d.clientId}\` again after checking local broker and network availability.`},`MCP config exists for ${d.clientId}, but live bridge verification failed: ${m.message}`,t.json,m.reasonCode??void 0):R({...h,nextAction:"agent.restart",nextStep:"Open a fresh agent session or restart the agent so it reloads the verified Skills Layer MCP connection."},`MCP verified for ${d.clientId}. ${m.message} Open a fresh agent session or restart the agent if tools are not visible yet.`,t.json,n)}let p=d.configured?{...d,nextAction:"mcp.verify",nextStep:`Run \`skills-layer mcp verify --client ${d.clientId}\` for a live tools/list check.`}:{...d,nextAction:"mcp.repair",nextStep:`Run \`${d.nextCommand}\`, then verify again.`};return R(p,d.configured?`MCP configuration is present for ${d.clientId}. Open a fresh agent session if tools are not visible, or run \`skills-layer mcp verify --client ${d.clientId}\` for a live check.`:`MCP needs repair for ${d.clientId}. Run \`${d.nextCommand}\`.`,t.json,n)}if(r==="disconnect"||r==="logout"){let i=await ke(n.paths.mcpConfigPath),o=k(t.client),s=o?Ot(o):null;if(o&&!s)return sP(o,t);let a=i&&Array.isArray(i.clientIds)?i.clientIds.filter(_=>typeof _=="string"):i&&f(i,"clientId")?[f(i,"clientId")]:[];if(!s&&a.length===0)return R({status:"mcp_not_configured",configured:!1,clientIds:[]},"MCP is not configured on this machine.",t.json,n);if(!s&&!t.all&&a.length>1)return x({status:"needs_mcp_client_scope",reasonCode:"mcp_client_scope_required",configuredClientIds:a,nextAction:`mcp.${r}`,nextStep:`Run \`skills-layer mcp ${r} --client <host-id>\` or add \`--all\`.`},`MCP ${r} requires --client or --all because multiple hosts are configured.`,t.json,"mcp_client_scope_required");let l=t.all?a:[s??a[0]],c=l[0],u=i?f(i,"baseUrl")??n.baseUrl:n.baseUrl,d=await qi({baseUrl:u,mcpUrl:i?f(i,"mcpUrl")??`${u}/mcp`:`${u}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:c,environment:i?f(i,"environment")??Dt(u):Dt(u),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:i});if(d.target.status==="skills_only"){let _=ch(d);return R(_,`${d.target.displayName} uses Skills Layer skill files, not MCP auto-install.`,t.json,n)}let p=es({baseUrl:n.baseUrl,mcpUrl:`${n.baseUrl}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:c,environment:Dt(n.baseUrl),now:n.now(),env:n.env,platform:n.platform,cwd:n.cwd,stateDir:n.paths.stateDir,mcpConfigPath:n.paths.mcpConfigPath,nodePath:process.execPath}),m=p.targets.filter(_=>l.includes(_.agentId)),h=a.filter(_=>!l.includes(_)),g=h.length>0,y=!1,v=i?f(i,"keyId"):void 0;if(!g&&n.apiKey&&(!i||v))try{await D(n,"/api/v1/me/session/revoke",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({includeCurrent:!1,revokeAllMcp:!1,humanKeyIds:[],mcpKeyIds:v?[v]:[]})}),y=!0}catch{y=!1}for(let _ of m)await _.disconnect?.();g&&i?await Ve(n.paths.mcpConfigPath,{...i,clientId:h[0],clientIds:h,savedAt:n.now()}):(await SP(i,n),await ay(p.bridgePath),await ly(p.brokerPath,p.brokerSocketPath,p.brokerLockPath),await We(n.paths.mcpConfigPath,{force:!0}),await We(n.paths.mcpPreferencePath,{force:!0}));let b=!g&&!!(n.apiKey&&i)&&!y,w=b&&(n.config?.userId&&v)?await xA(n,{baseUrl:u,userId:n.config.userId,humanKeyIds:[],mcpKeyIds:[v],revokeAllMcp:!1,revokeAdminMcp:!0,createdAt:n.now()}):!1;return R({status:b?"mcp_revocation_pending":"mcp_disconnected",configured:g,clientId:c,clientIds:l,remainingClientIds:h,serverCredentialsRevoked:y,revocationPending:b,pendingRecorded:w},b?w?"MCP disconnected locally. Server revocation is pending and will retry after this account authenticates again.":"MCP disconnected locally, but server revocation could not be recorded. Reconnect promptly; the machine credential remains bounded by expiry.":"MCP disconnected and its server credential was revoked.",t.json,n)}return E(`Unknown mcp command "${r}". Use setup, status, verify, repair, migrate, or disconnect.`,t.json)}async function qre(e,t){if(e.dryRun&&e.apply)return x({status:"error",reasonCode:"conflicting_mcp_migration_mode",nextAction:"mcp.migrate",nextStep:"Use --dry-run to preview or --apply to remove verified owned entries, but not both."},"Legacy MCP migration cannot use --dry-run and --apply together.",e.json,"conflicting_mcp_migration_mode");let n=k(e.path);if(!n)return x({status:"error",reasonCode:"mcp_legacy_project_path_required",nextAction:"mcp.migrate",nextStep:"Run `skills-layer mcp migrate --path <project-root> --dry-run --json`."},"Legacy MCP migration requires an explicit project root.",e.json,"mcp_legacy_project_path_required");let r=qo(t.cwd,n),i=await xR({projectRoot:r,stateDir:t.paths.stateDir,nodePath:process.execPath}),o=await ke(t.paths.mcpConfigPath),s=o&&Array.isArray(o.clientIds)?o.clientIds.filter(c=>typeof c=="string"&&Ot(c)!==null):o&&f(o,"clientId")&&Ot(f(o,"clientId"))?[f(o,"clientId")]:[],a=[];for(let c of s){let u=Ot(c);if(!u||!o)continue;let d=f(o,"baseUrl")??t.baseUrl;(await qi({baseUrl:d,mcpUrl:f(o,"mcpUrl")??`${d}/mcp`,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:u,environment:f(o,"environment")??Dt(d),now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath,mcpConfig:o})).configured&&a.push(u)}let l=await CR({discovery:i,verifiedGlobalHostIds:a,apply:!!e.apply});return l.plannedPaths.length===0?R({status:"mcp_legacy_migration_not_required",projectRoot:r,discovery:i,...l,nextAction:"none",nextStep:"No legacy project MCP registration requires migration."},"No legacy project MCP registration requires migration.",e.json,t):R({status:e.apply?"mcp_legacy_migration_applied":"mcp_legacy_migration_dry_run",projectRoot:r,discovery:i,...l,nextAction:e.apply?"mcp.status":"mcp.migrate",nextStep:e.apply?"Run `skills-layer mcp status --json` and restart affected hosts.":"Verify the replacement global registration, then rerun with `--apply`."},e.apply?`Removed ${l.cleanedPaths.length} verified legacy project registration(s).`:`Legacy MCP migration dry-run found ${l.plannedPaths.length} removable registration(s).`,e.json,t)}async function Vre(e,t,n){let r=e[0];if(!r)return x({status:"error",reasonCode:"missing_required_argument",command:"enterprise",argument:"command",nextAction:"enterprise.help",nextStep:"Run `skills-layer enterprise --help` to see available commands."},"enterprise requires a command. Run `skills-layer enterprise --help` to see available commands.",t.json,"missing_required_argument");if(r==="list"){let i;try{i=await D(n,"/api/v1/me/enterprises",{headers:re(n.apiKey,n.authBlockedMessage)})}catch(o){if(o instanceof Z&&o.status===404)return x({status:"not_supported",reasonCode:"enterprise_list_not_supported",nextAction:"operator.deploy",nextStep:"Ask an operator to deploy the current Enterprise API, then retry skills-layer enterprise list."},"This backend does not support Enterprise membership listing.",t.json,"enterprise_list_not_supported");throw o}return cn(i,Kre(i,n),"Enterprise memberships loaded.",t.json,n)}if(r==="checkout"){let i=JB(t.seats,"--seats","seats","enterprise checkout",t,{minimum:2});if(fe(i))return i;let o=O(t.enterpriseName??t.name,"enterprise checkout requires --enterprise-name <name>."),s=O(t.workspaceName??t.workspace,"enterprise checkout requires --workspace-name <name>."),a=tie(),l=await D(n,"/api/v1/enterprise/checkout",{method:"POST",headers:{...V(n.apiKey,n.authBlockedMessage),"idempotency-key":a},body:JSON.stringify({seatCount:i,enterpriseName:o,firstWorkspaceName:s,creationIntentId:a,createNewEnterprise:t.newEnterprise===!0})});return f(l,"status")==="enterprise_exists"?cn(l,Hre(l,n),"Existing Enterprise found.",t.json,n):await _P(l,t,n,"Enterprise checkout prepared.","Opening Enterprise checkout. Complete payment in your browser, then come back here.",{kind:"enterprise",statusPathForCheckoutId:c=>`/api/v1/enterprise/checkout/${encodeURIComponent(c)}`,waitingMessage:"Waiting for Enterprise checkout completion...",completedMessage:"Enterprise checkout completed."})}if(r==="rename"){let i=O(e[1],"enterprise rename requires <enterprise-id>."),o=O(t.enterpriseName??t.name??e[2],"enterprise rename requires --name <enterprise-name>.");return await Li(`/api/v1/enterprises/${encodeURIComponent(i)}`,{name:o},t,n,"Enterprise updated.")}if(r==="primary-admin"){let i=O(e[1],"enterprise primary-admin requires transfer, status, accept, or cancel.");if(i==="transfer"){let a=O(e[2],"enterprise primary-admin transfer requires <enterprise-id>."),l=O(e[3],"enterprise primary-admin transfer requires <target-user-id>.");return await Oe(`/api/v1/enterprises/${encodeURIComponent(a)}/primary-admin-transfers`,{targetUserId:l,outgoingAction:t.leaveEnterprise===!0?"leave_enterprise":"remain_admin"},t,n,"Primary Admin transfer started.")}let o=O(e[2],`enterprise primary-admin ${i} requires <transfer-id>.`),s=`/api/v1/enterprise/primary-admin-transfers/${encodeURIComponent(o)}`;return i==="status"?await me(s,t,n,"Primary Admin transfer loaded.",{authenticated:!0}):i==="accept"?await Oe(`${s}/accept`,{},t,n,"Primary Admin responsibility transferred."):i==="cancel"?await Oe(`${s}/cancel`,{},t,n,"Primary Admin transfer cancelled."):E(`Unknown enterprise primary-admin command "${i}". Use transfer, status, accept, or cancel.`,t.json)}if(r==="seats"){if(e[1]&&e[1]!=="add")return E(`Unknown enterprise seats command "${e[1]}".`,t.json);if(e[1]==="add"){let o=O(e[2],"enterprise seats add requires <enterprise-id>."),s=JB(t.seats,"--seats","seats","enterprise seats add",t,{minimum:1});if(fe(s))return s;let a=await D(n,"/api/v1/enterprise/seats/add",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({enterpriseId:o,additionalSeats:s})});return await _P(a,t,n,"Enterprise seat checkout prepared.",`Opening checkout for ${s} additional Enterprise seat${s===1?"":"s"}. Complete payment in your browser, then come back here.`,{kind:"enterprise_seats",statusPathForCheckoutId:l=>`/api/v1/enterprise/seats/checkout/${encodeURIComponent(l)}`,waitingMessage:"Waiting for Enterprise seat checkout completion...",completedMessage:"Enterprise seats added."})}let i=await D(n,"/api/v1/enterprise/seats",{headers:re(n.apiKey,n.authBlockedMessage)});return cn(i,Qre(i,n),"Enterprise seats loaded.",t.json,n)}if(r==="members"){let i=O(e[1],"enterprise members requires <enterprise-id>."),o=await D(n,`/api/v1/enterprises/${encodeURIComponent(i)}/members`,{headers:re(n.apiKey,n.authBlockedMessage)});return cn(o,Wre(o,n),"Enterprise members loaded.",t.json,n)}if(r==="invites"){let i=O(e[1],"enterprise invites requires <enterprise-id>."),o=await D(n,`/api/v1/enterprises/${encodeURIComponent(i)}/invites`,{headers:re(n.apiKey,n.authBlockedMessage)});return cn(o,Zre(o,n),"Enterprise invites loaded.",t.json,n)}if(r==="invite"){let i=O(e[1],"enterprise invite requires <enterprise-id>."),o=O(t.email??e[2],"enterprise invite requires --email <email>."),s=O(k(t.workspace),"enterprise invite requires --workspace <workspace-id|all|none>.");return await Oe(`/api/v1/enterprises/${encodeURIComponent(i)}/invites`,{email:o,role:k(t.role)??k(t.requestedRole)??"workspace_user",workspaceIds:gie(s)},t,n,"Enterprise invite created.")}if(r==="accept-invite"){let i=O(e[1],"enterprise accept-invite requires <invite-id>."),o=await D(n,`/api/v1/enterprise-invites/${encodeURIComponent(i)}/accept`,{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({})});return await ji(n,o),R(o,"Enterprise invite accepted.",t.json,n)}if(r==="revoke-invite"||r==="resend-invite"){let i=O(e[1],`enterprise ${r} requires <enterprise-id> and <invite-id>.`),o=O(e[2],`enterprise ${r} requires <enterprise-id> and <invite-id>.`),s=r==="revoke-invite"?"revoke":"resend";return await Oe(`/api/v1/enterprises/${encodeURIComponent(i)}/invites/${encodeURIComponent(o)}/${s}`,{},t,n,r==="revoke-invite"?"Enterprise invite revoked.":"Enterprise invite resent.")}if(r==="member"){let i=e[1];if(i!=="role"&&i!=="remove")return E(`Unknown enterprise member command "${i??""}".`,t.json);let o=O(e[2],"enterprise member <role|remove> requires <enterprise-id> and <user-id>."),s=O(e[3],"enterprise member <role|remove> requires <enterprise-id> and <user-id>.");if(i==="role"){let a=O(t.role??t.requestedRole,"enterprise member role requires --role <enterprise_admin|workspace_manager|workspace_user>.");return await Li(`/api/v1/enterprises/${encodeURIComponent(o)}/members/${encodeURIComponent(s)}`,{role:a},t,n,"Enterprise member role updated.")}if(i==="remove")return await Gu(`/api/v1/enterprises/${encodeURIComponent(o)}/members/${encodeURIComponent(s)}`,{method:"DELETE",headers:re(n.apiKey,n.authBlockedMessage)},t,n,"Enterprise member removed.")}if(r==="workspaces"){let i=O(e[1],"enterprise workspaces requires <enterprise-id>."),o=await D(n,`/api/v1/enterprises/${encodeURIComponent(i)}/workspaces`,{headers:re(n.apiKey,n.authBlockedMessage)});return cn(o,Jre(o,n),"Enterprise workspaces loaded.",t.json,n)}if(r==="workspace"){let i=e[1],o=O(e[2],"enterprise workspace <create|rename|archive> requires <enterprise-id>.");if(i==="create"){let a=O(t.workspaceName??t.name??e[3],"enterprise workspace create requires --name <workspace-name>.");return await Oe(`/api/v1/enterprises/${encodeURIComponent(o)}/workspaces`,{name:a},t,n,"Enterprise workspace created.")}let s=O(e[3],"enterprise workspace <rename|archive> requires <workspace-id>.");if(i==="rename"||i==="update"){let a=k(t.workspaceName)??k(t.name)??e[4],l=k(t.telemetryPolicy),c=k(t.guardianPolicy);return c&&c!=="standard"&&c!=="strict"?E("--guardian-policy must be standard or strict.",t.json):i==="rename"&&!a?E("enterprise workspace rename requires --name <workspace-name>.",t.json):!a&&!l&&!c?E("enterprise workspace update requires --name <workspace-name>, --telemetry-policy <best_effort|required> or --guardian-policy <standard|strict>.",t.json):l&&l!=="best_effort"&&l!=="required"?E("--telemetry-policy must be best_effort or required.",t.json):await Li(`/api/v1/workspaces/${encodeURIComponent(s)}`,{enterpriseId:o,...a?{name:a}:{},...l?{telemetryPolicy:l}:{},...c?{guardianPolicy:c}:{}},t,n,"Enterprise workspace updated.")}return i==="archive"?await Oe(`/api/v1/workspaces/${encodeURIComponent(s)}/archive`,{enterpriseId:o},t,n,"Enterprise workspace archived."):E(`Unknown enterprise workspace command "${i??""}".`,t.json)}if(r==="workspace-member"){let i=e[1];if(i!=="list"&&i!=="add"&&i!=="remove")return E(`Unknown enterprise workspace-member command "${i??""}".`,t.json);let o=O(e[2],"enterprise workspace-member <list|add|remove> requires <enterprise-id> <workspace-id>."),s=O(e[3],"enterprise workspace-member <list|add|remove> requires <enterprise-id> <workspace-id>.");if(i==="list"){let l=await D(n,`/api/v1/workspaces/${encodeURIComponent(s)}/members?enterpriseId=${encodeURIComponent(o)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return cn(l,Xre(l,n),"Workspace members loaded.",t.json,n)}let a=O(e[4],`enterprise workspace-member ${i} requires <user-id>.`);if(i==="add")return await Oe(`/api/v1/workspaces/${encodeURIComponent(s)}/members`,{enterpriseId:o,userId:a,role:k(t.role)??k(t.requestedRole)??"workspace_user"},t,n,"Workspace member added.");if(i==="remove")return await Gu(`/api/v1/workspaces/${encodeURIComponent(s)}/members/${encodeURIComponent(a)}`,{method:"DELETE",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({enterpriseId:o})},t,n,"Workspace member removed.")}if(r==="skill")return await Gre(e.slice(1),t,n);if(r==="install-authorize"){let i=O(e[1],"enterprise install-authorize requires <skill-slug>.");return await Oe(`/api/v1/skills/${encodeURIComponent(i)}/install-authorize`,{},t,n,"Install authorization evaluated.")}return E(`Unknown enterprise command "${r}".`,t.json)}async function Gre(e,t,n){let r=e[0];if(r==="quote"||r==="buy"){let i=O(e[1],`enterprise skill ${r} requires <enterprise-id> and <skill-slug>.`),o=O(e[2],`enterprise skill ${r} requires <enterprise-id> and <skill-slug>.`),s=await D(n,`/api/v1/enterprises/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/${r==="quote"?"quote":"checkout"}`,{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({})});return r==="quote"?cn(s,eie(s,i,o,n),"Enterprise skill quote loaded.",t.json,n):await _P(s,t,n,"Enterprise skill checkout prepared.",`Opening Enterprise skill checkout for ${o}. Complete payment in your browser, then come back here.`,{kind:"enterprise_skill",statusPathForCheckoutId:a=>`/api/v1/enterprises/_/skills/_/checkout/${encodeURIComponent(a)}`,waitingMessage:"Waiting for Enterprise skill checkout completion...",completedMessage:"Enterprise skill checkout completed."})}if(r==="entitlements"){let i=O(e[1],"enterprise skill entitlements requires <enterprise-id>."),o=await D(n,`/api/v1/enterprises/${encodeURIComponent(i)}/skill-entitlements`,{headers:re(n.apiKey,n.authBlockedMessage)});return cn(o,Yre(o,n),"Enterprise skill entitlements loaded.",t.json,n)}return E(`Unknown enterprise skill command "${r??""}".`,t.json)}async function _P(e,t,n,r,i,o){let s=f(e,"checkoutUrl"),a=f(e,"checkoutId"),l=f(e,"status");if(!t.json&&!t.noOpen&&(l==="checkout_required"&&s&&(n.emitInfo(i),await n.openUrl(s)||n.emitInfo(`Open this checkout URL manually to continue: ${s}`)),o&&a&&(l==="checkout_required"||l==="finalizing"))){n.emitInfo(o.waitingMessage);let c=o.statusPathForCheckoutId(a),u=await Qae(c,a,n);if(fe(u))return u;let d=f(u,"status");return d==="completion_pending"?cn(u,sie(u,o.kind,n),"Enterprise checkout completion is still pending.",t.json,n):d!=="completed"&&d!=="already_completed"?E(oie(d,o.kind),t.json):(n.emitInfo(o.completedMessage),cn(u,o.kind==="enterprise"?nie(u,n):o.kind==="enterprise_seats"?iie(u,n):rie(u,n),o.completedMessage,t.json,n))}return R(e,r,t.json,n)}function Hre(e,t){let n=Pe(t),r=L(e,"enterprise"),i=L(e,"membership"),o=Array.isArray(e.workspaces)?e.workspaces.filter(j):[],s=[`${n.ok("OK")} Existing Enterprise found. No payment was started.`,"",n.section("Enterprise")];if(s.push(` ${n.label("Name")}: ${r?f(r,"name")??"unknown":"unknown"}`),s.push(` ${n.label("ID")}: ${r?f(r,"enterpriseId")??"unknown":"unknown"}`),s.push(` ${n.label("Your role")}: ${jt(i?f(i,"role")??"unknown":"unknown")}`),o.length>0){s.push("",n.section("Workspaces"));for(let l of o)s.push(` ${n.arrow} ${f(l,"name")??"Unnamed"} (${f(l,"workspaceId")??"unknown"})`)}let a=f(e,"nextStep");return a&&s.push("",n.section("Next"),` ${n.arrow} ${a}`),s.join(`
|
|
2119
2119
|
`)}function Kre(e,t){let n=Pe(t),r=Array.isArray(e.results)?e.results.filter(j):[],i=[`${n.ok("OK")} Enterprise memberships loaded.`,"",n.section(`Enterprise memberships (${r.length})`)];return r.length===0?(i.push(` ${n.muted("No active Enterprise memberships.")}`),i.join(`
|
|
2120
2120
|
`)):(r.forEach((o,s)=>{i.push(`${s+1}. ${f(o,"name")??"Unnamed Enterprise"}`),i.push(` ${n.label("ID")}: ${f(o,"enterpriseId")??"unknown"}`),i.push(` ${n.label("Role")}: ${jt(f(o,"role")??"unknown")}`);let a=J(o,"seatCapacity"),l=J(o,"usedSeats"),c=J(o,"availableSeats");a!==void 0&&l!==void 0&&c!==void 0&&i.push(` ${n.label("Seats")}: ${l} used, ${c} available of ${a}`)}),i.join(`
|
|
2121
2121
|
`))}function Wre(e,t){let n=Pe(t),r=Array.isArray(e.results)?e.results.filter(j):[],i=[`${n.ok("OK")} Enterprise members loaded.`,"",n.section(`Enterprise members (${r.length})`)];return r.length===0?(i.push(` ${n.muted("No active Enterprise members.")}`),i.join(`
|
|
@@ -2135,38 +2135,38 @@ Run:
|
|
|
2135
2135
|
`)}function rie(e,t){let n=Pe(t),r=L(e,"entitlement"),i=r?f(r,"enterpriseId"):void 0,o=r?f(r,"skillSlug"):void 0,s=[`${n.ok("OK")} Enterprise skill is ready for workspace approval.`,"",n.section("Entitlement")];return s.push(` ${n.label("Skill")}: ${r?f(r,"skillName")??o??"unknown":"unknown"}`),o&&s.push(` ${n.label("Slug")}: ${o}`),r&&s.push(` ${n.label("Version")}: ${f(r,"version")??"latest"}`),i&&s.push(` ${n.label("Enterprise ID")}: ${i}`),s.push("",n.section("Next")),i&&s.push(` ${n.arrow} skills-layer enterprise skill entitlements ${i}`),o&&s.push(` ${n.arrow} skills-layer workspace approve <workspace-id> ${o}`),s.join(`
|
|
2136
2136
|
`)}function iie(e,t){let n=Pe(t),r=L(e,"enterprise"),i=J(e,"addedSeats"),o=r?J(r,"seatCapacity"):void 0,s=r?J(r,"usedSeats"):void 0,a=r?J(r,"availableSeats"):void 0,l=[`${n.ok("OK")} ${i??"Additional"} Enterprise seat${i===1?"":"s"} added.`,"",n.section("Enterprise")];return l.push(` ${n.label("Name")}: ${r?f(r,"name")??"unknown":"unknown"}`),l.push(` ${n.label("ID")}: ${r?f(r,"enterpriseId")??"unknown":"unknown"}`),o!==void 0&&s!==void 0&&a!==void 0&&l.push(` ${n.label("Seats")}: ${s} used, ${a} available of ${o}`),l.push("",n.section("Next"),` ${n.arrow} skills-layer enterprise seats`),l.join(`
|
|
2137
2137
|
`)}function oie(e,t){let n=e==="canceled"||e==="cancelled",r=t==="enterprise"?"Enterprise checkout":t==="enterprise_seats"?"Enterprise seat checkout":"Enterprise skill checkout",i=t==="enterprise"?"No Enterprise, workspace, or seats were created.":t==="enterprise_seats"?"No seats were added and the Enterprise capacity is unchanged.":"No Enterprise skill entitlement was created and no workspace access changed.",o=t==="enterprise"?"Enterprise checkout":t==="enterprise_seats"?"Enterprise seat purchase":"Enterprise skill purchase";return n?`${r} was cancelled. ${i} Rerun the ${o} command when you are ready.`:e==="expired"?`${r} expired. ${i} Start a new ${o} when you are ready.`:`${r} failed${e?` (${e})`:""}. ${i} Retry the ${o} command or contact support if payment was charged.`}function sie(e,t,n){let r=Pe(n),i=t==="enterprise"?"Enterprise checkout":t==="enterprise_seats"?"Enterprise seat checkout":"Enterprise skill checkout";return[`${r.muted("!")} ${i} payment or provisioning may already be in progress.`,"",r.section("Status"),` ${r.label("Checkout ID")}: ${f(e,"checkoutId")??"unknown"}`,` ${r.label("State")}: Completion pending`,"",r.section("Next"),` ${r.arrow} ${f(e,"nextStep")??"Check the same checkout status again. Do not start a second checkout."}`].join(`
|
|
2138
|
-
`)}function jt(e){if(e==="workspace_approved_only")return"Workspace-approved only";let t=e.replace(/[_-]+/gu," ").trim().toLowerCase();return t.length>0?t[0].toUpperCase()+t.slice(1):"Unknown"}function cn(e,t,n,r,i){return r?A(e,n,!0,i):{exitCode:0,stdout:t,stderr:""}}function Ot(e){let t=nl(e);return t.status==="unknown"?null:t.hostId}function aie(e){return Ot(e)!==null}function JM(e){return Xt.includes(e)}function sP(e,t){return x({status:"error",reasonCode:"unknown_mcp_client",requestedClient:e,nextAction:"mcp.status",nextStep:"Run `skills-layer mcp setup --all --dry-run` to see verified MCP host ids."},`Unknown MCP client "${e}". MCP hosts are separate from skill-install agents; run \`skills-layer mcp setup --all --dry-run\` to inspect them.`,t.json,"unknown_mcp_client")}function ch(e){let t=e.target.instructions,n=Array.isArray(t)&&typeof t[0]=="string"?t[0]:`Install skills with \`skills-layer install <skill> --agent ${e.clientId}\`.`;return{...e,status:"skills_only",configured:!1,nextCommand:null,nextAction:"install.skills",nextStep:n}}async function XP(e,t){let n=k(e.environment)??Dt(t.baseUrl),r=[...B2],i=`${t.baseUrl}/mcp`,o=es({baseUrl:t.baseUrl,mcpUrl:i,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:"codex",environment:n,now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath}),s=await lie(e,t,o);if(s.clientIds.length===0)return x({status:"needs_mcp_client_choice",reasonCode:"needs_mcp_client_choice",configured:!1,detectedClientIds:s.detectedClientIds,supportedClientIds:o.targets.filter(C=>C.status==="automatic").map(C=>C.agentId),nextAction:"mcp.setup.select_client",nextStep:"Run `skills-layer mcp setup --client <host-id>` or `skills-layer mcp setup --all`."},"No verified Tier 1 MCP host was detected, so no client was selected. Choose a host explicitly or use --all.",e.json,"needs_mcp_client_choice");let a=s.clientIds[0],l=es({baseUrl:t.baseUrl,mcpUrl:i,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:a,environment:n,now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath});if(e.dryRun){let C=l.targets.filter(P=>P.status==="automatic"&&s.clientIds.includes(Ot(P.agentId)));return{status:"mcp_setup_preview",evidenceStale:l.evidenceStale,warnings:l.warnings,dryRun:!0,configured:!1,unchanged:!0,clientId:a,clientIds:s.clientIds,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,plannedWrites:C.map(P=>({clientId:P.agentId,scope:"user_global",configPath:P.configPath})),skippedClients:l.targets.filter(P=>P.status!=="automatic").map(P=>({clientId:P.agentId,reason:P.reason})),bridgePath:l.bridgePath,brokerPath:l.brokerPath,nextAction:"mcp.setup"}}let c=l.targets.filter(C=>C.status==="automatic"&&s.clientIds.includes(Ot(C.agentId)));try{for(let C of c)await C.preflight?.()}catch(C){let P=C instanceof Error&&C.message.startsWith("mcp_config_symlink_rejected")?"mcp_config_symlink_rejected":"mcp_registration_ownership_ambiguous";return x({status:"mcp_setup_blocked",configured:!1,unchanged:!0,reasonCode:P,clientIds:s.clientIds,nextAction:"mcp.config.review",nextStep:"Review the existing user-global MCP entry. Skills Layer did not mint a credential or overwrite it."},C instanceof Error?C.message:"MCP host configuration preflight failed.",e.json,P)}if(bg(t.baseUrl)&&!t.credentialStore)return x({status:"security_unavailable",reasonCode:"mcp_secure_storage_required",configured:!1,unchanged:!0,nextAction:"mcp.setup",nextStep:"Run `skills-layer mcp setup --client <host-id>` on a machine with supported OS-secure credential storage."},"Skills Layer Cloud MCP setup requires supported OS-secure credential storage. No MCP credential was created.",e.json,"mcp_secure_storage_required");let u=Ho(),d=await D(t,"/api/v1/me/mcp-tokens",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({clientId:ey,linkedClientIds:s.clientIds,environment:n,scopes:r,handoffCodeHash:u.authorizationCodeHash,handoffCodeChallenge:u.codeChallenge})});if(f(d,"credentialHandoff")!=="ready")return R("MCP setup did not prepare a secure credential handoff.",e.json);let p=await D(t,"/api/v1/credential-handoffs/exchange",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({authorizationCode:u.authorizationCode,codeVerifier:u.codeVerifier})}),m=f(p,"apiKey");if(!m)return R("MCP token credential exchange failed closed.",e.json);let h;try{h=await cie(t,{token:m,clientId:ey,environment:n})}catch(C){if(!(C instanceof Sa))throw C;let P=f(p,"id"),N=!1;if(P)try{await D(t,"/api/v1/me/session/revoke",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({includeCurrent:!1,revokeAllMcp:!1,humanKeyIds:[],mcpKeyIds:[P]})}),N=!0}catch{t.config?.userId&&await xA(t,{baseUrl:t.baseUrl,userId:t.config.userId,humanKeyIds:[],mcpKeyIds:[P],revokeAllMcp:!1,revokeAdminMcp:!1,createdAt:t.now()})}return R(N?"OS-secure credential storage failed, so the new MCP credential was revoked and no local MCP setup was written.":"OS-secure credential storage failed. No local MCP setup was written; server revocation is pending or requires prompt retry.",e.json)}let g={...h,shared:!0,keyId:f(p,"id")??null,tokenPrefix:f(p,"keyPrefix")??null,scopes:Array.isArray(p.scopes)?p.scopes:[]},y=await ke(t.paths.mcpConfigPath),v=`${t.paths.stateDir}/mcp-credential-refs.json`,b=await ke(v),w=[...Ma(b??{},je),...Ma(y??{},je),...Ma(g,je)];if(await Ve(v,{tokens:Object.fromEntries(w.map(C=>[C.tokenRef,{tokenRef:C.tokenRef,credentialService:C.service,credentialStorage:"macos_keychain"}]))}),await Ve(t.paths.mcpConfigPath,{version:1,baseUrl:t.baseUrl,mcpUrl:i,clientId:a,clientIds:s.clientIds,environment:n,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,...g,brokerPath:l.brokerPath,brokerSocketPath:l.brokerSocketPath,brokerLockPath:l.brokerLockPath,brokerIntegrityProfile:"standard_v1",brokerChecksum:l.brokerChecksum,savedAt:t.now()}),t.credentialStore){let C=new Set(Ma(g,je).map(P=>`${P.service}:${P.tokenRef}`));for(let P of w)C.has(`${P.service}:${P.tokenRef}`)||await t.credentialStore.delete(P.service,P.tokenRef);await Ve(v,{tokens:Object.fromEntries(w.filter(P=>C.has(`${P.service}:${P.tokenRef}`)).map(P=>[P.tokenRef,{tokenRef:P.tokenRef,credentialService:P.service,credentialStorage:"macos_keychain"}]))})}let _=c;for(let C of _)await C.apply?.();return await We(t.paths.mcpPreferencePath,{force:!0}),{...Nt(p),status:"mcp_configured",evidenceStale:l.evidenceStale,warnings:l.warnings,clientId:a,clientIds:s.clientIds,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,environment:n,mcpUrl:i,bridgePath:l.bridgePath,brokerPath:l.brokerPath,brokerSocketPath:l.brokerSocketPath,nodePath:l.nodePath,bridgeChecksum:l.bridgeChecksum,brokerChecksum:l.brokerChecksum,saved:!0,readiness:{status:"configured_needs_agent_reload",verifyCommand:`skills-layer mcp verify --client ${a}`,nextStep:"Open a fresh agent session so the host can load the updated MCP configuration. Run verify or repair if Skills Layer tools are still not visible."},registrations:{status:"mcp_registration_plan",automaticCount:l.automaticCount,manualCount:l.manualCount,skillsOnlyCount:l.skillsOnlyCount,unsupportedCount:l.unsupportedCount,appliedCount:_.length,appliedClients:_.map(C=>C.agentId),targets:l.targets.map(C=>({agentId:C.agentId,displayName:C.displayName,tier:C.tier,status:C.status,transport:C.transport,configPath:C.configPath,bridgePath:C.bridgePath,restartRequired:C.restartRequired,reason:C.reason,instructions:C.instructions}))}}}async function lie(e,t,n){let r=k(e.client),i=n.targets.filter(l=>l.status==="automatic").flatMap(l=>{let c=Ot(l.agentId);return c?[c]:[]});if(r){let l=Ot(r);return{clientIds:l?[l]:[],detectedClientIds:[],selectionSource:"explicit"}}if(e.all)return{clientIds:i,detectedClientIds:i,selectionSource:"all"};let o=await rR({env:t.env,platform:t.platform,cwd:t.cwd,pathExists:t.pathExists}),s=new Set(i),a=o.map(l=>l.hostId).filter(l=>s.has(l));if(a.length>0)return{clientIds:a,detectedClientIds:a,selectionSource:"detected"};if(t.stdoutIsTty&&!e.json)try{let l=await t.promptSelect("Choose the MCP host to configure globally:",n.targets.filter(u=>u.status==="automatic").map(u=>({value:String(u.agentId),label:u.displayName,description:`User-global config: ${u.configPath}`}))),c=Ot(l);if(c)return{clientIds:[c],detectedClientIds:[],selectionSource:"explicit"}}catch{}return{clientIds:[],detectedClientIds:[],selectionSource:"choice_required"}}async function cie(e,t){if(!e.credentialStore){if(bg(e.baseUrl))throw new Sa;return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}let n=uie({baseUrl:e.baseUrl,userId:e.config?.userId,email:e.config?.email,clientId:t.clientId,environment:t.environment,stateDir:e.paths.stateDir});try{return await e.credentialStore.set(je,n,t.token),{tokenRef:n,credentialStorage:"macos_keychain",credentialService:je,tokenStorage:"macos_keychain"}}catch{if(bg(e.baseUrl))throw new Sa;return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}}async function SP(e,t){let n=`${t.paths.stateDir}/mcp-credential-refs.json`,r=await ke(n),i=[...Ma(e??{},je),...Ma(r??{},je)];if(!t.credentialStore){if(i.length)throw new Error("OS credential storage is unavailable; retry cleanup on this profile's original machine.");return}if((await Promise.allSettled(i.map(s=>t.credentialStore.delete(s.service,s.tokenRef)))).some(s=>s.status==="rejected"))throw new Error("MCP credential cleanup is incomplete; retry logout.");await We(n,{force:!0})}function Ma(e,t){let n=new Map;MB(e,t,n);let r=e.tokens;if(j(r))for(let i of Object.values(r))j(i)&&MB(i,t,n);return[...n.values()]}function MB(e,t,n){let r=f(e,"tokenRef");if(!r||f(e,"credentialStorage")!=="macos_keychain")return;let i=f(e,"credentialService")??t;n.set(`${i}:${r}`,{service:i,tokenRef:r})}function uie(e){let t=[e.baseUrl,e.userId??e.email??"unknown-user",e.clientId,e.environment,"mcpToken"].join(`
|
|
2139
|
-
`);return`skills-layer-cli:mcp-token:${Ue("sha256").update(t).digest("base64url").slice(0,32)}`}async function xP(e,t){if(e.noMcp)return{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."};let n=await ke(t.paths.mcpConfigPath),r=n?f(n,"baseUrl"):void 0,i=n?f(n,"clientId"):null;if(!e.withMcp&&r===t.baseUrl&&i)return{data:{status:"mcp_already_configured",configured:!0,clientId:i,mcpUrl:n?f(n,"mcpUrl")??`${t.baseUrl}/mcp`:`${t.baseUrl}/mcp`},message:"MCP is already configured for this machine."};let o=e.withMcp===!0;if(!o&&!e.json)try{let a=await t.promptSelect("Set up Skills Layer MCP for your AI tools on this machine?",[{value:"yes",label:"Yes, set up MCP",description:"Mint a scoped token and write local MCP configuration"},{value:"no",label:"Not now",description:"You can run skills-layer mcp setup later"}]);if(o=a==="yes",a==="no")return await We(t.paths.mcpPreferencePath,{force:!0}),{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."}}catch{return{}}if(!o)return{};let s=await XP(e,t);return fe(s)?{data:die(s),message:"Login completed, but MCP was not configured. Choose a verified host with `skills-layer mcp setup --client <host-id>` or use `--all`."}:{data:s,message:"MCP configuration written for this machine. Open a fresh agent session so your AI tools can load it."}}function die(e){let t="mcp_setup_failed";try{let n=JSON.parse(e.stderr);t=f(n,"reasonCode")??t}catch{e.stderr.includes("OS-secure credential storage")&&(t="mcp_secure_storage_required")}return{status:"mcp_not_configured",configured:!1,reasonCode:t,nextAction:"mcp.setup",nextCommand:"skills-layer mcp setup --client <host-id>",nextStep:"Run `skills-layer mcp setup --client <host-id>` after resolving the reported MCP prerequisite, or use `--all`."}}function CP(e,t){return t?t.status==="mcp_skipped"?{...e,nextAction:"whoami",nextStep:"Run `skills-layer whoami` to check your account."}:t.configured!==!1?{...e,nextAction:"mcp.verify",nextStep:"Open a fresh agent session so it can load Skills Layer, then run `skills-layer mcp verify` if the tools are not visible."}:t.configured===!1||t.status==="mcp_skipped"?{...e,nextAction:"mcp.setup",nextStep:"Run `skills-layer mcp setup` when you want Skills Layer available to your AI tools."}:e:e}async function wh(e,t){if(t.config?.edition==="community")return{};let n;try{n=await D(t,"/api/v1/me/working-modes",{headers:re(t.apiKey,t.authBlockedMessage)})}catch{return{}}await ji(t,n);let r=Array.isArray(n.modes)?n.modes.filter(j):[],i=f(n,"selectedModeId");if(!r.some(u=>f(u,"type")==="enterprise_workspace")){let u=r.find(p=>f(p,"modeId")===i),d=u?f(u,"label")??i:i;return i?{data:{status:"working_mode_selected",selectedModeId:i,...u?{mode:u}:{}},message:`Selected workspace: ${d}.`}:{}}let s=pie(r,i);if(s.length===0)return{};if(e.json)return x({status:"working_mode_selection_required",reasonCode:"working_mode_selection_required",selectedModeId:i??null,modes:r,nextAction:"workspace.select",nextStep:"Run `skills-layer workspace select personal` or `skills-layer workspace select <workspace-id>`."},"Select Personal or an Enterprise workspace to finish signing in.",!0,"working_mode_selection_required");let a;try{a=await t.promptSelect("Select your Skills Layer workspace:",s)}catch{return x({status:"working_mode_selection_required",reasonCode:"working_mode_selection_required",selectedModeId:f(n,"selectedModeId")??null,modes:r,nextAction:"workspace.select",nextStep:"Run `skills-layer workspace select personal` or `skills-layer workspace select <workspace-id>`."},"Select Personal or an Enterprise workspace to finish signing in.",e.json,"working_mode_selection_required")}let l=await D(t,"/api/v1/me/working-mode",{method:"PUT",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({modeId:a})});await ji(t,l);let c=s.find(u=>u.value===a)?.label??a;return{data:l,message:`Selected workspace: ${c}.`}}function pie(e,t){let n=new Map;for(let o of e){let s=f(o,"modeId"),a=f(o,"type");!s||a!=="personal"&&a!=="enterprise_workspace"||n.has(s)||n.set(s,o)}let r=[...n.values()],i=new Map;for(let o of r){let s=f(o,"modeId"),l=(f(o,"label")??s).trim().toLocaleLowerCase();i.set(l,[...i.get(l)??[],o])}return r.map(o=>{let s=f(o,"modeId"),a=f(o,"type"),l=f(o,"label")??s;if(a==="personal")return{value:s,label:l,description:s===t?"Currently selected \u2014 your personal library and public catalog":"Your personal library and public catalog"};let c=i.get(l.trim().toLocaleLowerCase())??[];if(c.length===1)return{value:s,label:l,...s===t?{description:"Currently selected"}:{}};let u=new Set(c.map(h=>f(h,"enterpriseId")).filter(Boolean)),d=u.size>1?f(o,"enterpriseId"):f(o,"workspaceId"),p=u.size>1?"Enterprise":"Workspace",m=fie(d??s);return{value:s,label:`${l} (${p} ${m})`,...s===t?{description:"Currently selected"}:{}}})}function fie(e){return e.replace(/^(?:enterprise|workspace)_/u,"").slice(0,8)}function mie(e){if(!e)return null;let t=e.mode??e.workingMode,n=j(t)?t:e,r=f(n,"modeId")??f(e,"selectedModeId"),i=f(n,"type");return!r||i!=="personal"&&i!=="enterprise_workspace"?null:{workingModeId:r,workingModeType:i,workingModeEnterpriseId:f(n,"enterpriseId"),workingModeWorkspaceId:f(n,"workspaceId"),workingModeGuardianPolicy:n.guardianPolicy==="standard"?"standard":"strict",workingModeRole:f(n,"role"),workingModeLabel:f(n,"label")}}async function ji(e,t){let n=mie(t);if(!n||!e.config)return e.config;let r={...e.config,...n,workingModeSavedAt:e.now()};return await CA(e.paths.configPath,r,e),e.config=r,r}async function UB(e,t,n){let r=[...new Set(t.map(i=>i.trim()).filter(Boolean))];for(let i of r){let o=await QP(e,i,n);if(o)return o}return null}async function QP(e,t,n){if(!e.apiKey)return null;let r=e.config?.workingModeType;if(r!=="personal"&&r!=="enterprise_workspace"){let i;try{i=await D(e,"/api/v1/me/install-policy",{headers:re(e.apiKey,e.authBlockedMessage)})}catch(o){if(o instanceof Z&&(o.status===403||o.status===409))return aP(o.details??{error:o.message},t,n.json);throw o}if(await ji(e,i),i.requiresWorkingModeSelection===!0)return x({status:"working_mode_selection_required",skillSlug:t,reasonCode:"working_mode_selection_required",nextAction:f(i,"nextAction")??"select_working_mode",nextStep:f(i,"nextStep")??"Select Personal or an Enterprise workspace before installing."},`Install blocked for ${t}. ${f(i,"nextStep")??"Select Personal or an Enterprise workspace before installing."}`,n.json,"working_mode_selection_required");r=e.config?.workingModeType}if(r!=="enterprise_workspace")return null;try{let i=await D(e,`/api/v1/skills/${encodeURIComponent(t)}/install-authorize`,{method:"POST",headers:V(e.apiKey,e.authBlockedMessage),body:JSON.stringify({})});return await ji(e,i),f(i,"status")==="authorized"?null:aP(i,t,n.json)}catch(i){if(i instanceof Z&&(i.status===403||i.status===409))return aP(i.details??{error:i.message},t,n.json);throw i}}function aP(e,t,n){let r=j(e.data)?e.data:e,i=f(e,"reasonCode")??f(r,"reasonCode"),o=f(e,"nextAction")??f(r,"nextAction"),s=f(e,"nextStep")??f(r,"nextStep"),a=f(r,"status")??"blocked";return x({...r,status:a,skillSlug:t,...i?{reasonCode:i}:{},...o?{nextAction:o}:{},...s?{nextStep:s}:{}},`Install blocked for ${t}${i?` (${i})`:""}.${s?` ${s}`:""}`,n,i)}function gie(e){let t=k(e);if(t)return t.split(",").map(n=>n.trim()).filter(Boolean)}async function hie(e,t,n){let r=e.join(" ").trim()||k(t.search)||"",i=new URLSearchParams;r&&i.set("query",r);let o=k(t.runtimeRisk);if(o&&!zB.includes(o))return cP("runtime-risk",o,zB,t);let s=k(t.agent);if(s&&!JM(s))return x({status:"error",reasonCode:"unknown_agent",filter:"agent",value:s,acceptedValues:Xt,nextAction:"search",nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown search --agent "${s}". Run \`skills-layer agents list\` to inspect supported agents.`,t.json,"unknown_agent");let a=k(t.trust);if(a&&!qB.includes(a))return cP("trust",a,qB,t);let l=k(t.securityCapability),c=Eie(l);if(l&&!c)return cP("security-capability",l,YM,t);let u=Iz(i,t);if(typeof u=="string")return x({status:"error",reasonCode:"invalid_limit",nextAction:"search",nextStep:"Use --limit with a positive whole number; values above 20 are clamped."},u,t.json,"invalid_limit");Ke(i,"agent",t.agent),Ke(i,"capability",t.capability),Ke(i,"trust",a),Ke(i,"runtime-risk",o),Ke(i,"security-capability",c);let d=await D(n,`/api/v1/search${Qe(i)}`);if(t.install!==void 0){let p=k(t.install);if(!p){if(t.json)return R("search --install requires an explicit skill slug in the public CLI package.",!0);let h=ur(d);if(h.length===0)return R("Search results do not include any installable skills. Run search again with a broader query.",!1);if(h.length===1)p=h[0].value;else try{p=await n.promptSelect("Select a search result to install:",h)}catch{return R("No search result was selected for install.",!1)}}let m=Sce(d);return m.includes(p)?await Wa([p],t,n,{origin:"search_result",fallbackPolicy:"eligible_public"}):R(m.length===0?`Search results do not include "${p}". Run search again with a matching query first.`:`Search results do not include "${p}". Run search again with a matching query or choose one of: ${m.join(", ")}.`,t.json)}return A({...d,...u.length?{warnings:[...Array.isArray(d.warnings)?d.warnings:[],...u]}:{}},"Search complete.",t.json,n)}var zB=NA,qB=el,YM=["filesystem_read","filesystem_write","network_access","api_access","browser_access","device_control","generated_code_execution","secret_handling","model_context","shell_access"],yie={network:"network_access",filesystem:"filesystem_read",files:"filesystem_read",file_read:"filesystem_read",file_write:"filesystem_write",shell:"shell_access",browser:"browser_access",device:"device_control",api:"api_access",secrets:"secret_handling",model:"model_context"},lP=["local","project","global","workspace"],Lu=["private","public","unlisted"],za=["private","public","unlisted"],VB=["github","gitlab","local","generic_git","domain"],vie=["owner","maintainer"],kie=["submitted","published","draft","pending_review","suspended","blocked","archived","unlisted"],wie=["open","acknowledged","fixed","closed","rejected","abusive","reopened","resolved"],bie=["visible","flagged","hidden"],_ie=["bug","quality","safety","other"],Sie=["approved","denied"],xie=["email","google","github","gitlab","microsoft"],Cie=["email","google","github","gitlab","microsoft"],GB=["catalog:read","library:read","creator:read","creator:submit","source:read","source:write","guardian:check","guardian:incident","workspace:read","workspace:write","workspace:approve","mcp:use"],HB=["automation","mcp","agent"],KB=["active","expired","revoked","all"],WB=["created-desc","created-asc","expires-desc","expires-asc","name-asc","name-desc","last-used-desc","last-used-asc"];var XM=["json","sarif","report","passport","markdown"],uh=[...FA,"score"],Iie=/^(?:card(?:_[A-Za-z0-9]+)*|pm_[A-Za-z0-9_]+)$/u,Pie=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Aie=/^[a-f0-9]{6,64}$/iu;function Rie(e,t,n,r){let i=k(t);if(!i)return{};if(!/^\d+$/u.test(i))return{failure:x({status:"error",reasonCode:"invalid_limit",command:e,value:i,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be a whole number from 1 to ${n}.`,r.json,"invalid_limit")};let o=Number.parseInt(i,10);return!Number.isInteger(o)||o<1||o>n?{failure:x({status:"error",reasonCode:"invalid_limit",command:e,value:i,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be between 1 and ${n}.`,r.json,"invalid_limit")}:{value:String(o)}}function cP(e,t,n,r){return x({status:"error",reasonCode:"invalid_search_filter",filter:e,value:t,acceptedValues:n,nextAction:"search",nextStep:e==="runtime-risk"?"Use --runtime-risk low, elevated, or high.":e==="limit"?"Use --limit with a whole number from 1 to 20.":`Use --${e} with one of: ${n.join(", ")}.`},e==="runtime-risk"?`Invalid runtime risk "${t}". Use one of: ${n.join(", ")}.`:e==="limit"?`Invalid search limit "${t}". Use a whole number from 1 to 20.`:`Invalid search --${e} "${t}". Use one of: ${n.join(", ")}.`,r.json,"invalid_search_filter")}function Eie(e){if(e)return YM.includes(e)?e:yie[e]}function Nr(e,t,n,r,i,o,s=t){return x({status:"error",reasonCode:o,[t]:n,acceptedValues:r,nextAction:e,nextStep:`Use --${s} with one of: ${r.join(", ")}.`},`Invalid ${e} --${s} "${n}". Use one of: ${r.join(", ")}.`,i.json,o)}function Mn(e,t,n,r,i,o,s=t){let a=k(n);if(!(!a||r.includes(a)))return Nr(e,t,a,r,i,o,s)}function Oi(e,t){let n=k(t.version);return n&&!Th(n)?eA(e,n,t):void 0}function $ie(e,t,n){return x({status:"error",reasonCode:"invalid_slug",value:t,acceptedFormat:"lowercase words separated by hyphens",nextAction:e,nextStep:"Use a lowercase skill slug such as project-planner or year9-history-study-guide."},`Invalid skill slug "${t}". Use lowercase letters, numbers, and single hyphens.`,n.json,"invalid_slug")}function QM(e,t,n){return t&&!Pie.test(t)?$ie(e,t,n):void 0}function Die(e,t,n){return x({status:"error",reasonCode:"invalid_format",format:t,acceptedValues:XM,nextAction:e,nextStep:"Use --format json, sarif, report, passport, or markdown."},`Invalid ${e} --format "${t}". Use json, sarif, report, passport, or markdown.`,n.json,"invalid_format")}function eU(e,t){let n=k(t.format);return n&&!XM.includes(n.toLowerCase())?Die(e,n,t):void 0}function Tie(e,t,n){return x({status:"error",reasonCode:"invalid_commit_sha",commitSha:t,nextAction:e,nextStep:"Use --commit-sha with a 6 to 64 character hexadecimal commit SHA."},`Invalid --commit-sha "${t}". Use a hexadecimal commit SHA.`,n.json,"invalid_commit_sha")}function Oie(e,t){let n=k(t.commitSha);return n&&!Aie.test(n)?Tie(e,n,t):void 0}function Lie(e,t){return x({status:"error",reasonCode:"invalid_base_url",baseUrl:e,nextAction:"backend",nextStep:"Use --base-url with HTTPS, or HTTP for loopback development only."},`Invalid backend base URL "${e}". Use HTTPS, or HTTP for loopback development only.`,t.json,"invalid_base_url")}function jie(e,t){try{tl(e);return}catch{return Lie(e,t)}}function ZB(e,t,n){return x({status:"error",reasonCode:"unexpected_argument",command:e,argument:t,nextAction:e,nextStep:`Run \`skills-layer ${e} --help\` to see supported arguments for this command.`},`Unexpected argument "${t}" for ${e}.`,n.json,"unexpected_argument")}function Qu(e,t){let n=k(t.scope);if(n&&!lP.includes(n))return{failure:x({status:"error",reasonCode:"invalid_install_filter",filter:"scope",value:n,acceptedValues:lP,nextAction:e,nextStep:"Use --scope local, project, global, or workspace."},`Invalid ${e} --scope "${n}". Use one of: ${lP.join(", ")}.`,t.json,"invalid_install_filter")};let r=k(t.agent);return r&&!(e==="install"&&r==="all")&&!JM(r)?{failure:x({status:"error",reasonCode:"unknown_agent",filter:"agent",value:r,acceptedValues:Xt,nextAction:e,nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown ${e} --agent "${r}". Run \`skills-layer agents\` to inspect supported agents.`,t.json,"unknown_agent")}:{scope:n,agent:r}}function tU(e,t){let n=Qu(e,t);if(n.failure)return n.failure;let r=k(t.version);if(e==="install"&&r&&!Th(r))return eA("install",r,t)}function eA(e,t,n){return x({status:"error",reasonCode:"invalid_version",command:e,version:t,nextAction:e,nextStep:"Use a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --version "${t}". Use a semver version or an external-<digest> version.`,n.json,"invalid_version")}function Nie(e,t,n){return x({status:"error",reasonCode:"invalid_expiry",command:e,expiresIn:t,acceptedFormat:"<positive whole number>d",maxDays:365,nextAction:e,nextStep:"Use --expires from 1d to 365d. Omit it for the 90-day default."},`Invalid --expires "${t}". Use a day duration from 1d to 365d. Omit it for the 90-day default.`,n.json,"invalid_expiry")}function Fie(e,t,n){let r=k(t);if(r&&qA(r)===null)return Nie(e,r,n)}function Ni(e,t,n,r,i,o){let s=k(e);if(!s)return{};if(!/^\d+$/u.test(s))return{failure:x({status:"error",reasonCode:r,[n]:s,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`,i.json,r)};let a=Number(s);return!Number.isSafeInteger(a)||a<o.minimum?{failure:x({status:"error",reasonCode:r,[n]:s,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`,i.json,r)}:{value:a}}function JB(e,t,n,r,i,o){let s=Ni(e,t,n,`invalid_${n.replace(/[A-Z]/gu,a=>`_${a.toLowerCase()}`)}`,i,o);return s.failure?s.failure:s.value===void 0?R(`${r} requires ${t} <count>.`,i.json):s.value}function Bie(e){let t=k(e.paymentMethod)??"card";return Iie.test(t)?{value:t}:{failure:x({status:"error",reasonCode:"invalid_payment_method",paymentMethod:t,acceptedValues:["card","card_<test-card>","pm_<provider-method-id>"],nextAction:"buy",nextStep:"Use --payment-method card or a provider token such as pm_<id>."},`Invalid payment method "${t}". Use card or a provider token such as pm_<id>.`,e.json,"invalid_payment_method")}}async function Mie(e,t,n){let r=new URLSearchParams,i=Iz(r,t);if(typeof i=="string")return x({status:"error",reasonCode:"invalid_limit",nextAction:"search",nextStep:"Use --limit with a positive whole number; values above 20 are clamped."},i,t.json,"invalid_limit");let o=k(t.sort);if(o&&!uh.includes(o))return x({status:"error",reasonCode:"invalid_sort",sort:o,acceptedValues:uh,nextAction:e,nextStep:`Use --sort with one of: ${uh.join(", ")}.`},`${e} --sort must be one of: ${uh.join(", ")}.`,t.json,"invalid_sort");Ke(r,"search",t.search),Ke(r,"sort",o);let s=await D(n,`/api/v1/${e}${Qe(r)}`);return A({...s,...i.length?{warnings:[...Array.isArray(s.warnings)?s.warnings:[],...i]}:{}},e==="trending"&&typeof s.basis=="string"?jA(s.basis):`${Fh(e)} skills loaded.`,t.json,n)}async function Uie(e,t,n){let r=e.join(" ").trim();if(!r)return R("recommend requires a task.",t.json);let i=Rie("recommend",t.limit,20,t);if(i.failure)return i.failure;let o=new URLSearchParams({task:r});Ke(o,"limit",i.value);let s=await D(n,`/api/v1/recommend?${o.toString()}`,{headers:Wo(n.apiKey)});return A(s,f(s,"summary")??"Recommendations loaded.",t.json,n)}async function zie(e,t,n){if(e.length<2)return R("compare requires two or more skill slugs.",t.json);if(e.length>5)return x({status:"error",reasonCode:"too_many_compare_slugs",requestedCount:e.length,maxItems:5,nextAction:"compare",nextStep:"Compare up to 5 skills at a time."},"compare supports up to 5 skill slugs at a time.",t.json,"too_many_compare_slugs");let r=new URLSearchParams({slugs:e.join(",")}),i=await D(n,`/api/v1/skills/compare?${r.toString()}`),o=Array.isArray(i.missing)?i.missing.filter(s=>typeof s=="string"):[];return o.length>0?x({...i,status:"not_found",reasonCode:"compare_missing_skills",missing:o,nextAction:"search",nextStep:`Run \`skills-layer search ${o[0]}\` to find the correct slug, then retry compare.`},`Comparison could not find: ${o.join(", ")}.`,t.json,"compare_missing_skills"):t.json?A(i,"Comparison loaded.",!0,n):{exitCode:0,stdout:$le(i,"Comparison loaded.",Pe(n),t.verbose),stderr:""}}async function qie(e,t,n){let r=O(e[0],"show requires a skill slug."),i=await D(n,`/api/v1/skills/${encodeURIComponent(r)}`);return A(Gh(i),"Skill loaded.",t.json,n)}async function Vie(e,t,n){let r=O(e[0],"trust requires a skill slug."),i=eU("trust",t);if(i)return i;let o=new URLSearchParams;Ke(o,"format",t.format),Ke(o,"version",t.version),Ke(o,"versionId",t.versionId);let s=await D(n,`/api/v1/skills/${encodeURIComponent(r)}/platform-score${Qe(o)}`);return k(t.format)?.toLowerCase()==="sarif"?{exitCode:0,stdout:JSON.stringify(s,null,2),stderr:""}:!t.json&&rC(s)?{exitCode:0,stdout:H(ZL(s)),stderr:""}:A(s,"Platform Score loaded.",t.json,n)}async function Gie(e,t,n){e.length===0&&n.renderMode.detail==="full"&&(e=["full"]);let r=e[0];if(t.json||n.renderMode.kind==="json-final"){if(r==="full")return A(dN(),"Help loaded.",!0,n);let a=e.length===1?Rg(r,bo):null;if(a)return A({status:"ok",kind:"goal_help",goal:a},"Help loaded.",!0,n);let l=r==="topic"?_o(e[1]):_o(r,e.slice(1));if(l)return A(l,"Help loaded.",!0,n);if(r!=="topic"&&!cre.has(r??""))return IP(e,!0)}if(!r){if(n.renderMode.kind==="json-stream"||!n.helpInteractive)return{exitCode:0,stdout:Lo(n.renderMode),stderr:""};let a;try{a=await n.promptSelect("What do you want to do?",sN(bo))}catch{a=void 0}if(!a)return{exitCode:0,stdout:Lo(n.renderMode),stderr:""};if(a==="full")return Ba(Lo(n.renderMode,!0),"full",t,n);let l=Rg(a,bo);return l?Ba(XC(l),l.id,t,n):{exitCode:0,stdout:Lo(n.renderMode),stderr:""}}if(r==="full")return Ba(Lo(n.renderMode,!0),"full",t,n);let o=e.length===1?Rg(r,bo):null;if(o)return Ba(XC(o),o.id,t,n);let s=vu(e[0],e.slice(1));if(s)return Ba(s,e.filter(Boolean).join(" "),t,n);if(r==="topic"){let a=vu(e[1]);if(a)return Ba(a,e[1]??"overview",t,n);let l=new URLSearchParams;return e[1]&&l.set("topic",e[1]),await me(`/api/v1/help${Qe(l)}`,t,n,"Help topic loaded.")}if(r==="standards")return await me("/api/v1/standards",t,n,"Marketplace standards loaded.");if(r==="marketplace-status"){let a=await D(n,"/api/v1/marketplace/status");return t.json?A(a,"Marketplace status loaded.",!0,n):A(Nle(a),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let a=await D(n,"/api/v1/capabilities");return A(Ble(a),"Edition capabilities loaded.",t.json,n)}if(r==="schema-plan")return R("help schema-plan is not included in the public npm CLI.",t.json);if(r==="optimize-tokens"){let a=O(t.text,"help optimize-tokens requires --text."),l=Mle(t.maxCharacters,t.json);if(fe(l))return l;let c=await D(n,"/api/v1/optimize-tokens",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({text:a,...l?{maxCharacters:l}:{}})});return A(c,"Token optimization complete.",t.json,n)}return R(`Unknown help command "${r}".`,t.json)}function Ba(e,t,n,r){return n.json?A({status:"ok",topic:t,content:e},"Help topic loaded.",!0,r):{exitCode:0,stdout:e,stderr:""}}function IP(e,t){let n=e.filter(Boolean).join(" ").trim()||"help";return x({status:"not_found",reasonCode:"help_topic_not_found",topic:n,nextAction:"help",nextStep:"Run `skills-layer --help`, `skills-layer help full`, or `skills-layer <command> --help` for a supported command."},`Help topic not found: ${n}.`,t,"help_topic_not_found")}async function Hie(e,t,n){let r=O(e[0]??t.path,"validate requires a file or directory."),i=Tt(n.cwd,r);if(!await pr(i))return $U("validate",r,t,n);let o=(await ma({cwd:n.cwd,sourcePath:r,limits:yo})).files;o=await Kie({files:o,resolvedTarget:i,flags:t,backend:n});let s=nt(o),a={files:o,sourceIntakeContext:k(t.sourceIntakeContext),publicationStatus:k(t.publicationStatus),dependencyAuditStatus:k(t.dependencyAuditStatus),category:k(t.category),discloseSource:!!t.discloseSource},l;try{l=await D(n,"/api/v1/validation/preview",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(ie(a))})}catch(d){if(d instanceof Z&&d.status===422&&d.details)l=Ice(d.details);else throw d}let c=Wie({...l,license:s.license,licenseIssues:s.issues.filter(d=>d.code.startsWith("license_"))},o),u=c.valid===!1||L(c,"validation")?.valid===!1;return t.json?u?x({...gz(c,n.renderMode.detail,"validate"),nextAction:"validate",nextStep:"Fix the listed issues, then run validate again."},"Validation failed.",!0,"bundle_invalid"):A(c,"Validation complete.",!0,n,"validate"):{exitCode:u?1:0,stdout:Ule(c,r,n),stderr:""}}async function Kie(e){if(nt(e.files).license?.status==="verified"||e.flags.json||!e.backend.stdoutIsTty)return e.files;let n=await Mk({cwd:e.backend.cwd,files:e.files,skip:!1,interactive:!0,prompt:nU(e.backend)});if(n.selection.mode==="skip"||await e.backend.promptSelect("Apply this licence change to the local bundle?",[{value:"apply",label:"Apply the reviewed change"},{value:"cancel",label:"Cancel without changing files"}])!=="apply")return e.files;let o=(await Ja(e.resolvedTarget)).isDirectory()?e.resolvedTarget:Me(e.resolvedTarget);return await Jp({targetDir:o,files:H1(e.files,n.selection),confirmed:!0}),(await ma({cwd:e.backend.cwd,sourcePath:o})).files}function Wie(e,t){return{...e,evalReadiness:Hk(t)}}function Zie(e,t){let n=Jie(e);return Es({status:n?"not_run":"generated_only",skillSlug:t.skillSlug,version:t.version,artifactDigest:ct(e),...n?{evalPackDigest:n}:{},generatedAt:t.generatedAt,runnerVersion:So,counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})}function Jie(e){let t=e.find(n=>{let r=$n(n.path,e);return r.type==="evidence"&&typeof n.content=="string"&&(r.relativePath.startsWith("evals/")||r.relativePath.endsWith(".eval.json")||r.relativePath.endsWith(".eval.yaml"))});if(t?.content)try{return Rs(JSON.parse(t.content))}catch{return}}async function Yie(e,t,n){let r=O(e[0]??t.path,"preview-trigger requires a file or directory."),i=Tt(n.cwd,r);if(!await pr(i))return $U("preview-trigger",r,t,n);let o=(await ma({cwd:n.cwd,sourcePath:r,limits:yo})).files,s=await D(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({files:o,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?A(s,"Trigger preview complete.",!0,n):{exitCode:0,stdout:zle(s,r,n),stderr:""}}async function Xie(e,t,n){let r=e[0];if(["create","sessions","resume","inspect","answer","resources","resource-decide","tool-contract","draft","validate","eval","improve","revise","materialize","finalize"].includes(r??""))return await XB(r,e.slice(1),t,n);if(r==="init")return t.quick?await XB("create",e.slice(1),{...t,mode:"quick"},n):await eoe(e.slice(1),t,n);if(r==="rules")return await me("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(r==="submissions")return await me("/api/v1/me/submissions",t,n,"Submissions loaded.",{authenticated:!0});if(r==="status"){let i=O(e[1],"creator status requires a skill slug.");try{return await me(`/api/v1/me/submissions/${encodeURIComponent(i)}/status`,t,n,"Submission status loaded.",{authenticated:!0})}catch(o){if(o instanceof Z&&o.status===404)return coe(i,t);throw o}}if(r==="charge-status"){let i=O(e[1],"creator charge-status requires a charge id.");return await me(`/api/v1/me/private-skill-charges/${encodeURIComponent(i)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(r==="spaces")return await roe(e.slice(1),t,n);if(r==="submit")return await AP(e.slice(1),t,n,!1);if(r==="submit-version")return await AP(e.slice(1),t,n,!0);if(r==="check-slug"){let i=O(e[1],"creator check-slug requires a slug.");return await aoe(i,t,n)}if(r==="rename"){let i=O(e[1],"creator rename requires the current slug."),o=O(e[2],"creator rename requires the new slug."),s=QM("creator.rename",o,t);return s||await Li(`/api/v1/me/submissions/${encodeURIComponent(i)}/slug`,{nextSkillSlug:o},t,n,"Skill renamed.")}if(r==="pricing")return await doe(e,t,n);if(r==="update-listing"){let i=O(e[1],"creator update-listing requires a skill slug.");return await poe(i,t,n)}if(r==="visibility"){let i=O(e[1],"creator visibility requires a skill slug."),o=Oi("creator.visibility",t);if(o)return o;let s=k(t.visibility)??e[2],a=uc(s);if(!a||!Lu.includes(a))return x({status:"error",reasonCode:"invalid_visibility",skillSlug:i,visibility:s??null,acceptedValues:Lu,nextAction:"creator.visibility",nextStep:"Use --visibility private, public, or unlisted."},`Invalid creator visibility "${s??""}". Use one of: ${Lu.join(", ")}.`,t.json,"invalid_visibility");let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/visibility`,{method:"PATCH",headers:V(n.apiKey),body:JSON.stringify(ie({visibility:a,dryRun:t.dryRun}))});return gse(l)?x(l,hse(l,i),t.json,f(l,"reasonCode")??f(l,"status")):A(l,t.dryRun?"Visibility preview loaded.":"Visibility updated.",t.json,n)}if(r==="security-report"){let i=O(e[1],"creator security-report requires a skill slug."),o=eU("creator.security-report",t);if(o)return o;let s=Oi("creator.security-report",t);if(s)return s;let a=new URLSearchParams;Ke(a,"format",t.format),Ke(a,"version",t.version),Ke(a,"versionId",t.versionId);let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/security-report${Qe(a)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?A(l,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:oce(l,i,n),stderr:""}}if(r==="rescan-security"){let i=O(e[1],"creator rescan-security requires a skill slug."),o=Oi("creator.rescan-security",t);if(o)return o;let s=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/security/rescan`,{method:"POST",headers:V(n.apiKey),body:JSON.stringify(ie(Ft(t,["version","versionId"])))});return t.json?A(s,"Security rescan requested.",!0,n):{exitCode:0,stdout:sce(s,i,n),stderr:""}}if(r==="provenance"){let i=O(e[1],"creator provenance requires a skill slug.");return await me(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership`,t,n,"Provenance loaded.",{authenticated:!0})}if(r==="claim"||r==="verify"||r==="dispute")return await foe(r,e,t,n);if(r==="issues"||r==="reviews"||r==="update-issue"||r==="moderate-review")return await koe(r,e,t,n);if(r==="analytics"){let i=O(e[1],"creator analytics requires a skill slug.");return await moe(i,t,n)}if(r==="delist"||r==="relist"){let i=O(e[1],`creator ${r} requires a skill slug.`),o=k(t.reason)??(r==="relist"?"Creator relisted skill":"");return o.trim().length<3?R("creator delist requires --reason (at least 3 characters).",t.json):await Li(`/api/v1/me/submissions/${encodeURIComponent(i)}`,{lifecycle:r==="delist"?"delisted":"active",reason:o},t,n,`${i} ${r==="delist"?"delisted":"relisted"}; existing buyers keep access.`)}if(r==="earnings")return await me("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0});if(r==="payout-profile")return k(t.country)?await iM(t,n):await goe(t,n);if(r==="payout-link")return await iM(t,n);if(r==="payouts")return await me("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0});if(r==="withdraw"){if(!k(t.amountCents))return R("creator withdraw requires --amount-cents.",t.json);let i=Ni(t.amountCents,"--amount-cents","amountCents","invalid_amount_cents",t,{minimum:1});if(i.failure)return i.failure;let o=k(t.idempotencyKey)??ole();if(t.json&&!k(t.mfaCode))return x({status:"blocked",reasonCode:"mfa_step_up_required",nextStep:"Run skills-layer creator withdraw --amount-cents <amount> in a human terminal to enter MFA and confirm the withdrawal."},"A fresh authenticator code is required.",!0,"mfa_step_up_required");if(t.json||!n.stdoutIsTty)return x({status:"blocked",reasonCode:"payout_human_confirmation_required",nextAction:"creator.withdraw",nextStep:"Use an interactive terminal. MCP returns a browser handoff, and automation credentials cannot withdraw."},"Creator withdrawal requires an interactive human confirmation. Use an interactive terminal; MCP returns a browser handoff and automation credentials cannot withdraw.",t.json,"payout_human_confirmation_required");let s=sU(t,n),a=ie({amountCents:i.value,reason:k(t.reason)}),l={...V(n.apiKey),"idempotency-key":o},c=await s("/api/v1/me/payouts",{method:"POST",headers:l,body:JSON.stringify(a)});if(c.status==="requested")return A(c,"Withdrawal requested.",!1,n);if(c.status!=="confirmation_required"||typeof c.confirmationId!="string"||typeof c.confirmationToken!="string"||typeof c.confirmationPhrase!="string")throw new Error("The payout service did not return a valid action-bound confirmation challenge.");let u=c.impact&&typeof c.impact=="object"?c.impact:{};if(await n.promptText(`Withdrawal impact: ${String(u.amountCents??i.value)} ${String(u.currency??"usd").toUpperCase()}, remaining withdrawable balance ${String(u.withdrawableAfterCents??"unknown")} cents.
|
|
2140
|
-
Type exactly "${c.confirmationPhrase}" to confirm: `)!==c.confirmationPhrase)return
|
|
2138
|
+
`)}function jt(e){if(e==="workspace_approved_only")return"Workspace-approved only";let t=e.replace(/[_-]+/gu," ").trim().toLowerCase();return t.length>0?t[0].toUpperCase()+t.slice(1):"Unknown"}function cn(e,t,n,r,i){return r?R(e,n,!0,i):{exitCode:0,stdout:t,stderr:""}}function Ot(e){let t=nl(e);return t.status==="unknown"?null:t.hostId}function aie(e){return Ot(e)!==null}function JM(e){return Xt.includes(e)}function sP(e,t){return x({status:"error",reasonCode:"unknown_mcp_client",requestedClient:e,nextAction:"mcp.status",nextStep:"Run `skills-layer mcp setup --all --dry-run` to see verified MCP host ids."},`Unknown MCP client "${e}". MCP hosts are separate from skill-install agents; run \`skills-layer mcp setup --all --dry-run\` to inspect them.`,t.json,"unknown_mcp_client")}function ch(e){let t=e.target.instructions,n=Array.isArray(t)&&typeof t[0]=="string"?t[0]:`Install skills with \`skills-layer install <skill> --agent ${e.clientId}\`.`;return{...e,status:"skills_only",configured:!1,nextCommand:null,nextAction:"install.skills",nextStep:n}}async function XP(e,t){let n=k(e.environment)??Dt(t.baseUrl),r=[...B2],i=`${t.baseUrl}/mcp`,o=es({baseUrl:t.baseUrl,mcpUrl:i,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:"codex",environment:n,now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath}),s=await lie(e,t,o);if(s.clientIds.length===0)return x({status:"needs_mcp_client_choice",reasonCode:"needs_mcp_client_choice",configured:!1,detectedClientIds:s.detectedClientIds,supportedClientIds:o.targets.filter(C=>C.status==="automatic").map(C=>C.agentId),nextAction:"mcp.setup.select_client",nextStep:"Run `skills-layer mcp setup --client <host-id>` or `skills-layer mcp setup --all`."},"No verified Tier 1 MCP host was detected, so no client was selected. Choose a host explicitly or use --all.",e.json,"needs_mcp_client_choice");let a=s.clientIds[0],l=es({baseUrl:t.baseUrl,mcpUrl:i,bearerTokenEnvVar:"SKILLS_LAYER_MCP_TOKEN",clientId:a,environment:n,now:t.now(),env:t.env,platform:t.platform,cwd:t.cwd,stateDir:t.paths.stateDir,mcpConfigPath:t.paths.mcpConfigPath,nodePath:process.execPath});if(e.dryRun){let C=l.targets.filter(P=>P.status==="automatic"&&s.clientIds.includes(Ot(P.agentId)));return{status:"mcp_setup_preview",evidenceStale:l.evidenceStale,warnings:l.warnings,dryRun:!0,configured:!1,unchanged:!0,clientId:a,clientIds:s.clientIds,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,plannedWrites:C.map(P=>({clientId:P.agentId,scope:"user_global",configPath:P.configPath})),skippedClients:l.targets.filter(P=>P.status!=="automatic").map(P=>({clientId:P.agentId,reason:P.reason})),bridgePath:l.bridgePath,brokerPath:l.brokerPath,nextAction:"mcp.setup"}}let c=l.targets.filter(C=>C.status==="automatic"&&s.clientIds.includes(Ot(C.agentId)));try{for(let C of c)await C.preflight?.()}catch(C){let P=C instanceof Error&&C.message.startsWith("mcp_config_symlink_rejected")?"mcp_config_symlink_rejected":"mcp_registration_ownership_ambiguous";return x({status:"mcp_setup_blocked",configured:!1,unchanged:!0,reasonCode:P,clientIds:s.clientIds,nextAction:"mcp.config.review",nextStep:"Review the existing user-global MCP entry. Skills Layer did not mint a credential or overwrite it."},C instanceof Error?C.message:"MCP host configuration preflight failed.",e.json,P)}if(bg(t.baseUrl)&&!t.credentialStore)return x({status:"security_unavailable",reasonCode:"mcp_secure_storage_required",configured:!1,unchanged:!0,nextAction:"mcp.setup",nextStep:"Run `skills-layer mcp setup --client <host-id>` on a machine with supported OS-secure credential storage."},"Skills Layer Cloud MCP setup requires supported OS-secure credential storage. No MCP credential was created.",e.json,"mcp_secure_storage_required");let u=Ho(),d=await D(t,"/api/v1/me/mcp-tokens",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({clientId:ey,linkedClientIds:s.clientIds,environment:n,scopes:r,handoffCodeHash:u.authorizationCodeHash,handoffCodeChallenge:u.codeChallenge})});if(f(d,"credentialHandoff")!=="ready")return E("MCP setup did not prepare a secure credential handoff.",e.json);let p=await D(t,"/api/v1/credential-handoffs/exchange",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({authorizationCode:u.authorizationCode,codeVerifier:u.codeVerifier})}),m=f(p,"apiKey");if(!m)return E("MCP token credential exchange failed closed.",e.json);let h;try{h=await cie(t,{token:m,clientId:ey,environment:n})}catch(C){if(!(C instanceof Sa))throw C;let P=f(p,"id"),N=!1;if(P)try{await D(t,"/api/v1/me/session/revoke",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({includeCurrent:!1,revokeAllMcp:!1,humanKeyIds:[],mcpKeyIds:[P]})}),N=!0}catch{t.config?.userId&&await xA(t,{baseUrl:t.baseUrl,userId:t.config.userId,humanKeyIds:[],mcpKeyIds:[P],revokeAllMcp:!1,revokeAdminMcp:!1,createdAt:t.now()})}return E(N?"OS-secure credential storage failed, so the new MCP credential was revoked and no local MCP setup was written.":"OS-secure credential storage failed. No local MCP setup was written; server revocation is pending or requires prompt retry.",e.json)}let g={...h,shared:!0,keyId:f(p,"id")??null,tokenPrefix:f(p,"keyPrefix")??null,scopes:Array.isArray(p.scopes)?p.scopes:[]},y=await ke(t.paths.mcpConfigPath),v=`${t.paths.stateDir}/mcp-credential-refs.json`,b=await ke(v),w=[...Ma(b??{},je),...Ma(y??{},je),...Ma(g,je)];if(await Ve(v,{tokens:Object.fromEntries(w.map(C=>[C.tokenRef,{tokenRef:C.tokenRef,credentialService:C.service,credentialStorage:"macos_keychain"}]))}),await Ve(t.paths.mcpConfigPath,{version:1,baseUrl:t.baseUrl,mcpUrl:i,clientId:a,clientIds:s.clientIds,environment:n,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,...g,brokerPath:l.brokerPath,brokerSocketPath:l.brokerSocketPath,brokerLockPath:l.brokerLockPath,brokerIntegrityProfile:"standard_v1",brokerChecksum:l.brokerChecksum,savedAt:t.now()}),t.credentialStore){let C=new Set(Ma(g,je).map(P=>`${P.service}:${P.tokenRef}`));for(let P of w)C.has(`${P.service}:${P.tokenRef}`)||await t.credentialStore.delete(P.service,P.tokenRef);await Ve(v,{tokens:Object.fromEntries(w.filter(P=>C.has(`${P.service}:${P.tokenRef}`)).map(P=>[P.tokenRef,{tokenRef:P.tokenRef,credentialService:P.service,credentialStorage:"macos_keychain"}]))})}let _=c;for(let C of _)await C.apply?.();return await We(t.paths.mcpPreferencePath,{force:!0}),{...Nt(p),status:"mcp_configured",evidenceStale:l.evidenceStale,warnings:l.warnings,clientId:a,clientIds:s.clientIds,selectionSource:s.selectionSource,detectedClientIds:s.detectedClientIds,environment:n,mcpUrl:i,bridgePath:l.bridgePath,brokerPath:l.brokerPath,brokerSocketPath:l.brokerSocketPath,nodePath:l.nodePath,bridgeChecksum:l.bridgeChecksum,brokerChecksum:l.brokerChecksum,saved:!0,readiness:{status:"configured_needs_agent_reload",verifyCommand:`skills-layer mcp verify --client ${a}`,nextStep:"Open a fresh agent session so the host can load the updated MCP configuration. Run verify or repair if Skills Layer tools are still not visible."},registrations:{status:"mcp_registration_plan",automaticCount:l.automaticCount,manualCount:l.manualCount,skillsOnlyCount:l.skillsOnlyCount,unsupportedCount:l.unsupportedCount,appliedCount:_.length,appliedClients:_.map(C=>C.agentId),targets:l.targets.map(C=>({agentId:C.agentId,displayName:C.displayName,tier:C.tier,status:C.status,transport:C.transport,configPath:C.configPath,bridgePath:C.bridgePath,restartRequired:C.restartRequired,reason:C.reason,instructions:C.instructions}))}}}async function lie(e,t,n){let r=k(e.client),i=n.targets.filter(l=>l.status==="automatic").flatMap(l=>{let c=Ot(l.agentId);return c?[c]:[]});if(r){let l=Ot(r);return{clientIds:l?[l]:[],detectedClientIds:[],selectionSource:"explicit"}}if(e.all)return{clientIds:i,detectedClientIds:i,selectionSource:"all"};let o=await rR({env:t.env,platform:t.platform,cwd:t.cwd,pathExists:t.pathExists}),s=new Set(i),a=o.map(l=>l.hostId).filter(l=>s.has(l));if(a.length>0)return{clientIds:a,detectedClientIds:a,selectionSource:"detected"};if(t.stdoutIsTty&&!e.json)try{let l=await t.promptSelect("Choose the MCP host to configure globally:",n.targets.filter(u=>u.status==="automatic").map(u=>({value:String(u.agentId),label:u.displayName,description:`User-global config: ${u.configPath}`}))),c=Ot(l);if(c)return{clientIds:[c],detectedClientIds:[],selectionSource:"explicit"}}catch{}return{clientIds:[],detectedClientIds:[],selectionSource:"choice_required"}}async function cie(e,t){if(!e.credentialStore){if(bg(e.baseUrl))throw new Sa;return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}let n=uie({baseUrl:e.baseUrl,userId:e.config?.userId,email:e.config?.email,clientId:t.clientId,environment:t.environment,stateDir:e.paths.stateDir});try{return await e.credentialStore.set(je,n,t.token),{tokenRef:n,credentialStorage:"macos_keychain",credentialService:je,tokenStorage:"macos_keychain"}}catch{if(bg(e.baseUrl))throw new Sa;return{token:t.token,credentialStorage:"local_file_locked",tokenStorage:"local_file_locked"}}}async function SP(e,t){let n=`${t.paths.stateDir}/mcp-credential-refs.json`,r=await ke(n),i=[...Ma(e??{},je),...Ma(r??{},je)];if(!t.credentialStore){if(i.length)throw new Error("OS credential storage is unavailable; retry cleanup on this profile's original machine.");return}if((await Promise.allSettled(i.map(s=>t.credentialStore.delete(s.service,s.tokenRef)))).some(s=>s.status==="rejected"))throw new Error("MCP credential cleanup is incomplete; retry logout.");await We(n,{force:!0})}function Ma(e,t){let n=new Map;MB(e,t,n);let r=e.tokens;if(j(r))for(let i of Object.values(r))j(i)&&MB(i,t,n);return[...n.values()]}function MB(e,t,n){let r=f(e,"tokenRef");if(!r||f(e,"credentialStorage")!=="macos_keychain")return;let i=f(e,"credentialService")??t;n.set(`${i}:${r}`,{service:i,tokenRef:r})}function uie(e){let t=[e.baseUrl,e.userId??e.email??"unknown-user",e.clientId,e.environment,"mcpToken"].join(`
|
|
2139
|
+
`);return`skills-layer-cli:mcp-token:${Ue("sha256").update(t).digest("base64url").slice(0,32)}`}async function xP(e,t){if(e.noMcp)return{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."};let n=await ke(t.paths.mcpConfigPath),r=n?f(n,"baseUrl"):void 0,i=n?f(n,"clientId"):null;if(!e.withMcp&&r===t.baseUrl&&i)return{data:{status:"mcp_already_configured",configured:!0,clientId:i,mcpUrl:n?f(n,"mcpUrl")??`${t.baseUrl}/mcp`:`${t.baseUrl}/mcp`},message:"MCP is already configured for this machine."};let o=e.withMcp===!0;if(!o&&!e.json)try{let a=await t.promptSelect("Set up Skills Layer MCP for your AI tools on this machine?",[{value:"yes",label:"Yes, set up MCP",description:"Mint a scoped token and write local MCP configuration"},{value:"no",label:"Not now",description:"You can run skills-layer mcp setup later"}]);if(o=a==="yes",a==="no")return await We(t.paths.mcpPreferencePath,{force:!0}),{data:{status:"mcp_skipped",configured:!1,nextCommand:"skills-layer mcp setup"},message:"MCP setup skipped. Run `skills-layer mcp setup` later when you want AI-tool access."}}catch{return{}}if(!o)return{};let s=await XP(e,t);return fe(s)?{data:die(s),message:"Login completed, but MCP was not configured. Choose a verified host with `skills-layer mcp setup --client <host-id>` or use `--all`."}:{data:s,message:"MCP configuration written for this machine. Open a fresh agent session so your AI tools can load it."}}function die(e){let t="mcp_setup_failed";try{let n=JSON.parse(e.stderr);t=f(n,"reasonCode")??t}catch{e.stderr.includes("OS-secure credential storage")&&(t="mcp_secure_storage_required")}return{status:"mcp_not_configured",configured:!1,reasonCode:t,nextAction:"mcp.setup",nextCommand:"skills-layer mcp setup --client <host-id>",nextStep:"Run `skills-layer mcp setup --client <host-id>` after resolving the reported MCP prerequisite, or use `--all`."}}function CP(e,t){return t?t.status==="mcp_skipped"?{...e,nextAction:"whoami",nextStep:"Run `skills-layer whoami` to check your account."}:t.configured!==!1?{...e,nextAction:"mcp.verify",nextStep:"Open a fresh agent session so it can load Skills Layer, then run `skills-layer mcp verify` if the tools are not visible."}:t.configured===!1||t.status==="mcp_skipped"?{...e,nextAction:"mcp.setup",nextStep:"Run `skills-layer mcp setup` when you want Skills Layer available to your AI tools."}:e:e}async function wh(e,t){if(t.config?.edition==="community")return{};let n;try{n=await D(t,"/api/v1/me/working-modes",{headers:re(t.apiKey,t.authBlockedMessage)})}catch{return{}}await ji(t,n);let r=Array.isArray(n.modes)?n.modes.filter(j):[],i=f(n,"selectedModeId");if(!r.some(u=>f(u,"type")==="enterprise_workspace")){let u=r.find(p=>f(p,"modeId")===i),d=u?f(u,"label")??i:i;return i?{data:{status:"working_mode_selected",selectedModeId:i,...u?{mode:u}:{}},message:`Selected workspace: ${d}.`}:{}}let s=pie(r,i);if(s.length===0)return{};if(e.json)return x({status:"working_mode_selection_required",reasonCode:"working_mode_selection_required",selectedModeId:i??null,modes:r,nextAction:"workspace.select",nextStep:"Run `skills-layer workspace select personal` or `skills-layer workspace select <workspace-id>`."},"Select Personal or an Enterprise workspace to finish signing in.",!0,"working_mode_selection_required");let a;try{a=await t.promptSelect("Select your Skills Layer workspace:",s)}catch{return x({status:"working_mode_selection_required",reasonCode:"working_mode_selection_required",selectedModeId:f(n,"selectedModeId")??null,modes:r,nextAction:"workspace.select",nextStep:"Run `skills-layer workspace select personal` or `skills-layer workspace select <workspace-id>`."},"Select Personal or an Enterprise workspace to finish signing in.",e.json,"working_mode_selection_required")}let l=await D(t,"/api/v1/me/working-mode",{method:"PUT",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({modeId:a})});await ji(t,l);let c=s.find(u=>u.value===a)?.label??a;return{data:l,message:`Selected workspace: ${c}.`}}function pie(e,t){let n=new Map;for(let o of e){let s=f(o,"modeId"),a=f(o,"type");!s||a!=="personal"&&a!=="enterprise_workspace"||n.has(s)||n.set(s,o)}let r=[...n.values()],i=new Map;for(let o of r){let s=f(o,"modeId"),l=(f(o,"label")??s).trim().toLocaleLowerCase();i.set(l,[...i.get(l)??[],o])}return r.map(o=>{let s=f(o,"modeId"),a=f(o,"type"),l=f(o,"label")??s;if(a==="personal")return{value:s,label:l,description:s===t?"Currently selected \u2014 your personal library and public catalog":"Your personal library and public catalog"};let c=i.get(l.trim().toLocaleLowerCase())??[];if(c.length===1)return{value:s,label:l,...s===t?{description:"Currently selected"}:{}};let u=new Set(c.map(h=>f(h,"enterpriseId")).filter(Boolean)),d=u.size>1?f(o,"enterpriseId"):f(o,"workspaceId"),p=u.size>1?"Enterprise":"Workspace",m=fie(d??s);return{value:s,label:`${l} (${p} ${m})`,...s===t?{description:"Currently selected"}:{}}})}function fie(e){return e.replace(/^(?:enterprise|workspace)_/u,"").slice(0,8)}function mie(e){if(!e)return null;let t=e.mode??e.workingMode,n=j(t)?t:e,r=f(n,"modeId")??f(e,"selectedModeId"),i=f(n,"type");return!r||i!=="personal"&&i!=="enterprise_workspace"?null:{workingModeId:r,workingModeType:i,workingModeEnterpriseId:f(n,"enterpriseId"),workingModeWorkspaceId:f(n,"workspaceId"),workingModeGuardianPolicy:n.guardianPolicy==="standard"?"standard":"strict",workingModeRole:f(n,"role"),workingModeLabel:f(n,"label")}}async function ji(e,t){let n=mie(t);if(!n||!e.config)return e.config;let r={...e.config,...n,workingModeSavedAt:e.now()};return await CA(e.paths.configPath,r,e),e.config=r,r}async function UB(e,t,n){let r=[...new Set(t.map(i=>i.trim()).filter(Boolean))];for(let i of r){let o=await QP(e,i,n);if(o)return o}return null}async function QP(e,t,n){if(!e.apiKey)return null;let r=e.config?.workingModeType;if(r!=="personal"&&r!=="enterprise_workspace"){let i;try{i=await D(e,"/api/v1/me/install-policy",{headers:re(e.apiKey,e.authBlockedMessage)})}catch(o){if(o instanceof Z&&(o.status===403||o.status===409))return aP(o.details??{error:o.message},t,n.json);throw o}if(await ji(e,i),i.requiresWorkingModeSelection===!0)return x({status:"working_mode_selection_required",skillSlug:t,reasonCode:"working_mode_selection_required",nextAction:f(i,"nextAction")??"select_working_mode",nextStep:f(i,"nextStep")??"Select Personal or an Enterprise workspace before installing."},`Install blocked for ${t}. ${f(i,"nextStep")??"Select Personal or an Enterprise workspace before installing."}`,n.json,"working_mode_selection_required");r=e.config?.workingModeType}if(r!=="enterprise_workspace")return null;try{let i=await D(e,`/api/v1/skills/${encodeURIComponent(t)}/install-authorize`,{method:"POST",headers:V(e.apiKey,e.authBlockedMessage),body:JSON.stringify({})});return await ji(e,i),f(i,"status")==="authorized"?null:aP(i,t,n.json)}catch(i){if(i instanceof Z&&(i.status===403||i.status===409))return aP(i.details??{error:i.message},t,n.json);throw i}}function aP(e,t,n){let r=j(e.data)?e.data:e,i=f(e,"reasonCode")??f(r,"reasonCode"),o=f(e,"nextAction")??f(r,"nextAction"),s=f(e,"nextStep")??f(r,"nextStep"),a=f(r,"status")??"blocked";return x({...r,status:a,skillSlug:t,...i?{reasonCode:i}:{},...o?{nextAction:o}:{},...s?{nextStep:s}:{}},`Install blocked for ${t}${i?` (${i})`:""}.${s?` ${s}`:""}`,n,i)}function gie(e){let t=k(e);if(t)return t.split(",").map(n=>n.trim()).filter(Boolean)}async function hie(e,t,n){let r=e.join(" ").trim()||k(t.search)||"",i=new URLSearchParams;r&&i.set("query",r);let o=k(t.runtimeRisk);if(o&&!zB.includes(o))return cP("runtime-risk",o,zB,t);let s=k(t.agent);if(s&&!JM(s))return x({status:"error",reasonCode:"unknown_agent",filter:"agent",value:s,acceptedValues:Xt,nextAction:"search",nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown search --agent "${s}". Run \`skills-layer agents list\` to inspect supported agents.`,t.json,"unknown_agent");let a=k(t.trust);if(a&&!qB.includes(a))return cP("trust",a,qB,t);let l=k(t.securityCapability),c=Eie(l);if(l&&!c)return cP("security-capability",l,YM,t);let u=Iz(i,t);if(typeof u=="string")return x({status:"error",reasonCode:"invalid_limit",nextAction:"search",nextStep:"Use --limit with a positive whole number; values above 20 are clamped."},u,t.json,"invalid_limit");Ke(i,"agent",t.agent),Ke(i,"capability",t.capability),Ke(i,"trust",a),Ke(i,"runtime-risk",o),Ke(i,"security-capability",c);let d=await D(n,`/api/v1/search${Qe(i)}`);if(t.install!==void 0){let p=k(t.install);if(!p){if(t.json)return E("search --install requires an explicit skill slug in the public CLI package.",!0);let h=ur(d);if(h.length===0)return E("Search results do not include any installable skills. Run search again with a broader query.",!1);if(h.length===1)p=h[0].value;else try{p=await n.promptSelect("Select a search result to install:",h)}catch{return E("No search result was selected for install.",!1)}}let m=Sce(d);return m.includes(p)?await Wa([p],t,n,{origin:"search_result",fallbackPolicy:"eligible_public"}):E(m.length===0?`Search results do not include "${p}". Run search again with a matching query first.`:`Search results do not include "${p}". Run search again with a matching query or choose one of: ${m.join(", ")}.`,t.json)}return R({...d,...u.length?{warnings:[...Array.isArray(d.warnings)?d.warnings:[],...u]}:{}},"Search complete.",t.json,n)}var zB=NA,qB=el,YM=["filesystem_read","filesystem_write","network_access","api_access","browser_access","device_control","generated_code_execution","secret_handling","model_context","shell_access"],yie={network:"network_access",filesystem:"filesystem_read",files:"filesystem_read",file_read:"filesystem_read",file_write:"filesystem_write",shell:"shell_access",browser:"browser_access",device:"device_control",api:"api_access",secrets:"secret_handling",model:"model_context"},lP=["local","project","global","workspace"],Lu=["private","public","unlisted"],za=["private","public","unlisted"],VB=["github","gitlab","local","generic_git","domain"],vie=["owner","maintainer"],kie=["submitted","published","draft","pending_review","suspended","blocked","archived","unlisted"],wie=["open","acknowledged","fixed","closed","rejected","abusive","reopened","resolved"],bie=["visible","flagged","hidden"],_ie=["bug","quality","safety","other"],Sie=["approved","denied"],xie=["email","google","github","gitlab","microsoft"],Cie=["email","google","github","gitlab","microsoft"],GB=["catalog:read","library:read","creator:read","creator:submit","source:read","source:write","guardian:check","guardian:incident","workspace:read","workspace:write","workspace:approve","mcp:use"],HB=["automation","mcp","agent"],KB=["active","expired","revoked","all"],WB=["created-desc","created-asc","expires-desc","expires-asc","name-asc","name-desc","last-used-desc","last-used-asc"];var XM=["json","sarif","report","passport","markdown"],uh=[...FA,"score"],Iie=/^(?:card(?:_[A-Za-z0-9]+)*|pm_[A-Za-z0-9_]+)$/u,Pie=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u,Aie=/^[a-f0-9]{6,64}$/iu;function Rie(e,t,n,r){let i=k(t);if(!i)return{};if(!/^\d+$/u.test(i))return{failure:x({status:"error",reasonCode:"invalid_limit",command:e,value:i,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be a whole number from 1 to ${n}.`,r.json,"invalid_limit")};let o=Number.parseInt(i,10);return!Number.isInteger(o)||o<1||o>n?{failure:x({status:"error",reasonCode:"invalid_limit",command:e,value:i,acceptedRange:`1-${n}`,nextAction:e,nextStep:`Use --limit with a whole number from 1 to ${n}.`},`${e} --limit must be between 1 and ${n}.`,r.json,"invalid_limit")}:{value:String(o)}}function cP(e,t,n,r){return x({status:"error",reasonCode:"invalid_search_filter",filter:e,value:t,acceptedValues:n,nextAction:"search",nextStep:e==="runtime-risk"?"Use --runtime-risk low, elevated, or high.":e==="limit"?"Use --limit with a whole number from 1 to 20.":`Use --${e} with one of: ${n.join(", ")}.`},e==="runtime-risk"?`Invalid runtime risk "${t}". Use one of: ${n.join(", ")}.`:e==="limit"?`Invalid search limit "${t}". Use a whole number from 1 to 20.`:`Invalid search --${e} "${t}". Use one of: ${n.join(", ")}.`,r.json,"invalid_search_filter")}function Eie(e){if(e)return YM.includes(e)?e:yie[e]}function Nr(e,t,n,r,i,o,s=t){return x({status:"error",reasonCode:o,[t]:n,acceptedValues:r,nextAction:e,nextStep:`Use --${s} with one of: ${r.join(", ")}.`},`Invalid ${e} --${s} "${n}". Use one of: ${r.join(", ")}.`,i.json,o)}function Mn(e,t,n,r,i,o,s=t){let a=k(n);if(!(!a||r.includes(a)))return Nr(e,t,a,r,i,o,s)}function Oi(e,t){let n=k(t.version);return n&&!Th(n)?eA(e,n,t):void 0}function $ie(e,t,n){return x({status:"error",reasonCode:"invalid_slug",value:t,acceptedFormat:"lowercase words separated by hyphens",nextAction:e,nextStep:"Use a lowercase skill slug such as project-planner or year9-history-study-guide."},`Invalid skill slug "${t}". Use lowercase letters, numbers, and single hyphens.`,n.json,"invalid_slug")}function QM(e,t,n){return t&&!Pie.test(t)?$ie(e,t,n):void 0}function Die(e,t,n){return x({status:"error",reasonCode:"invalid_format",format:t,acceptedValues:XM,nextAction:e,nextStep:"Use --format json, sarif, report, passport, or markdown."},`Invalid ${e} --format "${t}". Use json, sarif, report, passport, or markdown.`,n.json,"invalid_format")}function eU(e,t){let n=k(t.format);return n&&!XM.includes(n.toLowerCase())?Die(e,n,t):void 0}function Tie(e,t,n){return x({status:"error",reasonCode:"invalid_commit_sha",commitSha:t,nextAction:e,nextStep:"Use --commit-sha with a 6 to 64 character hexadecimal commit SHA."},`Invalid --commit-sha "${t}". Use a hexadecimal commit SHA.`,n.json,"invalid_commit_sha")}function Oie(e,t){let n=k(t.commitSha);return n&&!Aie.test(n)?Tie(e,n,t):void 0}function Lie(e,t){return x({status:"error",reasonCode:"invalid_base_url",baseUrl:e,nextAction:"backend",nextStep:"Use --base-url with HTTPS, or HTTP for loopback development only."},`Invalid backend base URL "${e}". Use HTTPS, or HTTP for loopback development only.`,t.json,"invalid_base_url")}function jie(e,t){try{tl(e);return}catch{return Lie(e,t)}}function ZB(e,t,n){return x({status:"error",reasonCode:"unexpected_argument",command:e,argument:t,nextAction:e,nextStep:`Run \`skills-layer ${e} --help\` to see supported arguments for this command.`},`Unexpected argument "${t}" for ${e}.`,n.json,"unexpected_argument")}function Qu(e,t){let n=k(t.scope);if(n&&!lP.includes(n))return{failure:x({status:"error",reasonCode:"invalid_install_filter",filter:"scope",value:n,acceptedValues:lP,nextAction:e,nextStep:"Use --scope local, project, global, or workspace."},`Invalid ${e} --scope "${n}". Use one of: ${lP.join(", ")}.`,t.json,"invalid_install_filter")};let r=k(t.agent);return r&&!(e==="install"&&r==="all")&&!JM(r)?{failure:x({status:"error",reasonCode:"unknown_agent",filter:"agent",value:r,acceptedValues:Xt,nextAction:e,nextStep:"Use --agent with a supported Skills Layer agent id."},`Unknown ${e} --agent "${r}". Run \`skills-layer agents\` to inspect supported agents.`,t.json,"unknown_agent")}:{scope:n,agent:r}}function tU(e,t){let n=Qu(e,t);if(n.failure)return n.failure;let r=k(t.version);if(e==="install"&&r&&!Th(r))return eA("install",r,t)}function eA(e,t,n){return x({status:"error",reasonCode:"invalid_version",command:e,version:t,nextAction:e,nextStep:"Use a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --version "${t}". Use a semver version or an external-<digest> version.`,n.json,"invalid_version")}function Nie(e,t,n){return x({status:"error",reasonCode:"invalid_expiry",command:e,expiresIn:t,acceptedFormat:"<positive whole number>d",maxDays:365,nextAction:e,nextStep:"Use --expires from 1d to 365d. Omit it for the 90-day default."},`Invalid --expires "${t}". Use a day duration from 1d to 365d. Omit it for the 90-day default.`,n.json,"invalid_expiry")}function Fie(e,t,n){let r=k(t);if(r&&qA(r)===null)return Nie(e,r,n)}function Ni(e,t,n,r,i,o){let s=k(e);if(!s)return{};if(!/^\d+$/u.test(s))return{failure:x({status:"error",reasonCode:r,[n]:s,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`,i.json,r)};let a=Number(s);return!Number.isSafeInteger(a)||a<o.minimum?{failure:x({status:"error",reasonCode:r,[n]:s,nextAction:t.includes("price")?"creator.pricing":"creator.withdraw",nextStep:`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`},`${t} must be a whole number ${o.minimum===0?"zero or greater":"greater than zero"}.`,i.json,r)}:{value:a}}function JB(e,t,n,r,i,o){let s=Ni(e,t,n,`invalid_${n.replace(/[A-Z]/gu,a=>`_${a.toLowerCase()}`)}`,i,o);return s.failure?s.failure:s.value===void 0?E(`${r} requires ${t} <count>.`,i.json):s.value}function Bie(e){let t=k(e.paymentMethod)??"card";return Iie.test(t)?{value:t}:{failure:x({status:"error",reasonCode:"invalid_payment_method",paymentMethod:t,acceptedValues:["card","card_<test-card>","pm_<provider-method-id>"],nextAction:"buy",nextStep:"Use --payment-method card or a provider token such as pm_<id>."},`Invalid payment method "${t}". Use card or a provider token such as pm_<id>.`,e.json,"invalid_payment_method")}}async function Mie(e,t,n){let r=new URLSearchParams,i=Iz(r,t);if(typeof i=="string")return x({status:"error",reasonCode:"invalid_limit",nextAction:"search",nextStep:"Use --limit with a positive whole number; values above 20 are clamped."},i,t.json,"invalid_limit");let o=k(t.sort);if(o&&!uh.includes(o))return x({status:"error",reasonCode:"invalid_sort",sort:o,acceptedValues:uh,nextAction:e,nextStep:`Use --sort with one of: ${uh.join(", ")}.`},`${e} --sort must be one of: ${uh.join(", ")}.`,t.json,"invalid_sort");Ke(r,"search",t.search),Ke(r,"sort",o);let s=await D(n,`/api/v1/${e}${Qe(r)}`);return R({...s,...i.length?{warnings:[...Array.isArray(s.warnings)?s.warnings:[],...i]}:{}},e==="trending"&&typeof s.basis=="string"?jA(s.basis):`${Fh(e)} skills loaded.`,t.json,n)}async function Uie(e,t,n){let r=e.join(" ").trim();if(!r)return E("recommend requires a task.",t.json);let i=Rie("recommend",t.limit,20,t);if(i.failure)return i.failure;let o=new URLSearchParams({task:r});Ke(o,"limit",i.value);let s=await D(n,`/api/v1/recommend?${o.toString()}`,{headers:Wo(n.apiKey)});return R(s,f(s,"summary")??"Recommendations loaded.",t.json,n)}async function zie(e,t,n){if(e.length<2)return E("compare requires two or more skill slugs.",t.json);if(e.length>5)return x({status:"error",reasonCode:"too_many_compare_slugs",requestedCount:e.length,maxItems:5,nextAction:"compare",nextStep:"Compare up to 5 skills at a time."},"compare supports up to 5 skill slugs at a time.",t.json,"too_many_compare_slugs");let r=new URLSearchParams({slugs:e.join(",")}),i=await D(n,`/api/v1/skills/compare?${r.toString()}`),o=Array.isArray(i.missing)?i.missing.filter(s=>typeof s=="string"):[];return o.length>0?x({...i,status:"not_found",reasonCode:"compare_missing_skills",missing:o,nextAction:"search",nextStep:`Run \`skills-layer search ${o[0]}\` to find the correct slug, then retry compare.`},`Comparison could not find: ${o.join(", ")}.`,t.json,"compare_missing_skills"):t.json?R(i,"Comparison loaded.",!0,n):{exitCode:0,stdout:$le(i,"Comparison loaded.",Pe(n),t.verbose),stderr:""}}async function qie(e,t,n){let r=O(e[0],"show requires a skill slug."),i=await D(n,`/api/v1/skills/${encodeURIComponent(r)}`);return R(Gh(i),"Skill loaded.",t.json,n)}async function Vie(e,t,n){let r=O(e[0],"trust requires a skill slug."),i=eU("trust",t);if(i)return i;let o=new URLSearchParams;Ke(o,"format",t.format),Ke(o,"version",t.version),Ke(o,"versionId",t.versionId);let s=await D(n,`/api/v1/skills/${encodeURIComponent(r)}/platform-score${Qe(o)}`);return k(t.format)?.toLowerCase()==="sarif"?{exitCode:0,stdout:JSON.stringify(s,null,2),stderr:""}:!t.json&&rC(s)?{exitCode:0,stdout:H(ZL(s)),stderr:""}:R(s,"Platform Score loaded.",t.json,n)}async function Gie(e,t,n){e.length===0&&n.renderMode.detail==="full"&&(e=["full"]);let r=e[0];if(t.json||n.renderMode.kind==="json-final"){if(r==="full")return R(dN(),"Help loaded.",!0,n);let a=e.length===1?Rg(r,bo):null;if(a)return R({status:"ok",kind:"goal_help",goal:a},"Help loaded.",!0,n);let l=r==="topic"?_o(e[1]):_o(r,e.slice(1));if(l)return R(l,"Help loaded.",!0,n);if(r!=="topic"&&!cre.has(r??""))return IP(e,!0)}if(!r){if(n.renderMode.kind==="json-stream"||!n.helpInteractive)return{exitCode:0,stdout:Lo(n.renderMode),stderr:""};let a;try{a=await n.promptSelect("What do you want to do?",sN(bo))}catch{a=void 0}if(!a)return{exitCode:0,stdout:Lo(n.renderMode),stderr:""};if(a==="full")return Ba(Lo(n.renderMode,!0),"full",t,n);let l=Rg(a,bo);return l?Ba(XC(l),l.id,t,n):{exitCode:0,stdout:Lo(n.renderMode),stderr:""}}if(r==="full")return Ba(Lo(n.renderMode,!0),"full",t,n);let o=e.length===1?Rg(r,bo):null;if(o)return Ba(XC(o),o.id,t,n);let s=vu(e[0],e.slice(1));if(s)return Ba(s,e.filter(Boolean).join(" "),t,n);if(r==="topic"){let a=vu(e[1]);if(a)return Ba(a,e[1]??"overview",t,n);let l=new URLSearchParams;return e[1]&&l.set("topic",e[1]),await me(`/api/v1/help${Qe(l)}`,t,n,"Help topic loaded.")}if(r==="standards")return await me("/api/v1/standards",t,n,"Marketplace standards loaded.");if(r==="marketplace-status"){let a=await D(n,"/api/v1/marketplace/status");return t.json?R(a,"Marketplace status loaded.",!0,n):R(Nle(a),"Marketplace status loaded.",!1,n)}if(r==="capabilities"){let a=await D(n,"/api/v1/capabilities");return R(Ble(a),"Edition capabilities loaded.",t.json,n)}if(r==="schema-plan")return E("help schema-plan is not included in the public npm CLI.",t.json);if(r==="optimize-tokens"){let a=O(t.text,"help optimize-tokens requires --text."),l=Mle(t.maxCharacters,t.json);if(fe(l))return l;let c=await D(n,"/api/v1/optimize-tokens",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({text:a,...l?{maxCharacters:l}:{}})});return R(c,"Token optimization complete.",t.json,n)}return E(`Unknown help command "${r}".`,t.json)}function Ba(e,t,n,r){return n.json?R({status:"ok",topic:t,content:e},"Help topic loaded.",!0,r):{exitCode:0,stdout:e,stderr:""}}function IP(e,t){let n=e.filter(Boolean).join(" ").trim()||"help";return x({status:"not_found",reasonCode:"help_topic_not_found",topic:n,nextAction:"help",nextStep:"Run `skills-layer --help`, `skills-layer help full`, or `skills-layer <command> --help` for a supported command."},`Help topic not found: ${n}.`,t,"help_topic_not_found")}async function Hie(e,t,n){let r=O(e[0]??t.path,"validate requires a file or directory."),i=Tt(n.cwd,r);if(!await pr(i))return $U("validate",r,t,n);let o=(await ma({cwd:n.cwd,sourcePath:r,limits:yo})).files;o=await Kie({files:o,resolvedTarget:i,flags:t,backend:n});let s=nt(o),a={files:o,sourceIntakeContext:k(t.sourceIntakeContext),publicationStatus:k(t.publicationStatus),dependencyAuditStatus:k(t.dependencyAuditStatus),category:k(t.category),discloseSource:!!t.discloseSource},l;try{l=await D(n,"/api/v1/validation/preview",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(ie(a))})}catch(d){if(d instanceof Z&&d.status===422&&d.details)l=Ice(d.details);else throw d}let c=Wie({...l,license:s.license,licenseIssues:s.issues.filter(d=>d.code.startsWith("license_"))},o),u=c.valid===!1||L(c,"validation")?.valid===!1;return t.json?u?x({...gz(c,n.renderMode.detail,"validate"),nextAction:"validate",nextStep:"Fix the listed issues, then run validate again."},"Validation failed.",!0,"bundle_invalid"):R(c,"Validation complete.",!0,n,"validate"):{exitCode:u?1:0,stdout:Ule(c,r,n),stderr:""}}async function Kie(e){if(nt(e.files).license?.status==="verified"||e.flags.json||!e.backend.stdoutIsTty)return e.files;let n=await Mk({cwd:e.backend.cwd,files:e.files,skip:!1,interactive:!0,prompt:nU(e.backend)});if(n.selection.mode==="skip"||await e.backend.promptSelect("Apply this licence change to the local bundle?",[{value:"apply",label:"Apply the reviewed change"},{value:"cancel",label:"Cancel without changing files"}])!=="apply")return e.files;let o=(await Ja(e.resolvedTarget)).isDirectory()?e.resolvedTarget:Me(e.resolvedTarget);return await Jp({targetDir:o,files:H1(e.files,n.selection),confirmed:!0}),(await ma({cwd:e.backend.cwd,sourcePath:o})).files}function Wie(e,t){return{...e,evalReadiness:Hk(t)}}function Zie(e,t){let n=Jie(e);return Es({status:n?"not_run":"generated_only",skillSlug:t.skillSlug,version:t.version,artifactDigest:ct(e),...n?{evalPackDigest:n}:{},generatedAt:t.generatedAt,runnerVersion:So,counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})}function Jie(e){let t=e.find(n=>{let r=$n(n.path,e);return r.type==="evidence"&&typeof n.content=="string"&&(r.relativePath.startsWith("evals/")||r.relativePath.endsWith(".eval.json")||r.relativePath.endsWith(".eval.yaml"))});if(t?.content)try{return Rs(JSON.parse(t.content))}catch{return}}async function Yie(e,t,n){let r=O(e[0]??t.path,"preview-trigger requires a file or directory."),i=Tt(n.cwd,r);if(!await pr(i))return $U("preview-trigger",r,t,n);let o=(await ma({cwd:n.cwd,sourcePath:r,limits:yo})).files,s=await D(n,"/api/v1/validation/trigger-preview",{method:"POST",headers:V(n.apiKey),body:JSON.stringify({files:o,shouldTriggerPrompts:t.shouldTrigger,shouldNotTriggerPrompts:t.shouldNotTrigger,paraphrasePrompts:t.paraphrase})});return t.json?R(s,"Trigger preview complete.",!0,n):{exitCode:0,stdout:zle(s,r,n),stderr:""}}async function Xie(e,t,n){let r=e[0];if(["create","sessions","resume","inspect","answer","resources","resource-decide","tool-contract","draft","validate","eval","improve","revise","materialize","finalize"].includes(r??""))return await XB(r,e.slice(1),t,n);if(r==="init")return t.quick?await XB("create",e.slice(1),{...t,mode:"quick"},n):await eoe(e.slice(1),t,n);if(r==="rules")return await me("/api/v1/creator/rules",t,n,"Creator rules loaded.");if(r==="submissions")return await me("/api/v1/me/submissions",t,n,"Submissions loaded.",{authenticated:!0});if(r==="status"){let i=O(e[1],"creator status requires a skill slug.");try{return await me(`/api/v1/me/submissions/${encodeURIComponent(i)}/status`,t,n,"Submission status loaded.",{authenticated:!0})}catch(o){if(o instanceof Z&&o.status===404)return coe(i,t);throw o}}if(r==="charge-status"){let i=O(e[1],"creator charge-status requires a charge id.");return await me(`/api/v1/me/private-skill-charges/${encodeURIComponent(i)}`,t,n,"Charge status loaded.",{authenticated:!0})}if(r==="spaces")return await roe(e.slice(1),t,n);if(r==="submit")return await AP(e.slice(1),t,n,!1);if(r==="submit-version")return await AP(e.slice(1),t,n,!0);if(r==="check-slug"){let i=O(e[1],"creator check-slug requires a slug.");return await aoe(i,t,n)}if(r==="rename"){let i=O(e[1],"creator rename requires the current slug."),o=O(e[2],"creator rename requires the new slug."),s=QM("creator.rename",o,t);return s||await Li(`/api/v1/me/submissions/${encodeURIComponent(i)}/slug`,{nextSkillSlug:o},t,n,"Skill renamed.")}if(r==="pricing")return await doe(e,t,n);if(r==="update-listing"){let i=O(e[1],"creator update-listing requires a skill slug.");return await poe(i,t,n)}if(r==="visibility"){let i=O(e[1],"creator visibility requires a skill slug."),o=Oi("creator.visibility",t);if(o)return o;let s=k(t.visibility)??e[2],a=uc(s);if(!a||!Lu.includes(a))return x({status:"error",reasonCode:"invalid_visibility",skillSlug:i,visibility:s??null,acceptedValues:Lu,nextAction:"creator.visibility",nextStep:"Use --visibility private, public, or unlisted."},`Invalid creator visibility "${s??""}". Use one of: ${Lu.join(", ")}.`,t.json,"invalid_visibility");let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/visibility`,{method:"PATCH",headers:V(n.apiKey),body:JSON.stringify(ie({visibility:a,dryRun:t.dryRun}))});return gse(l)?x(l,hse(l,i),t.json,f(l,"reasonCode")??f(l,"status")):R(l,t.dryRun?"Visibility preview loaded.":"Visibility updated.",t.json,n)}if(r==="security-report"){let i=O(e[1],"creator security-report requires a skill slug."),o=eU("creator.security-report",t);if(o)return o;let s=Oi("creator.security-report",t);if(s)return s;let a=new URLSearchParams;Ke(a,"format",t.format),Ke(a,"version",t.version),Ke(a,"versionId",t.versionId);let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/security-report${Qe(a)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return t.json||t.verbose?R(l,"Creator security report loaded.",t.json,n):{exitCode:0,stdout:oce(l,i,n),stderr:""}}if(r==="rescan-security"){let i=O(e[1],"creator rescan-security requires a skill slug."),o=Oi("creator.rescan-security",t);if(o)return o;let s=await D(n,`/api/v1/me/submissions/${encodeURIComponent(i)}/security/rescan`,{method:"POST",headers:V(n.apiKey),body:JSON.stringify(ie(Ft(t,["version","versionId"])))});return t.json?R(s,"Security rescan requested.",!0,n):{exitCode:0,stdout:sce(s,i,n),stderr:""}}if(r==="provenance"){let i=O(e[1],"creator provenance requires a skill slug.");return await me(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership`,t,n,"Provenance loaded.",{authenticated:!0})}if(r==="claim"||r==="verify"||r==="dispute")return await foe(r,e,t,n);if(r==="issues"||r==="reviews"||r==="update-issue"||r==="moderate-review")return await koe(r,e,t,n);if(r==="analytics"){let i=O(e[1],"creator analytics requires a skill slug.");return await moe(i,t,n)}if(r==="delist"||r==="relist"){let i=O(e[1],`creator ${r} requires a skill slug.`),o=k(t.reason)??(r==="relist"?"Creator relisted skill":"");return o.trim().length<3?E("creator delist requires --reason (at least 3 characters).",t.json):await Li(`/api/v1/me/submissions/${encodeURIComponent(i)}`,{lifecycle:r==="delist"?"delisted":"active",reason:o},t,n,`${i} ${r==="delist"?"delisted":"relisted"}; existing buyers keep access.`)}if(r==="earnings")return await me("/api/v1/me/earnings",t,n,"Creator earnings loaded.",{authenticated:!0});if(r==="payout-profile")return k(t.country)?await iM(t,n):await goe(t,n);if(r==="payout-link")return await iM(t,n);if(r==="payouts")return await me("/api/v1/me/payouts",t,n,"Creator payouts loaded.",{authenticated:!0});if(r==="withdraw"){if(!k(t.amountCents))return E("creator withdraw requires --amount-cents.",t.json);let i=Ni(t.amountCents,"--amount-cents","amountCents","invalid_amount_cents",t,{minimum:1});if(i.failure)return i.failure;let o=k(t.idempotencyKey)??ole();if(t.json&&!k(t.mfaCode))return x({status:"blocked",reasonCode:"mfa_step_up_required",nextStep:"Run skills-layer creator withdraw --amount-cents <amount> in a human terminal to enter MFA and confirm the withdrawal."},"A fresh authenticator code is required.",!0,"mfa_step_up_required");if(t.json||!n.stdoutIsTty)return x({status:"blocked",reasonCode:"payout_human_confirmation_required",nextAction:"creator.withdraw",nextStep:"Use an interactive terminal. MCP returns a browser handoff, and automation credentials cannot withdraw."},"Creator withdrawal requires an interactive human confirmation. Use an interactive terminal; MCP returns a browser handoff and automation credentials cannot withdraw.",t.json,"payout_human_confirmation_required");let s=sU(t,n),a=ie({amountCents:i.value,reason:k(t.reason)}),l={...V(n.apiKey),"idempotency-key":o},c=await s("/api/v1/me/payouts",{method:"POST",headers:l,body:JSON.stringify(a)});if(c.status==="requested")return R(c,"Withdrawal requested.",!1,n);if(c.status!=="confirmation_required"||typeof c.confirmationId!="string"||typeof c.confirmationToken!="string"||typeof c.confirmationPhrase!="string")throw new Error("The payout service did not return a valid action-bound confirmation challenge.");let u=c.impact&&typeof c.impact=="object"?c.impact:{};if(await n.promptText(`Withdrawal impact: ${String(u.amountCents??i.value)} ${String(u.currency??"usd").toUpperCase()}, remaining withdrawable balance ${String(u.withdrawableAfterCents??"unknown")} cents.
|
|
2140
|
+
Type exactly "${c.confirmationPhrase}" to confirm: `)!==c.confirmationPhrase)return E("Withdrawal cancelled; the confirmation phrase did not match.",!1);let p=await s("/api/v1/me/payouts",{method:"POST",headers:l,body:JSON.stringify({...a,confirmationId:c.confirmationId,confirmationToken:c.confirmationToken,confirmationPhrase:c.confirmationPhrase})});return R(p,"Withdrawal requested.",!1,n)}return r==="source"?await _oe(e.slice(1),t,n):E(`Unknown creator command "${r??""}".`,t.json)}var YB="\0derived";function PP(e,t){return`${e}-${Ue("sha256").update(JSON.stringify(t)).digest("hex").slice(0,32)}`}async function XB(e,t,n,r){let i=k(n.idempotencyKey)??(e==="create"?`creator-${Ge(12).toString("hex")}`:YB),o=k(n.sessionId)??t[0],s=k(n.expectedRevision),a=s===void 0?void 0:Number(s);if(s!==void 0&&(!Number.isInteger(a)||Number(a)<1))return E("--expected-revision must be a positive integer.",n.json);let l=g=>{if(!o)throw new Error(`creator ${g} requires a session id.`);if(a===void 0)throw new Error(`creator ${g} requires --expected-revision.`);return{sessionId:o,expectedRevision:a,idempotencyKey:i}},c,u="POST",d;if(e==="create"){let g=k(n.skill)??t[0],y=k(n.outcome)??k(n.description),v=k(n.mode)??"guided";v==="guided"&&!n.json&&r.stdoutIsTty&&(g||(g=(await r.promptText(`Choose a unique kebab-case skill name:
|
|
2141
2141
|
> `)).trim()),y||(y=(await r.promptText(`What outcome should this skill reliably produce?
|
|
2142
|
-
> `)).trim())),d=ie({idempotencyKey:i,mode:v,outcome:y,skillSlug:g,description:k(n.description),license:k(n.license),importedCandidateId:k(n.importedCandidateId)}),c="/api/v1/creator/sessions"}else if(e==="sessions")c="/api/v1/creator/sessions",u="GET";else if(e==="resume"){if(!o)return
|
|
2143
|
-
> `))}else return
|
|
2142
|
+
> `)).trim())),d=ie({idempotencyKey:i,mode:v,outcome:y,skillSlug:g,description:k(n.description),license:k(n.license),importedCandidateId:k(n.importedCandidateId)}),c="/api/v1/creator/sessions"}else if(e==="sessions")c="/api/v1/creator/sessions",u="GET";else if(e==="resume"){if(!o)return E("creator resume requires a skill slug or session id.",n.json);c=`/api/v1/creator/sessions/resume/${encodeURIComponent(o)}`,u="GET"}else if(e==="inspect"){if(!o)return E("creator inspect requires a session id.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(o)}`,u="GET"}else if(e==="answer"){let g=l("answer"),y=k(n.questionId);if(y){let v;if(n.answerJson!==void 0)v=ln(n.answerJson,"answer-json");else if(!n.json&&r.stdoutIsTty){let b=await D(r,`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}`,{headers:re(r.apiKey,r.authBlockedMessage)}),w=qa(b);if(!w)throw new Error("Creator response did not include the canonical interview turn");if(!w.currentQuestion||w.currentQuestion.id!==y)return E("The requested question is not the session's current canonical question.",n.json);v=zp(y,await r.promptText(`${w.currentQuestion.prompt}
|
|
2143
|
+
> `))}else return E("creator answer --question-id requires --answer-json outside an interactive terminal.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/turn-answers`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,questionId:y,answer:v}}else if(n.answers!==void 0){let v=ln(n.answers,"answers");if(!v||typeof v!="object"||Array.isArray(v))return E("creator answer requires --answers with a JSON object.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/answers`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,...k(n.skill)?{skillSlug:k(n.skill)}:{},answers:v}}else{if(n.json||!r.stdoutIsTty)return E("creator answer requires --question-id and --answer-json outside an interactive terminal.",n.json);let v=await D(r,`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}`,{headers:re(r.apiKey,r.authBlockedMessage)}),b;!h1(v)&&!k(n.skill)&&(b=(await r.promptText(`Choose a unique kebab-case skill name:
|
|
2144
2144
|
> `)).trim());let w=qa(v,!1);if(w?.currentQuestion){let _=zp(w.currentQuestion.id,await r.promptText(`${w.currentQuestion.prompt}
|
|
2145
|
-
> `));c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/turn-answers`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,questionId:w.currentQuestion.id,answer:_,...k(n.skill)??b?{skillSlug:k(n.skill)??b}:{}}}else{let _=await m1({suggestedDomain:g1(v),promptText:r.promptText});c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/answers`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,answers:_,...k(n.skill)??b?{skillSlug:k(n.skill)??b}:{}}}}}else if(e==="resources"){let g=l("resources"),y=n.suppliedResourcesJson===void 0?void 0:ln(n.suppliedResourcesJson,"supplied-resources-json");if(y!==void 0&&!Array.isArray(y))return
|
|
2145
|
+
> `));c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/turn-answers`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,questionId:w.currentQuestion.id,answer:_,...k(n.skill)??b?{skillSlug:k(n.skill)??b}:{}}}else{let _=await m1({suggestedDomain:g1(v),promptText:r.promptText});c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/answers`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,answers:_,...k(n.skill)??b?{skillSlug:k(n.skill)??b}:{}}}}}else if(e==="resources"){let g=l("resources"),y=n.suppliedResourcesJson===void 0?void 0:ln(n.suppliedResourcesJson,"supplied-resources-json");if(y!==void 0&&!Array.isArray(y))return E("creator resources --supplied-resources-json must be a JSON array.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/resource-plan`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,...y?{suppliedResources:y}:{}}}else if(e==="resource-decide"){let g=l("resource-decide"),y=ln(n.decisionsJson,"decisions-json");if(!Array.isArray(y))return E("creator resource-decide requires --decisions-json with a JSON array.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/resource-decisions`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,decisions:y}}else if(e==="tool-contract"){let g=l("tool-contract"),y=ln(n.patchJson,"patch-json");if(!y||typeof y!="object"||Array.isArray(y))return E("creator tool-contract requires --patch-json with a JSON object.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/tool-contract`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,patch:y}}else if(e==="draft"){let g=l("draft"),y=!!n.apply;if(!n.dryRun&&!y)return E("creator draft requires --dry-run or --apply.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/${y?"draft-apply":"draft-plan"}`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,...y?{planDigest:O(k(n.planDigest),"creator draft --apply requires --plan-digest.")}:{}}}else if(e==="validate"){let g=l("validate");c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/validate`,d={expectedRevision:g.expectedRevision,idempotencyKey:i}}else if(e==="eval"){let g=l("eval"),y=n.callerCapabilitiesJson===void 0?void 0:ln(n.callerCapabilitiesJson,"caller-capabilities-json");if(y!==void 0&&(!y||typeof y!="object"||Array.isArray(y)))return E("creator eval --caller-capabilities-json must be a JSON object.",n.json);let v=n.observationsJson===void 0?void 0:ln(n.observationsJson,"observations-json");if(v!==void 0&&!Array.isArray(v))return E("creator eval --observations-json must be a JSON array.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/evals`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,...y?{callerCapabilities:y}:{},...k(n.challengeDigest)?{challengeDigest:k(n.challengeDigest)}:{},...v?{observations:v}:{}}}else if(e==="improve"){let g=l("improve"),y=!!n.apply;if(y&&!k(n.planDigest))return E("creator improve --apply requires --plan-digest.",n.json);let v=n.additionalEvidenceJson===void 0||y?void 0:ln(n.additionalEvidenceJson,"additional-evidence-json");if(v!==void 0&&!Array.isArray(v))return E("creator improve --additional-evidence-json must be a JSON array.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/improvements${y?"/apply":""}`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,...y?{planDigest:k(n.planDigest)}:{},...v?{additionalEvidence:v}:{}}}else if(e==="revise"){let g=l("revise"),y=ln(n.patchJson,"patch-json");if(!y||typeof y!="object"||Array.isArray(y)||!Array.isArray(y.files)||y.files.length===0)return E("creator revise --patch-json must contain a non-empty files array.",n.json);let v=y,b=n.dryRun===!0;if(!b&&!k(n.planDigest))return E("creator revise apply requires --plan-digest from creator revise --dry-run.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/revisions${b?"/preview":""}`,d={expectedRevision:g.expectedRevision,...b?{}:{idempotencyKey:i,planDigest:k(n.planDigest)},files:v.files,...typeof v.skillSlug=="string"?{skillSlug:v.skillSlug}:{}}}else if(e==="materialize"){if(!o)return E("creator materialize requires a session id.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(o)}/materialize`}else{let g=l("finalize"),y=Ni(n.priceCents,"--price-cents","priceCents","invalid_price_cents",n,{minimum:0});if(y.failure)return y.failure;let v=n.tagsJson===void 0?void 0:ln(n.tagsJson,"tags-json");if(v!==void 0&&(!Array.isArray(v)||!v.every(b=>typeof b=="string"&&b.trim().length>0)))return E("creator finalize --tags-json must be a JSON array of non-empty strings.",n.json);c=`/api/v1/creator/sessions/${encodeURIComponent(g.sessionId)}/finalize`,d={expectedRevision:g.expectedRevision,idempotencyKey:i,version:O(k(n.version),"creator finalize requires --version."),...k(n.visibility)?{visibility:k(n.visibility)}:{},...y.value!==void 0?{priceCents:y.value}:{},...k(n.category)?{category:k(n.category)}:{},...v?{tags:v}:{},...n.attestRights?{attestRights:!0,rightsBasis:k(n.rightsBasis),distributionScope:k(n.distributionScope),sourceReference:k(n.sourceReference)}:{}}}d?.idempotencyKey===YB&&(d.idempotencyKey=PP("creator",{subcommand:e,endpoint:c,body:{...d,idempotencyKey:null}}));let p=await D(r,c,{method:u,headers:u==="GET"?re(r.apiKey,r.authBlockedMessage):V(r.apiKey),...d?{body:JSON.stringify(d)}:{}});(e==="create"||e==="resume")&&!n.json&&r.stdoutIsTty&&qa(p,!1)&&(p=await Qie(p,r));let m=e==="create"&&n.quick?(k(n.skill)??t[0])?.trim():void 0;if(e==="materialize"||!!m){let g;try{g=O1(p.data,m)}catch(w){let _=w;return await Qp({event:Xp({osFamily:Yp(r.platform),nodeMajor:Number(process.versions.node.split(".")[0]),operation:"materialize",outcome:"failed",operationId:`creator_materialize_failed_${Ue("sha256").update(c).update("\0").update(m??"unknown").digest("hex").slice(0,24)}`,occurredAt:r.now()}),publish:async C=>{await D(r,"/api/v1/creator/platform-telemetry",{method:"POST",headers:V(r.apiKey),body:JSON.stringify(C)})}}),x(p,_.message,n.json,_.reasonCode)}let y=k(n.dir)?Tt(r.cwd,k(n.dir)):K(r.paths.stateDir,"authoring",g.skillSlug),v=`creator_materialize_${Ue("sha256").update(y).update("\0").update(g.skillSlug).digest("hex").slice(0,24)}`,b;try{b=await Jp({targetDir:y,files:g.files,confirmed:n.confirmed})}catch(w){return await Qp({event:Xp({osFamily:Yp(r.platform),nodeMajor:Number(process.versions.node.split(".")[0]),operation:"materialize",outcome:"failed",operationId:`${v}:failed`,occurredAt:r.now()}),publish:async _=>{await D(r,"/api/v1/creator/platform-telemetry",{method:"POST",headers:V(r.apiKey),body:JSON.stringify(_)})}}),E(ve(w),n.json)}return b.status==="confirmation_required"?x({...p,materialization:b},rU(b.plan),n.json,"scaffold_overwrite_confirmation_required"):(await Qp({event:Xp({osFamily:Yp(r.platform),nodeMajor:Number(process.versions.node.split(".")[0]),operation:"materialize",outcome:"succeeded",operationId:v,occurredAt:r.now()}),publish:async w=>{await D(r,"/api/v1/creator/platform-telemetry",{method:"POST",headers:V(r.apiKey),body:JSON.stringify(w)})}}),R({...p,materialization:b},`Creator workspace materialized at ${y}.`,n.json,r))}return R(p,typeof p.summary=="string"?p.summary:`Creator ${e} completed.`,n.json,r)}async function Qie(e,t){let n=e,r=null;for(;;){await QB(n,t,!1);let i=qa(n);if(!i)throw new Error("Creator response did not include the canonical interview turn");if(!i.currentQuestion)try{let u=await D(t,`/api/v1/creator/sessions/${encodeURIComponent(String(n.sessionId))}/resource-plan`,{method:"POST",headers:V(t.apiKey),body:JSON.stringify({expectedRevision:n.revision,idempotencyKey:PP("creator-resource",{sessionId:n.sessionId,revision:n.revision})})});return await QB({...n,revision:u.revision},t,!0),u}catch(u){throw uP(u,n)}let o=i.confirmationSummary?`Review the normalized interview:
|
|
2146
2146
|
${JSON.stringify(i.confirmationSummary,null,2)}
|
|
2147
2147
|
`:"",s=i.currentQuestion.suggestedAnswer?`
|
|
2148
2148
|
Suggested answer: ${i.currentQuestion.suggestedAnswer}`:"",a=r?`Previous answer was not accepted: ${r}
|
|
2149
2149
|
`:"",l;try{l=await t.promptText(`${o}${a}[${i.progress.questionNumber}/${i.progress.maximumQuestions}] ${i.currentQuestion.prompt}${s}
|
|
2150
2150
|
Why: ${i.currentQuestion.whyAsked}
|
|
2151
|
-
> `)}catch(u){throw uP(u,n)}let c;try{c=zp(i.currentQuestion.id,l)}catch(u){r=ve(u);continue}try{n=await D(t,`/api/v1/creator/sessions/${encodeURIComponent(String(n.sessionId))}/turn-answers`,{method:"POST",headers:V(t.apiKey),body:JSON.stringify({expectedRevision:n.revision,idempotencyKey:PP("creator-turn",{sessionId:n.sessionId,revision:n.revision,questionId:i.currentQuestion.id,answer:c}),questionId:i.currentQuestion.id,answer:c})}),r=null}catch(u){if(u instanceof Z&&u.status===422){r=ve(u);continue}throw uP(u,n)}}}async function QB(e,t,n){await Ve(K(t.paths.stateDir,"creator-resume.json"),{version:1,baseUrl:t.baseUrl,sessionId:String(e.sessionId),skillSlug:qa(e,!1)?.skillSlug??null,revision:e.revision,completed:n,savedAt:t.now()})}function uP(e,t){let n=qa(t,!1)?.skillSlug||String(t.sessionId),r=e instanceof Z&&e.status===409?" The server revision is authoritative; reload it before answering again.":"";return new Error(`${ve(e)}${r} Resume with skills-layer creator resume ${n}.`)}function qa(e,t=!0){let n=e.data,r=n&&typeof n=="object"&&!Array.isArray(n)?n.turn:null;if(!r||typeof r!="object"||Array.isArray(r)){if(t)throw new Error("Creator response did not include the canonical interview turn");return null}return r}async function eoe(e,t,n){let r=k(t.skill)??e[0]??"my-skill",i=QM("creator.init",r,t);if(i)return i;let o=k(t.dir)?Tt(n.cwd,k(t.dir)):K(n.paths.stateDir,"authoring",r),s;try{s=d1(k(t.type))}catch(y){return
|
|
2152
|
-
`)}async function pr(e){try{return await zM(e),!0}catch{return!1}}function iU(e){return e.attestRights?{attestRights:!0,rightsBasis:k(e.rightsBasis)??"self_authored",distributionScope:k(e.distributionScope)??"commercial_distribution",rightsDeclarationVersion:Hj}:{}}async function AP(e,t,n,r){let i=k(t.visibility);if(i){let P=uc(i);if(!P||!Lu.includes(P))return Nr(r?"creator.submit-version":"creator.submit","visibility",i,Lu,t,"invalid_visibility")}let o=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(o.failure)return o.failure;let s=k(t.spacePack),a=s===void 0?void 0:oc(s);if(a===null)return Nr(r?"creator.submit-version":"creator.submit","spacePack",s,["5","10","20","50"],t,"invalid_private_skill_space_pack","space-pack");let l=k(t.creatorSessionId);if(l){let P=r?O(k(t.skill)??e[0],"creator submit-version with --creator-session-id requires a skill slug."):null,N=r?{creatorSessionId:l,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",...t.dryRun?{dryRun:!0}:{}}:{creatorSessionId:l,...t.dryRun?{dryRun:!0}:{},...a?{privateSkillSpacePack:a}:{}},T=r?`/api/v1/me/submissions/${encodeURIComponent(P)}/versions`:"/api/v1/me/submissions",X=await D(n,T,{method:"POST",headers:eM(n,t.dryRun?null:{path:T,creatorSessionId:l}),body:JSON.stringify(N)});return tM(X,t,n)??A(X,t.dryRun?"Submission preview ready.":X.status==="submission_incomplete"?`Creator session submission is incomplete. ${f(X,"nextStep")??"Retry this session submission to complete finalization."}`:"Finalized Creator session submitted.",t.json,n)}let c=r?O(k(t.skill)??e[0],"creator submit-version requires a skill slug."):k(t.skill),u=O(k(t.source)??(r?e[1]:e[0])??t.path,`creator ${r?"submit-version":"submit"} requires a <path-or-source> or --source <source>.`),d=await Hu(u,n.cwd);if(t.list)return await ioe(u,d,c,t,n);let p=Oi(r?"creator.submit-version":"creator.submit",t);if(p)return p;if(!d&&!zu(u)&&(xz(u)||/^(?:github|gitlab):/iu.test(u)))return ooe(u,t);let m=d?.files??(await ma({cwd:n.cwd,sourcePath:u,limits:yo})).files;if(!r&&!t.dryRun){let P=await soe(m,t,n);if(P)return P}if(t.dryRun&&dg(m))return toe(m,{slug:c,flags:t,backend:n});let h=dg(m)?await xC({baseUrl:n.baseUrl,apiKey:n.apiKey,fetchFn:n.fetchFn,files:m}):null,g=ie({...h?{hydrationManifestId:h.manifestId}:{files:m},version:k(t.version),dryRun:t.dryRun,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",evalSummary:Zie(m,{skillSlug:c??tA(m)??"unknown",version:k(t.version)??"0.0.0",generatedAt:n.now()}),replaceUnpublished:r&&t.replaceUnpublished===!0?!0:void 0,priceCents:o.value,privateSkillSpacePack:a,...iU(t),...d?{sourceMetadata:d.sourceMetadata}:{},...Ft(t,["displayName","skillType","category","visibility","source","skill"])}),y=r&&c?`/api/v1/me/submissions/${encodeURIComponent(c)}/versions`:"/api/v1/me/submissions",v=await D(n,y,{method:"POST",headers:eM(n,t.dryRun?null:{path:y,request:g,files:m}),body:JSON.stringify(g)});if(t.json||t.noOpen||v.status!=="checkout_required"||typeof v.checkoutUrl!="string"||typeof v.chargeId!="string")return tM(v,t,n)??A(v,t.dryRun?"Submission preview ready.":r?"Version submitted.":"Submission uploaded.",t.json,n);let b=L(v,"spacePack"),w=b?oc(b.code):null;n.emitInfo(w?`No private skill space is left. Opening checkout for ${Bp(w).label} (${Bp(w).displayPrice}); other packs: --space-pack 5|10|20|50. Complete the payment in your browser, then come back here.`:"Opening payment setup for skill submission. Complete the payment in your browser, then come back here."),await n.openUrl(v.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${v.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let C=await ele(v.chargeId,n);return fe(C)?C:C.status!=="submitted"?A({...v,chargeStatus:C.status},`Payment is still ${C.status}. You can rerun \`skills-layer creator charge-status ${v.chargeId}\` to continue tracking it.`,t.json,n):A(C,r?"Version submitted.":"Submission uploaded.",t.json,n)}function eM(e,t){let n=V(e.apiKey);if(!t)return n;let{hydrationManifestId:r,files:i,evalSummary:o,...s}=t.request??{},a=t.files?Ue("sha256").update(JSON.stringify(t.files.map(c=>[c.path,c.content??null,c.contentBase64??null]))).digest("hex"):null,l=Ue("sha256").update(JSON.stringify({path:t.path,creatorSessionId:t.creatorSessionId??null,request:s,bundleDigest:a})).digest("hex");return{...n,"idempotency-key":`cli-submit-${l.slice(0,48)}`}}function tM(e,t,n){if(e.status!=="checkout_required"||typeof e.checkoutUrl!="string"||typeof e.chargeId!="string")return null;let r=`Open ${e.checkoutUrl} to complete payment, then run \`skills-layer creator charge-status ${e.chargeId}\` to confirm the submission.`;return A({...e,paymentRequired:!0,checkoutUrl:e.checkoutUrl,chargeId:e.chargeId,nextAction:"creator.charge-status",nextStep:r},`Payment required to finish: ${r}`,t.json,n)}function toe(e,t){let n="creator.submit",r=nt(e),i=e.reduce((l,c)=>l+cs(c),0),o=t.slug??tA(e),s=["skill_name_availability","security_review","moderation","pricing_and_checkout","eval_evidence"],a=ie({status:r.valid?"ready":"blocked",reasonCode:r.valid?"local_preview_only":"invalid_bundle",dryRun:!0,previewMode:"local",operation:n,uploaded:!1,skillSlug:o,version:k(t.flags.version),bundle:{fileCount:e.length,totalBytes:i,transport:"source_hydration",artifactDigest:ct(e)},localChecks:[{check:"bundle_size",status:"passed"},{check:"paths",status:"passed"},{check:"secrets",status:"passed"},{check:"manifest",status:r.valid?"passed":"failed"}],serverChecks:{status:"not_run",checks:s},why:"The bundle exceeds the 2 MiB inline request limit, so the dry run previewed it locally and uploaded nothing.",validation:r,nextAction:r.valid?n:"validate",nextStep:r.valid?`Re-run without --dry-run to upload and submit. Server-only checks (${s.join(", ")}) run during the real submit.`:"Fix the bundle issues before submitting again."});return A(a,r.valid?`Local submission preview ready (${e.length} files, ${i} bytes; nothing uploaded). Server-only checks run on the real submit: ${s.join(", ")}.`:"Local submission preview blocked: the bundle does not satisfy the creator validation rules. Nothing was uploaded.",t.flags.json,t.backend)}var noe="Use `skills-layer creator spaces` or `skills-layer creator spaces buy --pack 5|10|20|50`.";function nM(e){if(e.status==="community_unlimited")return"Community edition supports unlimited private skills.";let t=n=>typeof e[n]=="number"?e[n]:0;return`Private skill spaces: ${t("availablePrivateSkillSpaces")} available of ${t("totalPrivateSkillSpaces")} (${t("activePrivateSkills")} active private skills; free ${t("freePrivateSkillSpacesUsed")} used, ${t("freePrivateSkillSpacesRemaining")} left; purchased ${t("purchasedPrivateSkillSpaces")}, ${t("purchasedPrivateSkillSpacesUsed")} used). Buy more with \`skills-layer creator spaces buy --pack 5|10|20|50\`: ${sc}.`}async function roe(e,t,n){let r=e[0];if(r===void 0||r==="status"){let u=await D(n,"/api/v1/me/private-skill-spaces",{headers:re(n.apiKey,n.authBlockedMessage)});return A(u,nM(u),t.json,n)}if(r!=="buy")return R(`Unknown creator spaces action "${r}". ${noe}`,t.json);let i=k(t.pack)??e[1],o=i===void 0?void 0:oc(i);if(o===null)return Nr("creator.spaces.buy","pack",i,["5","10","20","50"],t,"invalid_private_skill_space_pack","pack");let s=await D(n,"/api/v1/me/private-skill-spaces/checkout",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(o?{privateSkillSpacePack:o}:{})});if(s.status!=="checkout_required"||typeof s.checkoutUrl!="string")return A(s,nM(s),t.json,n);let a=Bp(oc(L(s,"spacePack")?.code)??"spaces_5"),l=`Checkout for ${a.label} (${a.displayPrice}) is ready. Complete the payment in your browser, then run \`skills-layer creator spaces\` to see the credited spaces.`;return t.json||t.noOpen?A(s,`${l} Checkout URL: ${s.checkoutUrl}`,t.json,n):(await n.openUrl(s.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${s.checkoutUrl}`),A(s,l,t.json,n))}async function ioe(e,t,n,r,i){if(t)return A(rM(aA(e,t,n)),"Source skills loaded.",r.json,i);let o=await xU(i,e,{source:e,skillSlug:n,listOnly:!0,operation:"creator.submit"},r);return o.kind==="failure"?o.result:A(rM(o.inspection),"Source skills loaded.",r.json,i)}function rM(e){return{...e,sourceSubmissionSupported:!0}}function ooe(e,t){let r=`skills-layer source connection start --provider ${PU(e)} --source ${e} --visibility private --provenance-intent private_source_import`;return x({status:"source_connection_required",reasonCode:"source_connection_required",source:e,nextAction:"source.connection.start",nextStep:r},`Creator submit can list ${e} safely, but publishing from a remote source requires a source connection. Run \`${r}\`.`,t.json,"source_connection_required")}async function soe(e,t,n){let r=k(t.skill)??tA(e);if(!r)return null;let i;try{i=await D(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(r)}`,{headers:re(n.apiKey,n.authBlockedMessage)})}catch(o){if(o instanceof Z&&o.status===404)return oU(r,t);throw o}if(i.available===!1||f(i,"reasonCode")==="unavailable"||f(i,"reasonCode")==="reserved"){let o=f(i,"assignedSlug"),s=ie({status:"duplicate_candidate",reasonCode:f(i,"reasonCode")??"slug_unavailable",requestedSlug:r,assignedSlug:o,nextAction:"creator.status",nextStep:`Run \`skills-layer creator status ${r}\`, \`skills-layer creator submissions\`, or submit a new version of the existing skill instead of creating a duplicate listing.`});return x(s,`A public skill slug "${r}" already exists or is not available. Run \`skills-layer creator status ${r}\`, check your creator submissions, or submit a new version instead of creating a duplicate listing.`,t.json,f(s,"reasonCode"))}return null}async function aoe(e,t,n){try{let r=await D(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return A(loe(r),"Slug status loaded.",t.json,n)}catch(r){if(r instanceof Z&&r.status===404)return oU(e,t);throw r}}function oU(e,t){let n={status:"slug_check_unavailable",reasonCode:"slug_check_route_unavailable",requestedSlug:e,nextAction:"creator.status",nextStep:`Slug availability could not be checked on the selected backend. Run \`skills-layer creator submissions\`, \`skills-layer creator status ${e}\`, or retry after selecting a compatible Skills Layer backend.`};return x(n,`Slug availability could not be checked for ${e} on the selected backend. Run \`skills-layer creator submissions\` or retry after selecting a compatible Skills Layer backend.`,t.json,"slug_check_route_unavailable")}function loe(e){let t=e.available===!0,n=f(e,"assignedSlug");if(t)return ie({requestedSlug:f(e,"requestedSlug"),available:!0,reasonCode:f(e,"reasonCode")??"available",assignedSlug:n});let r=L(e,"slugAssignment"),i=Array.isArray(r?.candidateSlugs)?r.candidateSlugs.filter(o=>typeof o=="string").slice(0,3):void 0;return ie({...e,...r?{slugAssignment:{...r,...i?{candidateSlugs:i}:{}}}:{},...i?{candidateSlugs:i}:{}})}function coe(e,t){return x({status:"not_submitted",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submit",nextStep:"Run `skills-layer creator submit <path> --dry-run` to validate a local skill before submitting it, or run `skills-layer creator submissions` to see your existing submissions."},`No creator submission was found for ${e}. Run \`skills-layer creator submit <path> --dry-run\` before checking status.`,t.json,"creator_submission_not_found")}function tA(e){let t=e.find(r=>r.path.split("/").pop()?.toLowerCase()==="skill.md");if(!t)return;let n=/^---\s*\n(?<body>[\s\S]*?)\n---/u.exec(t.content??"")?.groups?.body?.split(/\r?\n/u).map(r=>r.match(/^name\s*:\s*(?<name>.+?)\s*$/u)?.groups?.name?.trim().replace(/^["']|["']$/gu,"")).find(r=>!!r);return uoe(n??ot(Me(t.path)))}function uoe(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function doe(e,t,n){let r=O(e[1],"creator pricing requires a skill slug."),i=Oi("creator.pricing",t);if(i)return i;let o=new URLSearchParams;if(Ke(o,"version",t.version),!t.priceCents)return await me(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(s.failure)return s.failure;let a=s.value??0;if(t.dryRun){o.set("dryRun","true"),o.set("priceCents",String(a));let d=await D(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return d.dryRun!==!0||d.status!=="preview"?R("This backend does not support read-only pricing previews. Upgrade the backend before retrying.",t.json):A(d,"Pricing preview; the live price is unchanged.",t.json,n)}let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,{headers:re(n.apiKey,n.authBlockedMessage)}),c=J(l,"priceCents")??0,u=J(l,"revision");if(!u||!Number.isSafeInteger(u)||u<1)return R("Pricing authority did not return a valid revision.",t.json);if(a>c&&!t.confirmed){let d=ie({status:"pending_approval",reasonCode:"price_increase_confirmation_required",skillSlug:r,version:f(l,"version"),currentPriceCents:c,requestedPriceCents:a,currency:f(l,"currency")??"usd",nextStep:"Review the old and new USD prices, then rerun with --yes."});return A(d,"Pricing change requires explicit confirmation.",t.json,n)}return await Li(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing`,{priceCents:a,confirmPriceIncrease:t.confirmed,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:k(t.version),expectedRevision:u,idempotencyKey:k(t.idempotencyKey)?.trim()||`pricing-${Ge(12).toString("hex")}`,reason:"Creator changed the version list price through CLI.",...iU(t)},t,n,"Pricing updated.")}async function poe(e,t,n){let r=Mn("creator.update-listing","listingStatus",t.listingStatus,kie,t,"invalid_listing_status","listing-status");if(r)return r;try{return await Li(`/api/v1/me/submissions/${encodeURIComponent(e)}`,Ft(t,["displayName","summary","description","category","skillType","license","listingStatus"]),t,n,"Listing updated.")}catch(i){if(i instanceof Z&&i.status===404){let o={status:"listing_not_found_or_not_editable",reasonCode:"creator_listing_not_found_or_not_owned",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see editable listings, or \`skills-layer show ${e}\` to inspect the public catalog entry.`};return x(o,`No editable creator listing was found for ${e}. Run \`skills-layer creator submissions\` to see listings you can update.`,t.json,"creator_listing_not_found_or_not_owned")}throw i}}async function foe(e,t,n,r){let i=O(t[1],`creator ${e} requires a skill slug.`);if(e==="claim"){let o=Mn("creator.claim","requestedRole",n.requestedRole,vie,n,"invalid_requested_role","requested-role");if(o)return o}try{if(e==="claim")return await Oe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/claim`,Ft(n,["requestedRole","message"]),n,r,"Ownership claim submitted.");if(e==="verify"){let o=O(n.claimId,"creator verify requires --claim-id.");return await Oe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/verify`,{claimId:o},n,r,"Ownership claim verified.")}return O(n.message,"creator dispute requires --message."),await Oe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/dispute`,Ft(n,["message"]),n,r,"Ownership dispute submitted.")}catch(o){if(o instanceof Z&&o.status===404){let s={status:"ownership_action_unavailable",reasonCode:e==="claim"?"skill_not_found_or_not_claimable":"ownership_claim_not_found",skillSlug:i,requestedRole:k(n.requestedRole),nextAction:e==="claim"?"search":"creator.claim",nextStep:e==="claim"?`Run \`skills-layer search ${i}\`, \`skills-layer show ${i}\`, or submit/source-install the skill before claiming it.`:`Run \`skills-layer creator claim ${i}\` to start a new claim if the skill is claimable.`};return x(s,e==="claim"?`No claimable skill was found for ${i}. Search or show the skill first, then claim it only when it exists and is claimable.`:`No matching ownership claim was found for ${i}. Start a new claim if the skill is claimable.`,n.json,f(s,"reasonCode")??"ownership_action_unavailable")}throw o}}async function moe(e,t,n){try{return await me(`/api/v1/me/submissions/${encodeURIComponent(e)}/analytics`,t,n,"Analytics loaded.",{authenticated:!0})}catch(r){if(r instanceof Z&&r.status===404){let i={status:"no_creator_submission",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see skills you own, \`skills-layer show ${e}\` to inspect the catalog listing, or \`skills-layer creator claim ${e}\` if it is a claimable public-source skill.`};return x(i,`No creator-owned analytics submission was found for ${e}. Run \`skills-layer creator submissions\`, \`skills-layer show ${e}\`, or \`skills-layer creator claim ${e}\` if you should manage it.`,t.json,"creator_submission_not_found")}throw r}}async function goe(e,t){let n=await D(t,"/api/v1/me/payout-profile",{headers:re(t.apiKey,t.authBlockedMessage)});return A(n,"Creator payout profile loaded.",e.json,t)}function sU(e,t){let n={};return(r,i)=>TA({session:n,code:k(e.mfaCode),interactive:!e.json&&!t.nonInteractive&&t.stdoutIsTty,promptSecret:t.promptSecret,verify:async o=>{let s=await D(t,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({purpose:"creator_payout",code:o})});return O(s.stepUpGrant,"MFA verification did not return a step-up grant.")},request:o=>{let s=new Headers(i.headers);return o&&s.set("x-mfa-step-up-grant",o),D(t,r,{...i,headers:s})}})}async function iM(e,t){let n=hoe(k(e.mode));if(e.mode&&n===null)return R("creator payout-link --mode must be account_onboarding|account_update|onboarding|update.",e.json);let r;try{r=await sU(e,t)("/api/v1/me/payout-profile/link",{method:"POST",headers:V(t.apiKey),body:JSON.stringify(ie({...n?{mode:n}:{},country:k(e.country)}))})}catch(o){if(o instanceof Z&&voe(o))return x({status:"payout_setup_already_submitted",reasonCode:"payout_update_link_unavailable",nextAction:"creator.payout-profile",nextStep:"Run `skills-layer creator payout-profile` to confirm readiness, then use `skills-layer creator earnings` or `skills-layer creator withdraw --amount-cents <amount>`."},"Payout setup is already submitted for this account. Run `skills-layer creator payout-profile` to confirm readiness before requesting a withdrawal.",e.json,"payout_update_link_unavailable");throw o}let i=sz(r);return i&&yoe(e)&&e.showUrl!==!0&&(t.emitInfo("Opening payout setup in your browser. Finish the flow there, then come back here."),await t.openUrl(i)||t.emitInfo(`Open this payout setup URL manually to continue: ${i}`)),A(r,"Payout setup link created.",e.json,t)}function hoe(e){if(!e)return null;let t=e.trim().toLowerCase();return t==="account_onboarding"||t==="onboarding"?"account_onboarding":t==="account_update"||t==="update"?"account_update":null}function yoe(e){return!e.json&&!e.noOpen}function voe(e){let t=`${e.message} ${f(e.details??{},"error")??""}`.toLowerCase();return t.includes("account_update")&&t.includes("account_onboarding")&&t.includes("account link")}async function koe(e,t,n,r){let i=O(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await me(`/api/v1/me/skills/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await me(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews`,n,r,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let l=O(n.issueId,"creator update-issue requires --issue-id."),c=O(n.status,"creator update-issue requires --status."),u=Mn("creator.update-issue","status",c,wie,n,"invalid_issue_status");if(u)return u;let d=Oi("creator.update-issue",{...n,version:n.fixedVersion});if(d)return d;try{return await Li(`/api/v1/me/skills/${encodeURIComponent(i)}/issues/${encodeURIComponent(l)}`,Ft(n,["status","fixedVersion","note"]),n,r,"Issue updated.")}catch(p){if(p instanceof Z&&p.status===404)return woe(i,l,n);throw p}}let o=O(n.reviewId,"creator moderate-review requires --review-id."),s=O(n.status,"creator moderate-review requires --status."),a=Mn("creator.moderate-review","status",s,bie,n,"invalid_review_status");if(a)return a;try{return await Oe(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews/${encodeURIComponent(o)}/moderate`,Ft(n,["status","reason"]),n,r,"Review updated.")}catch(l){if(l instanceof Z&&l.status===404)return boe(i,o,n);throw l}}function woe(e,t,n){return x({status:"not_found",reasonCode:"issue_not_found",skillSlug:e,issueId:t,nextAction:"creator.issues",nextStep:`Run \`skills-layer creator issues ${e}\` to inspect open issues before updating one.`},`Issue ${t} was not found for ${e}. Run \`skills-layer creator issues ${e}\` first.`,n.json,"issue_not_found")}function boe(e,t,n){return x({status:"not_found",reasonCode:"review_not_found",skillSlug:e,reviewId:t,nextAction:"creator.reviews",nextStep:`Run \`skills-layer creator reviews ${e}\` to inspect review ids before moderating one.`},`Review ${t} was not found for ${e}. Run \`skills-layer creator reviews ${e}\` first.`,n.json,"review_not_found")}async function _oe(e,t,n){let r=e[0],i=O(e[1],`creator source ${r??""} requires a source connection id.`),o=k(t.skill)??e[2];if(r==="prepare"){let s=Oi("creator.source.prepare",t);if(s)return s;let a=Mn("creator.source.prepare","visibility",t.visibility,za,t,"invalid_visibility");if(a)return a;let l=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=k(t.source)??e[2],u=c?await Hu(c,n.cwd):void 0;return await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/prepare`,ie({...Ft(t,["skill","source","version","displayName","skillType","category","visibility"]),...l.value!==void 0?{priceCents:l.value}:{},source:c,...u?{files:u.files}:{}}),t,n,"Source release prepared.")}if(r==="publish-request"){let s=Oi("creator.source.publish-request",t);if(s)return s;let a=Mn("creator.source.publish-request","visibility",t.visibility,za,t,"invalid_visibility");if(a)return a;let l=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=t.approvalRequestId.length>0?t.approvalRequestId:k(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/publish-request`,ie({skillSlug:o,approvalRequestIds:c,confirmPriceIncrease:t.confirmed,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:k(t.version),...Ft(t,["visibility","license","discloseSource"]),...l.value!==void 0?{priceCents:l.value}:{}}),t,n,"Source publish requested.")}if(r==="release-status"){let s=new URLSearchParams;return o&&s.set("skill",o),await me(`/api/v1/me/source-connections/${encodeURIComponent(i)}/release-status${Qe(s)}`,t,n,"Source release status loaded.",{authenticated:!0})}return R(`Unknown creator source command "${r??""}".`,t.json)}function RP(e){return!e.list&&!e.dryRun}async function oM(e){if(!RP(e.flags)||k(e.flags.visibility)==="private"||k(e.flags.scope)==="workspace")return null;if(e.flags.all&&Array.isArray(e.inspection.catalogueDecisions)){let p=[];for(let m of ur(e.inspection)){let h=await Wa([],{...e.flags,all:!1,json:!0,source:f(e.inspection,"catalogueSourceInput")??e.source,skill:m.value},e.backend);if(h.exitCode!==0){let g=JSON.parse(h.stderr||h.stdout);return x({status:"source_install_batch_partial",reasonCode:g.reasonCode??"source_install_child_failed",failedSkill:m.value,results:p,failure:g.data},"Source installation stopped; earlier results are retained.",e.flags.json,g.reasonCode??"source_install_child_failed")}p.push(JSON.parse(h.stdout).data)}return A({status:"source_install_batch",results:p},"Source installation results loaded.",e.flags.json,e.backend)}let t=L(e.inspection,"catalogueMatch");if(!t&&e.selectedSkillSlug&&typeof e.inspection.catalogueSourceInput=="string"){let p=await jP(e.backend,e.source,{source:e.inspection.catalogueSourceInput,skillSlug:e.selectedSkillSlug,preferCatalogue:!0,listOnly:!0},e.flags);if(p.kind==="failure")return p.result;t=L(p.inspection,"catalogueMatch"),t&&(e.inspection=p.inspection)}if(!t)return null;let n=rr(e.source),r=f(t,"skillSlug"),i=f(t,"version"),o=f(t,"generationId"),s=n.kind==="github"?n.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,l=(Array.isArray(e.inspection.results)?e.inspection.results:[]).find(p=>j(p)&&p.skillSlug===e.selectedSkillSlug),c=j(l)?f(l,"relativeSkillRoot"):void 0,u=c&&s&&c!=="."?s==="."||c===s||c.startsWith(`${s}/`)?c:`${s}/${c}`:void 0,d=typeof t.sourceRoot=="string"&&(t.sourceRoot==="."||!t.sourceRoot.split("/").some(p=>!p||p==="."||p===".."||/[\\\p{Cc}\p{Cf}]/u.test(p)));return n.kind!=="github"||t.schemaVersion!=="skills-layer.source-catalogue-match.v1"||typeof t.repository!="string"||t.repository.toLowerCase()!==`${n.owner}/${n.repo}`.toLowerCase()||!d||t.sourceRoot!==s&&t.sourceRoot!==u||typeof t.commitSha!="string"||!/^[a-f0-9]{40}$/u.test(t.commitSha)||/^[a-f0-9]{40}$/iu.test(n.ref)&&n.ref.toLowerCase()!==t.commitSha||!r||!/^[a-z0-9][a-z0-9-]{0,255}$/u.test(r)||!i||!o||e.selectedSkillSlug&&e.selectedSkillSlug!==t.requestedSkillSlug?x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",source:e.source,nextStep:"Retry after the exact source-to-catalogue identity is refreshed. No raw-source fallback was activated."},"The catalogue match did not identify this exact GitHub skill and revision.",e.flags.json,"source_catalogue_identity_invalid"):Wa([r],{...e.flags,source:void 0,skill:void 0,version:i},e.backend,{...aU,expectedSourceGeneration:{generationId:o,version:i}})}var aU={origin:"direct",fallbackPolicy:"eligible_public"};function Soe(e){return{origin:"update_existing",fallbackPolicy:f(e??{},"acquisitionMode")==="authenticated_account"?"account_required":"eligible_public"}}async function Wa(e,t,n,r=aU){if(e[0]==="status"&&e[1])return me(`/api/v1/install-receipts/${encodeURIComponent(e[1])}`,t,n,"Install progress loaded.",{authenticated:!!n.apiKey});let i=tU("install",t);if(i)return i;if(t.localOnly&&(t.visibility!==void 0||k(t.scope)==="workspace"||n.config?.workingModeType==="enterprise_workspace"))return x({status:"local_only_intent_conflict",reasonCode:"local_only_intent_conflict"},"Local-only installation requires a personal local target and cannot request platform visibility or workspace authority.",t.json,"local_only_intent_conflict");let o=k(t.source);if(o){let h=k(t.skill),g=uM(o,h,t);if(g)return g;let y=await Hu(o,n.cwd);if(y)return await aM(o,y,h,t,n);if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let v=dM(o,t);if(v)return v;let b=t.list||t.dryRun||!h&&!t.all,w=await jP(n,o,{source:o,skillSlug:h,listOnly:b,...t.all?{all:!0}:{},preferCatalogue:RP(t),visibility:k(t.visibility)},t);if(w.kind==="failure")return w.result;let _=w.inspection;if(t.list)return A(_,"Source skills loaded.",t.json,n);let C=Ih(o,_,t);if(C)return C;let P=await ju({source:o,inspection:_,requestedSkillSlug:h,mode:"install",flags:t,backend:n});if(P.kind==="failure")return P.result;if(t.dryRun)return A(LP(o,_,P.skillSlug,t),"Source install preview ready.",t.json,n);let N=t.all?ur(_).map(Q=>Q.value):[P.skillSlug??ur(_)[0]?.value??ot(o)],T=await oM({inspection:_,source:o,selectedSkillSlug:P.skillSlug,flags:t,backend:n});if(T)return T;let X=await UB(n,N,t);if(X)return X;let G=f(_,"catalogueSourceInput")??o,ee=await lM({backend:n,flags:t,source:G,skillSlug:P.skillSlug,defaultAcceptUnverifiedSource:Ti(o,t,n,w.sourceAccess)==="public"});if(fe(ee))return ee;let te;try{te=await fM({source:G,skillSlug:P.skillSlug,flags:t,backend:n,sourceAccess:w.sourceAccess})}catch(Q){if(ee)return await hM({backend:n,flags:t,source:G,sourceAccess:w.sourceAccess,skillSlug:P.skillSlug??N[0],unverifiedMaterialization:ee,error:Q});if(Q instanceof Z)return gM(o,Q,t);throw Q}return await Uu({backend:n,result:te,fallbackSlug:P.skillSlug??f(te,"skillSlug")??o,source:G,sourceAccess:w.sourceAccess,flags:t,requestedVisibility:Ti(o,t,n,w.sourceAccess),...ee?{unverifiedMaterialization:ee}:{}})}let s=O(e[0]??t.install,"install requires a skill slug or --source.");if(xz(s)){let h=uM(s,k(t.skill),t);if(h)return h;let g=await Hu(s,n.cwd);if(g)return await aM(s,g,k(t.skill),t,n);if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let y=dM(s,t);if(y)return y;let v=k(t.skill),b,w="unknown",_=async Q=>{if(b)return null;let Ce=await jP(n,s,{source:s,skillSlug:v,listOnly:Q,...t.all?{all:!0}:{},preferCatalogue:RP(t),visibility:k(t.visibility)},t);return Ce.kind==="failure"?Ce.result:(b=Ce.inspection,w=Ce.sourceAccess,null)};if(t.list){let Q=await _(!0);return Q||A(b,"Source skills loaded.",t.json,n)}if(!v&&!t.all){let Q=await _(!0);if(Q)return Q;let Ce=b,pn=Ih(s,Ce,t);if(pn)return pn;let Qa=await ju({source:s,inspection:Ce,requestedSkillSlug:v,mode:"install",flags:t,backend:n});if(Qa.kind==="failure")return Qa.result;v=Qa.skillSlug}if(t.dryRun){let Q=await _(!0);if(Q)return Q;let Ce=b,pn=await ju({source:s,inspection:Ce,requestedSkillSlug:v,mode:"install",flags:t,backend:n});return pn.kind==="failure"?pn.result:(v=pn.skillSlug,A(LP(s,Ce,v,t),"Source install preview ready.",t.json,n))}let C=await _(!1);if(C)return C;let P=b,N=t.all?ur(P).map(Q=>Q.value):[v??ur(P)[0]?.value??ot(s)],T=await oM({inspection:P,source:s,selectedSkillSlug:v,flags:t,backend:n});if(T)return T;let X=await UB(n,N,t);if(X)return X;let G=f(P,"catalogueSourceInput")??s,ee=await lM({backend:n,flags:t,source:G,skillSlug:v,defaultAcceptUnverifiedSource:Ti(s,t,n,w)==="public"});if(fe(ee))return ee;let te;try{te=await fM({source:G,skillSlug:v,flags:t,backend:n,sourceAccess:w})}catch(Q){if(ee)return await hM({backend:n,flags:t,source:G,sourceAccess:w,skillSlug:v??N[0],unverifiedMaterialization:ee,error:Q});if(Q instanceof Z)return gM(s,Q,t);throw Q}return await Uu({backend:n,result:te,fallbackSlug:v??f(te,"skillSlug")??ot(s),source:G,sourceAccess:w,flags:t,requestedVisibility:Ti(s,t,n,w),...ee?{unverifiedMaterialization:ee}:{}})}if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");if(k(t.scope)==="workspace"){let h=O(t.workspace,"workspace installs require --workspace <workspace-id>."),g=await lU(n,`/api/v1/workspaces/${encodeURIComponent(h)}/skills/${encodeURIComponent(s)}/approve`,{dryRun:t.dryRun},t);return fe(g)?g:t.dryRun?await ese(g,"Workspace approval preview ready.",t,n):A(g,"Workspace approval requested.",t.json,n)}if(!n.apiKey&&r.fallbackPolicy==="eligible_public")return await dP({target:s,flags:t,backend:n,catalogContext:r});if(!t.dryRun){let h;try{h=await QP(n,s,t)}catch(g){if(EP(r,g))return await dP({target:s,flags:t,backend:n,catalogContext:r});throw g}if(h)return h}let a=await uU(s,t,n);if("result"in a)return a.result;let l=a.flags,c=ie({skillSlug:s,version:k(l.version),scope:k(l.scope),agent:k(l.agent),dryRun:t.dryRun}),u;try{u=await nA(n,c,t)}catch(h){if(EP(r,h))return await dP({target:s,flags:t,backend:n,catalogContext:r,effectiveFlags:l});throw h}if(fe(u))return u;let d=u;if(d.status==="purchase_required")return DU(d,s,t,n);if(await ji(n,d),t.dryRun)return await AU(d,l,n);let p=await rA(n,d,s,l,{expectedSourceGeneration:r.expectedSourceGeneration});if(fe(p))return p;let m=await sA(n,{...p,acquisitionMode:"authenticated_account",acquisitionOrigin:r.origin},s,l);return await Ha(n,m,s),Va(m,Array.isArray(m.materializedWrites)&&m.materializedWrites.length>0?"Skill installed.":l.agent?"Recorded; choose --scope project|global to install files.":"Recorded; no agent selected \u2014 rerun with --agent <id> to write the skill files.",t.json,n,k(l.agent))}async function dP(e){let t=e.backend.apiKey?{...e.backend,apiKey:void 0,authBlockedMessage:void 0}:e.backend,n=e.effectiveFlags;if(!n){let o=await uU(e.target,e.flags,e.backend);if("result"in o)return o.result;n=o.flags}let r=k(n.version),i={status:"anonymous_public",skillSlug:e.target,...r?{version:r}:{},scope:k(n.scope),agent:k(n.agent),acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin};if(e.flags.dryRun)try{let o=await bh(t,i,e.target,r,{exportMode:"public"});return await AU({...i,...Sh(o)},e.flags,t)}catch(o){if(o instanceof Z)return Go(o,e.flags.json);throw o}try{let o=await rA(t,i,e.target,n,{exportMode:"public",expectedSourceGeneration:e.catalogContext.expectedSourceGeneration});if(fe(o))return o;let s=await sA(t,{...o,acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin},e.target,n);return await Ha(t,s,e.target),Va(s,"Public skill installed locally without an account.",e.flags.json,t)}catch(o){if(o instanceof Z)return Go(o,e.flags.json);throw o}}function EP(e,t){return e.fallbackPolicy==="eligible_public"&&t instanceof Z&&t.status===401&&f(t.details??{},"reasonCode")==="api_key_invalid_or_expired"}async function lU(e,t,n,r){let i=o=>D(e,t,{method:"POST",headers:V(e.apiKey),body:JSON.stringify(o)});try{return await i(n)}catch(o){let s=cU(o);if(!s)throw o;return r.json||!e.stdoutIsTty?x({status:"warning_required",reasonCode:s.reasonCode,distributionPosture:s.posture,nextAction:"acknowledge_distribution_warning"},"A Guardian warning must be acknowledged before workspace approval. Interactive acknowledgement is unavailable in this mode.",r.json,"warning_acknowledgement_required"):(e.emitInfo(`Guardian warning: ${s.posture.effectiveDistributionStatus} (${s.posture.reasonCode}).`),await e.promptSelect("Approve this exact warned generation for the workspace?",[{value:"cancel",label:"Cancel approval",description:"Do not approve or materialize the skill."},{value:"acknowledge",label:"Acknowledge and continue",description:"Bind approval to this warning revision."}])!=="acknowledge"?x({status:"cancelled",reasonCode:"distribution_warning_declined",distributionPosture:s.posture},"Workspace approval cancelled without granting value.",r.json,"distribution_warning_declined"):i({...n,distributionWarningAcknowledgement:{contractVersion:s.posture.contractVersion,warningDigest:s.posture.warningDigest,authorityRevision:s.posture.authorityRevision,accepted:!0}}))}}async function nA(e,t,n,r="/api/v1/install"){let i=o=>D(e,r,{method:"POST",headers:V(e.apiKey),body:JSON.stringify(o)});try{return await i(t)}catch(o){let s=cU(o);if(!s)throw o;return n.json||!e.stdoutIsTty?x({status:"warning_required",reasonCode:s.reasonCode,distributionPosture:s.posture,nextAction:"acknowledge_distribution_warning"},"A Guardian warning must be acknowledged before install. Interactive acknowledgement is unavailable in this mode.",n.json,"warning_acknowledgement_required"):(e.emitInfo(`Guardian warning: ${s.posture.effectiveDistributionStatus} (${s.posture.reasonCode}). Next action: ${s.posture.nextAction}.`),await e.promptSelect("Continue with this exact warned skill generation?",[{value:"cancel",label:"Cancel install",description:"Do not grant or materialize the skill."},{value:"acknowledge",label:"Acknowledge and continue",description:"Bind consent to this warning and authority revision."}])!=="acknowledge"?x({status:"cancelled",reasonCode:"distribution_warning_declined",distributionPosture:s.posture},"Install cancelled without granting value.",n.json,"distribution_warning_declined"):await i({...t,distributionWarningAcknowledgement:{contractVersion:s.posture.contractVersion,warningDigest:s.posture.warningDigest,authorityRevision:s.posture.authorityRevision,accepted:!0}}))}}function cU(e){if(!(e instanceof Z)||e.status!==409||!e.details)return null;let t=j(e.details.data)?e.details.data:e.details,n=j(t.distributionPosture)?t.distributionPosture:null,r=n?.contractVersion,i=n?.warningDigest,o=n?.authorityRevision;return!n||r!=="skills-layer.distribution.v1"||typeof i!="string"||!/^sha256:[a-f0-9]{64}$/u.test(i)||typeof o!="number"||!Number.isSafeInteger(o)||o<1?null:{reasonCode:typeof t.reasonCode=="string"?t.reasonCode:"warning_acknowledgement_required",posture:{contractVersion:r,warningDigest:i,authorityRevision:o,effectiveDistributionStatus:typeof n.effectiveDistributionStatus=="string"?n.effectiveDistributionStatus:"published_with_warning",reasonCode:typeof n.reasonCode=="string"?n.reasonCode:"guardian_incident_warning",nextAction:typeof n.nextAction=="string"?n.nextAction:"review_warning_before_install"}}}async function uU(e,t,n){let r=k(t.scope),i=k(t.agent);if(t.json||t.dryRun||!n.stdoutIsTty||r==="workspace"||r==="local"||r!==void 0&&i!==void 0)return{flags:t};let o=et(n.env,n.platform,n.cwd),s=xoe(n),a=await Coe(n.paths.installTargetPreferencePath),l=a?.workingModeId===s,c=l&&a?.agent?o.find(w=>w.id===a.agent):void 0,u=c&&a?.scope?a.scope==="global"?c.targets.globalSkillsPath:c.targets.projectSkillsPath:void 0;if(i===void 0&&r===void 0&&a?.policy==="recheck_every_5"&&l&&c!==void 0&&(a.scope==="project"||a.scope==="global")&&u!==void 0&&a.usesSinceConfirmation>0&&a.usesSinceConfirmation<4)return await Ve(n.paths.installTargetPreferencePath,{...a,usesSinceConfirmation:a.usesSinceConfirmation+1,savedAt:n.now()}),{flags:{...t,agent:c.id,scope:a.scope}};let p=await WA({env:n.env,platform:n.platform,cwd:n.cwd,pathExists:pr}),m=p.filter(w=>w.detectionSources.includes("project")),h=i??Re(n.env.SKILLS_LAYER_AGENT),g=h?o.find(w=>w.id===h):void 0;if(h&&!g)return{result:R(`Unsupported agent "${h}". Run \`skills-layer agents list\` to choose a supported install target.`,t.json)};if(!g&&m.length===1&&(g=m[0]),!g){let w=Re(n.config?.lastSelectedAgent);g=w?p.find(_=>_.id===w)??o.find(_=>_.id===w):void 0}if(!g&&p.length===1&&(g=p[0]),!g&&p.length>1){let w=await n.promptSelect("Multiple supported agents were detected. Select one to install for:",p.map(_=>({value:_.id,label:`${_.displayName} (${_.detectionSources.join(", ")})`})));g=p.find(_=>_.id===w)}if(!g)return{result:R("No supported local agent was detected. Run `skills-layer agents list`, then retry with --agent <agent> and --scope <project|global>.",t.json)};let y=r;if(!y){let w=[{value:"project",label:"Project (this folder)"}];g.targets.globalSkillsPath&&w.push({value:"global",label:"Global (all projects)"}),y=w.length===1?w[0].value:await n.promptSelect(`Install ${e} for ${g.displayName} where?`,w)}let v=i!==void 0||r!==void 0,b=a?.policy==="ask_every_time"&&l;if(!v&&!b&&(y==="project"||y==="global")){let w=y==="project"?"Project":"Global",C=await n.promptSelect(`Remember ${g.displayName} / ${w} for future installs?`,[{value:"recheck_every_5",label:"Yes - recheck on every 5th install"},{value:"ask_every_time",label:"No - ask every time"}])==="recheck_every_5"?{version:1,policy:"recheck_every_5",agent:g.id,scope:y,usesSinceConfirmation:1,workingModeId:s,savedAt:n.now()}:{version:1,policy:"ask_every_time",usesSinceConfirmation:0,workingModeId:s,savedAt:n.now()};await Ve(n.paths.installTargetPreferencePath,C)}return{flags:{...t,agent:g.id,scope:y}}}function xoe(e){return e.apiKey?Re(e.config?.workingModeId)??"personal":"anonymous"}async function Coe(e){let t=await ke(e);return!j(t)||t.version!==1||t.policy!=="recheck_every_5"&&t.policy!=="ask_every_time"||typeof t.workingModeId!="string"||typeof t.savedAt!="string"||typeof t.usesSinceConfirmation!="number"||!Number.isInteger(t.usesSinceConfirmation)||t.usesSinceConfirmation<0||t.agent!==void 0&&typeof t.agent!="string"||t.scope!==void 0&&t.scope!=="project"&&t.scope!=="global"?null:t}async function rA(e,t,n,r,i={}){if(k(r.agent)==="all")return await Ioe(e,t,n,r,i);let o=iA(e,t,n,r);if(o.status==="skip")return t;if(o.status==="cache_only"){let h=await bh(e,t,o.skillSlug,o.version,i),g=await xh({backend:e,exportResult:h,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(g))return g;let v=(e.platform==="win32"?st:Lt).join(e.paths.bundlesDir,o.skillSlug,g.envelope.generation.semanticVersion,encodeURIComponent(g.envelope.generation.generationId),"bundle.zip");return await IA(v,g.bytes),{...t,...Sh(h),version:g.envelope.generation.semanticVersion,scope:"local",archiveSha256:g.archiveSha256,archiveHashFormat:g.archiveHashFormat,manifestSha256:g.envelope.manifest.sha256,generationId:g.envelope.generation.generationId,sourceContentDigest:ct(g.files),verificationStatus:"verified",cachedArtifact:{state:"verified",bundlePath:v,generation:g.envelope.generation,archiveSha256:g.archiveSha256,manifestSha256:g.envelope.manifest.sha256,savedAt:e.now()}}}if(o.status==="failure")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:o.skillSlug,nextStep:o.nextStep},o.message,r.json,"materialization_target_invalid");let s=await Ya({backend:e,skillSlug:o.skillSlug,agentId:o.agent.id,scope:o.scope,flags:r});if(s)return s;let a=await bh(e,t,o.skillSlug,o.version,i),l=await xh({backend:e,exportResult:a,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(l))return l;let c=(await lt(e)).installs[o.skillSlug],u=qn(c,{scope:o.scope,installedPath:(e.platform==="win32"?st:Lt).join(o.skillsPath,Mr(o.skillSlug)),platform:e.platform})[0]?.record,d=u?f(u,"sourceContentDigest"):void 0,p=ct(l.files);if(u?.verificationStatus==="unverified"&&!r.replaceUnverifiedSource&&(await Dr({targetDir:(e.platform==="win32"?st:Lt).join(o.skillsPath,Mr(o.skillSlug)),generation:l.envelope.generation,archiveSha256:l.archiveSha256,manifestSha256:l.envelope.manifest.sha256,files:l.envelope.manifest.files})).status!=="verified")return x({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:o.skillSlug,installedArchiveSha256:u.archiveSha256,approvedArchiveSha256:l.archiveSha256,installedContentDigest:d,approvedContentDigest:p,verificationStatus:"unverified",nextStep:"The installed bytes were left unchanged. Review the source difference and retry with --replace-unverified-source to replace them with the approved catalogue generation."},"The approved catalogue artifact differs from the installed unverified generation; no local files were replaced.",r.json,"verification_digest_mismatch");let m=await oA({backend:e,skillSlug:o.skillSlug,scope:o.scope,agent:o.agent,skillsPath:o.skillsPath,bytes:l.bytes,files:l.files,envelope:l.envelope,approval:l.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});return{...t,...Sh(a),archiveSha256:l.archiveSha256,archiveHashFormat:l.archiveHashFormat,scope:o.scope,agent:o.agent.id,targetAgent:o.agent.id,materializationPlan:{scope:o.scope,agent:o.agent.id},...Mu(e),...m,...m.guardianActivationReceipt?{warnings:[...Be(t,"warnings")??[],...Be(m,"warnings")??[]]}:{}}}async function Ioe(e,t,n,r,i){let o=L(t,"materializationPlan")??L(t,"installPlan"),s=k(r.scope)??f(t,"scope")??(o?f(o,"scope"):void 0),a=f(t,"skillSlug")??f(t,"slug")??n;if(s!=="project"&&s!=="global")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:a,nextStep:"Use --agent all with --scope project or --scope global."},"Installing for all compatible agents requires project or global scope.",r.json,"materialization_target_invalid");let l=et(e.env,e.platform,e.cwd),c=new Map;for(let w of l){let _=s==="global"?w.targets.globalSkillsPath:w.targets.projectSkillsPath;if(!_)continue;let C=Bo(_,e.platform),P=c.get(C);P?P.agents.push(w):c.set(C,{agent:w,agents:[w],skillsPath:_})}if(c.size===0)return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:a,nextStep:"Run `skills-layer agents list` and select a supported target with an available path."},`No supported agent exposes a ${s} skill path on this machine.`,r.json,"materialization_target_invalid");for(let w of c.values())for(let _ of w.agents){let C=await Ya({backend:e,skillSlug:a,agentId:_.id,scope:s,flags:r});if(C)return C}let u=f(t,"version")??f(t,"currentVersion"),d=await bh(e,t,a,u,i),p=await xh({backend:e,exportResult:d,flags:r,skillSlug:a,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(p))return p;let m=ct(p.files),h=(await lt(e)).installs[a],g;if(!r.replaceUnverifiedSource)for(let w of c.values()){let _=(e.platform==="win32"?st:Lt).join(w.skillsPath,Mr(a)),C=qn(h,{scope:s,installedPath:_,platform:e.platform})[0];if(C?.record.verificationStatus==="unverified"&&(await Dr({targetDir:_,generation:p.envelope.generation,archiveSha256:p.archiveSha256,manifestSha256:p.envelope.manifest.sha256,files:p.envelope.manifest.files})).status!=="verified"){g=C;break}}if(g)return x({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:a,materializationId:g.materializationId,installedContentDigest:f(g.record,"sourceContentDigest"),approvedContentDigest:m,verificationStatus:"unverified",nextStep:"The installed bytes were left unchanged. Review the source difference and use --replace-unverified-source to replace the unverified generation."},"The approved catalogue artifact differs from an installed unverified generation; no local files were replaced.",r.json,"verification_digest_mismatch");let y=[];for(let w of c.values()){let _=await oA({backend:e,skillSlug:a,scope:s,agent:w.agent,skillsPath:w.skillsPath,bytes:p.bytes,files:p.files,envelope:p.envelope,approval:p.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});y.push({...t,scope:s,agent:w.agent.id,targetAgent:w.agent.id,...Mu(e),..._})}let v=y[0],b=v[Ch];return{...t,...Sh(d),archiveSha256:p.archiveSha256,archiveHashFormat:p.archiveHashFormat,scope:s,agent:"all",targetAgents:l.map(w=>w.id),materializationPlan:{scope:s,agent:"all",physicalTargetCount:y.length,agentCount:l.length},materializationResults:y,materializedWrites:y.flatMap(w=>Array.isArray(w.materializedWrites)?w.materializedWrites:[]),materializedSkillRoot:f(v,"materializedSkillRoot"),...Mu(e),...fU(b)?{[Ch]:b}:{}}}async function Ya(e){let t=e.backend.config?.workingModeType==="enterprise_workspace",n=e.enforceRequired?"enforce":await rd(e.backend,e.skillSlug);if(!t&&n!=="enforce"&&n!=="enabled")return null;let r=Re(e.backend.config?.workingModeWorkspaceId);if(t&&!r)return x({status:"blocked",reasonCode:"guardian_workspace_context_unavailable",skillSlug:e.skillSlug,agent:e.agentId,scope:e.scope,nextAction:"workspace.current",nextStep:"Refresh the selected Enterprise workspace before materializing this skill."},"Enterprise materialization requires a current workspace-bound Guardian context.",e.flags.json,"guardian_workspace_context_unavailable");let i=await zn(e.backend,e.scope),o=(Be(i,"hooks")??[]).filter(j).find(u=>f(u,"agent")===e.agentId&&f(u,"scope")===e.scope&&u.active===!0),s=wr(e.agentId),a=yl({evaluationContext:"activation_eligibility",requestedMode:"enforce",workspacePolicy:t?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:s?.maximumTier==="strict_candidate",hookInstalled:!!o,strictHookVerified:o?.strictPreActionBlocking===!0&&o.evidenceCapability==="strict",exactActivationVerified:o?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"none",materializationState:"active"}),l=a.activationAllowed&&a.countedAsEnforced,c=t&&e.backend.config.workingModeGuardianPolicy==="standard"&&o!==void 0&&o.configActive!==!1;return l||c?(t&&(e.backend.guardianActivationReceipts??={},e.backend.guardianActivationReceipts[`${e.agentId}:${e.scope}`]={policy:e.backend.config.workingModeGuardianPolicy==="standard"?"standard":"strict",agent:e.agentId,scope:e.scope,tier:l?"strict_verified":"hook_unverified",observedAt:e.backend.now()}),null):x({status:"blocked",reasonCode:"guardian_enforcement_unavailable",skillSlug:e.skillSlug,workspaceId:r,agent:e.agentId,scope:e.scope,measuredProtection:{...a,evidenceCapability:o?.evidenceCapability??"unverified",evidenceReasons:o?.evidenceReasons??[s?.reasonCode??"host_has_no_supported_guardian_route"]},nextAction:"guardian.hook.install",nextStep:!o||o.configActive===!1?`Run skills-layer guardian hook install --agent ${e.agentId} --scope ${e.scope}.`:e.backend.config?.workingModeRole==="enterprise_admin"?`This host has no current strict verification. Select a qualified host or use skills-layer enterprise workspace update ${e.backend.config?.workingModeEnterpriseId??"<enterprise-id>"} ${r??"<workspace-id>"} --guardian-policy standard. Hook installation alone does not prove strict enforcement.`:"This host has no current strict verification. Ask your Enterprise Admin to select a qualified host or review the workspace Guardian policy. Hook installation alone does not prove strict enforcement."},t&&e.backend.config.workingModeGuardianPolicy==="standard"&&(!o||o.configActive===!1)?`No active Guardian hook is installed for ${e.agentId} at ${e.scope} scope.`:`${t?"Enterprise":"Guardian-enforced"} materialization was blocked because verified Guardian enforcement is unavailable.`,e.flags.json,"guardian_enforcement_unavailable")}function $P(e,t,n){let r=e.guardianActivationReceipts?.[`${t}:${n}`];return r?{guardianEnforcement:r.tier,guardianActivationReceipt:r,...r.tier==="hook_unverified"?{warnings:[`Guardian hook installed but not strict-verified on ${t}; workspace policy allows standard enforcement.`]}:{}}:{}}function Mu(e){return e.config?.workingModeType!=="enterprise_workspace"?{}:ie({workingModeType:"enterprise_workspace",enterpriseId:e.config.workingModeEnterpriseId,workspaceId:e.config.workingModeWorkspaceId,workingModeWorkspaceId:e.config.workingModeWorkspaceId})}function iA(e,t,n,r){let i=L(t,"materializationPlan")??L(t,"installPlan"),o=k(r.scope)??f(t,"scope")??(i?f(i,"scope"):void 0),s=f(t,"skillSlug")??f(t,"slug")??n;if(o==="local")return{status:"cache_only",skillSlug:s,version:f(t,"version")??f(t,"currentVersion")};if(o!=="project"&&o!=="global")return{status:"skip"};let a=k(r.agent)??f(t,"agent")??f(t,"targetAgent")??(i?f(i,"agent")??f(i,"targetAgent"):void 0)??Re(e.config?.lastSelectedAgent)??"codex",l=et(e.env,e.platform,e.cwd).find(u=>u.id===a);if(!l)return{status:"failure",skillSlug:s,message:`Unsupported agent "${a}". Run \`skills-layer agents list\` to choose a supported local install target.`,nextStep:"Run `skills-layer agents list` and retry with a supported --agent value."};let c=o==="global"?l.targets.globalSkillsPath:l.targets.projectSkillsPath;return c?{status:"ok",scope:o,agent:l,skillsPath:c,skillSlug:s,version:f(t,"version")??f(t,"currentVersion")}:{status:"failure",skillSlug:s,message:`${l.displayName} does not expose a ${o} skills path on this machine.`,nextStep:"Retry with --scope project, or choose another agent from `skills-layer agents list`."}}async function bh(e,t,n,r,i={}){if(typeof t.downloadUrl=="string"&&j(t.artifactEnvelope)&&j(t.artifactApproval)&&j(t.platformScoreAuthority))return t;let o=new URLSearchParams;r&&o.set("version",r);let s=i.exportMode==="public"||!e.apiKey,a=s?`/api/v1/skills/${encodeURIComponent(n)}/export${Qe(o)}`:`/api/v1/me/library/${encodeURIComponent(n)}/export${Qe(o)}`,l=await D(e,a,{headers:s?{}:re(e.apiKey,e.authBlockedMessage)});if(!s&&!j(l.platformScoreAuthority))try{let c=await D(e,`/api/v1/skills/${encodeURIComponent(n)}/export${Qe(o)}`,{headers:{}});return{...l,platformScoreAuthority:c.platformScoreAuthority}}catch(c){if(!(c instanceof Z)||![401,403,404].includes(c.status))throw c}return s?{...l,downloadUrl:Poe(n,f(l,"version")??r)}:l}function Poe(e,t){let n=new URLSearchParams;return t&&n.set("version",t),`/api/v1/skills/${encodeURIComponent(e)}/download${Qe(n)}`}function Aoe(e){let t=f(e,"visibility")??f(e,"versionVisibility"),n=f(e,"publicationStatus");return dU(e)&&(t==="public"||n==="clean_publishable"||n==="publishable_with_findings")}function Roe(e){return dU(e)}async function Uu(e){let t=_h(e.result),n=f(t,"skillSlug")??f(t,"slug")??e.fallbackSlug,r=e.requestedVisibility??(f(t,"visibility")==="public"||f(t,"versionVisibility")==="public"||f(t,"releaseVisibility")==="public"?"public":"private");if(!Roe(t)){let c=L(t,"publication"),u=f(t,"reasonCode")??(c?f(c,"reasonCode"):void 0)??"security_review_pending",d=!!e.unverifiedMaterialization,p=f(t,"version"),m=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"version")??f(e.unverifiedMaterialization,"currentVersion"):void 0,h=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"generationId"):void 0,g=c?f(c,"status")??f(t,"status")??"submitted":f(t,"status")??"submitted",y=g==="catalogue_submission_failed"||u==="source_ingestion_candidate_not_claimable",v=f(t,"workflowId"),b=f(t,"processingAttemptId"),w=f(t,"jobId"),_=f(t,"intakeReceiptId"),C=L(t,"progress")??{},P=!y&&t.continuationConfirmed!==!1&&!!(v||b||w)&&["queued","running","catalogue_processing_scheduled","held_for_moderation","source_install_pending_review","reused"].includes(g),N={status:y?"rejected":g==="reused"&&_?"reused":P?g==="reused"?"reused":"accepted":_?"accepted":"unconfirmed",reasonCode:u,continuationConfirmed:P,nextActor:f(C,"nextActor")??(P?"platform":u==="source_ingestion_candidate_not_claimable"?"operator":"requester")},T=ie({...e.unverifiedMaterialization,status:d?"installed_unverified":"install_pending_review",sourceItemStatus:f(t,"status")??"submitted",skillId:f(t,"skillId"),versionId:f(t,"versionId"),skillSlug:n,version:d?m:p,catalogueCandidateVersion:p,localProvisionalVersion:m,localGeneration:h,sourceContentDigest:e.unverifiedMaterialization?f(e.unverifiedMaterialization,"sourceContentDigest"):void 0,visibility:r,catalogueVisibilityRequested:r,requestedVisibility:r,catalogueStatus:g,publiclyDiscoverable:!1,intakeAdmission:N,assessmentStatus:f(C,"status")??(P?"pending":"unconfirmed"),publicationStatus:"not_published",distributionStatus:"verified_artifact_required",workflowId:v,processingAttemptId:b,jobId:w,intakeReceiptId:_,progress:t.progress,intakeReceiptIds:t.intakeReceiptIds,candidateIds:t.candidateIds,wakeStatus:t.wakeStatus,uploadIntent:t.uploadIntent,backgroundWorkStatus:P?"catalogue_review_continues_automatically":"retry_or_operator_action_required",publication:c?_h(c):void 0,activationStatus:d?"installed_unverified":"held",verificationStatus:d?"unverified":void 0,reasonCode:u,materializedWrites:d&&Array.isArray(e.unverifiedMaterialization?.materializedWrites)?e.unverifiedMaterialization.materializedWrites:[],materializationPlan:{scope:k(e.flags.scope)??"project",agent:k(e.flags.agent)??"codex",activation:d?"unverified_install_request_authorized":"approved_artifact_only"},nextStep:d?`Local installation is complete as Unverified / Unscored. ${P?"The durable assessment job remains scheduled.":"Continued assessment is not confirmed; retry submission or inspect the candidate status."} Verified publication requires valid four-dimension evidence and current distribution authority. Valid poor effectiveness is a warning, not a security block.`:P?`Run skills-layer ${_?`install status ${_}`:`creator status ${n}`}, then retry when verified distribution is available.`:"Submission continuation is not confirmed. Inspect the intake status or retry submission before waiting for assessment."});return d&&await Ha(e.backend,T,n),Va(T,d?`External source installed locally as unverified; ${P?"catalogue review continues":"catalogue continuation is unconfirmed"}.`:P?"Source submitted; installation is pending approval.":"Source installation is held; catalogue continuation is unconfirmed.",e.flags.json,e.backend)}let i=L(L(t,"progress")??{},"subject"),o=i?f(i,"generationId"):void 0,s=i?f(i,"version"):void 0;if(i&&(!o||!s||f(i,"slug")!==n))return x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",skillSlug:n,intakeReceiptId:t.intakeReceiptId,nextStep:"Retry after the source receipt identifies the exact approved skill, version and generation."},"The completed source receipt does not identify this exact skill and generation.",e.flags.json,"source_catalogue_identity_invalid");let a;try{a=await rA(e.backend,t,n,e.flags,{exportMode:Aoe(t)?"public":"auto",...i?{expectedSourceGeneration:{generationId:o,version:s}}:{}})}catch(c){if(!(c instanceof Z)||![404,502,503,504].includes(c.status))throw c;let u=ie({...t,...e.unverifiedMaterialization,status:e.unverifiedMaterialization?"installed_unverified":"catalogue_artifact_unavailable",activationStatus:e.unverifiedMaterialization?"installed_unverified":"not_installed",sourceItemStatus:f(t,"status"),catalogueStatus:f(t,"status"),publicationStatus:"published",continuationConfirmed:!0,reasonCode:"catalogue_artifact_unavailable",serverReasonCode:c.details?f(c.details,"reasonCode"):void 0,nextStep:"The catalogue version is published, but its approved artifact could not be downloaded. Retry the install when export is available. Any existing local source install remains unverified."});return e.unverifiedMaterialization?(await Ha(e.backend,u,n),Va(u,"Source installed locally as unverified; the published catalogue artifact is temporarily unavailable.",e.flags.json,e.backend)):x(u,"The published catalogue artifact is temporarily unavailable.",e.flags.json,"catalogue_artifact_unavailable")}if(fe(a))return a;let l=await sA(e.backend,a,n,e.flags);return await Ha(e.backend,l,n),Va(l,Woe(e.source,e.flags,e.backend,l,e.sourceAccess),e.flags.json,e.backend)}function _h(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>t==="localWrites"||t==="files"||t==="content"||t==="archiveBytes"?[]:Array.isArray(n)?[[t,n.map(r=>j(r)?_h(r):r)]]:j(n)?[[t,_h(n)]]:[[t,n]]))}function dU(e){if(pU(e.artifactApproval).status==="ok"&&e.artifactEnvelope!==void 0&&typeof e.downloadUrl=="string")return!0;let n=L(e,"publication"),r=n?f(n,"status")==="published":!1,i=f(e,"listingStatus")==="published",o=f(e,"versionStatus")==="published",s=f(e,"status");return i&&o&&(r||s==="published"||s==="reused"||s==="source_approved")}function Sh(e){return ie({version:f(e,"version"),storageKey:f(e,"storageKey"),expiresAt:f(e,"expiresAt")})}async function xh(e){let t=pU(e.exportResult.artifactApproval);if(t.status!=="ok"){let d=t.status==="missing";return $i(e,d?"artifact_v1_approval_missing":"artifact_v1_approval_invalid",d?`Export for ${e.skillSlug} did not include an authoritative approved Artifact Format v1 identity.`:`Export for ${e.skillSlug} included malformed Artifact Format v1 approval metadata.`)}let n=t.approval;if(e.expectedSourceGeneration&&(n.generation.generationId!==e.expectedSourceGeneration.generationId||n.generation.semanticVersion!==e.expectedSourceGeneration.version))return $i(e,"source_catalogue_generation_mismatch","The exported artifact does not match the exact version and generation resolved for this source.");let r=Eoe({backend:e.backend,exportResult:e.exportResult,approval:n,skillSlug:e.skillSlug});if(r.status!=="ok")return $i(e,r.reasonCode,r.message);if(e.exportResult.artifactEnvelope===void 0)return $i(e,"artifact_v1_envelope_missing",`Export for ${e.skillSlug} did not include an Artifact Format v1 envelope.`);let i=f(e.exportResult,"downloadUrl");if(!i)return x({status:"export_download_unavailable",reasonCode:"export_download_unavailable",skillSlug:e.skillSlug,nextStep:"Retry after the backend returns a signed bundle download URL."},`Export for ${e.skillSlug} did not include a signed download URL.`,e.flags.json,"export_download_unavailable");let o=await e.backend.fetchFn(Doe(e.backend.baseUrl,i));if(!o.ok)throw new Z(o.status,`Unable to download exported bundle (${o.status}).`);let s;try{s=await Toe(o)}catch(d){return $i(e,"artifact_v1_archive_bounds_failed",`Downloaded ${e.skillSlug} exceeded Artifact Format v1 archive bounds.`,{verificationError:ve(d)})}let a,l;try{a=Nd({archiveBytes:s,envelope:e.exportResult.artifactEnvelope}),l=Cl({archiveBytes:s,envelope:a})}catch(d){return $i(e,"artifact_v1_verification_failed",`Downloaded ${e.skillSlug} failed Artifact Format v1 verification.`,{verificationError:ve(d)})}if(!$oe(n,a))return $i(e,"artifact_v1_identity_mismatch",`Downloaded ${e.skillSlug} did not match the authoritative approved generation.`);let c=f(e.exportResult,"skillSlug"),u=f(e.exportResult,"version");return a.generation.skillSlug!==e.skillSlug||c!==void 0&&c!==a.generation.skillSlug||u!==void 0&&u!==a.generation.semanticVersion?$i(e,"artifact_v1_target_mismatch",`Downloaded ${e.skillSlug} was approved for a different skill or version.`):{status:"ok",bytes:s,files:l,envelope:a,approval:n,archiveSha256:a.archive.sha256,archiveBytesSha256:a.archive.sha256,archiveHashFormat:"artifact_v1_zip"}}function Eoe(e){let t=L(e.exportResult,"platformScoreAuthority"),n=t?.machineReport,r=t?.passport,i=t?.parityManifest,o=t?f(t,"passportPublicKey"):void 0;if(!t||!rC(n)||!o)return{status:"invalid",reasonCode:"platform_score_authority_missing",message:`Export for ${e.skillSlug} did not include a verifiable Platform Score authority.`};let s=Yc.safeParse(r),a=nC.safeParse(i);if(!s.success||!a.success)return{status:"invalid",reasonCode:"platform_score_authority_invalid",message:`Export for ${e.skillSlug} included malformed Platform Score authority metadata.`};let l=n.projection.report;if(l.subject.slug!==e.skillSlug||l.subject.version!==e.approval.generation.semanticVersion||l.subject.generationId!==e.approval.generation.generationId||l.subject.archiveSha256!==e.approval.archiveSha256||a.data.report.reportId!==l.reportId||a.data.report.revision!==l.revision||a.data.report.digest!==l.reportDigest)return{status:"invalid",reasonCode:"platform_score_authority_subject_mismatch",message:`Export for ${e.skillSlug} did not match the exact Platform Score generation.`};try{let c=QL({passport:s.data,publicKeys:{[s.data.issuer.keyId]:rre(o)},now:e.backend.now(),expectedSubject:l.subject,expectedReport:{reportId:l.reportId,revision:l.revision,digest:l.reportDigest},currentPassportId:s.data.passportId});if(!c.valid)return{status:"invalid",reasonCode:`platform_score_${c.reasonCode}`,message:`Export for ${e.skillSlug} failed signed Skill Passport verification.`}}catch{return{status:"invalid",reasonCode:"platform_score_passport_key_invalid",message:`Export for ${e.skillSlug} included an invalid Skill Passport public key.`}}return{status:"ok"}}function pU(e){return e==null?{status:"missing"}:!j(e)||e.status!=="approved"||!j(e.generation)||typeof e.generation.skillSlug!="string"||typeof e.generation.semanticVersion!="string"||typeof e.generation.generationId!="string"||typeof e.archiveSha256!="string"||typeof e.manifestSha256!="string"?{status:"invalid"}:{status:"ok",approval:{status:"approved",generation:{skillSlug:e.generation.skillSlug,semanticVersion:e.generation.semanticVersion,generationId:e.generation.generationId},archiveSha256:e.archiveSha256,manifestSha256:e.manifestSha256}}}function $oe(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&e.archiveSha256===t.archive.sha256&&e.manifestSha256===t.manifest.sha256}function $i(e,t,n,r={}){return x({status:"download_integrity_failed",reasonCode:t,skillSlug:e.skillSlug,version:f(e.exportResult,"version"),archiveHashFormat:"artifact_v1_zip",...r,nextStep:"Retry after the catalog serving generation is refreshed, or contact Skills Layer support if this repeats."},n,e.flags.json,t)}function Doe(e,t){return/^https?:\/\//iu.test(t)?t:`${dr(e)}${t.startsWith("/")?"":"/"}${t}`}async function Toe(e){let t=e.headers.get("content-length");if(t!==null){let a=Number(t);if(!Number.isSafeInteger(a)||a<0)throw new Error("Artifact response Content-Length is invalid.");if(a>ut.maxArchiveBytes)throw new Error("Artifact response exceeds the v1 archive byte limit.")}if(!e.body)throw new Error("Artifact response body is unavailable.");let n=e.body.getReader(),r=[],i=0;try{for(;;){let a=await n.read();if(a.done)break;if(i+=a.value.byteLength,i>ut.maxArchiveBytes)throw await n.cancel("Artifact response exceeds the v1 archive byte limit."),new Error("Artifact response exceeds the v1 archive byte limit.");r.push(Uint8Array.from(a.value))}}finally{n.releaseLock()}let o=new Uint8Array(i),s=0;for(let a of r)o.set(a,s),s+=a.byteLength;return o}async function oA(e){let t=e.verificationStatus??"verified";if(t==="verified"&&!e.approval)throw new Error("Verified materialization requires platform artifact approval.");let n=e.backend.platform==="win32"?st:Lt,r=ct(e.files),i=n.join(e.backend.paths.bundlesDir,e.skillSlug,e.envelope.generation.semanticVersion,encodeURIComponent(e.envelope.generation.generationId),"bundle.zip"),o=n.join(e.skillsPath,Mr(e.skillSlug)),s=et(e.backend.env,e.backend.platform,e.backend.cwd).filter(G=>{let ee=e.scope==="global"?G.targets.globalSkillsPath:G.targets.projectSkillsPath;return ee!==null&&Bo(ee,e.backend.platform)===Bo(e.skillsPath,e.backend.platform)}).map(G=>G.id).sort(),a=`activation_${Ge(16).toString("hex")}`,l={targetDir:o,generation:e.envelope.generation,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,files:e.envelope.manifest.files},c=lz({scope:e.scope,targetDir:o,platform:e.backend.platform}),u=await lt(e.backend);for(let[G,ee]of Object.entries(u.installs)){let te=[ee,...An(ee).map(Q=>Q.record)].flatMap(Q=>[Jt(Q)?.receipt.targetDir,f(Q,"materializedSkillRoot"),f(Q,"materializedPath")]);if(G!==e.skillSlug&&te.some(Q=>Q&&yA(o,Q,e.backend.platform)))throw new Error(`Install folder already belongs to another skill (${G}). Remove that installation or choose a different target before installing ${e.skillSlug}.`)}let d=u.installs[e.skillSlug],p=Yt(d)[c],m=JSON.stringify(p??null),h=Wu({state:"pending_activation",operationId:a,receipt:l,backend:e.backend}),g=Wu({state:"active",operationId:a,receipt:l,backend:e.backend}),y={skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,targetAgents:s.length>0?s:[e.agent.id],materializedPath:o,materializedSkillRoot:o,materializationId:c,bundlePath:i,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:r,verificationStatus:t,...Mu(e.backend),...$P(e.backend,e.agent.id,e.scope),localLifecycle:h,savedAt:e.backend.now()};await IA(i,e.bytes);let v=e.files.find(G=>ot(G.path).toLowerCase()==="skill.md"),b=v?await zae({backend:e.backend,skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,skillDocumentPath:n.join(o,...sM(v.path)),skillDocumentContent:v.content??""}):void 0,w,_=!1,C;try{let G={targetDir:o,...t==="verified"&&p?.verificationStatus==="unverified"&&!e.replaceUnverifiedSource?{expectedPreviousReceipt:l}:{},archiveBytes:e.bytes,envelope:e.envelope,preActivate:async({stageDir:ee})=>{let te=await Loe({backend:e.backend,stageDir:ee,envelope:e.envelope});return te.status==="passed"?(w=te.evalRun,{status:"passed",evidenceId:te.evidenceId}):{status:"failed",reasonCode:te.reasonCode}},checkpoint:async ee=>{if(ee==="after_static_eval"){await Br(e.backend,te=>{let Q=te.installs[e.skillSlug],Ce=Yt(Q)[c];if(JSON.stringify(Ce??null)!==m)throw new Error(`Local install materialization for ${e.skillSlug} changed during atomic activation.`);te.installs[e.skillSlug]=Fr({existing:Q,skillSlug:e.skillSlug,materialization:y,backend:e.backend})}),_=!0;return}ee==="after_stage_activated"&&await Br(e.backend,te=>{let Q=te.installs[e.skillSlug],Ce=Yt(Q)[c],pn=Ce?Jt(Ce):null;if(!pn||pn.state!=="pending_activation"||pn.operationId!==a)throw new Error(`Atomic activation receipt reservation for ${e.skillSlug} was lost before commit.`);te.installs[e.skillSlug]=Fr({existing:Q,skillSlug:e.skillSlug,materialization:{...y,localLifecycle:g,savedAt:e.backend.now()},backend:e.backend})})}};C=t==="verified"?await t2({...G,approval:e.approval}):await n2(G)}catch(G){throw _&&await mle({backend:e.backend,skillSlug:e.skillSlug,materializationId:c,operationId:a,baselineMaterialization:p}),G}if(!w)throw new Error("Static pre-activation Eval did not produce generation-bound evidence.");let P=await lt(e.backend),N=Yt(P.installs[e.skillSlug])[c],T=N?Jt(N):null;if(!T||T.state!=="active"||T.operationId!==a)throw new Error(`Atomic activation receipt for ${e.skillSlug} was not committed.`);let X=C.receipt.files.map(G=>({path:_U(e.backend.cwd,n.join(o,...sM(G.path))),bytes:G.sizeBytes}));return{...e.backend.config?.workingModeType==="enterprise_workspace"?{status:"installed"}:{},bundlePath:i,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,...Mu(e.backend),...$P(e.backend,e.agent.id,e.scope),materializedPath:o,materializedSkillRoot:o,materializationId:c,targetAgents:s.length>0?s:[e.agent.id],archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:r,verificationStatus:t,materializedWrites:X,...b?{guardianRuntimeMetadata:b}:{},localLifecycle:g,atomicActivation:{status:C.status,receipt:C.receipt,generation:C.receipt.generation,archiveSha256:C.receipt.archiveSha256,manifestSha256:C.receipt.manifestSha256,staticEvaluation:C.staticEvaluation,cleanupPending:C.cleanupPending,...C.cleanupPath?{cleanupPath:C.cleanupPath}:{}},[Ch]:w}}var Ch=Symbol("skills-layer.pre-activation-eval"),Ooe=new Set(["file_exists","json_valid","schema_match","section_exists","regex_match","artifact_valid"]);async function Loe(e){let t=await mU(e.stageDir),n=ct(t),r=yU(t,n),i=l=>nT({pack:l,files:t,activationState:"inactive_staging",skillSlug:e.envelope.generation.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,generatedAt:e.backend.now(),runnerVersion:DP()}),o=i(r.pack);if(o.outcome!=="completed")return{status:"failed",reasonCode:o.reasonCode};let s=i(vU(t,n));if(s.outcome!=="completed")return{status:"failed",reasonCode:s.reasonCode};if(s.result.summary.status!=="passed")return{status:"failed",reasonCode:`static_eval_${s.result.summary.status}`};let a=hU({files:t,skillSlug:e.envelope.generation.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,generatedAt:e.backend.now()});return{status:"passed",evidenceId:`${s.result.summary.evalPackDigest??"eval-pack-unavailable"}:${s.result.summary.artifactDigest}`,evalRun:a}}async function sA(e,t,n,r){let i=f(t,"materializedSkillRoot");if(!i)return t;let o=f(t,"skillSlug")??f(t,"slug")??n,s=f(t,"version")??f(t,"currentVersion")??k(r.version)??"local";try{let a=t[Ch],l;if(fU(a))l=a;else{let u=await mU(Tt(e.cwd,i));if(u.length===0)return dh(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"installed_files_unreadable"});l=hU({files:u,skillSlug:o,version:s,generatedAt:e.now()})}let c=await Voe(e,l.summary);return c.status==="recorded"?dh({...t,...c.effectiveness?{effectiveness:c.effectiveness}:{}},r,{status:"recorded",source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,evidenceRevision:c.evidenceRevision}):dh(t,r,{status:c.status,source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,reasonCode:c.reasonCode})}catch(a){return dh(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"local_eval_failed",message:ve(a)})}}function fU(e){return j(e)&&(e.source==="submitted"||e.source==="inferred"||e.source==="invalid_submitted")&&j(e.summary)&&e.summary.schemaVersion==="skills-layer.eval.summary.v1"}async function mU(e){let t=[];return await gU(e,e,t),t.sort((n,r)=>n.path.localeCompare(r.path))}async function gU(e,t,n){for(let r of await sre(t,{withFileTypes:!0})){if(joe(r.name))continue;let i=K(t,r.name);if(r.isDirectory()){await gU(e,i,n);continue}if(!(!r.isFile()||Foe(r.name)))try{n.push({path:Bu(e,i).split("\\").join("/"),content:await Fi(i,"utf8")})}catch{continue}}}function joe(e){return e===".git"||e==="node_modules"||e==="coverage"||e===Noe()||e==="dist"}function Noe(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}function Foe(e){return e==="bundle.zip"||/^\.skills-layer-.*\.json$/u.test(e)}function hU(e){let t=ct(e.files),n=yU(e.files,t);if(!sf(n.pack).valid)return{source:"invalid_submitted",summary:Es({status:"runner_unavailable",skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:t,evalPackDigest:Rs(n.pack),generatedAt:e.generatedAt,runnerVersion:DP(),counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})};let i=Moe(n.pack).map(s=>({id:s.id,assertions:s.assertions.map(a=>Uoe(a,e.files))})),o=zoe(i);return{source:n.source,summary:Es({status:qoe(o),skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:typeof n.pack.artifactDigest=="string"?n.pack.artifactDigest:t,evalPackDigest:Rs(n.pack),generatedAt:e.generatedAt,runnerVersion:DP(),counts:{cases:i.length,assertions:o.total,passed:o.passed,failed:o.failed,skipped:o.skipped}})}}function yU(e,t){let n=Boe(e);return n?{pack:n,source:"submitted"}:{pack:vU(e,t),source:"inferred"}}function Boe(e){for(let t of e){let n=$n(t.path,e);if(!(n.type!=="evidence"||!t.content||!n.relativePath.toLowerCase().endsWith(".eval.json")))try{let r=JSON.parse(t.content);if(j(r))return r}catch{return{schemaVersion:"invalid",artifactDigest:ct(e),origin:"submitted",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[]}}}}function vU(e,t){let r=e.find(i=>i.path.replaceAll("\\","/").split("/").at(-1)?.toLowerCase()==="skill.md")?.path??"SKILL.md";return{schemaVersion:"skills-layer.eval.pack.v1",artifactDigest:t,origin:"inferred",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[{id:"starter-runtime-shape",assertions:[{type:"file_exists",path:r},{type:"regex_match",path:r,pattern:"name:"},{type:"artifact_valid",artifactDigest:t}]}]}}function Moe(e){return Array.isArray(e.cases)?e.cases.flatMap(t=>!j(t)||typeof t.id!="string"||!Array.isArray(t.assertions)?[]:[{id:t.id,assertions:t.assertions.filter(j)}]):[]}function Uoe(e,t){return typeof e.type=="string"&&!Ooe.has(e.type)?{status:"skipped",reasonCode:"runner_unavailable"}:rf(e,{files:t})}function zoe(e){return e.reduce((t,n)=>{for(let r of n.assertions)t.total+=1,r.status==="passed"&&(t.passed+=1),r.status==="failed"&&(t.failed+=1),r.status==="skipped"&&(t.skipped+=1);return t},{total:0,passed:0,failed:0,skipped:0})}function qoe(e){return e.failed>0?"failed":e.passed>0?"passed":e.skipped>0?"runner_unavailable":"not_run"}function DP(){return`skills-layer-public-cli:${So}:local-install`}async function Voe(e,t){if(!e.apiKey)return{status:"local_only",reasonCode:"not_authenticated"};try{let n=await D(e,"/api/v1/me/evals/results",{method:"POST",headers:{"content-type":"application/json",...re(e.apiKey,e.authBlockedMessage)},body:JSON.stringify({evalSummary:t})}),r=L(n,"evalEvidence");return{status:"recorded",effectiveness:L(n,"effectiveness"),evidenceRevision:r?J(r,"revision"):void 0}}catch(n){return{status:"submit_failed",reasonCode:n instanceof Z?`http_${n.status}`:"request_failed"}}}function dh(e,t,n){return t.json?{...e,localEval:n}:e}function sM(e){let n=e.replaceAll("\\","/").replace(/^\/+/u,"").trim().split("/").filter(r=>r.length>0);if(n.length===0||n.some(r=>r==="."||r===".."))throw new Error(`Unsafe bundle path "${e}".`);return n}async function aM(e,t,n,r,i){let o=k(r.visibility)??"private";if(o!=="private"&&o!=="public")return x({status:"invalid_visibility",reasonCode:"invalid_visibility",source:e,requestedVisibility:o,nextStep:`Use \`skills-layer install ${e} --visibility private\` or \`--visibility public\`.`},"Local path install visibility must be private or public.",r.json,"invalid_visibility");let s=aA(e,t,n);if(r.list)return A(s,"Local source skills loaded.",r.json,i);let a=Ih(e,s,r);if(a)return a;let l=await ju({source:e,inspection:s,requestedSkillSlug:n,mode:"install",flags:r,backend:i});if(l.kind==="failure")return l.result;let c=l.skillSlug??ur(s)[0]?.value??bU(e),u=Goe(t.files,c),d=Wr({files:u,limits:yo}),p={mode:r.localOnly?"local_only":o==="public"?"explicit_public":"managed_private",upload:!r.localOnly,destination:r.localOnly?null:i.baseUrl,audience:r.localOnly?"local_device":o==="public"?"public_after_governed_review":"account_private",authentication:r.localOnly?"not_required":"required",files:d.preview.files.map(y=>({path:y.path,bytes:y.bytes})),totalBytes:d.preview.totalBytes};if(r.dryRun)return A({...LP(e,s,c,r),installKind:"local_source_submission",visibility:o,publicationStatus:"preview",catalogRecord:o,activationStatus:"not_started",uploadIntent:p,nextStep:r.localOnly?"Re-run without --dry-run for unverified, unscored local activation without upload.":`Re-run without --dry-run to create or reuse the ${o} central item. Local activation remains held until the exact generation completes security review and Artifact-v1 approval.`},"Local source submission preview ready.",r.json,i);if(r.localOnly){let y=await TP({backend:i,flags:r,source:e,skillSlug:c,files:u,defaultAcceptUnverifiedSource:!0});if(fe(y))return y;let v={...y,status:"installed_unverified",activationStatus:"installed_unverified",uploadIntent:p,intakeAdmission:{status:"not_requested"},assessmentStatus:"not_requested",publicationStatus:"not_requested",distributionStatus:"unverified_local",backgroundWorkStatus:"not_requested"};return await Ha(i,v,c),Va(v,"Local source installed as unverified and unscored. No files were uploaded.",r.json,i)}if(!i.apiKey)return x({reasonCode:"local_source_authentication_required",uploadIntent:p,nextStep:"Sign in for managed submission, or use --local-only for an unverified installation without upload."},"Managed local source submission requires authentication before uploading files.",r.json,"local_source_authentication_required");i.emitInfo(`Upload intent: ${p.files.length} selected files (${p.totalBytes} bytes) to ${i.baseUrl}; audience ${p.audience}; authenticated account required. Use --dry-run --json to inspect the file list or --local-only to avoid upload.`);let m=await QP(i,c,r);if(m)return m;let h;if(kU(r,i)){let y=await TP({backend:i,flags:r,source:e,skillSlug:c,files:u});if(fe(y))return y;h=y}let g;try{let y=dg(u)?await xC({baseUrl:i.baseUrl,apiKey:i.apiKey,fetchFn:i.fetchFn,files:u}):null;g=await D(i,"/api/v1/me/source-installs",{method:"POST",headers:{"content-type":"application/json",...re(i.apiKey,i.authBlockedMessage)},body:JSON.stringify(ie({...y?{hydrationManifestId:y.manifestId}:{files:u},skillSlug:c,version:k(r.version),visibility:o,category:k(r.category),displayName:k(r.displayName),skillType:k(r.skillType),sourceMetadata:t.sourceMetadata}))})}catch(y){return h?await Uu({backend:i,flags:r,source:e,fallbackSlug:c,sourceAccess:"authenticated",requestedVisibility:o,unverifiedMaterialization:h,result:{status:"catalogue_submission_failed",skillSlug:c,uploadIntent:p,reasonCode:y instanceof Z?"catalogue_submission_failed":"catalogue_submission_unavailable"}}):x({status:"catalogue_submission_failed",uploadIntent:p,activationStatus:"not_started",intakeAdmission:{status:"rejected"},assessmentStatus:"not_requested",publicationStatus:"not_published",distributionStatus:"verified_artifact_required",reasonCode:y instanceof Z?"catalogue_submission_failed":"catalogue_submission_unavailable",skillSlug:c,nextStep:"Retry the source submission when catalogue service is available. No local files were written."},"The source was not installed because catalogue submission did not complete.",r.json,"catalogue_submission_failed")}return await Uu({backend:i,result:{...g,uploadIntent:p},fallbackSlug:f(g,"skillSlug")??c,source:e,sourceAccess:"authenticated",flags:r,requestedVisibility:o,...h?{unverifiedMaterialization:h}:{}})}function Goe(e,t){let n=lA(e).find(i=>i.skillSlug===t);if(!n||n.relativeSkillRoot===".")return e.map(i=>({...i}));let r=`${n.relativeSkillRoot.replace(/\/+$/u,"")}/`;return e.filter(i=>i.path.replaceAll("\\","/").startsWith(r)).map(i=>({...i,path:i.path.replaceAll("\\","/").slice(r.length)}))}async function lM(e){if(!e.flags.all&&!(!e.defaultAcceptUnverifiedSource&&!kU(e.flags,e.backend)))try{let t=rr(e.source),n=await Sj({source:t,cwd:e.backend.cwd,platform:e.backend.platform,fetchFn:e.backend.fetchFn,...e.skillSlug?{requestedSkillSlug:e.skillSlug}:{}}),r=e.skillSlug?n.results.find(i=>i.skillSlug===e.skillSlug):n.results.length===1?n.results[0]:void 0;return r?await TP({backend:e.backend,flags:e.flags,source:e.source,skillSlug:r.skillSlug,files:r.files,relativeSkillRoot:r.relativeSkillRoot,defaultAcceptUnverifiedSource:e.defaultAcceptUnverifiedSource}):e.defaultAcceptUnverifiedSource?void 0:x({status:"unverified_source_snapshot_unavailable",reasonCode:"unverified_source_snapshot_unavailable",source:e.source,requestedSkillSlug:e.skillSlug,nextStep:"Use --list to inspect the source and --skill <skill-slug> to select one exact skill before retrying."},"The CLI could not resolve one immutable external skill snapshot for local activation.",e.flags.json,"unverified_source_snapshot_unavailable")}catch(t){return e.defaultAcceptUnverifiedSource?void 0:x({status:"unverified_source_snapshot_unavailable",reasonCode:"unverified_source_snapshot_unavailable",source:e.source,requestedSkillSlug:e.skillSlug,error:t instanceof Error?t.message.slice(0,512):"Source snapshot could not be loaded.",nextStep:"Check source access and retry the exact source after its immutable snapshot is available."},"The CLI could not load the external source snapshot for unverified local activation.",e.flags.json,"unverified_source_snapshot_unavailable")}}async function TP(e){let t=Wr({files:e.files,limits:yo}),n=nt(e.files,{profile:"external_ingest_tolerant"}),r=y2(e.files,h2),i=[...t.issues.filter(_=>_.severity==="error").map(_=>({code:_.code,concern:/^(?:secret_|pii_|sensitive_)/u.test(_.code)?"privacy":"integrity",..._.path?{path:_.path}:{}})),...n.issues.filter(_=>_.severity==="error").map(_=>({code:_.code,concern:"package_validity"})),...r.filter(_=>_.severity==="high"||_.severity==="critical").map(_=>({code:_.ruleId,concern:"security",path:_.filePath,..._.lineNumber?{lineNumber:_.lineNumber}:{}}))],o=i.map(_=>_.code);if(o.length>0){let _=i.some(C=>C.concern==="security")?"critical_local_preflight_blocked":"source_package_invalid";return x({status:"unverified_install_blocked",reasonCode:_,skillSlug:e.skillSlug,findingCodes:[...new Set(o)].sort((C,P)=>C.localeCompare(P)),blockingFindings:i,nextStep:"Do not activate this source. Review or remove the blocking content, then retry from a new immutable generation."},"External source did not satisfy the required local package checks and was not installed.",e.flags.json,_)}if(!(e.flags.acceptUnverifiedSource===!0||e.defaultAcceptUnverifiedSource===!0||await Hoe(e)))return x({status:"unverified_install_consent_required",reasonCode:"unverified_source_consent_required",skillSlug:e.skillSlug,nextStep:"Review the source, then retry with --accept-unverified-source to install it before platform approval."},"External source was not installed because informed unverified-source consent was not provided.",e.flags.json,"unverified_source_consent_required");let a=iA(e.backend,{skillSlug:e.skillSlug,materializationPlan:{scope:k(e.flags.scope)??"project",agent:k(e.flags.agent)??"codex"}},e.skillSlug,e.flags);if(a.status==="failure")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:e.skillSlug,nextStep:a.nextStep},a.message,e.flags.json,"materialization_target_invalid");if(a.status==="skip"||a.status==="cache_only")return x({status:"materialization_target_required",reasonCode:"materialization_target_required",skillSlug:e.skillSlug,nextStep:"Retry with --scope project|global and --agent <agent>."},"An explicit local target is required for an unverified external installation.",e.flags.json,"materialization_target_required");let l=await Ya({backend:e.backend,skillSlug:e.skillSlug,agentId:a.agent.id,scope:a.scope,flags:e.flags});if(l)return l;let c=ct(e.files),u=rr(e.source),d=u.kind==="github"?u.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,p=e.relativeSkillRoot,m=u.kind==="github"&&/^[a-f0-9]{40}$/u.test(u.ref)?{provider:"github",repository:`${u.owner}/${u.repo}`,commitSha:u.ref,sourceRoot:!p||p==="."?d:d==="."?p:`${d}/${p}`,sourceContentDigest:t.preview.bundleSha256}:void 0,h=c.slice(7,19),g=k(e.flags.version)??`0.0.0-external.${h}`,y=`generation_unverified_${c.slice(7,39)}`,v=e.files.filter(_=>$n(_.path,e.files).type==="runtime").map(_=>_.path),b=u0({generation:{skillSlug:e.skillSlug,semanticVersion:g,generationId:y},reviewPackageFiles:e.files,runtimeAllowlist:v});return{...await oA({backend:e.backend,skillSlug:e.skillSlug,scope:a.scope,agent:a.agent,skillsPath:a.skillsPath,bytes:b.archiveBytes,files:Cl({archiveBytes:b.archiveBytes,envelope:b.envelope}),envelope:b.envelope,verificationStatus:"unverified"}),source:e.source,sourceContentDigest:c,...m?{sourceSnapshot:{...m,runtimeDigest:c,archiveSha256:b.envelope.archive.sha256}}:{},platformScoreDecision:null,scoreAvailability:"unscored",scoreReasonCode:"unscored_local_source",localPreflight:{status:"passed",recommendation:t.issues.length+n.issues.length+r.length>0?"approved_with_notes":"approved",issueCount:t.issues.length+n.issues.length+r.length,findingCodes:[...t.issues.map(_=>_.code),...n.issues.map(_=>_.code),...r.map(_=>_.ruleId)]}}}function kU(e,t){return e.acceptUnverifiedSource===!0||!e.json&&!t.nonInteractive&&t.stdoutIsTty}async function Hoe(e){if(e.flags.json||e.backend.nonInteractive)return!1;try{return await e.backend.promptSelect(`${e.skillSlug} comes from ${e.source} and has not completed Skills Layer Security/Eval. Install this immutable generation as unverified?`,[{value:"decline",label:"Do not install",description:"Keep local agent files unchanged."},{value:"accept",label:"Install unverified",description:"Use locally now while catalogue review runs in parallel."}])==="accept"}catch{return!1}}function aA(e,t,n){let r=lA(t.files),i=n?r.find(o=>o.skillSlug===n)??null:r.length===1?r[0]??null:null;return{status:"ok",source:t.sourceMetadata,selectedSkill:i,results:r,issues:[],sourceInstallSupported:!0,sourceInstallMode:"local_private",publicationStatus:"none",originalSource:e}}function lA(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=Me(t.path).replaceAll("\\","/"),r=n==="."?".":n,i=wU(t.content??"")??bU(r==="."?t.path:r),o=Koe(t.content??"");return{skillSlug:i,name:i,...o?{description:o}:{},relativeSkillRoot:r,relativeSkillFile:t.path,sourceKind:"local",discoveryRoute:"local_bundle",validation:{valid:!0,issueCount:0}}})}function wU(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function Koe(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function bU(e){return(e.replaceAll("\\","/").replace(/\/+$/u,"").split("/").filter(Boolean).at(-1)??"local-skill").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||"local-skill"}function _U(e,t){let n=Bu(e,t);return n&&!n.startsWith("..")&&!st.isAbsolute(n)?n.split("\\").join("/"):t}function Ti(e,t,n,r="unknown"){let i=k(t.visibility);return i==="public"||i==="private"?i:r==="anonymous"&&OP(e)?"public":r==="authenticated"?"private":!n.apiKey&&OP(e)?"public":"private"}function OP(e){try{let t=rr(e).kind;return t==="github"||t==="gitlab"}catch{return/^https:\/\/(?:github|gitlab)\.com\//iu.test(e.trim())}}function cA(e,t,n,r="unknown"){return Ti(e,t,n,r)==="private"||k(t.visibility)==="unlisted"||r==="authenticated"?"/api/v1/me/source-installs":"/api/v1/source-imports"}function SU(e,t,n,r="unknown"){return{"content-type":"application/json",...cA(e,t,n,r)==="/api/v1/me/source-installs"?re(n.apiKey,n.authBlockedMessage):{}}}function Woe(e,t,n,r,i="unknown"){let o=r?f(r,"visibility")??f(r,"versionVisibility"):void 0,s=r?f(r,"publicationStatus"):void 0,a=r?f(r,"catalogRecord"):void 0,l=r?f(r,"status"):void 0;return o==="public"||s==="clean_publishable"||s==="publishable_with_findings"||l==="published"?"Public source install planned.":o==="private"||s==="private"||a==="private"||l==="private_source_installed"?"Private source skill installed.":Ti(e,t,n,i)==="public"?"Public source install planned.":"Private source skill installed."}async function ju(e){let t=ur(e.inspection);if(e.requestedSkillSlug)return t.length>0&&!t.some(n=>n.value===e.requestedSkillSlug)?{kind:"failure",result:Zoe(e.source,e.requestedSkillSlug,t.map(n=>n.value),e.flags)}:{kind:"selected",skillSlug:e.requestedSkillSlug};if(e.flags.all||e.flags.json&&e.flags.dryRun)return{kind:"selected",skillSlug:e.requestedSkillSlug};if(t.length<=1)return{kind:"selected",skillSlug:t[0]?.value};if(e.flags.json)return{kind:"failure",result:cM(e.source,t,e.flags)};try{return{kind:"selected",skillSlug:await e.backend.promptSelect(`${e.source} exposes multiple skills. Select one to ${e.mode}:`,t)}}catch{return{kind:"failure",result:cM(e.source,t,e.flags)}}}function cM(e,t,n){let r=t.map(i=>i.value);return x({status:"selection_required",reasonCode:"source_skill_selection_required",source:e,availableSkills:r,nextAction:"install.source.select",nextStep:`Re-run with --skill <skill-slug> using one of: ${r.join(", ")}. Use --all only if you intend to install every discovered skill.`},`Source "${e}" exposes multiple skills. Re-run with --list or --skill <skill-slug>. Available skills: ${r.join(", ")}.`,n.json,"source_skill_selection_required")}function uM(e,t,n){if(n.all&&t)return x({status:"error",reasonCode:"conflicting_source_selection",source:e,selectedSkillSlug:t,all:!0,nextAction:"install",nextStep:"Use either --all to install every discovered skill or --skill <skill-slug> to install one skill, not both."},"Source install cannot combine --all with --skill. Choose one selection mode before retrying.",n.json,"conflicting_source_selection")}function dM(e,t){try{if(rr(e).kind!=="local")return}catch{return}return x({status:"error",reasonCode:"invalid_source",source:e,nextAction:"install",nextStep:zu(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source URL, or run `skills-layer install --source <source> --list` with a supported source."},zu(e)?`Install source ${e} was not found or is not readable.`:`Install source "${e}" is not a supported remote source and no local path was found.`,t.json,"invalid_source")}function Zoe(e,t,n,r){return x({status:"not_found",reasonCode:"source_skill_not_found",source:e,requestedSkillSlug:t,availableSkills:n,nextAction:"install.source.list",nextStep:`Run \`skills-layer install --source ${e} --list\` to inspect discovered skills, then retry with one of the listed slugs.`},`Source ${e} does not contain a discovered skill named ${t}. Run with --list to inspect available skills.`,r.json,"source_skill_not_found")}function ur(e){let t=[e.results,e.skills,e.discoveredSkills,L(e,"source")?.results,L(e,"inspection")?.results],n=new Set,r=[];for(let i of t)if(Array.isArray(i))for(let o of i){let s=Joe(o);!s||n.has(s.value)||(n.add(s.value),r.push(s))}return r}function Joe(e){if(!j(e))return;let t=f(e,"skillSlug")??f(e,"slug")??f(e,"name");if(!t)return;let n=f(e,"displayName")??f(e,"title")??f(e,"name"),r=n&&n!==t?`${t} - ${n}`:t,i=L(e,"parsedSkill"),o=L(e,"frontmatter")??(i?L(i,"frontmatter"):void 0),s=f(e,"shortDescription")??f(e,"summary")??f(e,"description")??(o?f(o,"description"):void 0)??f(e,"relativeSkillRoot")??f(e,"path")??f(e,"discoveryRoute")??f(e,"sourceKind");return s?{value:t,label:r,description:s}:{value:t,label:r}}function pM(e,t,n,r,i,o={}){return ie({...t,skillSlug:n,scope:k(r.scope),agent:k(r.agent),workspace:k(r.workspace),version:k(r.version),visibility:o.visibility??k(r.visibility),category:k(r.category),displayName:k(r.displayName),skillType:k(r.skillType),all:r.all,acceptCapability:r.acceptCapability})}async function fM(e){let t=e.sourceAccess??"unknown",n=cA(e.source,e.flags,e.backend,t);try{return await D(e.backend,n,{method:"POST",headers:SU(e.source,e.flags,e.backend,t),body:JSON.stringify(pM(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{sourceAccess:t,...n==="/api/v1/source-imports"?{visibility:"public"}:{}}))})}catch(r){if(r instanceof Z&&r.status===401&&k(e.flags.visibility)!=="private"&&t!=="authenticated"&&OP(e.source))return await D(e.backend,"/api/v1/source-imports",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(pM(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{visibility:"public"}))});throw r}}function LP(e,t,n,r){return ie({status:"dry_run",source:e,selectedSkillSlug:n,all:r.all,scope:k(r.scope)??"local",agent:k(r.agent),workspace:k(r.workspace),acceptCapability:r.acceptCapability,candidates:ur(t).map(i=>({skillSlug:i.value,name:i.label,description:i.description})),nextStep:r.all?`Re-run without --dry-run to install every discovered skill from ${e}.`:`Re-run without --dry-run${n?"":" and add --skill <skill-slug> if needed"} to install from ${e}.`})}async function xU(e,t,n,r,i={}){try{return{kind:"ok",inspection:await D(e,"/api/v1/source-inspect",{method:"POST",headers:CU(e,i.authMode??"auto"),body:JSON.stringify(ie(n))})}}catch(o){if(o instanceof Z)return{kind:"failure",result:NP(t,o,r)};throw o}}function CU(e,t){return t==="anonymous"?{"content-type":"application/json"}:V(e.apiKey)}async function jP(e,t,n,r){try{let s=await D(e,"/api/v1/source-inspect",{method:"POST",headers:CU(e,"anonymous"),body:JSON.stringify(ie(n))}),a=mM(t,s,r);return a?{kind:"failure",result:a}:{kind:"ok",inspection:s,sourceAccess:"anonymous"}}catch(s){if(!(s instanceof Z))throw s;let a=s.details??{},l=f(a,"error")??s.message;if(!uA(s.status,l))return{kind:"failure",result:NP(t,s,r)};if(!e.apiKey)return{kind:"failure",result:NP(t,s,r)}}let i=await xU(e,t,n,r,{authMode:"authenticated"});if(i.kind==="failure")return i;let o=mM(t,i.inspection,r);return o?{kind:"failure",result:o}:{kind:"ok",inspection:i.inspection,sourceAccess:"authenticated"}}function mM(e,t,n){if(n.list||n.dryRun)return null;let r=[t.catalogueDecision,...Array.isArray(t.catalogueDecisions)?t.catalogueDecisions:[]].filter(i=>i!==void 0);for(let i of r){let o=j(i)?i.status:void 0;if(!j(i)||i.schemaVersion!=="skills-layer.source-catalogue-decision.v1"||!["approved","pending","new"].includes(String(o))){let s=["security_blocked","revoked","restricted","unavailable"].includes(String(o))?`source_catalogue_${o}`:"source_catalogue_identity_invalid";return x({status:s,reasonCode:s,source:e,catalogueDecision:i,nextStep:"Resolve the current catalogue decision before retrying this exact source."},"This source cannot be activated under its current catalogue decision.",n.json,s)}}if(t.catalogueSourceInput!==void 0){let i=rr(e),o=typeof t.catalogueSourceInput=="string"?rr(t.catalogueSourceInput):void 0,s=l=>l.replace(/(?:^|\/)SKILL\.md$/u,"")||".";if(!(i.kind==="github"&&o?.kind==="github"&&`${i.owner}/${i.repo}`.toLowerCase()===`${o.owner}/${o.repo}`.toLowerCase()&&s(i.subpath)===s(o.subpath)&&/^[a-f0-9]{40}$/u.test(o.ref)&&(!/^[a-f0-9]{40}$/iu.test(i.ref)||i.ref.toLowerCase()===o.ref)&&r.every(l=>{let c=j(l)?L(l,"subject"):void 0,u=c?f(c,"sourceRoot"):void 0,d=s(o.subpath);return c?.commitSha===o.ref&&typeof c.repository=="string"&&c.repository.toLowerCase()===`${o.owner}/${o.repo}`.toLowerCase()&&u&&(u==="."||!u.split("/").some(p=>!p||p==="."||p===".."||/[\\\p{Cc}\p{Cf}]/u.test(p)))&&(d==="."||u===d||u.startsWith(`${d}/`))})))return x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",source:e},"The inspected snapshot does not identify this exact source.",n.json,"source_catalogue_identity_invalid")}return null}function Ih(e,t,n){if(ur(t).length>0)return null;let i=Yoe(t);return x({status:"unsupported_source_layout",source:e,reasonCode:"source_no_discoverable_skills",issues:i,nextStep:"Run with --list to inspect the source, use a subfolder containing SKILL.md, or install from a Skills Layer-compatible source layout."},Xoe(e,i),n.json)}function Yoe(e){return(Array.isArray(e.issues)?e.issues:[]).filter(j).map(n=>({...f(n,"code")?{code:f(n,"code")}:{},...f(n,"message")?{message:f(n,"message")}:{},...f(n,"path")?{path:f(n,"path")}:{}}))}function NP(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(uA(t.status,i))return IU(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Go(t,n.json);let s={status:"unsupported_source_layout",source:e,reasonCode:"source_not_inspectable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return x(s,`Source ${e} could not be inspected as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}function gM(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(uA(t.status,i))return IU(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Go(t,n.json);let s={status:"unsupported_source_layout",source:e,reasonCode:"source_not_installable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return x(s,`Source ${e} could not be installed as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}async function hM(e){let t=e.error instanceof Z?e.error.details??{}:{},n=e.error instanceof Z?f(t,"reasonCode")??"catalogue_submission_failed":"catalogue_submission_unavailable";return await Uu({backend:e.backend,result:{...t,status:"catalogue_submission_failed",reasonCode:n,publiclyDiscoverable:!1},fallbackSlug:e.skillSlug,source:e.source,sourceAccess:e.sourceAccess,flags:e.flags,requestedVisibility:Ti(e.source,e.flags,e.backend,e.sourceAccess),unverifiedMaterialization:e.unverifiedMaterialization})}function uA(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function IU(e,t,n,r){let i=t.details??{},o=f(i,"error")??t.message,a=`skills-layer source connection start --provider ${PU(e)} --source ${e} --visibility private --provenance-intent private_source_import`,l={status:"private_source_access_required",source:e,reasonCode:"private_source_access_required",backendStatus:t.status,backendMessage:o,nextStep:a};return x(l,`Cloud could not ${r} ${e} directly. If this is a private source, start a private source connection first:
|
|
2151
|
+
> `)}catch(u){throw uP(u,n)}let c;try{c=zp(i.currentQuestion.id,l)}catch(u){r=ve(u);continue}try{n=await D(t,`/api/v1/creator/sessions/${encodeURIComponent(String(n.sessionId))}/turn-answers`,{method:"POST",headers:V(t.apiKey),body:JSON.stringify({expectedRevision:n.revision,idempotencyKey:PP("creator-turn",{sessionId:n.sessionId,revision:n.revision,questionId:i.currentQuestion.id,answer:c}),questionId:i.currentQuestion.id,answer:c})}),r=null}catch(u){if(u instanceof Z&&u.status===422){r=ve(u);continue}throw uP(u,n)}}}async function QB(e,t,n){await Ve(K(t.paths.stateDir,"creator-resume.json"),{version:1,baseUrl:t.baseUrl,sessionId:String(e.sessionId),skillSlug:qa(e,!1)?.skillSlug??null,revision:e.revision,completed:n,savedAt:t.now()})}function uP(e,t){let n=qa(t,!1)?.skillSlug||String(t.sessionId),r=e instanceof Z&&e.status===409?" The server revision is authoritative; reload it before answering again.":"";return new Error(`${ve(e)}${r} Resume with skills-layer creator resume ${n}.`)}function qa(e,t=!0){let n=e.data,r=n&&typeof n=="object"&&!Array.isArray(n)?n.turn:null;if(!r||typeof r!="object"||Array.isArray(r)){if(t)throw new Error("Creator response did not include the canonical interview turn");return null}return r}async function eoe(e,t,n){let r=k(t.skill)??e[0]??"my-skill",i=QM("creator.init",r,t);if(i)return i;let o=k(t.dir)?Tt(n.cwd,k(t.dir)):K(n.paths.stateDir,"authoring",r),s;try{s=d1(k(t.type))}catch(y){return E(ve(y),t.json)}let a=k(t.category),l=await F1(o),c=await Mk({cwd:n.cwd,files:l.files,explicitIdentifier:k(t.license),explicitLicenseFile:k(t.licenseFile),skip:!!t.skipLicense,interactive:!t.json&&n.stdoutIsTty,prompt:nU(n)}),u=p1({skillSlug:r,description:k(t.description)??`Helps with ${r.replaceAll("-"," ")}.`,skillType:s,category:a,licenseSelection:c.selection}),d=await Jp({targetDir:o,files:u,confirmed:t.confirmed});if(d.status==="confirmation_required"){let y={status:"confirmation_required",reasonCode:"scaffold_overwrite_confirmation_required",targetDir:d.plan.targetDir,changes:d.plan.changes,preservedEntryCount:d.plan.preservedEntryCount,nextAction:"creator.init",nextStep:"Review the reported create/replace diff, then rerun with --confirm only if every replacement is intended."};return x(y,rU(d.plan),t.json,"scaffold_overwrite_confirmation_required")}let p=nt(u),m=Hk(u),h=K(d.plan.targetDir,"SKILL.md"),g=ie({status:d.status,path:h,skillSlug:r,skillType:s,category:a,targetDir:d.plan.targetDir,files:u.map(y=>y.path),fileCount:u.length,licenseStatus:p.license?.status??"unspecified",licenseIdentifier:p.license?.identifier??void 0,licenseSource:c.source,evaluationStatus:m.status,evalReadiness:m,warnings:[...p.issues.filter(y=>y.severity==="warning"),...m.status==="attention_needed"?[{severity:"warning",code:"evaluation_readiness_limited",message:"The scaffold is structurally valid, but its evaluation readiness needs attention before submission."}]:[]],validation:p});return t.json?R(g,`Created ${h}.`,!0,n):{exitCode:0,stdout:Zle(g,d.plan.targetDir,h,n),stderr:""}}function nU(e){return{select:(t,n)=>e.promptSelect(t,n),text:t=>e.promptText(t)}}function rU(e){let t=e.changes.map(n=>`- ${n.action} ${n.path} (${n.previousBytes??0} -> ${n.nextBytes} bytes)`);return[`Creator init target already contains files at ${e.targetDir}.`,...t,"Re-run with --confirm only after reviewing every replacement."].join(`
|
|
2152
|
+
`)}async function pr(e){try{return await zM(e),!0}catch{return!1}}function iU(e){return e.attestRights?{attestRights:!0,rightsBasis:k(e.rightsBasis)??"self_authored",distributionScope:k(e.distributionScope)??"commercial_distribution",rightsDeclarationVersion:Hj}:{}}async function AP(e,t,n,r){let i=k(t.visibility);if(i){let P=uc(i);if(!P||!Lu.includes(P))return Nr(r?"creator.submit-version":"creator.submit","visibility",i,Lu,t,"invalid_visibility")}let o=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(o.failure)return o.failure;let s=k(t.spacePack),a=s===void 0?void 0:oc(s);if(a===null)return Nr(r?"creator.submit-version":"creator.submit","spacePack",s,["5","10","20","50"],t,"invalid_private_skill_space_pack","space-pack");let l=k(t.creatorSessionId);if(l){let P=r?O(k(t.skill)??e[0],"creator submit-version with --creator-session-id requires a skill slug."):null,N=r?{creatorSessionId:l,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",...t.dryRun?{dryRun:!0}:{}}:{creatorSessionId:l,...t.dryRun?{dryRun:!0}:{},...a?{privateSkillSpacePack:a}:{}},T=r?`/api/v1/me/submissions/${encodeURIComponent(P)}/versions`:"/api/v1/me/submissions",X=await D(n,T,{method:"POST",headers:eM(n,t.dryRun?null:{path:T,creatorSessionId:l}),body:JSON.stringify(N)});return tM(X,t,n)??R(X,t.dryRun?"Submission preview ready.":X.status==="submission_incomplete"?`Creator session submission is incomplete. ${f(X,"nextStep")??"Retry this session submission to complete finalization."}`:"Finalized Creator session submitted.",t.json,n)}let c=r?O(k(t.skill)??e[0],"creator submit-version requires a skill slug."):k(t.skill),u=O(k(t.source)??(r?e[1]:e[0])??t.path,`creator ${r?"submit-version":"submit"} requires a <path-or-source> or --source <source>.`),d=await Hu(u,n.cwd);if(t.list)return await ioe(u,d,c,t,n);let p=Oi(r?"creator.submit-version":"creator.submit",t);if(p)return p;if(!d&&!zu(u)&&(xz(u)||/^(?:github|gitlab):/iu.test(u)))return ooe(u,t);let m=d?.files??(await ma({cwd:n.cwd,sourcePath:u,limits:yo})).files;if(!r&&!t.dryRun){let P=await soe(m,t,n);if(P)return P}if(t.dryRun&&dg(m))return toe(m,{slug:c,flags:t,backend:n});let h=dg(m)?await xC({baseUrl:n.baseUrl,apiKey:n.apiKey,fetchFn:n.fetchFn,files:m}):null,g=ie({...h?{hydrationManifestId:h.manifestId}:{files:m},version:k(t.version),dryRun:t.dryRun,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",evalSummary:Zie(m,{skillSlug:c??tA(m)??"unknown",version:k(t.version)??"0.0.0",generatedAt:n.now()}),replaceUnpublished:r&&t.replaceUnpublished===!0?!0:void 0,priceCents:o.value,privateSkillSpacePack:a,...iU(t),...d?{sourceMetadata:d.sourceMetadata}:{},...Ft(t,["displayName","skillType","category","visibility","source","skill"])}),y=r&&c?`/api/v1/me/submissions/${encodeURIComponent(c)}/versions`:"/api/v1/me/submissions",v=await D(n,y,{method:"POST",headers:eM(n,t.dryRun?null:{path:y,request:g,files:m}),body:JSON.stringify(g)});if(t.json||t.noOpen||v.status!=="checkout_required"||typeof v.checkoutUrl!="string"||typeof v.chargeId!="string")return tM(v,t,n)??R(v,t.dryRun?"Submission preview ready.":r?"Version submitted.":"Submission uploaded.",t.json,n);let b=L(v,"spacePack"),w=b?oc(b.code):null;n.emitInfo(w?`No private skill space is left. Opening checkout for ${Bp(w).label} (${Bp(w).displayPrice}); other packs: --space-pack 5|10|20|50. Complete the payment in your browser, then come back here.`:"Opening payment setup for skill submission. Complete the payment in your browser, then come back here."),await n.openUrl(v.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${v.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let C=await ele(v.chargeId,n);return fe(C)?C:C.status!=="submitted"?R({...v,chargeStatus:C.status},`Payment is still ${C.status}. You can rerun \`skills-layer creator charge-status ${v.chargeId}\` to continue tracking it.`,t.json,n):R(C,r?"Version submitted.":"Submission uploaded.",t.json,n)}function eM(e,t){let n=V(e.apiKey);if(!t)return n;let{hydrationManifestId:r,files:i,evalSummary:o,...s}=t.request??{},a=t.files?Ue("sha256").update(JSON.stringify(t.files.map(c=>[c.path,c.content??null,c.contentBase64??null]))).digest("hex"):null,l=Ue("sha256").update(JSON.stringify({path:t.path,creatorSessionId:t.creatorSessionId??null,request:s,bundleDigest:a})).digest("hex");return{...n,"idempotency-key":`cli-submit-${l.slice(0,48)}`}}function tM(e,t,n){if(e.status!=="checkout_required"||typeof e.checkoutUrl!="string"||typeof e.chargeId!="string")return null;let r=`Open ${e.checkoutUrl} to complete payment, then run \`skills-layer creator charge-status ${e.chargeId}\` to confirm the submission.`;return R({...e,paymentRequired:!0,checkoutUrl:e.checkoutUrl,chargeId:e.chargeId,nextAction:"creator.charge-status",nextStep:r},`Payment required to finish: ${r}`,t.json,n)}function toe(e,t){let n="creator.submit",r=nt(e),i=e.reduce((l,c)=>l+cs(c),0),o=t.slug??tA(e),s=["skill_name_availability","security_review","moderation","pricing_and_checkout","eval_evidence"],a=ie({status:r.valid?"ready":"blocked",reasonCode:r.valid?"local_preview_only":"invalid_bundle",dryRun:!0,previewMode:"local",operation:n,uploaded:!1,skillSlug:o,version:k(t.flags.version),bundle:{fileCount:e.length,totalBytes:i,transport:"source_hydration",artifactDigest:ct(e)},localChecks:[{check:"bundle_size",status:"passed"},{check:"paths",status:"passed"},{check:"secrets",status:"passed"},{check:"manifest",status:r.valid?"passed":"failed"}],serverChecks:{status:"not_run",checks:s},why:"The bundle exceeds the 2 MiB inline request limit, so the dry run previewed it locally and uploaded nothing.",validation:r,nextAction:r.valid?n:"validate",nextStep:r.valid?`Re-run without --dry-run to upload and submit. Server-only checks (${s.join(", ")}) run during the real submit.`:"Fix the bundle issues before submitting again."});return R(a,r.valid?`Local submission preview ready (${e.length} files, ${i} bytes; nothing uploaded). Server-only checks run on the real submit: ${s.join(", ")}.`:"Local submission preview blocked: the bundle does not satisfy the creator validation rules. Nothing was uploaded.",t.flags.json,t.backend)}var noe="Use `skills-layer creator spaces` or `skills-layer creator spaces buy --pack 5|10|20|50`.";function nM(e){if(e.status==="community_unlimited")return"Community edition supports unlimited private skills.";let t=n=>typeof e[n]=="number"?e[n]:0;return`Private skill spaces: ${t("availablePrivateSkillSpaces")} available of ${t("totalPrivateSkillSpaces")} (${t("activePrivateSkills")} active private skills; free ${t("freePrivateSkillSpacesUsed")} used, ${t("freePrivateSkillSpacesRemaining")} left; purchased ${t("purchasedPrivateSkillSpaces")}, ${t("purchasedPrivateSkillSpacesUsed")} used). Buy more with \`skills-layer creator spaces buy --pack 5|10|20|50\`: ${sc}.`}async function roe(e,t,n){let r=e[0];if(r===void 0||r==="status"){let u=await D(n,"/api/v1/me/private-skill-spaces",{headers:re(n.apiKey,n.authBlockedMessage)});return R(u,nM(u),t.json,n)}if(r!=="buy")return E(`Unknown creator spaces action "${r}". ${noe}`,t.json);let i=k(t.pack)??e[1],o=i===void 0?void 0:oc(i);if(o===null)return Nr("creator.spaces.buy","pack",i,["5","10","20","50"],t,"invalid_private_skill_space_pack","pack");let s=await D(n,"/api/v1/me/private-skill-spaces/checkout",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(o?{privateSkillSpacePack:o}:{})});if(s.status!=="checkout_required"||typeof s.checkoutUrl!="string")return R(s,nM(s),t.json,n);let a=Bp(oc(L(s,"spacePack")?.code)??"spaces_5"),l=`Checkout for ${a.label} (${a.displayPrice}) is ready. Complete the payment in your browser, then run \`skills-layer creator spaces\` to see the credited spaces.`;return t.json||t.noOpen?R(s,`${l} Checkout URL: ${s.checkoutUrl}`,t.json,n):(await n.openUrl(s.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${s.checkoutUrl}`),R(s,l,t.json,n))}async function ioe(e,t,n,r,i){if(t)return R(rM(aA(e,t,n)),"Source skills loaded.",r.json,i);let o=await xU(i,e,{source:e,skillSlug:n,listOnly:!0,operation:"creator.submit"},r);return o.kind==="failure"?o.result:R(rM(o.inspection),"Source skills loaded.",r.json,i)}function rM(e){return{...e,sourceSubmissionSupported:!0}}function ooe(e,t){let r=`skills-layer source connection start --provider ${PU(e)} --source ${e} --visibility private --provenance-intent private_source_import`;return x({status:"source_connection_required",reasonCode:"source_connection_required",source:e,nextAction:"source.connection.start",nextStep:r},`Creator submit can list ${e} safely, but publishing from a remote source requires a source connection. Run \`${r}\`.`,t.json,"source_connection_required")}async function soe(e,t,n){let r=k(t.skill)??tA(e);if(!r)return null;let i;try{i=await D(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(r)}`,{headers:re(n.apiKey,n.authBlockedMessage)})}catch(o){if(o instanceof Z&&o.status===404)return oU(r,t);throw o}if(i.available===!1||f(i,"reasonCode")==="unavailable"||f(i,"reasonCode")==="reserved"){let o=f(i,"assignedSlug"),s=ie({status:"duplicate_candidate",reasonCode:f(i,"reasonCode")??"slug_unavailable",requestedSlug:r,assignedSlug:o,nextAction:"creator.status",nextStep:`Run \`skills-layer creator status ${r}\`, \`skills-layer creator submissions\`, or submit a new version of the existing skill instead of creating a duplicate listing.`});return x(s,`A public skill slug "${r}" already exists or is not available. Run \`skills-layer creator status ${r}\`, check your creator submissions, or submit a new version instead of creating a duplicate listing.`,t.json,f(s,"reasonCode"))}return null}async function aoe(e,t,n){try{let r=await D(n,`/api/v1/me/creator/slug-check?slug=${encodeURIComponent(e)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return R(loe(r),"Slug status loaded.",t.json,n)}catch(r){if(r instanceof Z&&r.status===404)return oU(e,t);throw r}}function oU(e,t){let n={status:"slug_check_unavailable",reasonCode:"slug_check_route_unavailable",requestedSlug:e,nextAction:"creator.status",nextStep:`Slug availability could not be checked on the selected backend. Run \`skills-layer creator submissions\`, \`skills-layer creator status ${e}\`, or retry after selecting a compatible Skills Layer backend.`};return x(n,`Slug availability could not be checked for ${e} on the selected backend. Run \`skills-layer creator submissions\` or retry after selecting a compatible Skills Layer backend.`,t.json,"slug_check_route_unavailable")}function loe(e){let t=e.available===!0,n=f(e,"assignedSlug");if(t)return ie({requestedSlug:f(e,"requestedSlug"),available:!0,reasonCode:f(e,"reasonCode")??"available",assignedSlug:n});let r=L(e,"slugAssignment"),i=Array.isArray(r?.candidateSlugs)?r.candidateSlugs.filter(o=>typeof o=="string").slice(0,3):void 0;return ie({...e,...r?{slugAssignment:{...r,...i?{candidateSlugs:i}:{}}}:{},...i?{candidateSlugs:i}:{}})}function coe(e,t){return x({status:"not_submitted",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submit",nextStep:"Run `skills-layer creator submit <path> --dry-run` to validate a local skill before submitting it, or run `skills-layer creator submissions` to see your existing submissions."},`No creator submission was found for ${e}. Run \`skills-layer creator submit <path> --dry-run\` before checking status.`,t.json,"creator_submission_not_found")}function tA(e){let t=e.find(r=>r.path.split("/").pop()?.toLowerCase()==="skill.md");if(!t)return;let n=/^---\s*\n(?<body>[\s\S]*?)\n---/u.exec(t.content??"")?.groups?.body?.split(/\r?\n/u).map(r=>r.match(/^name\s*:\s*(?<name>.+?)\s*$/u)?.groups?.name?.trim().replace(/^["']|["']$/gu,"")).find(r=>!!r);return uoe(n??ot(Me(t.path)))}function uoe(e){return e?.toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||void 0}async function doe(e,t,n){let r=O(e[1],"creator pricing requires a skill slug."),i=Oi("creator.pricing",t);if(i)return i;let o=new URLSearchParams;if(Ke(o,"version",t.version),!t.priceCents)return await me(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,t,n,"Pricing loaded.",{authenticated:!0});let s=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(s.failure)return s.failure;let a=s.value??0;if(t.dryRun){o.set("dryRun","true"),o.set("priceCents",String(a));let d=await D(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,{headers:re(n.apiKey,n.authBlockedMessage)});return d.dryRun!==!0||d.status!=="preview"?E("This backend does not support read-only pricing previews. Upgrade the backend before retrying.",t.json):R(d,"Pricing preview; the live price is unchanged.",t.json,n)}let l=await D(n,`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing${Qe(o)}`,{headers:re(n.apiKey,n.authBlockedMessage)}),c=J(l,"priceCents")??0,u=J(l,"revision");if(!u||!Number.isSafeInteger(u)||u<1)return E("Pricing authority did not return a valid revision.",t.json);if(a>c&&!t.confirmed){let d=ie({status:"pending_approval",reasonCode:"price_increase_confirmation_required",skillSlug:r,version:f(l,"version"),currentPriceCents:c,requestedPriceCents:a,currency:f(l,"currency")??"usd",nextStep:"Review the old and new USD prices, then rerun with --yes."});return R(d,"Pricing change requires explicit confirmation.",t.json,n)}return await Li(`/api/v1/me/submissions/${encodeURIComponent(r)}/pricing`,{priceCents:a,confirmPriceIncrease:t.confirmed,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:k(t.version),expectedRevision:u,idempotencyKey:k(t.idempotencyKey)?.trim()||`pricing-${Ge(12).toString("hex")}`,reason:"Creator changed the version list price through CLI.",...iU(t)},t,n,"Pricing updated.")}async function poe(e,t,n){let r=Mn("creator.update-listing","listingStatus",t.listingStatus,kie,t,"invalid_listing_status","listing-status");if(r)return r;try{return await Li(`/api/v1/me/submissions/${encodeURIComponent(e)}`,Ft(t,["displayName","summary","description","category","skillType","license","listingStatus"]),t,n,"Listing updated.")}catch(i){if(i instanceof Z&&i.status===404){let o={status:"listing_not_found_or_not_editable",reasonCode:"creator_listing_not_found_or_not_owned",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see editable listings, or \`skills-layer show ${e}\` to inspect the public catalog entry.`};return x(o,`No editable creator listing was found for ${e}. Run \`skills-layer creator submissions\` to see listings you can update.`,t.json,"creator_listing_not_found_or_not_owned")}throw i}}async function foe(e,t,n,r){let i=O(t[1],`creator ${e} requires a skill slug.`);if(e==="claim"){let o=Mn("creator.claim","requestedRole",n.requestedRole,vie,n,"invalid_requested_role","requested-role");if(o)return o}try{if(e==="claim")return await Oe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/claim`,Ft(n,["requestedRole","message"]),n,r,"Ownership claim submitted.");if(e==="verify"){let o=O(n.claimId,"creator verify requires --claim-id.");return await Oe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/verify`,{claimId:o},n,r,"Ownership claim verified.")}return O(n.message,"creator dispute requires --message."),await Oe(`/api/v1/me/skills/${encodeURIComponent(i)}/ownership/dispute`,Ft(n,["message"]),n,r,"Ownership dispute submitted.")}catch(o){if(o instanceof Z&&o.status===404){let s={status:"ownership_action_unavailable",reasonCode:e==="claim"?"skill_not_found_or_not_claimable":"ownership_claim_not_found",skillSlug:i,requestedRole:k(n.requestedRole),nextAction:e==="claim"?"search":"creator.claim",nextStep:e==="claim"?`Run \`skills-layer search ${i}\`, \`skills-layer show ${i}\`, or submit/source-install the skill before claiming it.`:`Run \`skills-layer creator claim ${i}\` to start a new claim if the skill is claimable.`};return x(s,e==="claim"?`No claimable skill was found for ${i}. Search or show the skill first, then claim it only when it exists and is claimable.`:`No matching ownership claim was found for ${i}. Start a new claim if the skill is claimable.`,n.json,f(s,"reasonCode")??"ownership_action_unavailable")}throw o}}async function moe(e,t,n){try{return await me(`/api/v1/me/submissions/${encodeURIComponent(e)}/analytics`,t,n,"Analytics loaded.",{authenticated:!0})}catch(r){if(r instanceof Z&&r.status===404){let i={status:"no_creator_submission",reasonCode:"creator_submission_not_found",skillSlug:e,nextAction:"creator.submissions",nextStep:`Run \`skills-layer creator submissions\` to see skills you own, \`skills-layer show ${e}\` to inspect the catalog listing, or \`skills-layer creator claim ${e}\` if it is a claimable public-source skill.`};return x(i,`No creator-owned analytics submission was found for ${e}. Run \`skills-layer creator submissions\`, \`skills-layer show ${e}\`, or \`skills-layer creator claim ${e}\` if you should manage it.`,t.json,"creator_submission_not_found")}throw r}}async function goe(e,t){let n=await D(t,"/api/v1/me/payout-profile",{headers:re(t.apiKey,t.authBlockedMessage)});return R(n,"Creator payout profile loaded.",e.json,t)}function sU(e,t){let n={};return(r,i)=>TA({session:n,code:k(e.mfaCode),interactive:!e.json&&!t.nonInteractive&&t.stdoutIsTty,promptSecret:t.promptSecret,verify:async o=>{let s=await D(t,"/api/v1/identity/mfa/verify",{method:"POST",headers:V(t.apiKey),body:JSON.stringify({purpose:"creator_payout",code:o})});return O(s.stepUpGrant,"MFA verification did not return a step-up grant.")},request:o=>{let s=new Headers(i.headers);return o&&s.set("x-mfa-step-up-grant",o),D(t,r,{...i,headers:s})}})}async function iM(e,t){let n=hoe(k(e.mode));if(e.mode&&n===null)return E("creator payout-link --mode must be account_onboarding|account_update|onboarding|update.",e.json);let r;try{r=await sU(e,t)("/api/v1/me/payout-profile/link",{method:"POST",headers:V(t.apiKey),body:JSON.stringify(ie({...n?{mode:n}:{},country:k(e.country)}))})}catch(o){if(o instanceof Z&&voe(o))return x({status:"payout_setup_already_submitted",reasonCode:"payout_update_link_unavailable",nextAction:"creator.payout-profile",nextStep:"Run `skills-layer creator payout-profile` to confirm readiness, then use `skills-layer creator earnings` or `skills-layer creator withdraw --amount-cents <amount>`."},"Payout setup is already submitted for this account. Run `skills-layer creator payout-profile` to confirm readiness before requesting a withdrawal.",e.json,"payout_update_link_unavailable");throw o}let i=sz(r);return i&&yoe(e)&&e.showUrl!==!0&&(t.emitInfo("Opening payout setup in your browser. Finish the flow there, then come back here."),await t.openUrl(i)||t.emitInfo(`Open this payout setup URL manually to continue: ${i}`)),R(r,"Payout setup link created.",e.json,t)}function hoe(e){if(!e)return null;let t=e.trim().toLowerCase();return t==="account_onboarding"||t==="onboarding"?"account_onboarding":t==="account_update"||t==="update"?"account_update":null}function yoe(e){return!e.json&&!e.noOpen}function voe(e){let t=`${e.message} ${f(e.details??{},"error")??""}`.toLowerCase();return t.includes("account_update")&&t.includes("account_onboarding")&&t.includes("account link")}async function koe(e,t,n,r){let i=O(t[1],`creator ${e} requires a skill slug.`);if(e==="issues")return await me(`/api/v1/me/skills/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});if(e==="reviews")return await me(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews`,n,r,"Reviews loaded.",{authenticated:!0});if(e==="update-issue"){let l=O(n.issueId,"creator update-issue requires --issue-id."),c=O(n.status,"creator update-issue requires --status."),u=Mn("creator.update-issue","status",c,wie,n,"invalid_issue_status");if(u)return u;let d=Oi("creator.update-issue",{...n,version:n.fixedVersion});if(d)return d;try{return await Li(`/api/v1/me/skills/${encodeURIComponent(i)}/issues/${encodeURIComponent(l)}`,Ft(n,["status","fixedVersion","note"]),n,r,"Issue updated.")}catch(p){if(p instanceof Z&&p.status===404)return woe(i,l,n);throw p}}let o=O(n.reviewId,"creator moderate-review requires --review-id."),s=O(n.status,"creator moderate-review requires --status."),a=Mn("creator.moderate-review","status",s,bie,n,"invalid_review_status");if(a)return a;try{return await Oe(`/api/v1/me/submissions/${encodeURIComponent(i)}/reviews/${encodeURIComponent(o)}/moderate`,Ft(n,["status","reason"]),n,r,"Review updated.")}catch(l){if(l instanceof Z&&l.status===404)return boe(i,o,n);throw l}}function woe(e,t,n){return x({status:"not_found",reasonCode:"issue_not_found",skillSlug:e,issueId:t,nextAction:"creator.issues",nextStep:`Run \`skills-layer creator issues ${e}\` to inspect open issues before updating one.`},`Issue ${t} was not found for ${e}. Run \`skills-layer creator issues ${e}\` first.`,n.json,"issue_not_found")}function boe(e,t,n){return x({status:"not_found",reasonCode:"review_not_found",skillSlug:e,reviewId:t,nextAction:"creator.reviews",nextStep:`Run \`skills-layer creator reviews ${e}\` to inspect review ids before moderating one.`},`Review ${t} was not found for ${e}. Run \`skills-layer creator reviews ${e}\` first.`,n.json,"review_not_found")}async function _oe(e,t,n){let r=e[0],i=O(e[1],`creator source ${r??""} requires a source connection id.`),o=k(t.skill)??e[2];if(r==="prepare"){let s=Oi("creator.source.prepare",t);if(s)return s;let a=Mn("creator.source.prepare","visibility",t.visibility,za,t,"invalid_visibility");if(a)return a;let l=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=k(t.source)??e[2],u=c?await Hu(c,n.cwd):void 0;return await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/prepare`,ie({...Ft(t,["skill","source","version","displayName","skillType","category","visibility"]),...l.value!==void 0?{priceCents:l.value}:{},source:c,...u?{files:u.files}:{}}),t,n,"Source release prepared.")}if(r==="publish-request"){let s=Oi("creator.source.publish-request",t);if(s)return s;let a=Mn("creator.source.publish-request","visibility",t.visibility,za,t,"invalid_visibility");if(a)return a;let l=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(l.failure)return l.failure;let c=t.approvalRequestId.length>0?t.approvalRequestId:k(t.approvalRequestId)?[String(t.approvalRequestId)]:[];return await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/publish-request`,ie({skillSlug:o,approvalRequestIds:c,confirmPriceIncrease:t.confirmed,confirmPriceDecrease:t.confirmFree===!0&&t.priceCents==="0",version:k(t.version),...Ft(t,["visibility","license","discloseSource"]),...l.value!==void 0?{priceCents:l.value}:{}}),t,n,"Source publish requested.")}if(r==="release-status"){let s=new URLSearchParams;return o&&s.set("skill",o),await me(`/api/v1/me/source-connections/${encodeURIComponent(i)}/release-status${Qe(s)}`,t,n,"Source release status loaded.",{authenticated:!0})}return E(`Unknown creator source command "${r??""}".`,t.json)}function RP(e){return!e.list&&!e.dryRun}async function oM(e){if(!RP(e.flags)||k(e.flags.visibility)==="private"||k(e.flags.scope)==="workspace")return null;if(e.flags.all&&Array.isArray(e.inspection.catalogueDecisions)){let p=[];for(let m of ur(e.inspection)){let h=await Wa([],{...e.flags,all:!1,json:!0,source:f(e.inspection,"catalogueSourceInput")??e.source,skill:m.value},e.backend);if(h.exitCode!==0){let g=JSON.parse(h.stderr||h.stdout);return x({status:"source_install_batch_partial",reasonCode:g.reasonCode??"source_install_child_failed",failedSkill:m.value,results:p,failure:g.data},"Source installation stopped; earlier results are retained.",e.flags.json,g.reasonCode??"source_install_child_failed")}p.push(JSON.parse(h.stdout).data)}return R({status:"source_install_batch",results:p},"Source installation results loaded.",e.flags.json,e.backend)}let t=L(e.inspection,"catalogueMatch");if(!t&&e.selectedSkillSlug&&typeof e.inspection.catalogueSourceInput=="string"){let p=await jP(e.backend,e.source,{source:e.inspection.catalogueSourceInput,skillSlug:e.selectedSkillSlug,preferCatalogue:!0,listOnly:!0},e.flags);if(p.kind==="failure")return p.result;t=L(p.inspection,"catalogueMatch"),t&&(e.inspection=p.inspection)}if(!t)return null;let n=rr(e.source),r=f(t,"skillSlug"),i=f(t,"version"),o=f(t,"generationId"),s=n.kind==="github"?n.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,l=(Array.isArray(e.inspection.results)?e.inspection.results:[]).find(p=>j(p)&&p.skillSlug===e.selectedSkillSlug),c=j(l)?f(l,"relativeSkillRoot"):void 0,u=c&&s&&c!=="."?s==="."||c===s||c.startsWith(`${s}/`)?c:`${s}/${c}`:void 0,d=typeof t.sourceRoot=="string"&&(t.sourceRoot==="."||!t.sourceRoot.split("/").some(p=>!p||p==="."||p===".."||/[\\\p{Cc}\p{Cf}]/u.test(p)));return n.kind!=="github"||t.schemaVersion!=="skills-layer.source-catalogue-match.v1"||typeof t.repository!="string"||t.repository.toLowerCase()!==`${n.owner}/${n.repo}`.toLowerCase()||!d||t.sourceRoot!==s&&t.sourceRoot!==u||typeof t.commitSha!="string"||!/^[a-f0-9]{40}$/u.test(t.commitSha)||/^[a-f0-9]{40}$/iu.test(n.ref)&&n.ref.toLowerCase()!==t.commitSha||!r||!/^[a-z0-9][a-z0-9-]{0,255}$/u.test(r)||!i||!o||e.selectedSkillSlug&&e.selectedSkillSlug!==t.requestedSkillSlug?x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",source:e.source,nextStep:"Retry after the exact source-to-catalogue identity is refreshed. No raw-source fallback was activated."},"The catalogue match did not identify this exact GitHub skill and revision.",e.flags.json,"source_catalogue_identity_invalid"):Wa([r],{...e.flags,source:void 0,skill:void 0,version:i},e.backend,{...aU,expectedSourceGeneration:{generationId:o,version:i}})}var aU={origin:"direct",fallbackPolicy:"eligible_public"};function Soe(e){return{origin:"update_existing",fallbackPolicy:f(e??{},"acquisitionMode")==="authenticated_account"?"account_required":"eligible_public"}}async function Wa(e,t,n,r=aU){if(e[0]==="status"&&e[1])return me(`/api/v1/install-receipts/${encodeURIComponent(e[1])}`,t,n,"Install progress loaded.",{authenticated:!!n.apiKey});let i=tU("install",t);if(i)return i;if(t.localOnly&&(t.visibility!==void 0||k(t.scope)==="workspace"||n.config?.workingModeType==="enterprise_workspace"))return x({status:"local_only_intent_conflict",reasonCode:"local_only_intent_conflict"},"Local-only installation requires a personal local target and cannot request platform visibility or workspace authority.",t.json,"local_only_intent_conflict");let o=k(t.source);if(o){let h=k(t.skill),g=uM(o,h,t);if(g)return g;let y=await Hu(o,n.cwd);if(y)return await aM(o,y,h,t,n);if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let v=dM(o,t);if(v)return v;let b=t.list||t.dryRun||!h&&!t.all,w=await jP(n,o,{source:o,skillSlug:h,listOnly:b,...t.all?{all:!0}:{},preferCatalogue:RP(t),visibility:k(t.visibility)},t);if(w.kind==="failure")return w.result;let _=w.inspection;if(t.list)return R(_,"Source skills loaded.",t.json,n);let C=Ih(o,_,t);if(C)return C;let P=await ju({source:o,inspection:_,requestedSkillSlug:h,mode:"install",flags:t,backend:n});if(P.kind==="failure")return P.result;if(t.dryRun)return R(LP(o,_,P.skillSlug,t),"Source install preview ready.",t.json,n);let N=t.all?ur(_).map(Q=>Q.value):[P.skillSlug??ur(_)[0]?.value??ot(o)],T=await oM({inspection:_,source:o,selectedSkillSlug:P.skillSlug,flags:t,backend:n});if(T)return T;let X=await UB(n,N,t);if(X)return X;let G=f(_,"catalogueSourceInput")??o,ee=await lM({backend:n,flags:t,source:G,skillSlug:P.skillSlug,defaultAcceptUnverifiedSource:Ti(o,t,n,w.sourceAccess)==="public"});if(fe(ee))return ee;let te;try{te=await fM({source:G,skillSlug:P.skillSlug,flags:t,backend:n,sourceAccess:w.sourceAccess})}catch(Q){if(ee)return await hM({backend:n,flags:t,source:G,sourceAccess:w.sourceAccess,skillSlug:P.skillSlug??N[0],unverifiedMaterialization:ee,error:Q});if(Q instanceof Z)return gM(o,Q,t);throw Q}return await Uu({backend:n,result:te,fallbackSlug:P.skillSlug??f(te,"skillSlug")??o,source:G,sourceAccess:w.sourceAccess,flags:t,requestedVisibility:Ti(o,t,n,w.sourceAccess),...ee?{unverifiedMaterialization:ee}:{}})}let s=O(e[0]??t.install,"install requires a skill slug or --source.");if(xz(s)){let h=uM(s,k(t.skill),t);if(h)return h;let g=await Hu(s,n.cwd);if(g)return await aM(s,g,k(t.skill),t,n);if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");let y=dM(s,t);if(y)return y;let v=k(t.skill),b,w="unknown",_=async Q=>{if(b)return null;let Ce=await jP(n,s,{source:s,skillSlug:v,listOnly:Q,...t.all?{all:!0}:{},preferCatalogue:RP(t),visibility:k(t.visibility)},t);return Ce.kind==="failure"?Ce.result:(b=Ce.inspection,w=Ce.sourceAccess,null)};if(t.list){let Q=await _(!0);return Q||R(b,"Source skills loaded.",t.json,n)}if(!v&&!t.all){let Q=await _(!0);if(Q)return Q;let Ce=b,pn=Ih(s,Ce,t);if(pn)return pn;let Qa=await ju({source:s,inspection:Ce,requestedSkillSlug:v,mode:"install",flags:t,backend:n});if(Qa.kind==="failure")return Qa.result;v=Qa.skillSlug}if(t.dryRun){let Q=await _(!0);if(Q)return Q;let Ce=b,pn=await ju({source:s,inspection:Ce,requestedSkillSlug:v,mode:"install",flags:t,backend:n});return pn.kind==="failure"?pn.result:(v=pn.skillSlug,R(LP(s,Ce,v,t),"Source install preview ready.",t.json,n))}let C=await _(!1);if(C)return C;let P=b,N=t.all?ur(P).map(Q=>Q.value):[v??ur(P)[0]?.value??ot(s)],T=await oM({inspection:P,source:s,selectedSkillSlug:v,flags:t,backend:n});if(T)return T;let X=await UB(n,N,t);if(X)return X;let G=f(P,"catalogueSourceInput")??s,ee=await lM({backend:n,flags:t,source:G,skillSlug:v,defaultAcceptUnverifiedSource:Ti(s,t,n,w)==="public"});if(fe(ee))return ee;let te;try{te=await fM({source:G,skillSlug:v,flags:t,backend:n,sourceAccess:w})}catch(Q){if(ee)return await hM({backend:n,flags:t,source:G,sourceAccess:w,skillSlug:v??N[0],unverifiedMaterialization:ee,error:Q});if(Q instanceof Z)return gM(s,Q,t);throw Q}return await Uu({backend:n,result:te,fallbackSlug:v??f(te,"skillSlug")??ot(s),source:G,sourceAccess:w,flags:t,requestedVisibility:Ti(s,t,n,w),...ee?{unverifiedMaterialization:ee}:{}})}if(t.localOnly)return x({reasonCode:"local_only_source_required"},"--local-only requires an existing local folder.",t.json,"local_only_source_required");if(k(t.scope)==="workspace"){let h=O(t.workspace,"workspace installs require --workspace <workspace-id>."),g=await lU(n,`/api/v1/workspaces/${encodeURIComponent(h)}/skills/${encodeURIComponent(s)}/approve`,{dryRun:t.dryRun},t);return fe(g)?g:t.dryRun?await ese(g,"Workspace approval preview ready.",t,n):R(g,"Workspace approval requested.",t.json,n)}if(!n.apiKey&&r.fallbackPolicy==="eligible_public")return await dP({target:s,flags:t,backend:n,catalogContext:r});if(!t.dryRun){let h;try{h=await QP(n,s,t)}catch(g){if(EP(r,g))return await dP({target:s,flags:t,backend:n,catalogContext:r});throw g}if(h)return h}let a=await uU(s,t,n);if("result"in a)return a.result;let l=a.flags,c=ie({skillSlug:s,version:k(l.version),scope:k(l.scope),agent:k(l.agent),dryRun:t.dryRun}),u;try{u=await nA(n,c,t)}catch(h){if(EP(r,h))return await dP({target:s,flags:t,backend:n,catalogContext:r,effectiveFlags:l});throw h}if(fe(u))return u;let d=u;if(d.status==="purchase_required")return DU(d,s,t,n);if(await ji(n,d),t.dryRun)return await AU(d,l,n);let p=await rA(n,d,s,l,{expectedSourceGeneration:r.expectedSourceGeneration});if(fe(p))return p;let m=await sA(n,{...p,acquisitionMode:"authenticated_account",acquisitionOrigin:r.origin},s,l);return await Ha(n,m,s),Va(m,Array.isArray(m.materializedWrites)&&m.materializedWrites.length>0?"Skill installed.":l.agent?"Recorded; choose --scope project|global to install files.":"Recorded; no agent selected \u2014 rerun with --agent <id> to write the skill files.",t.json,n,k(l.agent))}async function dP(e){let t=e.backend.apiKey?{...e.backend,apiKey:void 0,authBlockedMessage:void 0}:e.backend,n=e.effectiveFlags;if(!n){let o=await uU(e.target,e.flags,e.backend);if("result"in o)return o.result;n=o.flags}let r=k(n.version),i={status:"anonymous_public",skillSlug:e.target,...r?{version:r}:{},scope:k(n.scope),agent:k(n.agent),acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin};if(e.flags.dryRun)try{let o=await bh(t,i,e.target,r,{exportMode:"public"});return await AU({...i,...Sh(o)},e.flags,t)}catch(o){if(o instanceof Z)return Go(o,e.flags.json);throw o}try{let o=await rA(t,i,e.target,n,{exportMode:"public",expectedSourceGeneration:e.catalogContext.expectedSourceGeneration});if(fe(o))return o;let s=await sA(t,{...o,acquisitionMode:"anonymous_public",acquisitionOrigin:e.catalogContext.origin},e.target,n);return await Ha(t,s,e.target),Va(s,"Public skill installed locally without an account.",e.flags.json,t)}catch(o){if(o instanceof Z)return Go(o,e.flags.json);throw o}}function EP(e,t){return e.fallbackPolicy==="eligible_public"&&t instanceof Z&&t.status===401&&f(t.details??{},"reasonCode")==="api_key_invalid_or_expired"}async function lU(e,t,n,r){let i=o=>D(e,t,{method:"POST",headers:V(e.apiKey),body:JSON.stringify(o)});try{return await i(n)}catch(o){let s=cU(o);if(!s)throw o;return r.json||!e.stdoutIsTty?x({status:"warning_required",reasonCode:s.reasonCode,distributionPosture:s.posture,nextAction:"acknowledge_distribution_warning"},"A Guardian warning must be acknowledged before workspace approval. Interactive acknowledgement is unavailable in this mode.",r.json,"warning_acknowledgement_required"):(e.emitInfo(`Guardian warning: ${s.posture.effectiveDistributionStatus} (${s.posture.reasonCode}).`),await e.promptSelect("Approve this exact warned generation for the workspace?",[{value:"cancel",label:"Cancel approval",description:"Do not approve or materialize the skill."},{value:"acknowledge",label:"Acknowledge and continue",description:"Bind approval to this warning revision."}])!=="acknowledge"?x({status:"cancelled",reasonCode:"distribution_warning_declined",distributionPosture:s.posture},"Workspace approval cancelled without granting value.",r.json,"distribution_warning_declined"):i({...n,distributionWarningAcknowledgement:{contractVersion:s.posture.contractVersion,warningDigest:s.posture.warningDigest,authorityRevision:s.posture.authorityRevision,accepted:!0}}))}}async function nA(e,t,n,r="/api/v1/install"){let i=o=>D(e,r,{method:"POST",headers:V(e.apiKey),body:JSON.stringify(o)});try{return await i(t)}catch(o){let s=cU(o);if(!s)throw o;return n.json||!e.stdoutIsTty?x({status:"warning_required",reasonCode:s.reasonCode,distributionPosture:s.posture,nextAction:"acknowledge_distribution_warning"},"A Guardian warning must be acknowledged before install. Interactive acknowledgement is unavailable in this mode.",n.json,"warning_acknowledgement_required"):(e.emitInfo(`Guardian warning: ${s.posture.effectiveDistributionStatus} (${s.posture.reasonCode}). Next action: ${s.posture.nextAction}.`),await e.promptSelect("Continue with this exact warned skill generation?",[{value:"cancel",label:"Cancel install",description:"Do not grant or materialize the skill."},{value:"acknowledge",label:"Acknowledge and continue",description:"Bind consent to this warning and authority revision."}])!=="acknowledge"?x({status:"cancelled",reasonCode:"distribution_warning_declined",distributionPosture:s.posture},"Install cancelled without granting value.",n.json,"distribution_warning_declined"):await i({...t,distributionWarningAcknowledgement:{contractVersion:s.posture.contractVersion,warningDigest:s.posture.warningDigest,authorityRevision:s.posture.authorityRevision,accepted:!0}}))}}function cU(e){if(!(e instanceof Z)||e.status!==409||!e.details)return null;let t=j(e.details.data)?e.details.data:e.details,n=j(t.distributionPosture)?t.distributionPosture:null,r=n?.contractVersion,i=n?.warningDigest,o=n?.authorityRevision;return!n||r!=="skills-layer.distribution.v1"||typeof i!="string"||!/^sha256:[a-f0-9]{64}$/u.test(i)||typeof o!="number"||!Number.isSafeInteger(o)||o<1?null:{reasonCode:typeof t.reasonCode=="string"?t.reasonCode:"warning_acknowledgement_required",posture:{contractVersion:r,warningDigest:i,authorityRevision:o,effectiveDistributionStatus:typeof n.effectiveDistributionStatus=="string"?n.effectiveDistributionStatus:"published_with_warning",reasonCode:typeof n.reasonCode=="string"?n.reasonCode:"guardian_incident_warning",nextAction:typeof n.nextAction=="string"?n.nextAction:"review_warning_before_install"}}}async function uU(e,t,n){let r=k(t.scope),i=k(t.agent);if(t.json||t.dryRun||!n.stdoutIsTty||r==="workspace"||r==="local"||r!==void 0&&i!==void 0)return{flags:t};let o=et(n.env,n.platform,n.cwd),s=xoe(n),a=await Coe(n.paths.installTargetPreferencePath),l=a?.workingModeId===s,c=l&&a?.agent?o.find(w=>w.id===a.agent):void 0,u=c&&a?.scope?a.scope==="global"?c.targets.globalSkillsPath:c.targets.projectSkillsPath:void 0;if(i===void 0&&r===void 0&&a?.policy==="recheck_every_5"&&l&&c!==void 0&&(a.scope==="project"||a.scope==="global")&&u!==void 0&&a.usesSinceConfirmation>0&&a.usesSinceConfirmation<4)return await Ve(n.paths.installTargetPreferencePath,{...a,usesSinceConfirmation:a.usesSinceConfirmation+1,savedAt:n.now()}),{flags:{...t,agent:c.id,scope:a.scope}};let p=await WA({env:n.env,platform:n.platform,cwd:n.cwd,pathExists:pr}),m=p.filter(w=>w.detectionSources.includes("project")),h=i??Re(n.env.SKILLS_LAYER_AGENT),g=h?o.find(w=>w.id===h):void 0;if(h&&!g)return{result:E(`Unsupported agent "${h}". Run \`skills-layer agents list\` to choose a supported install target.`,t.json)};if(!g&&m.length===1&&(g=m[0]),!g){let w=Re(n.config?.lastSelectedAgent);g=w?p.find(_=>_.id===w)??o.find(_=>_.id===w):void 0}if(!g&&p.length===1&&(g=p[0]),!g&&p.length>1){let w=await n.promptSelect("Multiple supported agents were detected. Select one to install for:",p.map(_=>({value:_.id,label:`${_.displayName} (${_.detectionSources.join(", ")})`})));g=p.find(_=>_.id===w)}if(!g)return{result:E("No supported local agent was detected. Run `skills-layer agents list`, then retry with --agent <agent> and --scope <project|global>.",t.json)};let y=r;if(!y){let w=[{value:"project",label:"Project (this folder)"}];g.targets.globalSkillsPath&&w.push({value:"global",label:"Global (all projects)"}),y=w.length===1?w[0].value:await n.promptSelect(`Install ${e} for ${g.displayName} where?`,w)}let v=i!==void 0||r!==void 0,b=a?.policy==="ask_every_time"&&l;if(!v&&!b&&(y==="project"||y==="global")){let w=y==="project"?"Project":"Global",C=await n.promptSelect(`Remember ${g.displayName} / ${w} for future installs?`,[{value:"recheck_every_5",label:"Yes - recheck on every 5th install"},{value:"ask_every_time",label:"No - ask every time"}])==="recheck_every_5"?{version:1,policy:"recheck_every_5",agent:g.id,scope:y,usesSinceConfirmation:1,workingModeId:s,savedAt:n.now()}:{version:1,policy:"ask_every_time",usesSinceConfirmation:0,workingModeId:s,savedAt:n.now()};await Ve(n.paths.installTargetPreferencePath,C)}return{flags:{...t,agent:g.id,scope:y}}}function xoe(e){return e.apiKey?Re(e.config?.workingModeId)??"personal":"anonymous"}async function Coe(e){let t=await ke(e);return!j(t)||t.version!==1||t.policy!=="recheck_every_5"&&t.policy!=="ask_every_time"||typeof t.workingModeId!="string"||typeof t.savedAt!="string"||typeof t.usesSinceConfirmation!="number"||!Number.isInteger(t.usesSinceConfirmation)||t.usesSinceConfirmation<0||t.agent!==void 0&&typeof t.agent!="string"||t.scope!==void 0&&t.scope!=="project"&&t.scope!=="global"?null:t}async function rA(e,t,n,r,i={}){if(k(r.agent)==="all")return await Ioe(e,t,n,r,i);let o=iA(e,t,n,r);if(o.status==="skip")return t;if(o.status==="cache_only"){let h=await bh(e,t,o.skillSlug,o.version,i),g=await xh({backend:e,exportResult:h,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(g))return g;let v=(e.platform==="win32"?st:Lt).join(e.paths.bundlesDir,o.skillSlug,g.envelope.generation.semanticVersion,encodeURIComponent(g.envelope.generation.generationId),"bundle.zip");return await IA(v,g.bytes),{...t,...Sh(h),version:g.envelope.generation.semanticVersion,scope:"local",archiveSha256:g.archiveSha256,archiveHashFormat:g.archiveHashFormat,manifestSha256:g.envelope.manifest.sha256,generationId:g.envelope.generation.generationId,sourceContentDigest:ct(g.files),verificationStatus:"verified",cachedArtifact:{state:"verified",bundlePath:v,generation:g.envelope.generation,archiveSha256:g.archiveSha256,manifestSha256:g.envelope.manifest.sha256,savedAt:e.now()}}}if(o.status==="failure")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:o.skillSlug,nextStep:o.nextStep},o.message,r.json,"materialization_target_invalid");let s=await Ya({backend:e,skillSlug:o.skillSlug,agentId:o.agent.id,scope:o.scope,flags:r});if(s)return s;let a=await bh(e,t,o.skillSlug,o.version,i),l=await xh({backend:e,exportResult:a,flags:r,skillSlug:o.skillSlug,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(l))return l;let c=(await lt(e)).installs[o.skillSlug],u=qn(c,{scope:o.scope,installedPath:(e.platform==="win32"?st:Lt).join(o.skillsPath,Mr(o.skillSlug)),platform:e.platform})[0]?.record,d=u?f(u,"sourceContentDigest"):void 0,p=ct(l.files);if(u?.verificationStatus==="unverified"&&!r.replaceUnverifiedSource&&(await Dr({targetDir:(e.platform==="win32"?st:Lt).join(o.skillsPath,Mr(o.skillSlug)),generation:l.envelope.generation,archiveSha256:l.archiveSha256,manifestSha256:l.envelope.manifest.sha256,files:l.envelope.manifest.files})).status!=="verified")return x({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:o.skillSlug,installedArchiveSha256:u.archiveSha256,approvedArchiveSha256:l.archiveSha256,installedContentDigest:d,approvedContentDigest:p,verificationStatus:"unverified",nextStep:"The installed bytes were left unchanged. Review the source difference and retry with --replace-unverified-source to replace them with the approved catalogue generation."},"The approved catalogue artifact differs from the installed unverified generation; no local files were replaced.",r.json,"verification_digest_mismatch");let m=await oA({backend:e,skillSlug:o.skillSlug,scope:o.scope,agent:o.agent,skillsPath:o.skillsPath,bytes:l.bytes,files:l.files,envelope:l.envelope,approval:l.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});return{...t,...Sh(a),archiveSha256:l.archiveSha256,archiveHashFormat:l.archiveHashFormat,scope:o.scope,agent:o.agent.id,targetAgent:o.agent.id,materializationPlan:{scope:o.scope,agent:o.agent.id},...Mu(e),...m,...m.guardianActivationReceipt?{warnings:[...Be(t,"warnings")??[],...Be(m,"warnings")??[]]}:{}}}async function Ioe(e,t,n,r,i){let o=L(t,"materializationPlan")??L(t,"installPlan"),s=k(r.scope)??f(t,"scope")??(o?f(o,"scope"):void 0),a=f(t,"skillSlug")??f(t,"slug")??n;if(s!=="project"&&s!=="global")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:a,nextStep:"Use --agent all with --scope project or --scope global."},"Installing for all compatible agents requires project or global scope.",r.json,"materialization_target_invalid");let l=et(e.env,e.platform,e.cwd),c=new Map;for(let w of l){let _=s==="global"?w.targets.globalSkillsPath:w.targets.projectSkillsPath;if(!_)continue;let C=Bo(_,e.platform),P=c.get(C);P?P.agents.push(w):c.set(C,{agent:w,agents:[w],skillsPath:_})}if(c.size===0)return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:a,nextStep:"Run `skills-layer agents list` and select a supported target with an available path."},`No supported agent exposes a ${s} skill path on this machine.`,r.json,"materialization_target_invalid");for(let w of c.values())for(let _ of w.agents){let C=await Ya({backend:e,skillSlug:a,agentId:_.id,scope:s,flags:r});if(C)return C}let u=f(t,"version")??f(t,"currentVersion"),d=await bh(e,t,a,u,i),p=await xh({backend:e,exportResult:d,flags:r,skillSlug:a,expectedSourceGeneration:i.expectedSourceGeneration});if(fe(p))return p;let m=ct(p.files),h=(await lt(e)).installs[a],g;if(!r.replaceUnverifiedSource)for(let w of c.values()){let _=(e.platform==="win32"?st:Lt).join(w.skillsPath,Mr(a)),C=qn(h,{scope:s,installedPath:_,platform:e.platform})[0];if(C?.record.verificationStatus==="unverified"&&(await Dr({targetDir:_,generation:p.envelope.generation,archiveSha256:p.archiveSha256,manifestSha256:p.envelope.manifest.sha256,files:p.envelope.manifest.files})).status!=="verified"){g=C;break}}if(g)return x({status:"verification_digest_mismatch",reasonCode:"verification_digest_mismatch",skillSlug:a,materializationId:g.materializationId,installedContentDigest:f(g.record,"sourceContentDigest"),approvedContentDigest:m,verificationStatus:"unverified",nextStep:"The installed bytes were left unchanged. Review the source difference and use --replace-unverified-source to replace the unverified generation."},"The approved catalogue artifact differs from an installed unverified generation; no local files were replaced.",r.json,"verification_digest_mismatch");let y=[];for(let w of c.values()){let _=await oA({backend:e,skillSlug:a,scope:s,agent:w.agent,skillsPath:w.skillsPath,bytes:p.bytes,files:p.files,envelope:p.envelope,approval:p.approval,replaceUnverifiedSource:r.replaceUnverifiedSource===!0});y.push({...t,scope:s,agent:w.agent.id,targetAgent:w.agent.id,...Mu(e),..._})}let v=y[0],b=v[Ch];return{...t,...Sh(d),archiveSha256:p.archiveSha256,archiveHashFormat:p.archiveHashFormat,scope:s,agent:"all",targetAgents:l.map(w=>w.id),materializationPlan:{scope:s,agent:"all",physicalTargetCount:y.length,agentCount:l.length},materializationResults:y,materializedWrites:y.flatMap(w=>Array.isArray(w.materializedWrites)?w.materializedWrites:[]),materializedSkillRoot:f(v,"materializedSkillRoot"),...Mu(e),...fU(b)?{[Ch]:b}:{}}}async function Ya(e){let t=e.backend.config?.workingModeType==="enterprise_workspace",n=e.enforceRequired?"enforce":await rd(e.backend,e.skillSlug);if(!t&&n!=="enforce"&&n!=="enabled")return null;let r=Re(e.backend.config?.workingModeWorkspaceId);if(t&&!r)return x({status:"blocked",reasonCode:"guardian_workspace_context_unavailable",skillSlug:e.skillSlug,agent:e.agentId,scope:e.scope,nextAction:"workspace.current",nextStep:"Refresh the selected Enterprise workspace before materializing this skill."},"Enterprise materialization requires a current workspace-bound Guardian context.",e.flags.json,"guardian_workspace_context_unavailable");let i=await zn(e.backend,e.scope),o=(Be(i,"hooks")??[]).filter(j).find(u=>f(u,"agent")===e.agentId&&f(u,"scope")===e.scope&&u.active===!0),s=wr(e.agentId),a=yl({evaluationContext:"activation_eligibility",requestedMode:"enforce",workspacePolicy:t?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:s?.maximumTier==="strict_candidate",hookInstalled:!!o,strictHookVerified:o?.strictPreActionBlocking===!0&&o.evidenceCapability==="strict",exactActivationVerified:o?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"none",materializationState:"active"}),l=a.activationAllowed&&a.countedAsEnforced,c=t&&e.backend.config.workingModeGuardianPolicy==="standard"&&o!==void 0&&o.configActive!==!1;return l||c?(t&&(e.backend.guardianActivationReceipts??={},e.backend.guardianActivationReceipts[`${e.agentId}:${e.scope}`]={policy:e.backend.config.workingModeGuardianPolicy==="standard"?"standard":"strict",agent:e.agentId,scope:e.scope,tier:l?"strict_verified":"hook_unverified",observedAt:e.backend.now()}),null):x({status:"blocked",reasonCode:"guardian_enforcement_unavailable",skillSlug:e.skillSlug,workspaceId:r,agent:e.agentId,scope:e.scope,measuredProtection:{...a,evidenceCapability:o?.evidenceCapability??"unverified",evidenceReasons:o?.evidenceReasons??[s?.reasonCode??"host_has_no_supported_guardian_route"]},nextAction:"guardian.hook.install",nextStep:!o||o.configActive===!1?`Run skills-layer guardian hook install --agent ${e.agentId} --scope ${e.scope}.`:e.backend.config?.workingModeRole==="enterprise_admin"?`This host has no current strict verification. Select a qualified host or use skills-layer enterprise workspace update ${e.backend.config?.workingModeEnterpriseId??"<enterprise-id>"} ${r??"<workspace-id>"} --guardian-policy standard. Hook installation alone does not prove strict enforcement.`:"This host has no current strict verification. Ask your Enterprise Admin to select a qualified host or review the workspace Guardian policy. Hook installation alone does not prove strict enforcement."},t&&e.backend.config.workingModeGuardianPolicy==="standard"&&(!o||o.configActive===!1)?`No active Guardian hook is installed for ${e.agentId} at ${e.scope} scope.`:`${t?"Enterprise":"Guardian-enforced"} materialization was blocked because verified Guardian enforcement is unavailable.`,e.flags.json,"guardian_enforcement_unavailable")}function $P(e,t,n){let r=e.guardianActivationReceipts?.[`${t}:${n}`];return r?{guardianEnforcement:r.tier,guardianActivationReceipt:r,...r.tier==="hook_unverified"?{warnings:[`Guardian hook installed but not strict-verified on ${t}; workspace policy allows standard enforcement.`]}:{}}:{}}function Mu(e){return e.config?.workingModeType!=="enterprise_workspace"?{}:ie({workingModeType:"enterprise_workspace",enterpriseId:e.config.workingModeEnterpriseId,workspaceId:e.config.workingModeWorkspaceId,workingModeWorkspaceId:e.config.workingModeWorkspaceId})}function iA(e,t,n,r){let i=L(t,"materializationPlan")??L(t,"installPlan"),o=k(r.scope)??f(t,"scope")??(i?f(i,"scope"):void 0),s=f(t,"skillSlug")??f(t,"slug")??n;if(o==="local")return{status:"cache_only",skillSlug:s,version:f(t,"version")??f(t,"currentVersion")};if(o!=="project"&&o!=="global")return{status:"skip"};let a=k(r.agent)??f(t,"agent")??f(t,"targetAgent")??(i?f(i,"agent")??f(i,"targetAgent"):void 0)??Re(e.config?.lastSelectedAgent)??"codex",l=et(e.env,e.platform,e.cwd).find(u=>u.id===a);if(!l)return{status:"failure",skillSlug:s,message:`Unsupported agent "${a}". Run \`skills-layer agents list\` to choose a supported local install target.`,nextStep:"Run `skills-layer agents list` and retry with a supported --agent value."};let c=o==="global"?l.targets.globalSkillsPath:l.targets.projectSkillsPath;return c?{status:"ok",scope:o,agent:l,skillsPath:c,skillSlug:s,version:f(t,"version")??f(t,"currentVersion")}:{status:"failure",skillSlug:s,message:`${l.displayName} does not expose a ${o} skills path on this machine.`,nextStep:"Retry with --scope project, or choose another agent from `skills-layer agents list`."}}async function bh(e,t,n,r,i={}){if(typeof t.downloadUrl=="string"&&j(t.artifactEnvelope)&&j(t.artifactApproval)&&j(t.platformScoreAuthority))return t;let o=new URLSearchParams;r&&o.set("version",r);let s=i.exportMode==="public"||!e.apiKey,a=s?`/api/v1/skills/${encodeURIComponent(n)}/export${Qe(o)}`:`/api/v1/me/library/${encodeURIComponent(n)}/export${Qe(o)}`,l=await D(e,a,{headers:s?{}:re(e.apiKey,e.authBlockedMessage)});if(!s&&!j(l.platformScoreAuthority))try{let c=await D(e,`/api/v1/skills/${encodeURIComponent(n)}/export${Qe(o)}`,{headers:{}});return{...l,platformScoreAuthority:c.platformScoreAuthority}}catch(c){if(!(c instanceof Z)||![401,403,404].includes(c.status))throw c}return s?{...l,downloadUrl:Poe(n,f(l,"version")??r)}:l}function Poe(e,t){let n=new URLSearchParams;return t&&n.set("version",t),`/api/v1/skills/${encodeURIComponent(e)}/download${Qe(n)}`}function Aoe(e){let t=f(e,"visibility")??f(e,"versionVisibility"),n=f(e,"publicationStatus");return dU(e)&&(t==="public"||n==="clean_publishable"||n==="publishable_with_findings")}function Roe(e){return dU(e)}async function Uu(e){let t=_h(e.result),n=f(t,"skillSlug")??f(t,"slug")??e.fallbackSlug,r=e.requestedVisibility??(f(t,"visibility")==="public"||f(t,"versionVisibility")==="public"||f(t,"releaseVisibility")==="public"?"public":"private");if(!Roe(t)){let c=L(t,"publication"),u=f(t,"reasonCode")??(c?f(c,"reasonCode"):void 0)??"security_review_pending",d=!!e.unverifiedMaterialization,p=f(t,"version"),m=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"version")??f(e.unverifiedMaterialization,"currentVersion"):void 0,h=e.unverifiedMaterialization?f(e.unverifiedMaterialization,"generationId"):void 0,g=c?f(c,"status")??f(t,"status")??"submitted":f(t,"status")??"submitted",y=g==="catalogue_submission_failed"||u==="source_ingestion_candidate_not_claimable",v=f(t,"workflowId"),b=f(t,"processingAttemptId"),w=f(t,"jobId"),_=f(t,"intakeReceiptId"),C=L(t,"progress")??{},P=!y&&t.continuationConfirmed!==!1&&!!(v||b||w)&&["queued","running","catalogue_processing_scheduled","held_for_moderation","source_install_pending_review","reused"].includes(g),N={status:y?"rejected":g==="reused"&&_?"reused":P?g==="reused"?"reused":"accepted":_?"accepted":"unconfirmed",reasonCode:u,continuationConfirmed:P,nextActor:f(C,"nextActor")??(P?"platform":u==="source_ingestion_candidate_not_claimable"?"operator":"requester")},T=ie({...e.unverifiedMaterialization,status:d?"installed_unverified":"install_pending_review",sourceItemStatus:f(t,"status")??"submitted",skillId:f(t,"skillId"),versionId:f(t,"versionId"),skillSlug:n,version:d?m:p,catalogueCandidateVersion:p,localProvisionalVersion:m,localGeneration:h,sourceContentDigest:e.unverifiedMaterialization?f(e.unverifiedMaterialization,"sourceContentDigest"):void 0,visibility:r,catalogueVisibilityRequested:r,requestedVisibility:r,catalogueStatus:g,publiclyDiscoverable:!1,intakeAdmission:N,assessmentStatus:f(C,"status")??(P?"pending":"unconfirmed"),publicationStatus:"not_published",distributionStatus:"verified_artifact_required",workflowId:v,processingAttemptId:b,jobId:w,intakeReceiptId:_,progress:t.progress,intakeReceiptIds:t.intakeReceiptIds,candidateIds:t.candidateIds,wakeStatus:t.wakeStatus,uploadIntent:t.uploadIntent,backgroundWorkStatus:P?"catalogue_review_continues_automatically":"retry_or_operator_action_required",publication:c?_h(c):void 0,activationStatus:d?"installed_unverified":"held",verificationStatus:d?"unverified":void 0,reasonCode:u,materializedWrites:d&&Array.isArray(e.unverifiedMaterialization?.materializedWrites)?e.unverifiedMaterialization.materializedWrites:[],materializationPlan:{scope:k(e.flags.scope)??"project",agent:k(e.flags.agent)??"codex",activation:d?"unverified_install_request_authorized":"approved_artifact_only"},nextStep:d?`Local installation is complete as Unverified / Unscored. ${P?"The durable assessment job remains scheduled.":"Continued assessment is not confirmed; retry submission or inspect the candidate status."} Verified publication requires valid four-dimension evidence and current distribution authority. Valid poor effectiveness is a warning, not a security block.`:P?`Run skills-layer ${_?`install status ${_}`:`creator status ${n}`}, then retry when verified distribution is available.`:"Submission continuation is not confirmed. Inspect the intake status or retry submission before waiting for assessment."});return d&&await Ha(e.backend,T,n),Va(T,d?`External source installed locally as unverified; ${P?"catalogue review continues":"catalogue continuation is unconfirmed"}.`:P?"Source submitted; installation is pending approval.":"Source installation is held; catalogue continuation is unconfirmed.",e.flags.json,e.backend)}let i=L(L(t,"progress")??{},"subject"),o=i?f(i,"generationId"):void 0,s=i?f(i,"version"):void 0;if(i&&(!o||!s||f(i,"slug")!==n))return x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",skillSlug:n,intakeReceiptId:t.intakeReceiptId,nextStep:"Retry after the source receipt identifies the exact approved skill, version and generation."},"The completed source receipt does not identify this exact skill and generation.",e.flags.json,"source_catalogue_identity_invalid");let a;try{a=await rA(e.backend,t,n,e.flags,{exportMode:Aoe(t)?"public":"auto",...i?{expectedSourceGeneration:{generationId:o,version:s}}:{}})}catch(c){if(!(c instanceof Z)||![404,502,503,504].includes(c.status))throw c;let u=ie({...t,...e.unverifiedMaterialization,status:e.unverifiedMaterialization?"installed_unverified":"catalogue_artifact_unavailable",activationStatus:e.unverifiedMaterialization?"installed_unverified":"not_installed",sourceItemStatus:f(t,"status"),catalogueStatus:f(t,"status"),publicationStatus:"published",continuationConfirmed:!0,reasonCode:"catalogue_artifact_unavailable",serverReasonCode:c.details?f(c.details,"reasonCode"):void 0,nextStep:"The catalogue version is published, but its approved artifact could not be downloaded. Retry the install when export is available. Any existing local source install remains unverified."});return e.unverifiedMaterialization?(await Ha(e.backend,u,n),Va(u,"Source installed locally as unverified; the published catalogue artifact is temporarily unavailable.",e.flags.json,e.backend)):x(u,"The published catalogue artifact is temporarily unavailable.",e.flags.json,"catalogue_artifact_unavailable")}if(fe(a))return a;let l=await sA(e.backend,a,n,e.flags);return await Ha(e.backend,l,n),Va(l,Woe(e.source,e.flags,e.backend,l,e.sourceAccess),e.flags.json,e.backend)}function _h(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>t==="localWrites"||t==="files"||t==="content"||t==="archiveBytes"?[]:Array.isArray(n)?[[t,n.map(r=>j(r)?_h(r):r)]]:j(n)?[[t,_h(n)]]:[[t,n]]))}function dU(e){if(pU(e.artifactApproval).status==="ok"&&e.artifactEnvelope!==void 0&&typeof e.downloadUrl=="string")return!0;let n=L(e,"publication"),r=n?f(n,"status")==="published":!1,i=f(e,"listingStatus")==="published",o=f(e,"versionStatus")==="published",s=f(e,"status");return i&&o&&(r||s==="published"||s==="reused"||s==="source_approved")}function Sh(e){return ie({version:f(e,"version"),storageKey:f(e,"storageKey"),expiresAt:f(e,"expiresAt")})}async function xh(e){let t=pU(e.exportResult.artifactApproval);if(t.status!=="ok"){let d=t.status==="missing";return $i(e,d?"artifact_v1_approval_missing":"artifact_v1_approval_invalid",d?`Export for ${e.skillSlug} did not include an authoritative approved Artifact Format v1 identity.`:`Export for ${e.skillSlug} included malformed Artifact Format v1 approval metadata.`)}let n=t.approval;if(e.expectedSourceGeneration&&(n.generation.generationId!==e.expectedSourceGeneration.generationId||n.generation.semanticVersion!==e.expectedSourceGeneration.version))return $i(e,"source_catalogue_generation_mismatch","The exported artifact does not match the exact version and generation resolved for this source.");let r=Eoe({backend:e.backend,exportResult:e.exportResult,approval:n,skillSlug:e.skillSlug});if(r.status!=="ok")return $i(e,r.reasonCode,r.message);if(e.exportResult.artifactEnvelope===void 0)return $i(e,"artifact_v1_envelope_missing",`Export for ${e.skillSlug} did not include an Artifact Format v1 envelope.`);let i=f(e.exportResult,"downloadUrl");if(!i)return x({status:"export_download_unavailable",reasonCode:"export_download_unavailable",skillSlug:e.skillSlug,nextStep:"Retry after the backend returns a signed bundle download URL."},`Export for ${e.skillSlug} did not include a signed download URL.`,e.flags.json,"export_download_unavailable");let o=await e.backend.fetchFn(Doe(e.backend.baseUrl,i));if(!o.ok)throw new Z(o.status,`Unable to download exported bundle (${o.status}).`);let s;try{s=await Toe(o)}catch(d){return $i(e,"artifact_v1_archive_bounds_failed",`Downloaded ${e.skillSlug} exceeded Artifact Format v1 archive bounds.`,{verificationError:ve(d)})}let a,l;try{a=Nd({archiveBytes:s,envelope:e.exportResult.artifactEnvelope}),l=Cl({archiveBytes:s,envelope:a})}catch(d){return $i(e,"artifact_v1_verification_failed",`Downloaded ${e.skillSlug} failed Artifact Format v1 verification.`,{verificationError:ve(d)})}if(!$oe(n,a))return $i(e,"artifact_v1_identity_mismatch",`Downloaded ${e.skillSlug} did not match the authoritative approved generation.`);let c=f(e.exportResult,"skillSlug"),u=f(e.exportResult,"version");return a.generation.skillSlug!==e.skillSlug||c!==void 0&&c!==a.generation.skillSlug||u!==void 0&&u!==a.generation.semanticVersion?$i(e,"artifact_v1_target_mismatch",`Downloaded ${e.skillSlug} was approved for a different skill or version.`):{status:"ok",bytes:s,files:l,envelope:a,approval:n,archiveSha256:a.archive.sha256,archiveBytesSha256:a.archive.sha256,archiveHashFormat:"artifact_v1_zip"}}function Eoe(e){let t=L(e.exportResult,"platformScoreAuthority"),n=t?.machineReport,r=t?.passport,i=t?.parityManifest,o=t?f(t,"passportPublicKey"):void 0;if(!t||!rC(n)||!o)return{status:"invalid",reasonCode:"platform_score_authority_missing",message:`Export for ${e.skillSlug} did not include a verifiable Platform Score authority.`};let s=Yc.safeParse(r),a=nC.safeParse(i);if(!s.success||!a.success)return{status:"invalid",reasonCode:"platform_score_authority_invalid",message:`Export for ${e.skillSlug} included malformed Platform Score authority metadata.`};let l=n.projection.report;if(l.subject.slug!==e.skillSlug||l.subject.version!==e.approval.generation.semanticVersion||l.subject.generationId!==e.approval.generation.generationId||l.subject.archiveSha256!==e.approval.archiveSha256||a.data.report.reportId!==l.reportId||a.data.report.revision!==l.revision||a.data.report.digest!==l.reportDigest)return{status:"invalid",reasonCode:"platform_score_authority_subject_mismatch",message:`Export for ${e.skillSlug} did not match the exact Platform Score generation.`};try{let c=QL({passport:s.data,publicKeys:{[s.data.issuer.keyId]:rre(o)},now:e.backend.now(),expectedSubject:l.subject,expectedReport:{reportId:l.reportId,revision:l.revision,digest:l.reportDigest},currentPassportId:s.data.passportId});if(!c.valid)return{status:"invalid",reasonCode:`platform_score_${c.reasonCode}`,message:`Export for ${e.skillSlug} failed signed Skill Passport verification.`}}catch{return{status:"invalid",reasonCode:"platform_score_passport_key_invalid",message:`Export for ${e.skillSlug} included an invalid Skill Passport public key.`}}return{status:"ok"}}function pU(e){return e==null?{status:"missing"}:!j(e)||e.status!=="approved"||!j(e.generation)||typeof e.generation.skillSlug!="string"||typeof e.generation.semanticVersion!="string"||typeof e.generation.generationId!="string"||typeof e.archiveSha256!="string"||typeof e.manifestSha256!="string"?{status:"invalid"}:{status:"ok",approval:{status:"approved",generation:{skillSlug:e.generation.skillSlug,semanticVersion:e.generation.semanticVersion,generationId:e.generation.generationId},archiveSha256:e.archiveSha256,manifestSha256:e.manifestSha256}}}function $oe(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&e.archiveSha256===t.archive.sha256&&e.manifestSha256===t.manifest.sha256}function $i(e,t,n,r={}){return x({status:"download_integrity_failed",reasonCode:t,skillSlug:e.skillSlug,version:f(e.exportResult,"version"),archiveHashFormat:"artifact_v1_zip",...r,nextStep:"Retry after the catalog serving generation is refreshed, or contact Skills Layer support if this repeats."},n,e.flags.json,t)}function Doe(e,t){return/^https?:\/\//iu.test(t)?t:`${dr(e)}${t.startsWith("/")?"":"/"}${t}`}async function Toe(e){let t=e.headers.get("content-length");if(t!==null){let a=Number(t);if(!Number.isSafeInteger(a)||a<0)throw new Error("Artifact response Content-Length is invalid.");if(a>ut.maxArchiveBytes)throw new Error("Artifact response exceeds the v1 archive byte limit.")}if(!e.body)throw new Error("Artifact response body is unavailable.");let n=e.body.getReader(),r=[],i=0;try{for(;;){let a=await n.read();if(a.done)break;if(i+=a.value.byteLength,i>ut.maxArchiveBytes)throw await n.cancel("Artifact response exceeds the v1 archive byte limit."),new Error("Artifact response exceeds the v1 archive byte limit.");r.push(Uint8Array.from(a.value))}}finally{n.releaseLock()}let o=new Uint8Array(i),s=0;for(let a of r)o.set(a,s),s+=a.byteLength;return o}async function oA(e){let t=e.verificationStatus??"verified";if(t==="verified"&&!e.approval)throw new Error("Verified materialization requires platform artifact approval.");let n=e.backend.platform==="win32"?st:Lt,r=ct(e.files),i=n.join(e.backend.paths.bundlesDir,e.skillSlug,e.envelope.generation.semanticVersion,encodeURIComponent(e.envelope.generation.generationId),"bundle.zip"),o=n.join(e.skillsPath,Mr(e.skillSlug)),s=et(e.backend.env,e.backend.platform,e.backend.cwd).filter(G=>{let ee=e.scope==="global"?G.targets.globalSkillsPath:G.targets.projectSkillsPath;return ee!==null&&Bo(ee,e.backend.platform)===Bo(e.skillsPath,e.backend.platform)}).map(G=>G.id).sort(),a=`activation_${Ge(16).toString("hex")}`,l={targetDir:o,generation:e.envelope.generation,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,files:e.envelope.manifest.files},c=lz({scope:e.scope,targetDir:o,platform:e.backend.platform}),u=await lt(e.backend);for(let[G,ee]of Object.entries(u.installs)){let te=[ee,...An(ee).map(Q=>Q.record)].flatMap(Q=>[Jt(Q)?.receipt.targetDir,f(Q,"materializedSkillRoot"),f(Q,"materializedPath")]);if(G!==e.skillSlug&&te.some(Q=>Q&&yA(o,Q,e.backend.platform)))throw new Error(`Install folder already belongs to another skill (${G}). Remove that installation or choose a different target before installing ${e.skillSlug}.`)}let d=u.installs[e.skillSlug],p=Yt(d)[c],m=JSON.stringify(p??null),h=Wu({state:"pending_activation",operationId:a,receipt:l,backend:e.backend}),g=Wu({state:"active",operationId:a,receipt:l,backend:e.backend}),y={skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,targetAgents:s.length>0?s:[e.agent.id],materializedPath:o,materializedSkillRoot:o,materializationId:c,bundlePath:i,archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:r,verificationStatus:t,...Mu(e.backend),...$P(e.backend,e.agent.id,e.scope),localLifecycle:h,savedAt:e.backend.now()};await IA(i,e.bytes);let v=e.files.find(G=>ot(G.path).toLowerCase()==="skill.md"),b=v?await zae({backend:e.backend,skillSlug:e.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,skillDocumentPath:n.join(o,...sM(v.path)),skillDocumentContent:v.content??""}):void 0,w,_=!1,C;try{let G={targetDir:o,...t==="verified"&&p?.verificationStatus==="unverified"&&!e.replaceUnverifiedSource?{expectedPreviousReceipt:l}:{},archiveBytes:e.bytes,envelope:e.envelope,preActivate:async({stageDir:ee})=>{let te=await Loe({backend:e.backend,stageDir:ee,envelope:e.envelope});return te.status==="passed"?(w=te.evalRun,{status:"passed",evidenceId:te.evidenceId}):{status:"failed",reasonCode:te.reasonCode}},checkpoint:async ee=>{if(ee==="after_static_eval"){await Br(e.backend,te=>{let Q=te.installs[e.skillSlug],Ce=Yt(Q)[c];if(JSON.stringify(Ce??null)!==m)throw new Error(`Local install materialization for ${e.skillSlug} changed during atomic activation.`);te.installs[e.skillSlug]=Fr({existing:Q,skillSlug:e.skillSlug,materialization:y,backend:e.backend})}),_=!0;return}ee==="after_stage_activated"&&await Br(e.backend,te=>{let Q=te.installs[e.skillSlug],Ce=Yt(Q)[c],pn=Ce?Jt(Ce):null;if(!pn||pn.state!=="pending_activation"||pn.operationId!==a)throw new Error(`Atomic activation receipt reservation for ${e.skillSlug} was lost before commit.`);te.installs[e.skillSlug]=Fr({existing:Q,skillSlug:e.skillSlug,materialization:{...y,localLifecycle:g,savedAt:e.backend.now()},backend:e.backend})})}};C=t==="verified"?await t2({...G,approval:e.approval}):await n2(G)}catch(G){throw _&&await mle({backend:e.backend,skillSlug:e.skillSlug,materializationId:c,operationId:a,baselineMaterialization:p}),G}if(!w)throw new Error("Static pre-activation Eval did not produce generation-bound evidence.");let P=await lt(e.backend),N=Yt(P.installs[e.skillSlug])[c],T=N?Jt(N):null;if(!T||T.state!=="active"||T.operationId!==a)throw new Error(`Atomic activation receipt for ${e.skillSlug} was not committed.`);let X=C.receipt.files.map(G=>({path:_U(e.backend.cwd,n.join(o,...sM(G.path))),bytes:G.sizeBytes}));return{...e.backend.config?.workingModeType==="enterprise_workspace"?{status:"installed"}:{},bundlePath:i,version:e.envelope.generation.semanticVersion,scope:e.scope,agent:e.agent.id,targetAgent:e.agent.id,...Mu(e.backend),...$P(e.backend,e.agent.id,e.scope),materializedPath:o,materializedSkillRoot:o,materializationId:c,targetAgents:s.length>0?s:[e.agent.id],archiveSha256:e.envelope.archive.sha256,manifestSha256:e.envelope.manifest.sha256,generationId:e.envelope.generation.generationId,sourceContentDigest:r,verificationStatus:t,materializedWrites:X,...b?{guardianRuntimeMetadata:b}:{},localLifecycle:g,atomicActivation:{status:C.status,receipt:C.receipt,generation:C.receipt.generation,archiveSha256:C.receipt.archiveSha256,manifestSha256:C.receipt.manifestSha256,staticEvaluation:C.staticEvaluation,cleanupPending:C.cleanupPending,...C.cleanupPath?{cleanupPath:C.cleanupPath}:{}},[Ch]:w}}var Ch=Symbol("skills-layer.pre-activation-eval"),Ooe=new Set(["file_exists","json_valid","schema_match","section_exists","regex_match","artifact_valid"]);async function Loe(e){let t=await mU(e.stageDir),n=ct(t),r=yU(t,n),i=l=>nT({pack:l,files:t,activationState:"inactive_staging",skillSlug:e.envelope.generation.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,generatedAt:e.backend.now(),runnerVersion:DP()}),o=i(r.pack);if(o.outcome!=="completed")return{status:"failed",reasonCode:o.reasonCode};let s=i(vU(t,n));if(s.outcome!=="completed")return{status:"failed",reasonCode:s.reasonCode};if(s.result.summary.status!=="passed")return{status:"failed",reasonCode:`static_eval_${s.result.summary.status}`};let a=hU({files:t,skillSlug:e.envelope.generation.skillSlug,version:e.envelope.generation.semanticVersion,generationId:e.envelope.generation.generationId,generatedAt:e.backend.now()});return{status:"passed",evidenceId:`${s.result.summary.evalPackDigest??"eval-pack-unavailable"}:${s.result.summary.artifactDigest}`,evalRun:a}}async function sA(e,t,n,r){let i=f(t,"materializedSkillRoot");if(!i)return t;let o=f(t,"skillSlug")??f(t,"slug")??n,s=f(t,"version")??f(t,"currentVersion")??k(r.version)??"local";try{let a=t[Ch],l;if(fU(a))l=a;else{let u=await mU(Tt(e.cwd,i));if(u.length===0)return dh(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"installed_files_unreadable"});l=hU({files:u,skillSlug:o,version:s,generatedAt:e.now()})}let c=await Voe(e,l.summary);return c.status==="recorded"?dh({...t,...c.effectiveness?{effectiveness:c.effectiveness}:{}},r,{status:"recorded",source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,evidenceRevision:c.evidenceRevision}):dh(t,r,{status:c.status,source:l.source,summaryStatus:l.summary.status,evalPackDigest:l.summary.evalPackDigest,reasonCode:c.reasonCode})}catch(a){return dh(t,r,{status:"runner_unavailable",summaryStatus:"runner_unavailable",reasonCode:"local_eval_failed",message:ve(a)})}}function fU(e){return j(e)&&(e.source==="submitted"||e.source==="inferred"||e.source==="invalid_submitted")&&j(e.summary)&&e.summary.schemaVersion==="skills-layer.eval.summary.v1"}async function mU(e){let t=[];return await gU(e,e,t),t.sort((n,r)=>n.path.localeCompare(r.path))}async function gU(e,t,n){for(let r of await sre(t,{withFileTypes:!0})){if(joe(r.name))continue;let i=K(t,r.name);if(r.isDirectory()){await gU(e,i,n);continue}if(!(!r.isFile()||Foe(r.name)))try{n.push({path:Bu(e,i).split("\\").join("/"),content:await Fi(i,"utf8")})}catch{continue}}}function joe(e){return e===".git"||e==="node_modules"||e==="coverage"||e===Noe()||e==="dist"}function Noe(){return[46,68,83,95,83,116,111,114,101].map(e=>String.fromCharCode(e)).join("")}function Foe(e){return e==="bundle.zip"||/^\.skills-layer-.*\.json$/u.test(e)}function hU(e){let t=ct(e.files),n=yU(e.files,t);if(!sf(n.pack).valid)return{source:"invalid_submitted",summary:Es({status:"runner_unavailable",skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:t,evalPackDigest:Rs(n.pack),generatedAt:e.generatedAt,runnerVersion:DP(),counts:{cases:0,assertions:0,passed:0,failed:0,skipped:0}})};let i=Moe(n.pack).map(s=>({id:s.id,assertions:s.assertions.map(a=>Uoe(a,e.files))})),o=zoe(i);return{source:n.source,summary:Es({status:qoe(o),skillSlug:e.skillSlug,version:e.version,generationId:e.generationId,artifactDigest:typeof n.pack.artifactDigest=="string"?n.pack.artifactDigest:t,evalPackDigest:Rs(n.pack),generatedAt:e.generatedAt,runnerVersion:DP(),counts:{cases:i.length,assertions:o.total,passed:o.passed,failed:o.failed,skipped:o.skipped}})}}function yU(e,t){let n=Boe(e);return n?{pack:n,source:"submitted"}:{pack:vU(e,t),source:"inferred"}}function Boe(e){for(let t of e){let n=$n(t.path,e);if(!(n.type!=="evidence"||!t.content||!n.relativePath.toLowerCase().endsWith(".eval.json")))try{let r=JSON.parse(t.content);if(j(r))return r}catch{return{schemaVersion:"invalid",artifactDigest:ct(e),origin:"submitted",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[]}}}}function vU(e,t){let r=e.find(i=>i.path.replaceAll("\\","/").split("/").at(-1)?.toLowerCase()==="skill.md")?.path??"SKILL.md";return{schemaVersion:"skills-layer.eval.pack.v1",artifactDigest:t,origin:"inferred",confidence:"starter",creatorReviewed:!1,redaction:{mode:"content_free"},cases:[{id:"starter-runtime-shape",assertions:[{type:"file_exists",path:r},{type:"regex_match",path:r,pattern:"name:"},{type:"artifact_valid",artifactDigest:t}]}]}}function Moe(e){return Array.isArray(e.cases)?e.cases.flatMap(t=>!j(t)||typeof t.id!="string"||!Array.isArray(t.assertions)?[]:[{id:t.id,assertions:t.assertions.filter(j)}]):[]}function Uoe(e,t){return typeof e.type=="string"&&!Ooe.has(e.type)?{status:"skipped",reasonCode:"runner_unavailable"}:rf(e,{files:t})}function zoe(e){return e.reduce((t,n)=>{for(let r of n.assertions)t.total+=1,r.status==="passed"&&(t.passed+=1),r.status==="failed"&&(t.failed+=1),r.status==="skipped"&&(t.skipped+=1);return t},{total:0,passed:0,failed:0,skipped:0})}function qoe(e){return e.failed>0?"failed":e.passed>0?"passed":e.skipped>0?"runner_unavailable":"not_run"}function DP(){return`skills-layer-public-cli:${So}:local-install`}async function Voe(e,t){if(!e.apiKey)return{status:"local_only",reasonCode:"not_authenticated"};try{let n=await D(e,"/api/v1/me/evals/results",{method:"POST",headers:{"content-type":"application/json",...re(e.apiKey,e.authBlockedMessage)},body:JSON.stringify({evalSummary:t})}),r=L(n,"evalEvidence");return{status:"recorded",effectiveness:L(n,"effectiveness"),evidenceRevision:r?J(r,"revision"):void 0}}catch(n){return{status:"submit_failed",reasonCode:n instanceof Z?`http_${n.status}`:"request_failed"}}}function dh(e,t,n){return t.json?{...e,localEval:n}:e}function sM(e){let n=e.replaceAll("\\","/").replace(/^\/+/u,"").trim().split("/").filter(r=>r.length>0);if(n.length===0||n.some(r=>r==="."||r===".."))throw new Error(`Unsafe bundle path "${e}".`);return n}async function aM(e,t,n,r,i){let o=k(r.visibility)??"private";if(o!=="private"&&o!=="public")return x({status:"invalid_visibility",reasonCode:"invalid_visibility",source:e,requestedVisibility:o,nextStep:`Use \`skills-layer install ${e} --visibility private\` or \`--visibility public\`.`},"Local path install visibility must be private or public.",r.json,"invalid_visibility");let s=aA(e,t,n);if(r.list)return R(s,"Local source skills loaded.",r.json,i);let a=Ih(e,s,r);if(a)return a;let l=await ju({source:e,inspection:s,requestedSkillSlug:n,mode:"install",flags:r,backend:i});if(l.kind==="failure")return l.result;let c=l.skillSlug??ur(s)[0]?.value??bU(e),u=Goe(t.files,c),d=Wr({files:u,limits:yo}),p={mode:r.localOnly?"local_only":o==="public"?"explicit_public":"managed_private",upload:!r.localOnly,destination:r.localOnly?null:i.baseUrl,audience:r.localOnly?"local_device":o==="public"?"public_after_governed_review":"account_private",authentication:r.localOnly?"not_required":"required",files:d.preview.files.map(y=>({path:y.path,bytes:y.bytes})),totalBytes:d.preview.totalBytes};if(r.dryRun)return R({...LP(e,s,c,r),installKind:"local_source_submission",visibility:o,publicationStatus:"preview",catalogRecord:o,activationStatus:"not_started",uploadIntent:p,nextStep:r.localOnly?"Re-run without --dry-run for unverified, unscored local activation without upload.":`Re-run without --dry-run to create or reuse the ${o} central item. Local activation remains held until the exact generation completes security review and Artifact-v1 approval.`},"Local source submission preview ready.",r.json,i);if(r.localOnly){let y=await TP({backend:i,flags:r,source:e,skillSlug:c,files:u,defaultAcceptUnverifiedSource:!0});if(fe(y))return y;let v={...y,status:"installed_unverified",activationStatus:"installed_unverified",uploadIntent:p,intakeAdmission:{status:"not_requested"},assessmentStatus:"not_requested",publicationStatus:"not_requested",distributionStatus:"unverified_local",backgroundWorkStatus:"not_requested"};return await Ha(i,v,c),Va(v,"Local source installed as unverified and unscored. No files were uploaded.",r.json,i)}if(!i.apiKey)return x({reasonCode:"local_source_authentication_required",uploadIntent:p,nextStep:"Sign in for managed submission, or use --local-only for an unverified installation without upload."},"Managed local source submission requires authentication before uploading files.",r.json,"local_source_authentication_required");i.emitInfo(`Upload intent: ${p.files.length} selected files (${p.totalBytes} bytes) to ${i.baseUrl}; audience ${p.audience}; authenticated account required. Use --dry-run --json to inspect the file list or --local-only to avoid upload.`);let m=await QP(i,c,r);if(m)return m;let h;if(kU(r,i)){let y=await TP({backend:i,flags:r,source:e,skillSlug:c,files:u});if(fe(y))return y;h=y}let g;try{let y=dg(u)?await xC({baseUrl:i.baseUrl,apiKey:i.apiKey,fetchFn:i.fetchFn,files:u}):null;g=await D(i,"/api/v1/me/source-installs",{method:"POST",headers:{"content-type":"application/json",...re(i.apiKey,i.authBlockedMessage)},body:JSON.stringify(ie({...y?{hydrationManifestId:y.manifestId}:{files:u},skillSlug:c,version:k(r.version),visibility:o,category:k(r.category),displayName:k(r.displayName),skillType:k(r.skillType),sourceMetadata:t.sourceMetadata}))})}catch(y){return h?await Uu({backend:i,flags:r,source:e,fallbackSlug:c,sourceAccess:"authenticated",requestedVisibility:o,unverifiedMaterialization:h,result:{status:"catalogue_submission_failed",skillSlug:c,uploadIntent:p,reasonCode:y instanceof Z?"catalogue_submission_failed":"catalogue_submission_unavailable"}}):x({status:"catalogue_submission_failed",uploadIntent:p,activationStatus:"not_started",intakeAdmission:{status:"rejected"},assessmentStatus:"not_requested",publicationStatus:"not_published",distributionStatus:"verified_artifact_required",reasonCode:y instanceof Z?"catalogue_submission_failed":"catalogue_submission_unavailable",skillSlug:c,nextStep:"Retry the source submission when catalogue service is available. No local files were written."},"The source was not installed because catalogue submission did not complete.",r.json,"catalogue_submission_failed")}return await Uu({backend:i,result:{...g,uploadIntent:p},fallbackSlug:f(g,"skillSlug")??c,source:e,sourceAccess:"authenticated",flags:r,requestedVisibility:o,...h?{unverifiedMaterialization:h}:{}})}function Goe(e,t){let n=lA(e).find(i=>i.skillSlug===t);if(!n||n.relativeSkillRoot===".")return e.map(i=>({...i}));let r=`${n.relativeSkillRoot.replace(/\/+$/u,"")}/`;return e.filter(i=>i.path.replaceAll("\\","/").startsWith(r)).map(i=>({...i,path:i.path.replaceAll("\\","/").slice(r.length)}))}async function lM(e){if(!e.flags.all&&!(!e.defaultAcceptUnverifiedSource&&!kU(e.flags,e.backend)))try{let t=rr(e.source),n=await Sj({source:t,cwd:e.backend.cwd,platform:e.backend.platform,fetchFn:e.backend.fetchFn,...e.skillSlug?{requestedSkillSlug:e.skillSlug}:{}}),r=e.skillSlug?n.results.find(i=>i.skillSlug===e.skillSlug):n.results.length===1?n.results[0]:void 0;return r?await TP({backend:e.backend,flags:e.flags,source:e.source,skillSlug:r.skillSlug,files:r.files,relativeSkillRoot:r.relativeSkillRoot,defaultAcceptUnverifiedSource:e.defaultAcceptUnverifiedSource}):e.defaultAcceptUnverifiedSource?void 0:x({status:"unverified_source_snapshot_unavailable",reasonCode:"unverified_source_snapshot_unavailable",source:e.source,requestedSkillSlug:e.skillSlug,nextStep:"Use --list to inspect the source and --skill <skill-slug> to select one exact skill before retrying."},"The CLI could not resolve one immutable external skill snapshot for local activation.",e.flags.json,"unverified_source_snapshot_unavailable")}catch(t){return e.defaultAcceptUnverifiedSource?void 0:x({status:"unverified_source_snapshot_unavailable",reasonCode:"unverified_source_snapshot_unavailable",source:e.source,requestedSkillSlug:e.skillSlug,error:t instanceof Error?t.message.slice(0,512):"Source snapshot could not be loaded.",nextStep:"Check source access and retry the exact source after its immutable snapshot is available."},"The CLI could not load the external source snapshot for unverified local activation.",e.flags.json,"unverified_source_snapshot_unavailable")}}async function TP(e){let t=Wr({files:e.files,limits:yo}),n=nt(e.files,{profile:"external_ingest_tolerant"}),r=y2(e.files,h2),i=[...t.issues.filter(_=>_.severity==="error").map(_=>({code:_.code,concern:/^(?:secret_|pii_|sensitive_)/u.test(_.code)?"privacy":"integrity",..._.path?{path:_.path}:{}})),...n.issues.filter(_=>_.severity==="error").map(_=>({code:_.code,concern:"package_validity"})),...r.filter(_=>_.severity==="high"||_.severity==="critical").map(_=>({code:_.ruleId,concern:"security",path:_.filePath,..._.lineNumber?{lineNumber:_.lineNumber}:{}}))],o=i.map(_=>_.code);if(o.length>0){let _=i.some(C=>C.concern==="security")?"critical_local_preflight_blocked":"source_package_invalid";return x({status:"unverified_install_blocked",reasonCode:_,skillSlug:e.skillSlug,findingCodes:[...new Set(o)].sort((C,P)=>C.localeCompare(P)),blockingFindings:i,nextStep:"Do not activate this source. Review or remove the blocking content, then retry from a new immutable generation."},"External source did not satisfy the required local package checks and was not installed.",e.flags.json,_)}if(!(e.flags.acceptUnverifiedSource===!0||e.defaultAcceptUnverifiedSource===!0||await Hoe(e)))return x({status:"unverified_install_consent_required",reasonCode:"unverified_source_consent_required",skillSlug:e.skillSlug,nextStep:"Review the source, then retry with --accept-unverified-source to install it before platform approval."},"External source was not installed because informed unverified-source consent was not provided.",e.flags.json,"unverified_source_consent_required");let a=iA(e.backend,{skillSlug:e.skillSlug,materializationPlan:{scope:k(e.flags.scope)??"project",agent:k(e.flags.agent)??"codex"}},e.skillSlug,e.flags);if(a.status==="failure")return x({status:"materialization_target_invalid",reasonCode:"materialization_target_invalid",skillSlug:e.skillSlug,nextStep:a.nextStep},a.message,e.flags.json,"materialization_target_invalid");if(a.status==="skip"||a.status==="cache_only")return x({status:"materialization_target_required",reasonCode:"materialization_target_required",skillSlug:e.skillSlug,nextStep:"Retry with --scope project|global and --agent <agent>."},"An explicit local target is required for an unverified external installation.",e.flags.json,"materialization_target_required");let l=await Ya({backend:e.backend,skillSlug:e.skillSlug,agentId:a.agent.id,scope:a.scope,flags:e.flags});if(l)return l;let c=ct(e.files),u=rr(e.source),d=u.kind==="github"?u.subpath.replace(/(?:^|\/)SKILL\.md$/u,"")||".":void 0,p=e.relativeSkillRoot,m=u.kind==="github"&&/^[a-f0-9]{40}$/u.test(u.ref)?{provider:"github",repository:`${u.owner}/${u.repo}`,commitSha:u.ref,sourceRoot:!p||p==="."?d:d==="."?p:`${d}/${p}`,sourceContentDigest:t.preview.bundleSha256}:void 0,h=c.slice(7,19),g=k(e.flags.version)??`0.0.0-external.${h}`,y=`generation_unverified_${c.slice(7,39)}`,v=e.files.filter(_=>$n(_.path,e.files).type==="runtime").map(_=>_.path),b=u0({generation:{skillSlug:e.skillSlug,semanticVersion:g,generationId:y},reviewPackageFiles:e.files,runtimeAllowlist:v});return{...await oA({backend:e.backend,skillSlug:e.skillSlug,scope:a.scope,agent:a.agent,skillsPath:a.skillsPath,bytes:b.archiveBytes,files:Cl({archiveBytes:b.archiveBytes,envelope:b.envelope}),envelope:b.envelope,verificationStatus:"unverified"}),source:e.source,sourceContentDigest:c,...m?{sourceSnapshot:{...m,runtimeDigest:c,archiveSha256:b.envelope.archive.sha256}}:{},platformScoreDecision:null,scoreAvailability:"unscored",scoreReasonCode:"unscored_local_source",localPreflight:{status:"passed",recommendation:t.issues.length+n.issues.length+r.length>0?"approved_with_notes":"approved",issueCount:t.issues.length+n.issues.length+r.length,findingCodes:[...t.issues.map(_=>_.code),...n.issues.map(_=>_.code),...r.map(_=>_.ruleId)]}}}function kU(e,t){return e.acceptUnverifiedSource===!0||!e.json&&!t.nonInteractive&&t.stdoutIsTty}async function Hoe(e){if(e.flags.json||e.backend.nonInteractive)return!1;try{return await e.backend.promptSelect(`${e.skillSlug} comes from ${e.source} and has not completed Skills Layer Security/Eval. Install this immutable generation as unverified?`,[{value:"decline",label:"Do not install",description:"Keep local agent files unchanged."},{value:"accept",label:"Install unverified",description:"Use locally now while catalogue review runs in parallel."}])==="accept"}catch{return!1}}function aA(e,t,n){let r=lA(t.files),i=n?r.find(o=>o.skillSlug===n)??null:r.length===1?r[0]??null:null;return{status:"ok",source:t.sourceMetadata,selectedSkill:i,results:r,issues:[],sourceInstallSupported:!0,sourceInstallMode:"local_private",publicationStatus:"none",originalSource:e}}function lA(e){return e.filter(t=>t.path.split("/").at(-1)?.toLowerCase()==="skill.md").map(t=>{let n=Me(t.path).replaceAll("\\","/"),r=n==="."?".":n,i=wU(t.content??"")??bU(r==="."?t.path:r),o=Koe(t.content??"");return{skillSlug:i,name:i,...o?{description:o}:{},relativeSkillRoot:r,relativeSkillFile:t.path,sourceKind:"local",discoveryRoute:"local_bundle",validation:{valid:!0,issueCount:0}}})}function wU(e){return/^---\s*[\s\S]*?\nname:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function Koe(e){return/^---\s*[\s\S]*?\ndescription:\s*["']?([^"'\n]+)["']?\s*(?:\n|$)/u.exec(e)?.[1]?.trim()}function bU(e){return(e.replaceAll("\\","/").replace(/\/+$/u,"").split("/").filter(Boolean).at(-1)??"local-skill").toLowerCase().replace(/[^a-z0-9]+/gu,"-").replace(/^-+|-+$/gu,"")||"local-skill"}function _U(e,t){let n=Bu(e,t);return n&&!n.startsWith("..")&&!st.isAbsolute(n)?n.split("\\").join("/"):t}function Ti(e,t,n,r="unknown"){let i=k(t.visibility);return i==="public"||i==="private"?i:r==="anonymous"&&OP(e)?"public":r==="authenticated"?"private":!n.apiKey&&OP(e)?"public":"private"}function OP(e){try{let t=rr(e).kind;return t==="github"||t==="gitlab"}catch{return/^https:\/\/(?:github|gitlab)\.com\//iu.test(e.trim())}}function cA(e,t,n,r="unknown"){return Ti(e,t,n,r)==="private"||k(t.visibility)==="unlisted"||r==="authenticated"?"/api/v1/me/source-installs":"/api/v1/source-imports"}function SU(e,t,n,r="unknown"){return{"content-type":"application/json",...cA(e,t,n,r)==="/api/v1/me/source-installs"?re(n.apiKey,n.authBlockedMessage):{}}}function Woe(e,t,n,r,i="unknown"){let o=r?f(r,"visibility")??f(r,"versionVisibility"):void 0,s=r?f(r,"publicationStatus"):void 0,a=r?f(r,"catalogRecord"):void 0,l=r?f(r,"status"):void 0;return o==="public"||s==="clean_publishable"||s==="publishable_with_findings"||l==="published"?"Public source install planned.":o==="private"||s==="private"||a==="private"||l==="private_source_installed"?"Private source skill installed.":Ti(e,t,n,i)==="public"?"Public source install planned.":"Private source skill installed."}async function ju(e){let t=ur(e.inspection);if(e.requestedSkillSlug)return t.length>0&&!t.some(n=>n.value===e.requestedSkillSlug)?{kind:"failure",result:Zoe(e.source,e.requestedSkillSlug,t.map(n=>n.value),e.flags)}:{kind:"selected",skillSlug:e.requestedSkillSlug};if(e.flags.all||e.flags.json&&e.flags.dryRun)return{kind:"selected",skillSlug:e.requestedSkillSlug};if(t.length<=1)return{kind:"selected",skillSlug:t[0]?.value};if(e.flags.json)return{kind:"failure",result:cM(e.source,t,e.flags)};try{return{kind:"selected",skillSlug:await e.backend.promptSelect(`${e.source} exposes multiple skills. Select one to ${e.mode}:`,t)}}catch{return{kind:"failure",result:cM(e.source,t,e.flags)}}}function cM(e,t,n){let r=t.map(i=>i.value);return x({status:"selection_required",reasonCode:"source_skill_selection_required",source:e,availableSkills:r,nextAction:"install.source.select",nextStep:`Re-run with --skill <skill-slug> using one of: ${r.join(", ")}. Use --all only if you intend to install every discovered skill.`},`Source "${e}" exposes multiple skills. Re-run with --list or --skill <skill-slug>. Available skills: ${r.join(", ")}.`,n.json,"source_skill_selection_required")}function uM(e,t,n){if(n.all&&t)return x({status:"error",reasonCode:"conflicting_source_selection",source:e,selectedSkillSlug:t,all:!0,nextAction:"install",nextStep:"Use either --all to install every discovered skill or --skill <skill-slug> to install one skill, not both."},"Source install cannot combine --all with --skill. Choose one selection mode before retrying.",n.json,"conflicting_source_selection")}function dM(e,t){try{if(rr(e).kind!=="local")return}catch{return}return x({status:"error",reasonCode:"invalid_source",source:e,nextAction:"install",nextStep:zu(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source URL, or run `skills-layer install --source <source> --list` with a supported source."},zu(e)?`Install source ${e} was not found or is not readable.`:`Install source "${e}" is not a supported remote source and no local path was found.`,t.json,"invalid_source")}function Zoe(e,t,n,r){return x({status:"not_found",reasonCode:"source_skill_not_found",source:e,requestedSkillSlug:t,availableSkills:n,nextAction:"install.source.list",nextStep:`Run \`skills-layer install --source ${e} --list\` to inspect discovered skills, then retry with one of the listed slugs.`},`Source ${e} does not contain a discovered skill named ${t}. Run with --list to inspect available skills.`,r.json,"source_skill_not_found")}function ur(e){let t=[e.results,e.skills,e.discoveredSkills,L(e,"source")?.results,L(e,"inspection")?.results],n=new Set,r=[];for(let i of t)if(Array.isArray(i))for(let o of i){let s=Joe(o);!s||n.has(s.value)||(n.add(s.value),r.push(s))}return r}function Joe(e){if(!j(e))return;let t=f(e,"skillSlug")??f(e,"slug")??f(e,"name");if(!t)return;let n=f(e,"displayName")??f(e,"title")??f(e,"name"),r=n&&n!==t?`${t} - ${n}`:t,i=L(e,"parsedSkill"),o=L(e,"frontmatter")??(i?L(i,"frontmatter"):void 0),s=f(e,"shortDescription")??f(e,"summary")??f(e,"description")??(o?f(o,"description"):void 0)??f(e,"relativeSkillRoot")??f(e,"path")??f(e,"discoveryRoute")??f(e,"sourceKind");return s?{value:t,label:r,description:s}:{value:t,label:r}}function pM(e,t,n,r,i,o={}){return ie({...t,skillSlug:n,scope:k(r.scope),agent:k(r.agent),workspace:k(r.workspace),version:k(r.version),visibility:o.visibility??k(r.visibility),category:k(r.category),displayName:k(r.displayName),skillType:k(r.skillType),all:r.all,acceptCapability:r.acceptCapability})}async function fM(e){let t=e.sourceAccess??"unknown",n=cA(e.source,e.flags,e.backend,t);try{return await D(e.backend,n,{method:"POST",headers:SU(e.source,e.flags,e.backend,t),body:JSON.stringify(pM(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{sourceAccess:t,...n==="/api/v1/source-imports"?{visibility:"public"}:{}}))})}catch(r){if(r instanceof Z&&r.status===401&&k(e.flags.visibility)!=="private"&&t!=="authenticated"&&OP(e.source))return await D(e.backend,"/api/v1/source-imports",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(pM(e.source,{source:e.source},e.skillSlug,e.flags,e.backend,{visibility:"public"}))});throw r}}function LP(e,t,n,r){return ie({status:"dry_run",source:e,selectedSkillSlug:n,all:r.all,scope:k(r.scope)??"local",agent:k(r.agent),workspace:k(r.workspace),acceptCapability:r.acceptCapability,candidates:ur(t).map(i=>({skillSlug:i.value,name:i.label,description:i.description})),nextStep:r.all?`Re-run without --dry-run to install every discovered skill from ${e}.`:`Re-run without --dry-run${n?"":" and add --skill <skill-slug> if needed"} to install from ${e}.`})}async function xU(e,t,n,r,i={}){try{return{kind:"ok",inspection:await D(e,"/api/v1/source-inspect",{method:"POST",headers:CU(e,i.authMode??"auto"),body:JSON.stringify(ie(n))})}}catch(o){if(o instanceof Z)return{kind:"failure",result:NP(t,o,r)};throw o}}function CU(e,t){return t==="anonymous"?{"content-type":"application/json"}:V(e.apiKey)}async function jP(e,t,n,r){try{let s=await D(e,"/api/v1/source-inspect",{method:"POST",headers:CU(e,"anonymous"),body:JSON.stringify(ie(n))}),a=mM(t,s,r);return a?{kind:"failure",result:a}:{kind:"ok",inspection:s,sourceAccess:"anonymous"}}catch(s){if(!(s instanceof Z))throw s;let a=s.details??{},l=f(a,"error")??s.message;if(!uA(s.status,l))return{kind:"failure",result:NP(t,s,r)};if(!e.apiKey)return{kind:"failure",result:NP(t,s,r)}}let i=await xU(e,t,n,r,{authMode:"authenticated"});if(i.kind==="failure")return i;let o=mM(t,i.inspection,r);return o?{kind:"failure",result:o}:{kind:"ok",inspection:i.inspection,sourceAccess:"authenticated"}}function mM(e,t,n){if(n.list||n.dryRun)return null;let r=[t.catalogueDecision,...Array.isArray(t.catalogueDecisions)?t.catalogueDecisions:[]].filter(i=>i!==void 0);for(let i of r){let o=j(i)?i.status:void 0;if(!j(i)||i.schemaVersion!=="skills-layer.source-catalogue-decision.v1"||!["approved","pending","new"].includes(String(o))){let s=["security_blocked","revoked","restricted","unavailable"].includes(String(o))?`source_catalogue_${o}`:"source_catalogue_identity_invalid";return x({status:s,reasonCode:s,source:e,catalogueDecision:i,nextStep:"Resolve the current catalogue decision before retrying this exact source."},"This source cannot be activated under its current catalogue decision.",n.json,s)}}if(t.catalogueSourceInput!==void 0){let i=rr(e),o=typeof t.catalogueSourceInput=="string"?rr(t.catalogueSourceInput):void 0,s=l=>l.replace(/(?:^|\/)SKILL\.md$/u,"")||".";if(!(i.kind==="github"&&o?.kind==="github"&&`${i.owner}/${i.repo}`.toLowerCase()===`${o.owner}/${o.repo}`.toLowerCase()&&s(i.subpath)===s(o.subpath)&&/^[a-f0-9]{40}$/u.test(o.ref)&&(!/^[a-f0-9]{40}$/iu.test(i.ref)||i.ref.toLowerCase()===o.ref)&&r.every(l=>{let c=j(l)?L(l,"subject"):void 0,u=c?f(c,"sourceRoot"):void 0,d=s(o.subpath);return c?.commitSha===o.ref&&typeof c.repository=="string"&&c.repository.toLowerCase()===`${o.owner}/${o.repo}`.toLowerCase()&&u&&(u==="."||!u.split("/").some(p=>!p||p==="."||p===".."||/[\\\p{Cc}\p{Cf}]/u.test(p)))&&(d==="."||u===d||u.startsWith(`${d}/`))})))return x({status:"source_catalogue_identity_invalid",reasonCode:"source_catalogue_identity_invalid",source:e},"The inspected snapshot does not identify this exact source.",n.json,"source_catalogue_identity_invalid")}return null}function Ih(e,t,n){if(ur(t).length>0)return null;let i=Yoe(t);return x({status:"unsupported_source_layout",source:e,reasonCode:"source_no_discoverable_skills",issues:i,nextStep:"Run with --list to inspect the source, use a subfolder containing SKILL.md, or install from a Skills Layer-compatible source layout."},Xoe(e,i),n.json)}function Yoe(e){return(Array.isArray(e.issues)?e.issues:[]).filter(j).map(n=>({...f(n,"code")?{code:f(n,"code")}:{},...f(n,"message")?{message:f(n,"message")}:{},...f(n,"path")?{path:f(n,"path")}:{}}))}function NP(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(uA(t.status,i))return IU(e,t,n,"inspect");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Go(t,n.json);let s={status:"unsupported_source_layout",source:e,reasonCode:"source_not_inspectable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return x(s,`Source ${e} could not be inspected as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}function gM(e,t,n){let r=t.details??{},i=f(r,"error")??t.message;if(uA(t.status,i))return IU(e,t,n,"install");if(!(t.status===404||/not found|does not contain any discoverable skills|no discoverable skills/iu.test(i)))return Go(t,n.json);let s={status:"unsupported_source_layout",source:e,reasonCode:"source_not_installable",backendStatus:t.status,backendMessage:i,nextStep:"Try --list, a specific subfolder containing SKILL.md, or a Skills Layer-compatible source URL."};return x(s,`Source ${e} could not be installed as a Skills Layer-compatible source. Try --list, a specific subfolder containing SKILL.md, or a supported source layout.`,n.json)}async function hM(e){let t=e.error instanceof Z?e.error.details??{}:{},n=e.error instanceof Z?f(t,"reasonCode")??"catalogue_submission_failed":"catalogue_submission_unavailable";return await Uu({backend:e.backend,result:{...t,status:"catalogue_submission_failed",reasonCode:n,publiclyDiscoverable:!1},fallbackSlug:e.skillSlug,source:e.source,sourceAccess:e.sourceAccess,flags:e.flags,requestedVisibility:Ti(e.source,e.flags,e.backend,e.sourceAccess),unverifiedMaterialization:e.unverifiedMaterialization})}function uA(e,t){return e===401||e===403||/private source|provider authorization|unauthorized|forbidden|access denied/iu.test(t)}function IU(e,t,n,r){let i=t.details??{},o=f(i,"error")??t.message,a=`skills-layer source connection start --provider ${PU(e)} --source ${e} --visibility private --provenance-intent private_source_import`,l={status:"private_source_access_required",source:e,reasonCode:"private_source_access_required",backendStatus:t.status,backendMessage:o,nextStep:a};return x(l,`Cloud could not ${r} ${e} directly. If this is a private source, start a private source connection first:
|
|
2153
2153
|
${a}`,n.json,"private_source_access_required")}function PU(e){return/gitlab\./iu.test(e)?"gitlab":/github\./iu.test(e)||/^gh:/iu.test(e)?"github":"generic_git"}function Xoe(e,t){let n=[`No Skills Layer-compatible skills were found in ${e}.`];if(t.length>0){n.push("Detected issues:");for(let r of t.slice(0,5)){let i=r.code??"source-inspection";n.push(`- ${i}: ${r.message??"No details returned."}${r.path?` (${r.path})`:""}`)}}return n.push("Try --list, a subfolder containing SKILL.md, or a Skills Layer-compatible source layout."),n.join(`
|
|
2154
|
-
`)}async function AU(e,t,n){if(RU(e)){let l=f(e,"reasonCode")??f(e,"reason")??"install_not_ready",c=f(e,"why")??f(e,"summary")??"The requested skill is not ready to install from this backend.";return x(e,`Install preview is not ready: ${c}`,t.json,l)}let r=k(t.agent)==="all"?et(n.env,n.platform,n.cwd).map(l=>({...t,agent:l.id})):[t];for(let l of r){let c=iA(n,e,"",l);if(c.status!=="ok")continue;let u=await Ya({backend:n,skillSlug:c.skillSlug,agentId:c.agent.id,scope:c.scope,flags:t});if(u)return u}let i=Object.values(n.guardianActivationReceipts??{}).map(l=>$P(n,l.agent,l.scope)),o=i.flatMap(l=>Array.isArray(l.warnings)?l.warnings:[]),s=await EU({...e,...i[0],warnings:[...Array.isArray(e.warnings)?e.warnings:[],...o]},n),a=Array.isArray(s.warnings)&&s.warnings.length>0;return Qoe(s,a?"Install preview ready with warnings.":"Install preview ready.",t,n)}function Qoe(e,t,n,r){return n.json?
|
|
2155
|
-
`)}function tse(e,t){let n=L(e,"trust"),r=L(e,"securityPosture"),i=L(e,"capabilityProfile"),o=n?.securityScore??n?.score??e.securityScore??r?.securityScore,s=qe(n,"runtimeRisk")??f(e,"runtimeRisk")??qe(r,"runtimeRisk")??qe(i,"runtimeRisk"),a=qe(n,"recommendation")??f(e,"recommendation")??qe(r,"recommendation"),l=qe(n,"label")??qe(n,"trust")??f(e,"trustStatus")??f(e,"trust")??qe(r,"label");if(o===void 0&&!s&&!a&&!l)return[];let c=[t.section("Trust")];return s&&c.push(` ${t.label("Runtime risk")}: ${s}`),a&&c.push(` ${t.label("Recommendation")}: ${a}`),l&&c.push(` ${t.label("Status")}: ${l}`),c.push(` ${t.label("Source")}: skills-layer trust`),c}async function ed(e,t,n){let r=[],i=[];if(!t.apiKey)return{warnings:r,revokedSlugs:i};let o=await lt(t),s=Object.entries(o.installs).filter(([l,c])=>(!n||l===n)&&c.acquisitionMode==="authenticated_account"&&(!c.acquisitionBaseUrl||c.acquisitionBaseUrl===t.baseUrl));if(!s.length)return{warnings:r,revokedSlugs:i};let a=[];try{for(let l=0;l<s.length;l+=50){let c=new URLSearchParams({slugs:s.slice(l,l+50).map(([d])=>d).join(",")}),u=await D(t,`/api/v1/me/entitlements?${c}`,{headers:re(t.apiKey,t.authBlockedMessage)});if(!Array.isArray(u.results))throw new Error("Entitlement status unavailable");a.push(...u.results.filter(j))}}catch{return{warnings:["Could not verify entitlements online; local copies were kept."],revokedSlugs:i}}for(let[l,c]of s){let u=a.find(h=>h.skillSlug===l);if(!u||u.status!=="revoked"||u.reason!=="refunded"||u.paid!==!0)continue;let d=typeof c.entitlementId=="string"&&c.entitlementId===u.entitlementId,p=typeof c.acquiredByUserId=="string"&&c.acquiredByUserId===t.config?.userId&&c.acquisitionBaseUrl===t.baseUrl;if(!d&&!p){r.push(`Kept ${l}: its receipt cannot be matched to this buyer's refunded grant.`);continue}let m=An(c);if(!m.length){r.push(`No managed agent copy found for refunded ${l}. Manually copied folders cannot be removed automatically.`);continue}for(let h of m){let g=typeof h.record.acquisitionBaseUrl=="string"?h.record:m.length===1?c:{},y=typeof g.entitlementId=="string"&&g.entitlementId===u.entitlementId,v=g.acquiredByUserId===t.config?.userId&&typeof g.acquiredByUserId=="string"&&g.acquisitionBaseUrl===t.baseUrl;if(!y&&!v){r.push(`Kept ${l}: this agent copy belongs to an unverified buyer receipt.`);continue}if(i.includes(l)||i.push(l),!(h.lifecycle?.state==="quarantined"||h.lifecycle?.state==="externally_removed")){if(!h.lifecycle||!["active","pending_activation"].includes(h.lifecycle.state)){r.push(`Kept ${l}: modified or unverifiable local copy; inspect it before removing it manually.`);continue}if(e.dryRun){r.push(`Would remove ${l} \u2014 refunded on ${String(u.revokedAt??"unknown date")}.`);continue}try{await pA({backend:t,skillSlug:l,record:gr(c,h),materializationId:h.materializationId,lifecycle:h.lifecycle,reasonCode:"refunded",purpose:"quarantine_revoked",status:"removed"}),r.push(`Removed ${l} \u2014 refunded on ${String(u.revokedAt??"unknown date")}.`)}catch{r.push(`Kept ${l}: modified or unverifiable local copy; inspect it before removing it manually.`)}}}}return{warnings:r,revokedSlugs:i}}async function nse(e,t){let n=Qu("installed",e);if(n.failure)return n.failure;let r=await ed(e,t),i=e.dryRun?await lt(t):await Bi(t),o=uz(i).filter(s=>(!n.scope||f(s,"scope")===n.scope)&&(!n.agent||mr(s).includes(n.agent)));return A({status:"ok",results:o,warnings:r.warnings},`Found ${o.length} local install records. ${r.warnings.join(" ")}`,e.json,t,"installed")}async function rse(e,t,n){let r=O(e[0],"remove requires a skill slug."),i=tU("remove",t);if(i)return i;let s=(t.dryRun?await lt(n):await Bi(n,r)).installs[r];if(!s)return x({status:"not_installed",reasonCode:"local_install_not_found",skillSlug:r},`${r} is not installed locally. Run \`skills-layer installed\` or \`skills-layer sync\` to inspect local records.`,t.json,"local_install_not_found");let a=k(t.scope),l=k(t.agent),c=qn(s,{scope:a,agent:l});if(c.length>1){let g=ule({backend:n,skillSlug:r,materializations:c,scope:a,agent:l});g.length===1&&(c=g)}if(c.length===0&&An(s).length>0)return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:r,requestedScope:a,requestedAgent:l},`${r} is not installed for the requested local target.`,t.json,"local_install_target_not_found");if(c.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:r,availableTargets:c.map(g=>({materializationId:g.materializationId,scope:f(g.record,"scope"),targetAgents:mr(g.record),materializedSkillRoot:f(g.record,"materializedSkillRoot")})),nextAction:"remove",nextStep:`Run the command from the intended project folder, or retry with --scope project|global and --agent <agent> to remove one exact ${r} materialization.`},`${r} is installed in more than one local target. Select the exact target to remove.`,t.json,"local_install_target_selection_required");let u=c[0],d=u?gr(s,u):s,p=u?.lifecycle??null;if(!p){let g=dz(s);if(g){try{await ise({backend:n,skillSlug:r,record:s,cachedArtifact:g})}catch{return x({status:"blocked",reasonCode:"cached_artifact_remove_failed",skillSlug:r,nextAction:"install",nextStep:"The cache receipt or its immutable bundle could not be verified. Leave it unchanged and reinstall only after resolving the local cache issue."},`Skills Layer could not safely remove ${r}'s verified cache receipt.`,t.json,"cached_artifact_remove_failed")}let y={status:"removed",skillSlug:r,storageKind:"cached_artifact"};return t.json?A(y,`Removed cached ${r}.`,!0,n):{exitCode:0,stdout:pP(r,n),stderr:""}}return x({status:"blocked",reasonCode:"exact_install_receipt_missing",skillSlug:r,nextAction:"install",nextStep:`Reinstall ${r} from an approved Artifact Format v1 export before removing or quarantining it.`},`Skills Layer cannot safely remove ${r} because its exact-generation receipt is missing or invalid.`,t.json,"exact_install_receipt_missing")}if(p.state==="quarantined"){let g={status:"removed",skillSlug:r,removedRecord:d,localLifecycle:p};return t.json?A(g,`${r} is already removed from discovery.`,!0,n):{exitCode:0,stdout:pP(r,n),stderr:""}}if(p.state==="externally_removed"||p.state==="host_detached"){if(t.forget){let g=Vr(p.receipt),y=await aae(n,{skillSlug:r,generationId:p.receipt.generation.generationId,receiptSha256:g});return await Br(n,v=>{let b=v.installs[r];if(!b)return;let w=cz({existing:b,materializationId:u.materializationId,backend:n});w?v.installs[r]=w:delete v.installs[r]}),A({status:"forgotten",skillSlug:r,materializationId:u.materializationId,receiptSha256:g,forgottenAssociationCount:y,cloudAuthorityChanged:!1,nextAction:"installed",nextStep:"The local terminal tombstone and its terminal session evidence were removed. Cloud ownership, entitlement, workspace approval, and Trust Ledger history remain unchanged."},`${r}'s exact local tombstone was forgotten.`,t.json,n)}return A({status:p.state,skillSlug:r,tombstoneRetained:!0,localLifecycle:p,nextAction:"install",nextStep:`Reinstall ${r} to rematerialize it. Its local tombstone remains available for audit and recovery.`},`${r} is already absent from the exact local target; its recovery tombstone was retained.`,t.json,n)}if(t.forget)return x({status:"blocked",reasonCode:"guardian_forget_requires_terminal_tombstone",skillSlug:r,localLifecycle:p,nextAction:"remove",nextStep:"Use normal remove for an active installation. --forget only deletes a retained externally_removed or host_detached tombstone."},"Skills Layer only forgets an explicit terminal local tombstone.",t.json,"guardian_forget_requires_terminal_tombstone");if(p.state!=="active"&&p.state!=="pending_activation")return x({status:"blocked",reasonCode:"local_lifecycle_busy",skillSlug:r,localLifecycle:p},`${r} cannot be removed while its local lifecycle is ${p.state}.`,t.json,"local_lifecycle_busy");let m;try{m=await pA({backend:n,skillSlug:r,record:d,materializationId:u.materializationId,lifecycle:p,reasonCode:"user_removed",purpose:"quarantine_revoked",status:"removed"})}catch(g){return x({status:"blocked",reasonCode:"exact_generation_quarantine_failed",skillSlug:r,error:ve(g),nextAction:"guardian.incident.review",nextStep:"Do not run the skill. Inspect local drift or permissions, then retry removal after the exact tree is restored."},`Skills Layer could not atomically remove the exact installed generation for ${r}.`,t.json,"exact_generation_quarantine_failed")}let h={status:"removed",skillSlug:r,removedRecord:m.record,localLifecycle:m.lifecycle};return t.json?A(h,`Removed ${r}.`,!0,n):{exitCode:0,stdout:pP(r,n),stderr:""}}async function ise(e){let t=e.backend.platform==="win32"?st:Lt,n=t.join(e.backend.paths.bundlesDir,e.skillSlug,e.cachedArtifact.generation.semanticVersion,encodeURIComponent(e.cachedArtifact.generation.generationId),"bundle.zip");if(t.normalize(e.cachedArtifact.bundlePath)!==t.normalize(n))throw new Error("Cached artifact path does not match its exact generation.");let r=await Xu(n);if(!r.isFile()||r.isSymbolicLink())throw new Error("Cached artifact is not a regular file.");if(`sha256:${Ue("sha256").update(await Fi(n)).digest("hex")}`!==e.cachedArtifact.archiveSha256)throw new Error("Cached artifact digest does not match its receipt.");let o=K(Me(n),`.bundle.remove-${Ge(12).toString("hex")}`);await zo(n,o);try{let s=await lt(e.backend),a=s.installs[e.skillSlug],l=a?dz(a):null;if(!a||!l||l.bundlePath!==e.cachedArtifact.bundlePath||l.archiveSha256!==e.cachedArtifact.archiveSha256)throw new Error("Cached install record changed during removal.");delete s.installs[e.skillSlug],await _A(e.backend,s)}catch(s){throw await zo(o,n).catch(()=>{}),s}await We(o,{force:!0})}async function pA(e){if(e.lifecycle.receipt.generation.skillSlug!==e.skillSlug)throw new Error("Install receipt skill identity does not match the indexed slug.");let t=`quarantine_${Ge(16).toString("hex")}`,n={status:"authorized",authorizationId:`${e.purpose}_${Ge(16).toString("hex")}`,purpose:e.purpose,generation:e.lifecycle.receipt.generation,archiveSha256:e.lifecycle.receipt.archiveSha256,manifestSha256:e.lifecycle.receipt.manifestSha256},r=await o2({receipt:e.lifecycle.receipt,reasonCode:e.reasonCode,quarantineRoot:K(e.backend.paths.stateDir,"quarantine"),discoveryRoots:ose(e.backend,e.lifecycle.receipt.targetDir),authorizeQuarantine:async()=>n}),i=Wu({state:"quarantined",operationId:t,receipt:e.lifecycle.receipt,quarantine:r,backend:e.backend}),o;if(await Br(e.backend,s=>{let a=s.installs[e.skillSlug],l=a?Yt(a)[e.materializationId]:void 0,c=l?Jt(l):null;if(!a||!l||!c||c.operationId!==e.lifecycle.operationId)throw new Error("Local install record changed while its exact generation was quarantined.");o={...l,status:e.status,...e.reasonCode==="refunded"?{removedReason:"refunded"}:{},localLifecycle:i,savedAt:e.backend.now()},s.installs[e.skillSlug]=Fr({existing:a,skillSlug:e.skillSlug,materialization:o,backend:e.backend})}),!o)throw new Error("Local install quarantine did not commit its exact target record.");return{record:o,lifecycle:i,quarantine:r}}function ose(e,t){let n=new Set([Me(t)]);for(let r of et(e.env,e.platform,e.cwd)){n.add(r.targets.projectSkillsPath),r.targets.globalSkillsPath&&n.add(r.targets.globalSkillsPath);for(let i of[r.pathContracts.project,r.pathContracts.global]){i.preferredPath&&n.add(i.preferredPath);for(let o of[...i.compatibleReadOnlyPaths,...i.legacyReadOnlyPaths])n.add(o.path)}}return[...n]}async function sse(e,t,n){let r=O(e[0],"update requires a skill slug."),i=Qu("update",t);if(i.failure)return i.failure;let o=new URLSearchParams,s=k(t.pin);if(s&&!Th(s))return x({status:"error",reasonCode:"invalid_pin",skillSlug:r,requestedPin:s,nextAction:"update",nextStep:"Use --pin with a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --pin "${s}". Use a semver version or an external-<digest> version.`,t.json,"invalid_pin");Ke(o,"pin",s),t.dryRun&&o.set("dryRun","true");let a=await ed(t,n,r);if(a.revokedSlugs.includes(r))return A({status:"entitlement_revoked",skillSlug:r,reasonCode:"entitlement_revoked_refunded",warnings:a.warnings,nextStep:`Buy ${r} again to restore access.`},a.warnings.join(" ")||`${r} was refunded; access is revoked.`,t.json,n);let c=(t.dryRun?await lt(n):await Bi(n,r)).installs[r],u=qn(c,i);if(u.length===0&&An(c).length>0&&(i.scope||i.agent))return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:r,requestedScope:i.scope,requestedAgent:i.agent,nextAction:"installed",nextStep:"Run `skills-layer installed --json` and select one of the recorded targets."},`${r} is not installed for the requested local target.`,t.json,"local_install_target_not_found");if(u.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:r,nextAction:"update",nextStep:"Retry with --scope and --agent to update one exact materialization."},`${r} has more than one local materialization. Select the exact target to update.`,t.json,"local_install_target_selection_required");let d=u[0]&&c?gr(c,u[0]):c,p=Soe(d),m=n,h;try{h=await D(n,`/api/v1/skills/${encodeURIComponent(r)}${Qe(o)}`,{headers:Wo(n.apiKey)})}catch(y){if(EP(p,y))m={...n,apiKey:void 0,authBlockedMessage:void 0},h=await D(m,`/api/v1/skills/${encodeURIComponent(r)}${Qe(o)}`);else{if(y instanceof Z&&y.status===404&&d){let v={status:"backend_missing",reasonCode:"local_install_backend_missing",skillSlug:r,localInstall:d,installedVersion:f(d,"version")??f(d,"currentVersion"),selectedBackend:n.baseUrl,nextStep:`This skill is installed locally, but no catalog update source was found on ${n.baseUrl}. Reinstall from its source, run \`skills-layer search ${r}\`, or run \`skills-layer remove ${r}\` if you no longer need it.`};return x(v,`${r} is installed locally, but no catalog update source was found on this backend. Reinstall from its source, search for a replacement, or remove the local install.`,t.json,"local_install_backend_missing")}if(y instanceof Z)return Go(y,t.json);throw y}}if(h.catalogRefreshPending===!0||j(h.skill)&&h.skill.catalogRefreshPending===!0)return A({status:"catalog_refresh_pending",skillSlug:r,nextStep:`Publication is still refreshing. Retry skills-layer update ${r} shortly.`,localInstall:d},"Publication is still refreshing. Your installed copy is unchanged; retry update shortly.",t.json,n);let g=cse(r,h,d,n);if(s&&!ase(g,s))return x({status:"not_found",reasonCode:"pin_not_resolved",skillSlug:r,requestedPin:s,installedVersion:f(d,"version")??f(d,"currentVersion"),currentVersion:f(g,"currentVersion"),nextAction:"update",nextStep:`Choose a version returned by \`skills-layer show ${r} --json\` or omit --pin to check the latest available version.`},`${r} does not have a resolvable version for --pin ${s}.`,t.json,"pin_not_resolved");if(!t.dryRun&&d){let y=f(d,"version")??f(d,"currentVersion"),v=f(g,"latestAvailableVersion"),b=s??v;if(!!(b&&b!==y)){let _={...t,dryRun:!1,pin:void 0,version:b,scope:k(t.scope)??f(d,"scope")??"project",agent:k(t.agent)??f(d,"agent")??f(d,"targetAgent")??"codex"};return await Wa([r],_,m,p)}}return t.json?A(g,"Update check complete.",!0,n):{exitCode:0,stdout:pse(g,n),stderr:""}}function Th(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u.test(e)||/^external-[0-9A-Za-z][0-9A-Za-z._-]*$/u.test(e)}function ase(e,t){let n=[f(e,"version"),f(e,"currentVersion"),f(e,"latestVersion"),f(e,"targetVersion"),f(e,"availableVersion")].filter(Boolean),r=L(e,"update");return r&&n.push(f(r,"version"),f(r,"currentVersion"),f(r,"latestVersion"),f(r,"targetVersion"),f(r,"availableVersion")),n.some(i=>i===t)}async function lse(e,t){let n=Qu("sync",e);if(n.failure)return n.failure;let r=await ed(e,t),i=e.dryRun?await lt(t):await Bi(t),o=uz(i).filter(l=>(!n.scope||f(l,"scope")===n.scope)&&(!n.agent||mr(l).includes(n.agent))),a={status:"synced",results:await Promise.all(o.map(async l=>use(l,t))),warnings:r.warnings};return e.json?A(a,"Local install records synced.",!0,t):{exitCode:0,stdout:fse(a,t)+r.warnings.map(l=>`
|
|
2154
|
+
`)}async function AU(e,t,n){if(RU(e)){let l=f(e,"reasonCode")??f(e,"reason")??"install_not_ready",c=f(e,"why")??f(e,"summary")??"The requested skill is not ready to install from this backend.";return x(e,`Install preview is not ready: ${c}`,t.json,l)}let r=k(t.agent)==="all"?et(n.env,n.platform,n.cwd).map(l=>({...t,agent:l.id})):[t];for(let l of r){let c=iA(n,e,"",l);if(c.status!=="ok")continue;let u=await Ya({backend:n,skillSlug:c.skillSlug,agentId:c.agent.id,scope:c.scope,flags:t});if(u)return u}let i=Object.values(n.guardianActivationReceipts??{}).map(l=>$P(n,l.agent,l.scope)),o=i.flatMap(l=>Array.isArray(l.warnings)?l.warnings:[]),s=await EU({...e,...i[0],warnings:[...Array.isArray(e.warnings)?e.warnings:[],...o]},n),a=Array.isArray(s.warnings)&&s.warnings.length>0;return Qoe(s,a?"Install preview ready with warnings.":"Install preview ready.",t,n)}function Qoe(e,t,n,r){return n.json?R(e,t,!0,r):{exitCode:0,stdout:dA(e,t,r),stderr:""}}async function ese(e,t,n,r){if(RU(e)){let o=f(e,"reasonCode")??f(e,"reason")??"workspace_approval_not_ready",s=f(e,"why")??f(e,"summary")??f(e,"nextStep")??"The requested workspace approval is not ready.";return x(e,`Workspace approval preview is not ready: ${s}`,n.json,o)}let i=await EU(e,r);return n.json?R(i,t,!0,r):{exitCode:0,stdout:dA(i,t,r),stderr:""}}function RU(e){let t=f(e,"status")?.toLowerCase(),n=f(e,"reasonCode")?.toLowerCase();return t==="not_found"||t==="missing"||t==="blocked"||t==="not_ready"||n==="skill_not_found"||n==="not_found"}async function EU(e,t){let n=o=>({...e,...o,warnings:[...new Set([...Be(e,"warnings")??[],...Be(o,"warnings")??[]])]}),r=yM(e);if(r)return n(r);let i=f(e,"skillSlug")??f(e,"slug");if(!i)return e;try{let o=await D(t,`/api/v1/skills/${encodeURIComponent(i)}/trust`),s=yM(o);return s?n(s):e}catch{return e}}function yM(e){let t=L(e,"securityReport")??L(e,"report")??e,n=L(e,"trust")??L(t,"trust")??t,r=L(e,"securityPosture")??L(t,"securityPosture"),i=L(e,"capabilityProfile")??L(t,"capabilityProfile"),o=ie({securityScore:J(n,"securityScore")??J(n,"score")??J(e,"securityScore")??(r?J(r,"securityScore"):void 0),runtimeRisk:f(n,"runtimeRisk")??f(e,"runtimeRisk")??(r?f(r,"runtimeRisk"):void 0)??(i?f(i,"runtimeRisk"):void 0),recommendation:f(n,"recommendation")??f(e,"recommendation")??(r?f(r,"recommendation"):void 0),detectedCapabilities:Be(n,"detectedCapabilities")??Be(e,"detectedCapabilities")??(i?Be(i,"detectedCapabilities"):void 0),capabilityMismatches:Be(n,"capabilityMismatches")??Be(e,"capabilityMismatches")??(i?Be(i,"capabilityMismatches"):void 0),organizationPolicyDecision:f(n,"organizationPolicyDecision")??f(n,"policyDecision")??f(e,"organizationPolicyDecision")??f(e,"policyDecision")??(r?f(r,"organizationPolicyDecision"):void 0)});if(Object.keys(o).length!==0)return ie({trust:o,effectiveness:L(e,"effectiveness")??L(t,"effectiveness"),runtimeRisk:f(o,"runtimeRisk"),detectedCapabilities:Array.isArray(o.detectedCapabilities)?o.detectedCapabilities:void 0,capabilityMismatches:Array.isArray(o.capabilityMismatches)?o.capabilityMismatches:void 0,organizationPolicyDecision:f(o,"organizationPolicyDecision"),warnings:Be(e,"warnings")??Be(t,"warnings")??Be(n,"warnings")})}function Va(e,t,n,r,i){return n?R(e,t,!0,r):{exitCode:0,stdout:dA(e,t,r,i),stderr:""}}function dA(e,t,n,r){let i=Pe(n),o=[`${i.ok("OK")} ${t}`];for(let T of Be(e,"warnings")??[])typeof T=="string"&&o.push(`Warning: ${T}`);if(e.verificationStatus==="unverified"&&e.publiclyDiscoverable===!1){o.push("","Local installation complete \u2014 Unverified / Unscored."),e.catalogueVisibilityRequested==="public"?o.push("This skill is not publicly listed. Catalogue admission does not guarantee publication."):o.push("This is not a public listing. Private catalogue approval is separate from local installation.");let T=f(e,"reasonCode");T&&o.push(`Catalogue review reason: ${T}`)}let s=f(e,"skillSlug")??f(e,"slug"),a=f(e,"version")??f(e,"currentVersion"),l=f(e,"catalogueCandidateVersion"),c=f(e,"localProvisionalVersion"),u=f(e,"localGeneration"),d=f(e,"sourceContentDigest");(s||a||l||c||u||d)&&(o.push("",i.section("Skill")),s&&o.push(` ${i.label("Slug")}: ${s}`),l?o.push(` ${i.label("Catalogue Candidate Version")}: ${l}`):a&&o.push(` ${i.label("Version")}: ${a}`),c&&o.push(` ${i.label("Local Provisional Version")}: ${c}`),u&&o.push(` ${i.label("Local Generation")}: ${u}`),d&&o.push(` ${i.label("Source Content Digest")}: ${d}`));let p=f(e,"visibility")??f(e,"versionVisibility"),m=f(e,"catalogueVisibilityRequested")??f(e,"requestedVisibility"),h=f(e,"catalogueStatus"),g=typeof e.publiclyDiscoverable=="boolean"?e.publiclyDiscoverable:void 0,y=f(e,"publicationStatus"),v=f(e,"catalogRecord");(p||m||h||g!==void 0||y||v)&&(o.push("",i.section("Privacy")),m?o.push(` ${i.label("Catalogue Visibility Requested")}: ${m}`):p&&o.push(` ${i.label("Visibility")}: ${p}`),h&&o.push(` ${i.label("Catalogue Status")}: ${h}`),g!==void 0&&o.push(` ${i.label("Publicly Discoverable")}: ${g?"yes":"no"}`),y&&o.push(` ${i.label("Publication")}: ${y}`),v&&o.push(` ${i.label("Catalog record")}: ${v}`));let b=L(e,"materializationPlan")??L(e,"installPlan"),w=f(e,"scope")??(b?f(b,"scope"):void 0),_=f(e,"agent")??f(e,"targetAgent")??(b?f(b,"agent")??f(b,"targetAgent"):void 0),C=Array.isArray(e.materializedWrites)?e.materializedWrites.filter(j):[];if(w||_||C.length>0)if(o.push("",i.section("Local Materialization")),w&&o.push(` ${i.label("Scope")}: ${w}`),_&&o.push(` ${i.label("Agent")}: ${_}`),C.length===0)o.push(` ${i.muted("No local files were written by this command.")}`);else for(let T of C.slice(0,at)){let X=f(T,"path");X&&o.push(` ${i.arrow} ${X}`)}let P=tce(e,i).filter(T=>!T.includes("materialized writes:"));P.length>0&&o.push("",...P);let N=!w&&C.length===0&&s?[`skills-layer install ${s} --scope project --agent ${_??r??"<agent>"}`]:cce(e);return N.length>0&&o.push("",i.section("Next"),...N.map(T=>` ${i.arrow} ${T}`)),o.join(`
|
|
2155
|
+
`)}function tse(e,t){let n=L(e,"trust"),r=L(e,"securityPosture"),i=L(e,"capabilityProfile"),o=n?.securityScore??n?.score??e.securityScore??r?.securityScore,s=qe(n,"runtimeRisk")??f(e,"runtimeRisk")??qe(r,"runtimeRisk")??qe(i,"runtimeRisk"),a=qe(n,"recommendation")??f(e,"recommendation")??qe(r,"recommendation"),l=qe(n,"label")??qe(n,"trust")??f(e,"trustStatus")??f(e,"trust")??qe(r,"label");if(o===void 0&&!s&&!a&&!l)return[];let c=[t.section("Trust")];return s&&c.push(` ${t.label("Runtime risk")}: ${s}`),a&&c.push(` ${t.label("Recommendation")}: ${a}`),l&&c.push(` ${t.label("Status")}: ${l}`),c.push(` ${t.label("Source")}: skills-layer trust`),c}async function ed(e,t,n){let r=[],i=[];if(!t.apiKey)return{warnings:r,revokedSlugs:i};let o=await lt(t),s=Object.entries(o.installs).filter(([l,c])=>(!n||l===n)&&c.acquisitionMode==="authenticated_account"&&(!c.acquisitionBaseUrl||c.acquisitionBaseUrl===t.baseUrl));if(!s.length)return{warnings:r,revokedSlugs:i};let a=[];try{for(let l=0;l<s.length;l+=50){let c=new URLSearchParams({slugs:s.slice(l,l+50).map(([d])=>d).join(",")}),u=await D(t,`/api/v1/me/entitlements?${c}`,{headers:re(t.apiKey,t.authBlockedMessage)});if(!Array.isArray(u.results))throw new Error("Entitlement status unavailable");a.push(...u.results.filter(j))}}catch{return{warnings:["Could not verify entitlements online; local copies were kept."],revokedSlugs:i}}for(let[l,c]of s){let u=a.find(h=>h.skillSlug===l);if(!u||u.status!=="revoked"||u.reason!=="refunded"||u.paid!==!0)continue;let d=typeof c.entitlementId=="string"&&c.entitlementId===u.entitlementId,p=typeof c.acquiredByUserId=="string"&&c.acquiredByUserId===t.config?.userId&&c.acquisitionBaseUrl===t.baseUrl;if(!d&&!p){r.push(`Kept ${l}: its receipt cannot be matched to this buyer's refunded grant.`);continue}let m=An(c);if(!m.length){r.push(`No managed agent copy found for refunded ${l}. Manually copied folders cannot be removed automatically.`);continue}for(let h of m){let g=typeof h.record.acquisitionBaseUrl=="string"?h.record:m.length===1?c:{},y=typeof g.entitlementId=="string"&&g.entitlementId===u.entitlementId,v=g.acquiredByUserId===t.config?.userId&&typeof g.acquiredByUserId=="string"&&g.acquisitionBaseUrl===t.baseUrl;if(!y&&!v){r.push(`Kept ${l}: this agent copy belongs to an unverified buyer receipt.`);continue}if(i.includes(l)||i.push(l),!(h.lifecycle?.state==="quarantined"||h.lifecycle?.state==="externally_removed")){if(!h.lifecycle||!["active","pending_activation"].includes(h.lifecycle.state)){r.push(`Kept ${l}: modified or unverifiable local copy; inspect it before removing it manually.`);continue}if(e.dryRun){r.push(`Would remove ${l} \u2014 refunded on ${String(u.revokedAt??"unknown date")}.`);continue}try{await pA({backend:t,skillSlug:l,record:gr(c,h),materializationId:h.materializationId,lifecycle:h.lifecycle,reasonCode:"refunded",purpose:"quarantine_revoked",status:"removed"}),r.push(`Removed ${l} \u2014 refunded on ${String(u.revokedAt??"unknown date")}.`)}catch{r.push(`Kept ${l}: modified or unverifiable local copy; inspect it before removing it manually.`)}}}}return{warnings:r,revokedSlugs:i}}async function nse(e,t){let n=Qu("installed",e);if(n.failure)return n.failure;let r=await ed(e,t),i=e.dryRun?await lt(t):await Bi(t),o=uz(i).filter(s=>(!n.scope||f(s,"scope")===n.scope)&&(!n.agent||mr(s).includes(n.agent)));return R({status:"ok",results:o,warnings:r.warnings},`Found ${o.length} local install records. ${r.warnings.join(" ")}`,e.json,t,"installed")}async function rse(e,t,n){let r=O(e[0],"remove requires a skill slug."),i=tU("remove",t);if(i)return i;let s=(t.dryRun?await lt(n):await Bi(n,r)).installs[r];if(!s)return x({status:"not_installed",reasonCode:"local_install_not_found",skillSlug:r},`${r} is not installed locally. Run \`skills-layer installed\` or \`skills-layer sync\` to inspect local records.`,t.json,"local_install_not_found");let a=k(t.scope),l=k(t.agent),c=qn(s,{scope:a,agent:l});if(c.length>1){let g=ule({backend:n,skillSlug:r,materializations:c,scope:a,agent:l});g.length===1&&(c=g)}if(c.length===0&&An(s).length>0)return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:r,requestedScope:a,requestedAgent:l},`${r} is not installed for the requested local target.`,t.json,"local_install_target_not_found");if(c.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:r,availableTargets:c.map(g=>({materializationId:g.materializationId,scope:f(g.record,"scope"),targetAgents:mr(g.record),materializedSkillRoot:f(g.record,"materializedSkillRoot")})),nextAction:"remove",nextStep:`Run the command from the intended project folder, or retry with --scope project|global and --agent <agent> to remove one exact ${r} materialization.`},`${r} is installed in more than one local target. Select the exact target to remove.`,t.json,"local_install_target_selection_required");let u=c[0],d=u?gr(s,u):s,p=u?.lifecycle??null;if(!p){let g=dz(s);if(g){try{await ise({backend:n,skillSlug:r,record:s,cachedArtifact:g})}catch{return x({status:"blocked",reasonCode:"cached_artifact_remove_failed",skillSlug:r,nextAction:"install",nextStep:"The cache receipt or its immutable bundle could not be verified. Leave it unchanged and reinstall only after resolving the local cache issue."},`Skills Layer could not safely remove ${r}'s verified cache receipt.`,t.json,"cached_artifact_remove_failed")}let y={status:"removed",skillSlug:r,storageKind:"cached_artifact"};return t.json?R(y,`Removed cached ${r}.`,!0,n):{exitCode:0,stdout:pP(r,n),stderr:""}}return x({status:"blocked",reasonCode:"exact_install_receipt_missing",skillSlug:r,nextAction:"install",nextStep:`Reinstall ${r} from an approved Artifact Format v1 export before removing or quarantining it.`},`Skills Layer cannot safely remove ${r} because its exact-generation receipt is missing or invalid.`,t.json,"exact_install_receipt_missing")}if(p.state==="quarantined"){let g={status:"removed",skillSlug:r,removedRecord:d,localLifecycle:p};return t.json?R(g,`${r} is already removed from discovery.`,!0,n):{exitCode:0,stdout:pP(r,n),stderr:""}}if(p.state==="externally_removed"||p.state==="host_detached"){if(t.forget){let g=Vr(p.receipt),y=await aae(n,{skillSlug:r,generationId:p.receipt.generation.generationId,receiptSha256:g});return await Br(n,v=>{let b=v.installs[r];if(!b)return;let w=cz({existing:b,materializationId:u.materializationId,backend:n});w?v.installs[r]=w:delete v.installs[r]}),R({status:"forgotten",skillSlug:r,materializationId:u.materializationId,receiptSha256:g,forgottenAssociationCount:y,cloudAuthorityChanged:!1,nextAction:"installed",nextStep:"The local terminal tombstone and its terminal session evidence were removed. Cloud ownership, entitlement, workspace approval, and Trust Ledger history remain unchanged."},`${r}'s exact local tombstone was forgotten.`,t.json,n)}return R({status:p.state,skillSlug:r,tombstoneRetained:!0,localLifecycle:p,nextAction:"install",nextStep:`Reinstall ${r} to rematerialize it. Its local tombstone remains available for audit and recovery.`},`${r} is already absent from the exact local target; its recovery tombstone was retained.`,t.json,n)}if(t.forget)return x({status:"blocked",reasonCode:"guardian_forget_requires_terminal_tombstone",skillSlug:r,localLifecycle:p,nextAction:"remove",nextStep:"Use normal remove for an active installation. --forget only deletes a retained externally_removed or host_detached tombstone."},"Skills Layer only forgets an explicit terminal local tombstone.",t.json,"guardian_forget_requires_terminal_tombstone");if(p.state!=="active"&&p.state!=="pending_activation")return x({status:"blocked",reasonCode:"local_lifecycle_busy",skillSlug:r,localLifecycle:p},`${r} cannot be removed while its local lifecycle is ${p.state}.`,t.json,"local_lifecycle_busy");let m;try{m=await pA({backend:n,skillSlug:r,record:d,materializationId:u.materializationId,lifecycle:p,reasonCode:"user_removed",purpose:"quarantine_revoked",status:"removed"})}catch(g){return x({status:"blocked",reasonCode:"exact_generation_quarantine_failed",skillSlug:r,error:ve(g),nextAction:"guardian.incident.review",nextStep:"Do not run the skill. Inspect local drift or permissions, then retry removal after the exact tree is restored."},`Skills Layer could not atomically remove the exact installed generation for ${r}.`,t.json,"exact_generation_quarantine_failed")}let h={status:"removed",skillSlug:r,removedRecord:m.record,localLifecycle:m.lifecycle};return t.json?R(h,`Removed ${r}.`,!0,n):{exitCode:0,stdout:pP(r,n),stderr:""}}async function ise(e){let t=e.backend.platform==="win32"?st:Lt,n=t.join(e.backend.paths.bundlesDir,e.skillSlug,e.cachedArtifact.generation.semanticVersion,encodeURIComponent(e.cachedArtifact.generation.generationId),"bundle.zip");if(t.normalize(e.cachedArtifact.bundlePath)!==t.normalize(n))throw new Error("Cached artifact path does not match its exact generation.");let r=await Xu(n);if(!r.isFile()||r.isSymbolicLink())throw new Error("Cached artifact is not a regular file.");if(`sha256:${Ue("sha256").update(await Fi(n)).digest("hex")}`!==e.cachedArtifact.archiveSha256)throw new Error("Cached artifact digest does not match its receipt.");let o=K(Me(n),`.bundle.remove-${Ge(12).toString("hex")}`);await zo(n,o);try{let s=await lt(e.backend),a=s.installs[e.skillSlug],l=a?dz(a):null;if(!a||!l||l.bundlePath!==e.cachedArtifact.bundlePath||l.archiveSha256!==e.cachedArtifact.archiveSha256)throw new Error("Cached install record changed during removal.");delete s.installs[e.skillSlug],await _A(e.backend,s)}catch(s){throw await zo(o,n).catch(()=>{}),s}await We(o,{force:!0})}async function pA(e){if(e.lifecycle.receipt.generation.skillSlug!==e.skillSlug)throw new Error("Install receipt skill identity does not match the indexed slug.");let t=`quarantine_${Ge(16).toString("hex")}`,n={status:"authorized",authorizationId:`${e.purpose}_${Ge(16).toString("hex")}`,purpose:e.purpose,generation:e.lifecycle.receipt.generation,archiveSha256:e.lifecycle.receipt.archiveSha256,manifestSha256:e.lifecycle.receipt.manifestSha256},r=await o2({receipt:e.lifecycle.receipt,reasonCode:e.reasonCode,quarantineRoot:K(e.backend.paths.stateDir,"quarantine"),discoveryRoots:ose(e.backend,e.lifecycle.receipt.targetDir),authorizeQuarantine:async()=>n}),i=Wu({state:"quarantined",operationId:t,receipt:e.lifecycle.receipt,quarantine:r,backend:e.backend}),o;if(await Br(e.backend,s=>{let a=s.installs[e.skillSlug],l=a?Yt(a)[e.materializationId]:void 0,c=l?Jt(l):null;if(!a||!l||!c||c.operationId!==e.lifecycle.operationId)throw new Error("Local install record changed while its exact generation was quarantined.");o={...l,status:e.status,...e.reasonCode==="refunded"?{removedReason:"refunded"}:{},localLifecycle:i,savedAt:e.backend.now()},s.installs[e.skillSlug]=Fr({existing:a,skillSlug:e.skillSlug,materialization:o,backend:e.backend})}),!o)throw new Error("Local install quarantine did not commit its exact target record.");return{record:o,lifecycle:i,quarantine:r}}function ose(e,t){let n=new Set([Me(t)]);for(let r of et(e.env,e.platform,e.cwd)){n.add(r.targets.projectSkillsPath),r.targets.globalSkillsPath&&n.add(r.targets.globalSkillsPath);for(let i of[r.pathContracts.project,r.pathContracts.global]){i.preferredPath&&n.add(i.preferredPath);for(let o of[...i.compatibleReadOnlyPaths,...i.legacyReadOnlyPaths])n.add(o.path)}}return[...n]}async function sse(e,t,n){let r=O(e[0],"update requires a skill slug."),i=Qu("update",t);if(i.failure)return i.failure;let o=new URLSearchParams,s=k(t.pin);if(s&&!Th(s))return x({status:"error",reasonCode:"invalid_pin",skillSlug:r,requestedPin:s,nextAction:"update",nextStep:"Use --pin with a semver version such as 1.2.3 or an external-<digest> Skills Layer version."},`Invalid --pin "${s}". Use a semver version or an external-<digest> version.`,t.json,"invalid_pin");Ke(o,"pin",s),t.dryRun&&o.set("dryRun","true");let a=await ed(t,n,r);if(a.revokedSlugs.includes(r))return R({status:"entitlement_revoked",skillSlug:r,reasonCode:"entitlement_revoked_refunded",warnings:a.warnings,nextStep:`Buy ${r} again to restore access.`},a.warnings.join(" ")||`${r} was refunded; access is revoked.`,t.json,n);let c=(t.dryRun?await lt(n):await Bi(n,r)).installs[r],u=qn(c,i);if(u.length===0&&An(c).length>0&&(i.scope||i.agent))return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:r,requestedScope:i.scope,requestedAgent:i.agent,nextAction:"installed",nextStep:"Run `skills-layer installed --json` and select one of the recorded targets."},`${r} is not installed for the requested local target.`,t.json,"local_install_target_not_found");if(u.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:r,nextAction:"update",nextStep:"Retry with --scope and --agent to update one exact materialization."},`${r} has more than one local materialization. Select the exact target to update.`,t.json,"local_install_target_selection_required");let d=u[0]&&c?gr(c,u[0]):c,p=Soe(d),m=n,h;try{h=await D(n,`/api/v1/skills/${encodeURIComponent(r)}${Qe(o)}`,{headers:Wo(n.apiKey)})}catch(y){if(EP(p,y))m={...n,apiKey:void 0,authBlockedMessage:void 0},h=await D(m,`/api/v1/skills/${encodeURIComponent(r)}${Qe(o)}`);else{if(y instanceof Z&&y.status===404&&d){let v={status:"backend_missing",reasonCode:"local_install_backend_missing",skillSlug:r,localInstall:d,installedVersion:f(d,"version")??f(d,"currentVersion"),selectedBackend:n.baseUrl,nextStep:`This skill is installed locally, but no catalog update source was found on ${n.baseUrl}. Reinstall from its source, run \`skills-layer search ${r}\`, or run \`skills-layer remove ${r}\` if you no longer need it.`};return x(v,`${r} is installed locally, but no catalog update source was found on this backend. Reinstall from its source, search for a replacement, or remove the local install.`,t.json,"local_install_backend_missing")}if(y instanceof Z)return Go(y,t.json);throw y}}if(h.catalogRefreshPending===!0||j(h.skill)&&h.skill.catalogRefreshPending===!0)return R({status:"catalog_refresh_pending",skillSlug:r,nextStep:`Publication is still refreshing. Retry skills-layer update ${r} shortly.`,localInstall:d},"Publication is still refreshing. Your installed copy is unchanged; retry update shortly.",t.json,n);let g=cse(r,h,d,n);if(s&&!ase(g,s))return x({status:"not_found",reasonCode:"pin_not_resolved",skillSlug:r,requestedPin:s,installedVersion:f(d,"version")??f(d,"currentVersion"),currentVersion:f(g,"currentVersion"),nextAction:"update",nextStep:`Choose a version returned by \`skills-layer show ${r} --json\` or omit --pin to check the latest available version.`},`${r} does not have a resolvable version for --pin ${s}.`,t.json,"pin_not_resolved");if(!t.dryRun&&d){let y=f(d,"version")??f(d,"currentVersion"),v=f(g,"latestAvailableVersion"),b=s??v;if(!!(b&&b!==y)){let _={...t,dryRun:!1,pin:void 0,version:b,scope:k(t.scope)??f(d,"scope")??"project",agent:k(t.agent)??f(d,"agent")??f(d,"targetAgent")??"codex"};return await Wa([r],_,m,p)}}return t.json?R(g,"Update check complete.",!0,n):{exitCode:0,stdout:pse(g,n),stderr:""}}function Th(e){return/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u.test(e)||/^external-[0-9A-Za-z][0-9A-Za-z._-]*$/u.test(e)}function ase(e,t){let n=[f(e,"version"),f(e,"currentVersion"),f(e,"latestVersion"),f(e,"targetVersion"),f(e,"availableVersion")].filter(Boolean),r=L(e,"update");return r&&n.push(f(r,"version"),f(r,"currentVersion"),f(r,"latestVersion"),f(r,"targetVersion"),f(r,"availableVersion")),n.some(i=>i===t)}async function lse(e,t){let n=Qu("sync",e);if(n.failure)return n.failure;let r=await ed(e,t),i=e.dryRun?await lt(t):await Bi(t),o=uz(i).filter(l=>(!n.scope||f(l,"scope")===n.scope)&&(!n.agent||mr(l).includes(n.agent))),a={status:"synced",results:await Promise.all(o.map(async l=>use(l,t))),warnings:r.warnings};return e.json?R(a,"Local install records synced.",!0,t):{exitCode:0,stdout:fse(a,t)+r.warnings.map(l=>`
|
|
2156
2156
|
${l}`).join(""),stderr:""}}function cse(e,t,n,r){let i=n?f(n,"version")??f(n,"currentVersion"):void 0,o=f(t,"currentVersion")??f(t,"version"),s=n?i&&o&&i!==o?"update_available":"up_to_date":"not_installed";return ie({...t,skillSlug:f(t,"skillSlug")??f(t,"slug")??e,updateStatus:s,installedVersion:i,latestAvailableVersion:o,selectedBackend:r.baseUrl,localInstall:n,nextStep:s==="not_installed"?`Run \`skills-layer install ${e}\` to install this skill locally.`:s==="update_available"?`Run \`skills-layer install ${e}\` to apply the latest available version.`:`No update is needed for ${e}.`})}async function use(e,t){let n=f(e,"skillSlug")??f(e,"slug");if(!n)return{...e,syncStatus:"local_only",backendStatus:"unchecked"};try{let r=await D(t,`/api/v1/skills/${encodeURIComponent(n)}`,{headers:Wo(t.apiKey)}),o=(f(r,"claimedOrigin")??f(r,"sourceKind")??f(e,"sourceKind"))==="public_source"||f(e,"sourceKind")==="external";return{...e,syncStatus:o?"source_backed":"catalog_backed",backendStatus:"found",latestAvailableVersion:f(r,"currentVersion")??f(r,"version"),catalog:dse(r)}}catch(r){return r instanceof Z&&r.status===404?{...e,syncStatus:"backend_missing",backendStatus:"not_found",selectedBackend:t.baseUrl}:{...e,syncStatus:"unchecked",backendStatus:"error",backendError:ve(r)}}}function dse(e){return ie({slug:f(e,"slug")??f(e,"skillSlug"),currentVersion:f(e,"currentVersion")??f(e,"version"),claimedOrigin:f(e,"claimedOrigin"),trust:f(e,"trust")??f(e,"publicationStatus")})}function pse(e,t){let n=Pe(t),r=f(e,"skillSlug")??f(e,"slug")??"skill",i=f(e,"updateStatus")??"checked",o=[`${n.ok("OK")} Update check complete.`,"",n.section("Update")];o.push(` ${n.label("Skill")}: ${r}`),o.push(` ${n.label("Status")}: ${i.replaceAll("_"," ")}`);let s=f(e,"installedVersion"),a=f(e,"latestAvailableVersion");s&&o.push(` ${n.label("Installed version")}: ${s}`),a&&o.push(` ${n.label("Latest available version")}: ${a}`);let l=L(e,"localInstall"),c=l?f(l,"materializedPath")??f(l,"path"):void 0,u=l?f(l,"scope"):void 0,d=l?f(l,"targetAgent")??f(l,"agent"):void 0;l&&(o.push("",n.section("Local Install")),u&&o.push(` ${n.label("Scope")}: ${u}`),d&&o.push(` ${n.label("Agent")}: ${d}`),c&&o.push(` ${n.label("Path")}: ${c}`));let p=f(e,"nextStep");return p&&o.push("",n.section("Next"),` ${n.arrow} ${p}`),o.join(`
|
|
2157
2157
|
`)}function fse(e,t){let n=Pe(t),r=[`${n.ok("OK")} Local install records synced.`,"",n.section(`Results (${e.results.length})`)];return e.results.length===0?(r.push(` ${n.muted("No local install records found.")}`),r.join(`
|
|
2158
2158
|
`)):(e.results.slice(0,at).forEach((i,o)=>{let s=f(i,"skillSlug")??f(i,"slug")??`item-${o+1}`,a=f(i,"syncStatus")??"unchecked",l=f(i,"version")??f(i,"currentVersion");r.push(`${o+1}. ${s}`),r.push(` status: ${a.replaceAll("_"," ")}${l?`; version: ${l}`:""}`),a==="backend_missing"&&r.push(` ${n.muted("Installed locally, but missing from the selected backend catalog.")}`)}),e.results.length>at&&r.push(` ${n.muted(`... ${e.results.length-at} more`)}`),r.push("",n.section("Next")),r.push(` ${n.arrow} skills-layer installed`),r.push(` ${n.arrow} skills-layer update <skill-slug>`),r.join(`
|
|
2159
2159
|
`))}function pP(e,t){let n=Pe(t);return[`${n.ok("OK")} Removed ${e}.`,"",n.section("Local Install"),` ${n.label("Skill")}: ${e}`,` ${n.label("Status")}: removed locally`,"",n.section("Next"),` ${n.arrow} skills-layer installed`,` ${n.arrow} skills-layer sync`].join(`
|
|
2160
2160
|
`)}function mse(e,t,n){let r=Pe(n),i=f(t,"version")??f(t,"currentVersion"),o=f(t,"scope");return[`${r.ok("OK")} Restore record found for ${e}.`,"",r.section("Local Install"),` ${r.label("Skill")}: ${e}`,...i?[` ${r.label("Version")}: ${i}`]:[],...o?[` ${r.label("Scope")}: ${o}`]:[],"",r.section("Next"),` ${r.arrow} skills-layer installed`,` ${r.arrow} skills-layer sync`,` ${r.arrow} skills-layer update ${e}`].join(`
|
|
2161
2161
|
`)}function gse(e){let t=f(e,"status"),n=f(e,"reasonCode");return t==="invalid_transition"||t==="forbidden"||t==="not_found"||n==="invalid_transition"}function hse(e,t){let n=f(e,"why")??f(e,"reason")??f(e,"error"),r=f(e,"currentVisibility"),i=f(e,"nextVisibility")??f(e,"visibility"),o=r||i?` Current visibility: ${r??"unknown"}; requested visibility: ${i??"unknown"}.`:"",s=f(e,"nextStep")??`Run \`skills-layer creator status ${t}\` and choose a valid visibility transition.`;return`Visibility was not changed for ${t}.${o}${n?` ${n}`:""}
|
|
2162
|
-
Next step: ${s}`}async function yse(e,t,n){let r=Qu("restore",t);if(r.failure)return r.failure;let i=await lt(n),o=O(e[0],"restore requires a skill slug."),s=i.installs[o];if(!s)return x({status:"missing_record",reasonCode:"restore_record_not_found",skillSlug:o,record:null,nextAction:"installed",nextStep:`Run \`skills-layer installed\` to see local records, \`skills-layer sync\` to refresh status, or \`skills-layer search ${o}\` if you want to find a catalog/source replacement.`},`No restorable local install record was found for ${o}. Run \`skills-layer installed\`, \`skills-layer sync\`, or \`skills-layer search ${o}\` next.`,t.json,"restore_record_not_found");if(s.removedReason==="refunded"||An(s).some(_=>_.record.removedReason==="refunded")){let _=!1;try{let C=await D(n,`/api/v1/me/entitlements?${new URLSearchParams({slugs:o})}`,{headers:re(n.apiKey,n.authBlockedMessage)});_=un(C.results).some(P=>P.skillSlug===o&&P.status==="active")}catch{}if(!_)return x({status:"blocked",reasonCode:"entitlement_revoked_refunded",skillSlug:o,nextStep:`Buy ${o} again before restoring it.`},"A refunded skill cannot be restored without active access.",t.json,"entitlement_revoked_refunded")}let a=qn(s,{scope:r.scope,agent:r.agent});if(a.length===0&&An(s).length>0)return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:o,requestedScope:r.scope,requestedAgent:r.agent,nextAction:"installed",nextStep:"Run `skills-layer installed --json` and select one of the recorded quarantined targets."},`${o} has no restorable record for the requested local target.`,t.json,"local_install_target_not_found");if(a.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:o,nextAction:"restore",nextStep:"Retry with --scope and --agent to restore one exact quarantined materialization."},`${o} has more than one local materialization. Select the exact target to restore.`,t.json,"local_install_target_selection_required");let l=a[0],c=l?gr(s,l):s,u=l?.lifecycle??null;if(!u)return x({status:"blocked",reasonCode:"exact_install_receipt_missing",skillSlug:o,nextAction:"install",nextStep:`Reinstall ${o} from the approved catalog; legacy records cannot authorize an exact-generation restore.`},`Skills Layer cannot restore ${o} because its exact-generation lifecycle record is missing or invalid.`,t.json,"exact_install_receipt_missing");if(u.state!=="quarantined"||!u.quarantine)return x({status:"blocked",reasonCode:"restore_not_quarantined",skillSlug:o,localLifecycle:u,nextAction:"installed",nextStep:"Only a physically quarantined exact generation can be restored."},`${o} does not have a quarantined exact generation to restore.`,t.json,"restore_not_quarantined");let d=new URLSearchParams({version:u.receipt.generation.semanticVersion,operation:"restore",generationId:u.receipt.generation.generationId}),p=f(c,"acquisitionMode")==="anonymous_public",m;try{m=await D(n,p?`/api/v1/skills/${encodeURIComponent(o)}/export${Qe(d)}`:`/api/v1/me/library/${encodeURIComponent(o)}/export${Qe(d)}`,{headers:p?{}:re(n.apiKey,n.authBlockedMessage)})}catch(_){if(_ instanceof Z)return Go(_,t.json);throw _}if(m.restoreAuthorization===void 0)return x({status:"blocked",reasonCode:"restore_authorization_missing",skillSlug:o,generation:u.receipt.generation,nextAction:"restore",nextStep:"Retry after the Skills Layer API returns a fresh restoreAuthorization bound to this exact generation."},`The backend did not authorize restoration of ${o}'s exact quarantined generation.`,t.json,"restore_authorization_missing");let h=fz(m.restoreAuthorization);if(!h||h.purpose!=="restore_fresh_approval"||!vse(h,u.receipt))return x({status:"blocked",reasonCode:"restore_authorization_invalid",skillSlug:o,generation:u.receipt.generation,nextAction:"restore",nextStep:"Do not restore. Refresh backend approval for this exact artifact generation."},`The backend returned an invalid or mismatched restore authorization for ${o}.`,t.json,"restore_authorization_invalid");let g=`restore_${Ge(16).toString("hex")}`,y=Wu({state:"restore_pending",operationId:g,receipt:u.receipt,quarantine:u.quarantine,backend:n});await Br(n,_=>{let C=_.installs[o],P=C&&l?Yt(C)[l.materializationId]:void 0,N=P?Jt(P):null;if(!C||!P||N?.operationId!==u.operationId||N.state!=="quarantined")throw new Error("Local install record changed before its exact restore reservation was created.");_.installs[o]=Fr({existing:C,skillSlug:o,materialization:{...P,localLifecycle:y,savedAt:n.now()},backend:n})});let v;try{await s2({quarantine:u.quarantine,authorizeRestore:async()=>h,finalizeRestore:async()=>{let _=!0;return await Br(n,C=>{let P=C.installs[o],N=P&&l?Yt(P)[l.materializationId]:void 0,T=N?Jt(N):null;if(!P||!N||!T||T.state!=="restore_pending"||T.operationId!==g){_=!1;return}let X=Wu({state:"active",operationId:g,receipt:u.receipt,backend:n});v={...N,status:"restored",localLifecycle:X,savedAt:n.now()},C.installs[o]=Fr({existing:P,skillSlug:o,materialization:v,backend:n})}),_?{status:"released",releaseId:`local_restore_${Ge(16).toString("hex")}`}:{status:"denied",reasonCode:"restore_reservation_lost"}}})}catch(_){return await Br(n,C=>{let P=C.installs[o],N=P&&l?Yt(P)[l.materializationId]:void 0,T=N?Jt(N):null;!P||!N||T?.operationId!==g||(C.installs[o]=Fr({existing:P,skillSlug:o,materialization:{...N,localLifecycle:u,savedAt:n.now()},backend:n}))}).catch(()=>{}),x({status:"blocked",reasonCode:"exact_generation_restore_failed",skillSlug:o,error:ve(_),nextAction:"restore",nextStep:"Keep the generation quarantined. Resolve local path, drift, or permission problems before retrying."},`Skills Layer could not atomically restore ${o}.`,t.json,"exact_generation_restore_failed")}if(!v)throw new Error(`Atomic restore for ${o} completed without committing its local lifecycle record.`);let b=Jt(v),w={status:"restored",skillSlug:o,record:v,localLifecycle:b};return t.json?A(w,`Restored ${o}.`,!0,n):{exitCode:0,stdout:mse(o,v,n),stderr:""}}function vse(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&e.archiveSha256===t.archiveSha256&&e.manifestSha256===t.manifestSha256}async function kse(e,t,n){let r=O(e[0],"check requires a skill slug.");return await me(`/api/v1/skills/${encodeURIComponent(r)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function wse(e,t,n){let r=O(e[0]??t.source,"import requires a source."),i=Mn("import","visibility",t.visibility,za,t,"invalid_visibility");if(i)return i;let o=await Hu(r,n.cwd);if(o)return await bse(r,o,t,n);let s=_se(r,t);if(s)return s;let a=cA(r,t,n,n.apiKey?"authenticated":"unknown"),l=await D(n,a,{method:"POST",headers:SU(r,t,n,n.apiKey?"authenticated":"unknown"),body:JSON.stringify(ie({source:r,skillSlug:k(t.skill),visibility:k(t.visibility)??Ti(r,t,n)}))});return await Ve(n.paths.importsPath,{version:1,lastImport:l,savedAt:n.now()}),A(l,"Source import submitted.",t.json,n)}async function bse(e,t,n,r){let i=k(n.skill),o=aA(e,t,i);if(!r.apiKey)return x({status:"error",reasonCode:"local_import_sign_in_required",source:e,nextAction:"login",nextStep:`Run \`skills-layer login\`, then retry \`skills-layer import ${e}\` (the same flow as \`skills-layer creator submit ${e}\`).`},"Importing a local folder submits it through your creator account, so you must sign in first. Run `skills-layer login`, then retry. Nothing was uploaded.",n.json,"local_import_sign_in_required");let s=Ih(e,o,n);if(s)return s;let a=await ju({source:e,inspection:o,requestedSkillSlug:i,mode:"import",flags:n,backend:r});if(a.kind==="failure")return a.result;let c=lA(t.files).find(d=>d.skillSlug===a.skillSlug),u=c.relativeSkillRoot==="."?e:`${e.replace(/[\\/]+$/u,"")}/${c.relativeSkillRoot}`;return k(n.version)?await AP([u],{...n,source:void 0,path:void 0,skill:c.skillSlug},r,!1):x({status:"error",nextAction:"import",nextStep:"Pass --version <semver>, for example --version 1.0.0."},"A local import requires --version <semver>.",n.json,"version_required")}function _se(e,t){try{return rr(e).kind!=="local"?null:x({status:"error",reasonCode:"invalid_source",source:e,nextAction:"import",nextStep:zu(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or --help for import examples."},zu(e)?`Import source ${e} was not found or is not readable.`:`Import source "${e}" is not a supported source. Use a local path, GitHub/GitLab source, or URL.`,t.json,"invalid_source")}catch(n){return x({status:"error",reasonCode:"invalid_source",source:e,error:ve(n),nextAction:"import",nextStep:"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or URL."},`Import source "${e}" is invalid. ${ve(n)}`,t.json,"invalid_source")}}function zu(e){return/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/u.test(e)}function $U(e,t,n,r){let i=Tt(r.cwd,t);return x({status:"error",reasonCode:"source_path_not_found",path:i,nextAction:e,nextStep:`Check that ${t} exists and contains a readable SKILL.md, then retry.`},`${e} source path does not exist: ${i}`,n.json,"source_path_not_found")}async function Sse(e,t,n){let r=e[0];if(r==="reference"&&e[1]==="resolve"){let i=O(e[2],"source reference resolve requires a reference."),o=await D(n,`/api/v1/source-references/resolve?reference=${encodeURIComponent(i)}`);return o.status==="not_found"?x({...o,status:"not_found",reasonCode:"source_reference_not_found",reference:i,nextAction:"source.connection.start",nextStep:"Start or complete the source connection before resolving this reference."},`Source reference ${i} was not found.`,t.json,"source_reference_not_found"):A(o,"Source reference resolved.",t.json,n)}return r==="connection"?await xse(e.slice(1),t,n):R(`Unknown source command "${e.join(" ")}".`,t.json)}async function xse(e,t,n){let r=e[0];if(r==="start"){let o=k(t.provider),s=k(t.source),a=k(t.visibility),l=o?.replace(/-/gu,"_");if(l&&!VB.includes(l))return Nr("source.connection.start","provider",o??"",VB,t,"invalid_source_provider");let c=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(c.failure)return c.failure;let u=Cse(o,s,a,t);if(u)return u;let d=Ft(t,["provider","source","mode","visibility","priceCents","license","provenanceIntent","discloseSource"]),p=k(t.skill);return p&&(d.requestedSkillSlug=p),await Oe("/api/v1/me/source-connections",d,t,n,"Source connection started.")}let i=O(e[1],`source connection ${r??""} requires a connection id.`);if(r==="status")return await me(`/api/v1/me/source-connections/${encodeURIComponent(i)}`,t,n,"Source connection loaded.",{authenticated:!0});if(r==="complete"){let o=Oie("source.connection.complete",t);return o||await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/complete`,Ft(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed.")}return r==="cancel"?await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/cancel`,{},t,n,"Source connection cancelled."):r==="revoke"?await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/revoke`,{},t,n,"Source connection revoked."):R(`Unknown source connection command "${r??""}".`,t.json)}function Cse(e,t,n,r){if(n){let i=uc(n);if(!i||!za.includes(i))return x({status:"error",reasonCode:"invalid_visibility",visibility:n,acceptedValues:za,nextAction:"source.connection.start",nextStep:"Use --visibility private, public, or unlisted."},`Invalid source connection visibility "${n}". Use one of: ${za.join(", ")}.`,r.json,"invalid_visibility")}if(!e||!t)return null;try{let i=rr(t);if((e==="github"||e==="gitlab")&&i.kind!==e)return fP(e,t,r);if(e==="domain"){let o=new URL(t);if(o.protocol!=="https:"||!o.hostname)return fP(e,t,r)}}catch{return fP(e,t,r)}return null}function fP(e,t,n){return x({status:"error",reasonCode:"invalid_source",provider:e,source:t,nextAction:"source.connection.start",nextStep:e==="github"?"Use a GitHub source such as https://github.com/OWNER/REPO or github:OWNER/REPO.":e==="gitlab"?"Use a GitLab source such as https://gitlab.com/GROUP/REPO or gitlab:GROUP/REPO.":"Use a valid source URL or provider-specific source."},`Invalid ${e} source "${t}".`,n.json,"invalid_source")}async function Ise(e,t,n){if(e[0]!=="request")return R(`Unknown approval command "${e[0]??""}".`,t.json);let r=e[1];if(r!=="status"&&r!=="complete")return R("approval request requires `status <approval-request-id>` or `complete <approval-request-id> --decision <approved|denied>`.",t.json);let i=O(e[2],`approval request ${r??""} requires an approval id.`);if(r==="status")return await me(`/api/v1/me/approvals/${encodeURIComponent(i)}`,t,n,"Approval status loaded.",{authenticated:!0});let o=O(t.decision,"approval request complete requires --decision."),s=Mn("approval.request.complete","decision",o,Sie,t,"invalid_decision");return s||await Oe(`/api/v1/me/approvals/${encodeURIComponent(i)}/complete`,ie({decision:o,evidence:ln(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed.")}async function Pse(e,t,n){let r=e[0]??"list";if(r==="list"){let o=await D(n,"/api/v1/me/workspaces",{headers:re(n.apiKey,n.authBlockedMessage)});return cn(o,Ase(o,n),"Available workspaces loaded.",t.json,n)}if(r==="current"){let o=await D(n,"/api/v1/me/working-mode",{headers:re(n.apiKey,n.authBlockedMessage)});return await ji(n,o),cn(o,Rse(o,n),"Selected workspace loaded.",t.json,n)}if(r==="select"||r==="use"){let o=O(e[1],"workspace select requires personal or a workspace id."),s=await D(n,"/api/v1/me/working-modes",{headers:re(n.apiKey,n.authBlockedMessage)}),a=(Array.isArray(s.modes)?s.modes:[]).filter(j),l=o.toLowerCase()==="personal",c=a.filter(m=>l?f(m,"type")==="personal"&&f(m,"modeId")==="personal":f(m,"type")==="enterprise_workspace"&&f(m,"workspaceId")===o);if(c.length===0)return x({status:"not_found_or_forbidden",reasonCode:"workspace_working_mode_not_found",...l?{selection:"personal"}:{workspaceId:o},nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list`, then select Personal or an exact workspace id shown there."},l?"Personal is not available for this account.":`Workspace ${o} was not found in your Enterprise workspace access.`,t.json,"workspace_working_mode_not_found");if(c.length>1)return x({status:"ambiguous_workspace",reasonCode:"workspace_working_mode_ambiguous",workspaceId:o,nextAction:"workspace.list",nextStep:"Workspace ids should be unique. Run `skills-layer workspace list` and use the exact workspace id shown there."},`Workspace ${o} matched more than one Enterprise workspace.`,t.json,"workspace_working_mode_ambiguous");let u=f(c[0],"modeId");if(!u)return x({status:"error",reasonCode:"workspace_working_mode_invalid",workspaceId:o,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` and retry with Personal or an exact selectable workspace id."},`Workspace ${o} is missing its selection identifier.`,t.json,"workspace_working_mode_invalid");let d=await D(n,"/api/v1/me/working-mode",{method:"PUT",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({modeId:u})});await ji(n,d);let p=f(c[0],"label");return A(d,l?"Selected workspace: Personal.":`Selected workspace: ${p?`${p} (${o})`:o}.`,t.json,n)}if(!["request","approve","reject","skills","guide"].includes(r))return R(`Unknown workspace command "${r}".`,t.json);let i=O(e[1],`workspace ${r} requires a workspace id.`);if(r==="request"||r==="approve"||r==="reject"){let o=O(e[2],`workspace ${r} requires a skill slug.`);try{if(r==="request")return await Oe(`/api/v1/workspaces/${encodeURIComponent(i)}/skill-requests`,{skillSlug:o,reason:k(t.reason)},t,n,"Workspace skill request captured.");if(r==="approve"){let s=await lU(n,`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/approve`,{},t);return fe(s)?s:A(s,"Workspace skill approval evaluated.",t.json,n)}return await Oe(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/${r}`,{},t,n,"Workspace skill rejected.")}catch(s){if(s instanceof Z&&(s.status===403||s.status===404))return r==="reject"&&kM(s)?vM(i,o,t):r==="approve"&&Ese(s)?$se(i,o,t,s):mP(i,t);throw s}}if(r==="skills")try{return await me(`/api/v1/workspaces/${encodeURIComponent(i)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0})}catch(o){if(o instanceof Z&&(o.status===403||o.status===404))return mP(i,t);throw o}if(r==="guide"){let o=O(e[2],"workspace guide requires a skill slug.");try{return await me(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}catch(s){if(s instanceof Z&&s.status===404)return kM(s)?vM(i,o,t):mP(i,t);throw s}}return R(`Unknown workspace command "${r}".`,t.json)}function Ase(e,t){let n=Pe(t),r=Array.isArray(e.results)?e.results.filter(j):[],i=[`${n.ok("OK")} Available workspaces loaded.`,"",n.section(`Available workspaces (${r.length+1})`),"1. Personal",` ${n.label("Type")}: Personal`];return r.forEach((o,s)=>{i.push(`${s+2}. ${f(o,"name")??"Unnamed workspace"}`),i.push(` ${n.label("ID")}: ${f(o,"workspaceId")??"unknown"}`),i.push(` ${n.label("Enterprise ID")}: ${f(o,"enterpriseId")??"unknown"}`),i.push(` ${n.label("Status")}: ${jt(f(o,"status")??"unknown")}`)}),i.push("",n.section("Next"),` ${n.arrow} skills-layer workspace select personal`,` ${n.arrow} skills-layer workspace select <workspace-id>`),i.join(`
|
|
2162
|
+
Next step: ${s}`}async function yse(e,t,n){let r=Qu("restore",t);if(r.failure)return r.failure;let i=await lt(n),o=O(e[0],"restore requires a skill slug."),s=i.installs[o];if(!s)return x({status:"missing_record",reasonCode:"restore_record_not_found",skillSlug:o,record:null,nextAction:"installed",nextStep:`Run \`skills-layer installed\` to see local records, \`skills-layer sync\` to refresh status, or \`skills-layer search ${o}\` if you want to find a catalog/source replacement.`},`No restorable local install record was found for ${o}. Run \`skills-layer installed\`, \`skills-layer sync\`, or \`skills-layer search ${o}\` next.`,t.json,"restore_record_not_found");if(s.removedReason==="refunded"||An(s).some(_=>_.record.removedReason==="refunded")){let _=!1;try{let C=await D(n,`/api/v1/me/entitlements?${new URLSearchParams({slugs:o})}`,{headers:re(n.apiKey,n.authBlockedMessage)});_=un(C.results).some(P=>P.skillSlug===o&&P.status==="active")}catch{}if(!_)return x({status:"blocked",reasonCode:"entitlement_revoked_refunded",skillSlug:o,nextStep:`Buy ${o} again before restoring it.`},"A refunded skill cannot be restored without active access.",t.json,"entitlement_revoked_refunded")}let a=qn(s,{scope:r.scope,agent:r.agent});if(a.length===0&&An(s).length>0)return x({status:"not_installed",reasonCode:"local_install_target_not_found",skillSlug:o,requestedScope:r.scope,requestedAgent:r.agent,nextAction:"installed",nextStep:"Run `skills-layer installed --json` and select one of the recorded quarantined targets."},`${o} has no restorable record for the requested local target.`,t.json,"local_install_target_not_found");if(a.length>1)return x({status:"target_selection_required",reasonCode:"local_install_target_selection_required",skillSlug:o,nextAction:"restore",nextStep:"Retry with --scope and --agent to restore one exact quarantined materialization."},`${o} has more than one local materialization. Select the exact target to restore.`,t.json,"local_install_target_selection_required");let l=a[0],c=l?gr(s,l):s,u=l?.lifecycle??null;if(!u)return x({status:"blocked",reasonCode:"exact_install_receipt_missing",skillSlug:o,nextAction:"install",nextStep:`Reinstall ${o} from the approved catalog; legacy records cannot authorize an exact-generation restore.`},`Skills Layer cannot restore ${o} because its exact-generation lifecycle record is missing or invalid.`,t.json,"exact_install_receipt_missing");if(u.state!=="quarantined"||!u.quarantine)return x({status:"blocked",reasonCode:"restore_not_quarantined",skillSlug:o,localLifecycle:u,nextAction:"installed",nextStep:"Only a physically quarantined exact generation can be restored."},`${o} does not have a quarantined exact generation to restore.`,t.json,"restore_not_quarantined");let d=new URLSearchParams({version:u.receipt.generation.semanticVersion,operation:"restore",generationId:u.receipt.generation.generationId}),p=f(c,"acquisitionMode")==="anonymous_public",m;try{m=await D(n,p?`/api/v1/skills/${encodeURIComponent(o)}/export${Qe(d)}`:`/api/v1/me/library/${encodeURIComponent(o)}/export${Qe(d)}`,{headers:p?{}:re(n.apiKey,n.authBlockedMessage)})}catch(_){if(_ instanceof Z)return Go(_,t.json);throw _}if(m.restoreAuthorization===void 0)return x({status:"blocked",reasonCode:"restore_authorization_missing",skillSlug:o,generation:u.receipt.generation,nextAction:"restore",nextStep:"Retry after the Skills Layer API returns a fresh restoreAuthorization bound to this exact generation."},`The backend did not authorize restoration of ${o}'s exact quarantined generation.`,t.json,"restore_authorization_missing");let h=fz(m.restoreAuthorization);if(!h||h.purpose!=="restore_fresh_approval"||!vse(h,u.receipt))return x({status:"blocked",reasonCode:"restore_authorization_invalid",skillSlug:o,generation:u.receipt.generation,nextAction:"restore",nextStep:"Do not restore. Refresh backend approval for this exact artifact generation."},`The backend returned an invalid or mismatched restore authorization for ${o}.`,t.json,"restore_authorization_invalid");let g=`restore_${Ge(16).toString("hex")}`,y=Wu({state:"restore_pending",operationId:g,receipt:u.receipt,quarantine:u.quarantine,backend:n});await Br(n,_=>{let C=_.installs[o],P=C&&l?Yt(C)[l.materializationId]:void 0,N=P?Jt(P):null;if(!C||!P||N?.operationId!==u.operationId||N.state!=="quarantined")throw new Error("Local install record changed before its exact restore reservation was created.");_.installs[o]=Fr({existing:C,skillSlug:o,materialization:{...P,localLifecycle:y,savedAt:n.now()},backend:n})});let v;try{await s2({quarantine:u.quarantine,authorizeRestore:async()=>h,finalizeRestore:async()=>{let _=!0;return await Br(n,C=>{let P=C.installs[o],N=P&&l?Yt(P)[l.materializationId]:void 0,T=N?Jt(N):null;if(!P||!N||!T||T.state!=="restore_pending"||T.operationId!==g){_=!1;return}let X=Wu({state:"active",operationId:g,receipt:u.receipt,backend:n});v={...N,status:"restored",localLifecycle:X,savedAt:n.now()},C.installs[o]=Fr({existing:P,skillSlug:o,materialization:v,backend:n})}),_?{status:"released",releaseId:`local_restore_${Ge(16).toString("hex")}`}:{status:"denied",reasonCode:"restore_reservation_lost"}}})}catch(_){return await Br(n,C=>{let P=C.installs[o],N=P&&l?Yt(P)[l.materializationId]:void 0,T=N?Jt(N):null;!P||!N||T?.operationId!==g||(C.installs[o]=Fr({existing:P,skillSlug:o,materialization:{...N,localLifecycle:u,savedAt:n.now()},backend:n}))}).catch(()=>{}),x({status:"blocked",reasonCode:"exact_generation_restore_failed",skillSlug:o,error:ve(_),nextAction:"restore",nextStep:"Keep the generation quarantined. Resolve local path, drift, or permission problems before retrying."},`Skills Layer could not atomically restore ${o}.`,t.json,"exact_generation_restore_failed")}if(!v)throw new Error(`Atomic restore for ${o} completed without committing its local lifecycle record.`);let b=Jt(v),w={status:"restored",skillSlug:o,record:v,localLifecycle:b};return t.json?R(w,`Restored ${o}.`,!0,n):{exitCode:0,stdout:mse(o,v,n),stderr:""}}function vse(e,t){return e.generation.skillSlug===t.generation.skillSlug&&e.generation.semanticVersion===t.generation.semanticVersion&&e.generation.generationId===t.generation.generationId&&e.archiveSha256===t.archiveSha256&&e.manifestSha256===t.manifestSha256}async function kse(e,t,n){let r=O(e[0],"check requires a skill slug.");return await me(`/api/v1/skills/${encodeURIComponent(r)}/trust`,t,n,"Install trust checked.",{authenticated:!!n.apiKey})}async function wse(e,t,n){let r=O(e[0]??t.source,"import requires a source."),i=Mn("import","visibility",t.visibility,za,t,"invalid_visibility");if(i)return i;let o=await Hu(r,n.cwd);if(o)return await bse(r,o,t,n);let s=_se(r,t);if(s)return s;let a=cA(r,t,n,n.apiKey?"authenticated":"unknown"),l=await D(n,a,{method:"POST",headers:SU(r,t,n,n.apiKey?"authenticated":"unknown"),body:JSON.stringify(ie({source:r,skillSlug:k(t.skill),visibility:k(t.visibility)??Ti(r,t,n)}))});return await Ve(n.paths.importsPath,{version:1,lastImport:l,savedAt:n.now()}),R(l,"Source import submitted.",t.json,n)}async function bse(e,t,n,r){let i=k(n.skill),o=aA(e,t,i);if(!r.apiKey)return x({status:"error",reasonCode:"local_import_sign_in_required",source:e,nextAction:"login",nextStep:`Run \`skills-layer login\`, then retry \`skills-layer import ${e}\` (the same flow as \`skills-layer creator submit ${e}\`).`},"Importing a local folder submits it through your creator account, so you must sign in first. Run `skills-layer login`, then retry. Nothing was uploaded.",n.json,"local_import_sign_in_required");let s=Ih(e,o,n);if(s)return s;let a=await ju({source:e,inspection:o,requestedSkillSlug:i,mode:"import",flags:n,backend:r});if(a.kind==="failure")return a.result;let c=lA(t.files).find(d=>d.skillSlug===a.skillSlug),u=c.relativeSkillRoot==="."?e:`${e.replace(/[\\/]+$/u,"")}/${c.relativeSkillRoot}`;return k(n.version)?await AP([u],{...n,source:void 0,path:void 0,skill:c.skillSlug},r,!1):x({status:"error",nextAction:"import",nextStep:"Pass --version <semver>, for example --version 1.0.0."},"A local import requires --version <semver>.",n.json,"version_required")}function _se(e,t){try{return rr(e).kind!=="local"?null:x({status:"error",reasonCode:"invalid_source",source:e,nextAction:"import",nextStep:zu(e)?"Check that the local path exists and contains SKILL.md, or pass a supported GitHub/GitLab/source URL.":"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or --help for import examples."},zu(e)?`Import source ${e} was not found or is not readable.`:`Import source "${e}" is not a supported source. Use a local path, GitHub/GitLab source, or URL.`,t.json,"invalid_source")}catch(n){return x({status:"error",reasonCode:"invalid_source",source:e,error:ve(n),nextAction:"import",nextStep:"Use an existing local path such as ./my-skill, a GitHub/GitLab source, or URL."},`Import source "${e}" is invalid. ${ve(n)}`,t.json,"invalid_source")}}function zu(e){return/^(?:\.{1,2}(?:[\\/]|$)|[\\/]|[A-Za-z]:[\\/])/u.test(e)}function $U(e,t,n,r){let i=Tt(r.cwd,t);return x({status:"error",reasonCode:"source_path_not_found",path:i,nextAction:e,nextStep:`Check that ${t} exists and contains a readable SKILL.md, then retry.`},`${e} source path does not exist: ${i}`,n.json,"source_path_not_found")}async function Sse(e,t,n){let r=e[0];if(r==="reference"&&e[1]==="resolve"){let i=O(e[2],"source reference resolve requires a reference."),o=await D(n,`/api/v1/source-references/resolve?reference=${encodeURIComponent(i)}`);return o.status==="not_found"?x({...o,status:"not_found",reasonCode:"source_reference_not_found",reference:i,nextAction:"source.connection.start",nextStep:"Start or complete the source connection before resolving this reference."},`Source reference ${i} was not found.`,t.json,"source_reference_not_found"):R(o,"Source reference resolved.",t.json,n)}return r==="connection"?await xse(e.slice(1),t,n):E(`Unknown source command "${e.join(" ")}".`,t.json)}async function xse(e,t,n){let r=e[0];if(r==="start"){let o=k(t.provider),s=k(t.source),a=k(t.visibility),l=o?.replace(/-/gu,"_");if(l&&!VB.includes(l))return Nr("source.connection.start","provider",o??"",VB,t,"invalid_source_provider");let c=Ni(t.priceCents,"--price-cents","priceCents","invalid_price_cents",t,{minimum:0});if(c.failure)return c.failure;let u=Cse(o,s,a,t);if(u)return u;let d=Ft(t,["provider","source","mode","visibility","priceCents","license","provenanceIntent","discloseSource"]),p=k(t.skill);return p&&(d.requestedSkillSlug=p),await Oe("/api/v1/me/source-connections",d,t,n,"Source connection started.")}let i=O(e[1],`source connection ${r??""} requires a connection id.`);if(r==="status")return await me(`/api/v1/me/source-connections/${encodeURIComponent(i)}`,t,n,"Source connection loaded.",{authenticated:!0});if(r==="complete"){let o=Oie("source.connection.complete",t);return o||await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/complete`,Ft(t,["providerOwnerId","providerRepoId","providerProjectId","providerInstallationId","commitSha"]),t,n,"Source connection completed.")}return r==="cancel"?await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/cancel`,{},t,n,"Source connection cancelled."):r==="revoke"?await Oe(`/api/v1/me/source-connections/${encodeURIComponent(i)}/revoke`,{},t,n,"Source connection revoked."):E(`Unknown source connection command "${r??""}".`,t.json)}function Cse(e,t,n,r){if(n){let i=uc(n);if(!i||!za.includes(i))return x({status:"error",reasonCode:"invalid_visibility",visibility:n,acceptedValues:za,nextAction:"source.connection.start",nextStep:"Use --visibility private, public, or unlisted."},`Invalid source connection visibility "${n}". Use one of: ${za.join(", ")}.`,r.json,"invalid_visibility")}if(!e||!t)return null;try{let i=rr(t);if((e==="github"||e==="gitlab")&&i.kind!==e)return fP(e,t,r);if(e==="domain"){let o=new URL(t);if(o.protocol!=="https:"||!o.hostname)return fP(e,t,r)}}catch{return fP(e,t,r)}return null}function fP(e,t,n){return x({status:"error",reasonCode:"invalid_source",provider:e,source:t,nextAction:"source.connection.start",nextStep:e==="github"?"Use a GitHub source such as https://github.com/OWNER/REPO or github:OWNER/REPO.":e==="gitlab"?"Use a GitLab source such as https://gitlab.com/GROUP/REPO or gitlab:GROUP/REPO.":"Use a valid source URL or provider-specific source."},`Invalid ${e} source "${t}".`,n.json,"invalid_source")}async function Ise(e,t,n){if(e[0]!=="request")return E(`Unknown approval command "${e[0]??""}".`,t.json);let r=e[1];if(r!=="status"&&r!=="complete")return E("approval request requires `status <approval-request-id>` or `complete <approval-request-id> --decision <approved|denied>`.",t.json);let i=O(e[2],`approval request ${r??""} requires an approval id.`);if(r==="status")return await me(`/api/v1/me/approvals/${encodeURIComponent(i)}`,t,n,"Approval status loaded.",{authenticated:!0});let o=O(t.decision,"approval request complete requires --decision."),s=Mn("approval.request.complete","decision",o,Sie,t,"invalid_decision");return s||await Oe(`/api/v1/me/approvals/${encodeURIComponent(i)}/complete`,ie({decision:o,evidence:ln(t.decisionEvidenceJson,"decision-evidence-json")}),t,n,"Approval completed.")}async function Pse(e,t,n){let r=e[0]??"list";if(r==="list"){let o=await D(n,"/api/v1/me/workspaces",{headers:re(n.apiKey,n.authBlockedMessage)});return cn(o,Ase(o,n),"Available workspaces loaded.",t.json,n)}if(r==="current"){let o=await D(n,"/api/v1/me/working-mode",{headers:re(n.apiKey,n.authBlockedMessage)});return await ji(n,o),cn(o,Rse(o,n),"Selected workspace loaded.",t.json,n)}if(r==="select"||r==="use"){let o=O(e[1],"workspace select requires personal or a workspace id."),s=await D(n,"/api/v1/me/working-modes",{headers:re(n.apiKey,n.authBlockedMessage)}),a=(Array.isArray(s.modes)?s.modes:[]).filter(j),l=o.toLowerCase()==="personal",c=a.filter(m=>l?f(m,"type")==="personal"&&f(m,"modeId")==="personal":f(m,"type")==="enterprise_workspace"&&f(m,"workspaceId")===o);if(c.length===0)return x({status:"not_found_or_forbidden",reasonCode:"workspace_working_mode_not_found",...l?{selection:"personal"}:{workspaceId:o},nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list`, then select Personal or an exact workspace id shown there."},l?"Personal is not available for this account.":`Workspace ${o} was not found in your Enterprise workspace access.`,t.json,"workspace_working_mode_not_found");if(c.length>1)return x({status:"ambiguous_workspace",reasonCode:"workspace_working_mode_ambiguous",workspaceId:o,nextAction:"workspace.list",nextStep:"Workspace ids should be unique. Run `skills-layer workspace list` and use the exact workspace id shown there."},`Workspace ${o} matched more than one Enterprise workspace.`,t.json,"workspace_working_mode_ambiguous");let u=f(c[0],"modeId");if(!u)return x({status:"error",reasonCode:"workspace_working_mode_invalid",workspaceId:o,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` and retry with Personal or an exact selectable workspace id."},`Workspace ${o} is missing its selection identifier.`,t.json,"workspace_working_mode_invalid");let d=await D(n,"/api/v1/me/working-mode",{method:"PUT",headers:V(n.apiKey,n.authBlockedMessage),body:JSON.stringify({modeId:u})});await ji(n,d);let p=f(c[0],"label");return R(d,l?"Selected workspace: Personal.":`Selected workspace: ${p?`${p} (${o})`:o}.`,t.json,n)}if(!["request","approve","reject","skills","guide"].includes(r))return E(`Unknown workspace command "${r}".`,t.json);let i=O(e[1],`workspace ${r} requires a workspace id.`);if(r==="request"||r==="approve"||r==="reject"){let o=O(e[2],`workspace ${r} requires a skill slug.`);try{if(r==="request")return await Oe(`/api/v1/workspaces/${encodeURIComponent(i)}/skill-requests`,{skillSlug:o,reason:k(t.reason)},t,n,"Workspace skill request captured.");if(r==="approve"){let s=await lU(n,`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/approve`,{},t);return fe(s)?s:R(s,"Workspace skill approval evaluated.",t.json,n)}return await Oe(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/${r}`,{},t,n,"Workspace skill rejected.")}catch(s){if(s instanceof Z&&(s.status===403||s.status===404))return r==="reject"&&kM(s)?vM(i,o,t):r==="approve"&&Ese(s)?$se(i,o,t,s):mP(i,t);throw s}}if(r==="skills")try{return await me(`/api/v1/workspaces/${encodeURIComponent(i)}/skills`,t,n,"Workspace skills loaded.",{authenticated:!0})}catch(o){if(o instanceof Z&&(o.status===403||o.status===404))return mP(i,t);throw o}if(r==="guide"){let o=O(e[2],"workspace guide requires a skill slug.");try{return await me(`/api/v1/workspaces/${encodeURIComponent(i)}/skills/${encodeURIComponent(o)}/install-guide`,t,n,"Workspace install guide loaded.",{authenticated:!0})}catch(s){if(s instanceof Z&&s.status===404)return kM(s)?vM(i,o,t):mP(i,t);throw s}}return E(`Unknown workspace command "${r}".`,t.json)}function Ase(e,t){let n=Pe(t),r=Array.isArray(e.results)?e.results.filter(j):[],i=[`${n.ok("OK")} Available workspaces loaded.`,"",n.section(`Available workspaces (${r.length+1})`),"1. Personal",` ${n.label("Type")}: Personal`];return r.forEach((o,s)=>{i.push(`${s+2}. ${f(o,"name")??"Unnamed workspace"}`),i.push(` ${n.label("ID")}: ${f(o,"workspaceId")??"unknown"}`),i.push(` ${n.label("Enterprise ID")}: ${f(o,"enterpriseId")??"unknown"}`),i.push(` ${n.label("Status")}: ${jt(f(o,"status")??"unknown")}`)}),i.push("",n.section("Next"),` ${n.arrow} skills-layer workspace select personal`,` ${n.arrow} skills-layer workspace select <workspace-id>`),i.join(`
|
|
2163
2163
|
`)}function Rse(e,t){let n=Pe(t),r=j(e.mode)?e.mode:void 0,i=r?f(r,"type"):void 0,o=f(e,"selectedModeId"),s=[`${n.ok("OK")} Selected workspace loaded.`,""];return i==="personal"||o==="personal"?(s.push(n.section("Selected workspace: Personal")),s.join(`
|
|
2164
2164
|
`)):r?(s.push(n.section(`Selected workspace: ${f(r,"label")??f(r,"name")??"Enterprise workspace"}`)),s.push(` ${n.label("Workspace ID")}: ${f(r,"workspaceId")??"unknown"}`),s.push(` ${n.label("Enterprise ID")}: ${f(r,"enterpriseId")??"unknown"}`),s.join(`
|
|
2165
2165
|
`)):(s.push(n.section("Selected workspace"),` ${n.muted("No workspace is currently selected.")}`),s.join(`
|
|
2166
|
-
`))}function mP(e,t){return x({status:"not_found_or_forbidden",reasonCode:"workspace_not_found_or_forbidden",workspaceId:e,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` to find a workspace you can access, then retry with that workspace id."},`Workspace ${e} was not found or you do not have access. Run \`skills-layer workspace list\` to inspect accessible workspaces.`,t.json,"workspace_not_found_or_forbidden")}function vM(e,t,n){let r={status:"approval_not_found",reasonCode:"workspace_skill_approval_not_found",workspaceId:e,skillSlug:t,nextAction:"workspace.approve",nextStep:`Run \`skills-layer workspace approve ${e} ${t}\` first, then run \`skills-layer workspace guide ${e} ${t}\` after the approval exists.`};return x(r,`Workspace approval not found for ${t}. Run \`skills-layer workspace approve ${e} ${t}\` first.`,n.json,"workspace_skill_approval_not_found")}function kM(e){let t=e.details??{},n=f(t,"reasonCode")?.toLowerCase(),r=`${f(t,"error")??e.message}`.toLowerCase();return n==="workspace_skill_approval_not_found"||r.includes("workspace")&&r.includes("approval")&&r.includes("not found")}function Ese(e){let t=e.details??{},n=f(t,"reasonCode")?.toLowerCase(),r=`${f(t,"error")??e.message}`.toLowerCase();return n==="skill_not_found"||r.includes("skill")&&r.includes("not found")}function $se(e,t,n,r){let i=r.details??{},o={status:"not_found",reasonCode:"skill_not_found",workspaceId:e,skillSlug:t,nextAction:"search",nextStep:f(i,"nextStep")??`Run \`skills-layer search ${t}\` to find the public skill before approving it for workspace ${e}.`};return x(o,`Skill ${t} was not found. Run \`skills-layer search ${t}\` before approving it for the workspace.`,n.json,"skill_not_found")}async function Dse(e,t,n){let r=O(e[0],"buy requires a skill slug."),i=Bie(t);if(i.failure)return i.failure;if(k(t.workspace))return x({reasonCode:"invalid_input"},"buy does not support --workspace; use skills-layer enterprise skill buy <enterprise-id> <skill-slug>.",t.json,"invalid_input");let o=await nA(n,{skillSlug:r,paymentMethod:i.value},t,"/api/v1/buy");if(fe(o))return o;if(o.status==="already_owned")return A(o,`You already own ${r}. Run \`skills-layer install ${r}\` to install or update it.`,t.json,n);if(t.noOpen&&o.status==="checkout_required"&&typeof o.checkoutUrl=="string")return A({...o,nextAction:"open_checkout_url",nextStep:`Open ${o.checkoutUrl} to complete payment, then run skills-layer install ${r}.`},`Payment is required for ${r}.`,t.json,n);if(t.json||t.noOpen||o.status!=="checkout_required"||typeof o.checkoutUrl!="string"||typeof o.purchaseId!="string")return A(o,`Purchase flow started for ${r}.`,t.json,n);n.emitInfo(`Opening checkout for ${r}. Complete the payment in your browser, then come back here.`),await n.openUrl(o.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${o.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let a=await Xae(o.purchaseId,n);return fe(a)?a:a.status!=="succeeded"?A({...o,purchaseStatus:a.status},`Checkout is still ${a.status} for ${r}. You can rerun install after payment reconciliation completes.`,t.json,n):(n.emitInfo("Payment confirmed. Continuing with install."),await Wa([r],t,n,{origin:"post_purchase",fallbackPolicy:"account_required"}))}async function Tse(e,t,n){let r=e[0]??"list";if(r==="list")return await me("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(r==="spending")return await me("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let i=O(e[1],`purchases ${r} requires a purchase id.`);if(r==="status")return await me(`/api/v1/purchases/${encodeURIComponent(i)}`,t,n,"Purchase status loaded.",{authenticated:!0});if(r==="invoice")return await me(`/api/v1/purchases/${encodeURIComponent(i)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0});if(r==="refund-quote"){let o=await D(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund-quote`,{headers:re(n.apiKey,n.authBlockedMessage)}),s=j(o.quote)?o.quote:o,a=l=>typeof l=="number"?`USD ${(l/100).toFixed(2)}`:"unavailable";return A(o,`Refundable: ${a(s.refundableAmountCents)}. Non-refundable: ${a(s.nonRefundableAmountCents)}. Refund window ends: ${String(s.refundWindowEndsAt??"unavailable")}.`,t.json,n)}if(r==="refund"){let o=await D(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund`,{method:"POST",headers:V(n.apiKey),body:JSON.stringify(Ft(t,["reason"]))}),s=o.status==="refunded"?await ed(t,n):{warnings:[]};return A({...o,warnings:[...s.warnings,"Manually copied folders cannot be removed automatically; other machines check on sync, installed or update."]},o.status==="refunded"?"Refund completed.":"Refund requested.",t.json,n)}return R(`Unknown purchases command "${r}".`,t.json)}function DU(e,t,n,r){let i=typeof e.amountCents=="number"?` (USD ${(e.amountCents/100).toFixed(2)})`:"";return A({...e,status:"action_required",reasonCode:"purchase_required",nextAction:"buy",nextStep:`skills-layer buy ${t}`},`Purchase required${i}. Run \`skills-layer buy ${t}\`.`,n.json,r)}async function Ose(e,t,n){let r=e[0];if(r==="search"){let i=new URLSearchParams;return Ke(i,"query",e.slice(1).join(" ").trim()||k(t.query)),Ke(i,"limit",k(t.limit)),await me(`/api/v1/me/search${Qe(i)}`,t,n,"Authenticated library search complete.",{authenticated:!0})}if(r==="add"){let i=O(e[1],"library add requires a skill slug."),o=await nA(n,{skillSlug:i},t);return fe(o)?o:o.status==="purchase_required"?DU(o,i,t,n):A(o,"Skill added to library.",t.json,n)}return R(`Unknown library command "${r}".`,t.json)}async function Lse(e,t,n){let r=O(e[0],"export requires a skill slug.");if(t.showUrl&&k(t.output))return x({status:"error",reasonCode:"conflicting_export_output",nextAction:"export",nextStep:"Use either --show-url to inspect the signed URL or --output <file> to download the bundle, not both."},"export cannot use --show-url and --output together.",t.json,"conflicting_export_output");let i=new URLSearchParams,o=k(t.version);if(o&&!Th(o))return eA("export",o,t);Ke(i,"version",o);let s=await D(n,`/api/v1/me/library/${encodeURIComponent(r)}/export${Qe(i)}`,{headers:re(n.apiKey,n.authBlockedMessage)}),a=k(t.output);if(a){let l=await xh({backend:n,exportResult:s,flags:t,skillSlug:r});if(fe(l))return l;let c=Tt(n.cwd,a);await IA(c,l.bytes);let u={...s};return delete u.downloadUrl,A({...u,archiveSha256:l.archiveSha256,archiveSha256Meaning:"artifact_v1_exact_zip_bytes_sha256",downloadedArchiveSha256:l.archiveBytesSha256,downloadedFileSha256:l.archiveBytesSha256,archiveHashFormat:l.archiveHashFormat,generationId:l.envelope.generation.generationId,manifestSha256:l.envelope.manifest.sha256,outputPath:c,downloaded:!0},`Exported ${r} to ${c}. Downloaded file SHA-256: ${l.archiveBytesSha256}.`,t.json,n)}return A(s,a?`Exported ${r} to ${a}.`:"Export prepared.",t.json,n)}async function wM(e,t,n,r){if(e==="show"){let a=t[0]?.trim(),l=a?`?skillSlug=${encodeURIComponent(a)}`:"";return await me(`/api/v1/me/library/reviews${l}`,n,r,"Reviews loaded.",{authenticated:!0})}let i=O(t[0],"add-review requires a skill slug."),o=O(n.rating,"add-review requires --rating.");if(!/^[1-5]$/u.test(o))return x({status:"error",reasonCode:"invalid_rating",rating:o,acceptedValues:["1","2","3","4","5"],nextAction:"add-review",nextStep:"Use --rating with a whole number from 1 to 5."},`Invalid review rating "${o}". Use a whole number from 1 to 5.`,n.json,"invalid_rating");let s=Ft(n,["rating","feedback"]);if(typeof n.evalSummary=="string"){let a=await ke(qo(r.cwd,n.evalSummary));if(a===null)return x({status:"error",reasonCode:"invalid_eval_summary_file",path:n.evalSummary,nextAction:"add-review",nextStep:"Pass --eval-summary with a readable JSON redacted eval summary envelope."},`Could not read eval summary JSON from ${n.evalSummary}.`,n.json,"invalid_eval_summary_file");s.evalSummary=a}return await Oe(`/api/v1/me/library/${encodeURIComponent(i)}/review`,s,n,r,"Review added.")}async function bM(e,t,n,r){let i=O(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);if(e==="show")return await me(`/api/v1/me/library/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});O(n.message,"add-issue requires --message.");let o=Mn("add-issue","issueType",n.issueType,_ie,n,"invalid_issue_type","issue-type");return o||await Oe(`/api/v1/me/library/${encodeURIComponent(i)}/report-issue`,Ft(n,["issueType","message"]),n,r,"Issue reported.")}async function jse(e,t,n){let r=e[0];if(r==="hook"){let i=e[1];if(i==="install")return await LU(t,n);if(i==="status")return await Hse(t,n);if(i==="run"){let o=await Zse(t,n),s=k(t.agent);if(s&&vr(s)){let a=ls(n.env);await by({agentId:s,associationState:a?await Fse(s,t,n):"unreadable",activationEvent:a?await Mse(s,n):!1,delegatedExecution:o[TU]===!0,env:n.env,rawPayloadBase64:Re(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64),result:o})}return o}return R(`Unknown guardian hook command "${i??""}".`,t.json)}if(r==="session"){let i=e[1];return i==="bind"?await Kse(e.slice(2),t,n):R(`Unknown guardian session command "${i??""}".`,t.json)}if(r==="enable")return e[1]||t.skill?await gP("enforce",e,t,n):R("guardian enable requires a skill slug.",t.json);if(r==="disable")return await gP("disabled",e,t,n);if(r==="enable-warnings-only")return await gP("warning_only",e,t,n);if(r==="status")return await zse(e,t,n);if(r==="launch")return await Wse(e.slice(1),t,n);if(r==="exec")try{let i=await Use(e,t,n);return await _M(i,e,t,n),i}catch(i){throw await _M({exitCode:1,stdout:"",stderr:ve(i)},e,t,n),i}if(r==="check"){let i=O(e[1]??t.skill,"guardian check requires a skill slug.");if((await ed({...t,dryRun:!0},n,i)).revokedSlugs.includes(i))return A({status:"blocked",decision:"block",reasonCode:"entitlement_revoked_refunded",skillSlug:i,nextStep:`Run skills-layer remove ${i}, or buy it again.`},"This skill was refunded; execution is blocked.",t.json,n);let s=LM(t,"check");if(t.grantJson.length>0)return x({status:"error",reasonCode:"caller_supplied_authorization_grants_rejected",nextAction:"guardian.approval.prepare",nextStep:"Use an authenticated one-action approval or `skills-layer guardian exec` for shell execution."},"Guardian enforcement does not accept caller-authored authorization grants.",t.json,"caller_supplied_authorization_grants_rejected");let a=xce(t.cloudTrustLedger);if(a.status==="invalid")return R(a.message,t.json);let l=UP(t.telemetryMode,a.policy==="off"?"local_only":"cloud_managed");if(l.status==="invalid")return R(l.message,t.json);let c=await KU({skillSlug:i,version:k(t.version),action:s,flags:t,backend:n,telemetryMode:l.mode});if(c.status!=="ok")return c.result;let u=c.context.installedPath,d=k(t.version)??c.context.version,p=ie({skillSlug:i,version:d,action:s,path:u,guardianPreference:await rd(n,i),unmanagedPolicy:c.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:l.mode,localPreflight:qu(c.context)}),m=await D(n,"/api/v1/guardian/enforce",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(p)});return await Ga(n,{skillSlug:i,version:d,action:s,decisionStatus:qP(m),reasonCode:Ah(m),telemetryMode:l.mode,path:u,authority:m}),A({...m,localPreflight:qu(c.context)},"Guardian check complete.",t.json,n)}if(r==="incident"){let i=O(e[1]??t.skill,"guardian incident requires a skill slug."),o=O(t.version,"guardian incident requires --version."),s=UP(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return R(s.message,t.json);let a=k(t.path);if(a&&!await pr(Tt(n.cwd,a)))return x({status:"error",reasonCode:"invalid_incident_path",path:a,nextAction:"guardian.incident",nextStep:"Use --path with an installed skill directory, or omit --path so Skills Layer resolves the local install record."},`Guardian incident path does not exist: ${a}`,t.json,"invalid_incident_path");let l=a??(await WU({skillSlug:i,flags:t,backend:n})).installedPath,c=LM(t,"incident"),u=ln(t.evidenceJson,"evidence-json"),d=s.mode==="cloud_managed"&&!n.apiKey?"local_only":s.mode,p=n.now(),m=ie({skillSlug:i,version:o,action:c,evidence:u,path:l,telemetryMode:d,incident:!0,reason:k(t.reason),generatedAt:p,...d==="cloud_managed"?{incidentIdempotencyKey:sle()}:{}});if(d==="local_only"){if(!l)return R("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let v=await $M({backend:n,skillSlug:i,version:o,installedPath:l,action:c,reason:k(t.reason)??"Guardian local-only incident"});if(f(v,"status")!=="quarantined"){let w=f(v,"reasonCode")??"guardian_exact_quarantine_failed";return x(v,`Guardian could not physically quarantine the exact installed generation for ${i}.`,t.json,w)}await Ga(n,{skillSlug:i,version:o,action:c,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:d,path:l});let b=DM(n,i);return await BM(b,JSON.stringify({request:m,response:null,localResponse:v,savedAt:n.now()},null,2)),A({status:"written",skillSlug:i,version:o,telemetryMode:d,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:v,incidentStatePath:b,incidentPath:v.incidentPath},n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence.",t.json,n)}let h=await ale(n,m),g=l?await $M({backend:n,skillSlug:i,version:o,installedPath:l,action:c,reason:k(t.reason)??"Guardian Cloud-managed incident"}):null;if(g&&f(g,"status")!=="quarantined"){let v=f(g,"reasonCode")??"guardian_exact_quarantine_failed";return x({...g,cloudResponse:h},`Guardian recorded the Cloud incident but could not physically quarantine the exact local generation for ${i}.`,t.json,v)}await Mo(n.paths.incidentsDir,{recursive:!0});let y=DM(n,i);return await BM(y,JSON.stringify({request:m,response:h,localResponse:g,savedAt:n.now()},null,2)),await Ga(n,{skillSlug:i,version:o,action:c,decisionStatus:qP(h),reasonCode:Ah(h),telemetryMode:s.mode,path:l,authority:h}),A({...h,telemetryMode:s.mode,localResponse:g,incidentPath:y},"Guardian incident recorded.",t.json,n)}return R(`Unknown guardian command "${r??""}".`,t.json)}var TU=Symbol("guardian-delegated-execution");async function _M(e,t,n,r){if(!ls(r.env))return;let i=r.env.SKILLS_LAYER_GUARDIAN_CANARY_AGENT_ID,o=r.env.SKILLS_LAYER_GUARDIAN_CANARY_SCOPE;if(!i||!vr(i)||o!=="project"&&o!=="global")return;let s=k(n.skill)??t[1];s&&await by({agentId:i,associationState:await Nse(i,o,s,r),activationEvent:!1,env:r.env,rawPayloadBase64:Buffer.from(JSON.stringify({positionals:t,json:n.json})).toString("base64url"),reportingSource:"guarded_execution",result:e})}async function Nse(e,t,n,r){let i=await vE({agentId:e,scope:t,skillSlug:n,env:r.env});if(!i)return"unreadable";try{let o=await Vo(r,t),s=o.associations[i.associationKey];if(!s||s.agentId!==e||s.scope!==t||s.skillSlug!==n)return"missing";let a=pl(o,{agentId:e,sessionId:s.sessionId,asOf:r.now()});return a.associations.some(c=>tt(c)===i.associationKey)?a.status==="active"||a.status==="active_authority_stale"?"active":a.status==="terminal"?"terminal":a.status==="ambiguous"?"ambiguous":"missing":"missing"}catch{return"unreadable"}}async function Fse(e,t,n){let r=Xa(k(t.scope));return r.status==="invalid"?"unreadable":await Bse(e,r.scope,n)}async function Bse(e,t,n){let r=Re(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!r)return"unreadable";let i;try{i=JSON.parse(Buffer.from(r,"base64url").toString("utf8"))}catch{return"unreadable"}let o=hd(e,i)?.sessionId??NU(e,i);if(!o)return"unreadable";try{let s=await Vo(n,t),a=pl(s,{agentId:e,sessionId:o,asOf:n.now()});return a.status==="active"||a.status==="active_authority_stale"?"active":a.status==="unrelated"||a.status==="expected_missing_authority"?"missing":a.status}catch{return"unreadable"}}async function Mse(e,t){let n=Re(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!n)return!1;try{let r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));return hd(e,r)!==null}catch{return!1}}async function Use(e,t,n){let r=k(t.skill),i=O(r??e[1],"guardian exec requires a skill slug."),o=r?e.slice(1):e.slice(2);if(o.length===0)return R("guardian exec requires a command after --.",t.json);if(t.actionJson!==void 0)return x({status:"error",reasonCode:"caller_supplied_execution_action_rejected",nextAction:"guardian.execution.prepare",nextStep:"Guardian derives the canonical shell action from the exact command and execution plan."},"Guardian guarded execution does not accept a caller-authored action.",t.json,"caller_supplied_execution_action_rejected");if(t.grantJson.length>0)return x({status:"error",reasonCode:"caller_supplied_authorization_grants_rejected",nextAction:"guardian.execution.prepare",nextStep:"Use the authenticated atomic Guardian execution prepare flow."},"Guardian guarded execution does not accept caller-authored authorization grants.",t.json,"caller_supplied_authorization_grants_rejected");let s=UP(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return R(s.message,t.json);let a=AM(o),l=await KU({skillSlug:i,version:k(t.version),action:a,flags:t,backend:n,telemetryMode:s.mode});if(l.status!=="ok")return l.result;let c=l.context.installedPath,u=k(t.version)??l.context.version;if(!u)return x({status:"blocked",reasonCode:"guardian_exact_version_required",skillSlug:i,nextStep:"Install the skill through Skills Layer or pass its exact --version before guarded execution."},"Guardian guarded execution requires an exact installed skill version.",t.json,"guardian_exact_version_required");let d=await wae({commandArgs:o,skillSlug:i,version:u,flags:t,backend:n,localContext:l.context});if(d.status==="blocked")return d.result;let p=AM(o,d.request),m=await D(n,"/api/v1/guardian/execution/prepare",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({request:d.request,...t.dryRun?{dryRun:!0}:{}})}),h=typeof f(m,"token")=="string"&&L(m,"plan")!==void 0&&L(m,"binding")!==void 0;if(!kae(m)&&!h){let C=Ah(m);return await Ga(n,{skillSlug:i,version:u,action:p,decisionStatus:"blocked",reasonCode:C,telemetryMode:s.mode,path:c,authority:m}),x({...m,status:"blocked",reasonCode:C,skillSlug:i},"Guardian blocked guarded execution.",t.json,C)}if(await Ga(n,{skillSlug:i,version:u,action:p,decisionStatus:"allowed",reasonCode:"within_contract",telemetryMode:s.mode,path:c,authority:m}),t.dryRun)return A({status:"allowed",skillSlug:i,guardian:m,localPreflight:qu(l.context),command:{executable:ot(d.request.executableRealPath),executableSha256:d.request.executableSha256,argvSha256:YU(d.request.argv),cwdRealPath:d.request.cwdRealPath,executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let g=m,y=f(g,"token"),v=L(g,"plan"),b=L(g,"binding");if(!y||!v||!b)return x({status:"blocked",reasonCode:"guardian_grant_response_invalid",skillSlug:i},"Guardian returned an invalid execution grant.",t.json,"guardian_grant_response_invalid");await D(n,"/api/v1/guardian/execution-grants/consume",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({token:y,plan:v,binding:b})});let w;try{w=await O2({plan:v,ambientEnvironment:n.env,approvedSecrets:d.approvedSecrets})}catch(C){let P=C instanceof $e?C.reasonCode:"guardian_process_failed";return x({status:"blocked",reasonCode:P,skillSlug:i,planHash:b.planHash},"Guardian refused the contained process launch.",t.json,P)}let _={executable:ot(v.executableRealPath),argsCount:v.argv.length,exitCode:w.exitCode??1,reason:w.reason,signal:w.signal,stdout:w.stdout,stderr:w.stderr,outputTruncated:w.outputTruncated,planHash:w.planHash};return{exitCode:_.exitCode,stdout:t.json?JSON.stringify({status:_.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:i,guardian:m,localPreflight:qu(l.context),command:_},warnings:[],links:[],reasonCode:_.exitCode===0?null:"command_failed",handoff:null},null,2):Rae(_),stderr:_.stderr}}async function gP(e,t,n,r){let i=O(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),o=await D(r,"/api/v1/guardian/mode",{method:"POST",headers:V(r.apiKey),body:JSON.stringify({skillSlug:i,requestedPreference:e,source:"public-cli"})});if(o.preferenceAccepted===!0){if(f(o,"effectiveMode")==="enforce"){let s=(await Bi(r,i)).installs[i],a=An(s).filter(u=>u.lifecycle?.state==="active"||u.lifecycle?.state==="pending_activation"),l=et(r.env,r.platform,r.cwd),c=new Set;for(let u of a){let d=f(u.record,"scope"),p=mr(u.record);if(d!=="project"&&d!=="global"||p.length===0)return x({status:"blocked",reasonCode:"guardian_install_target_unavailable",skillSlug:i,materializationId:u.materializationId,scope:d,targetAgents:p,nextAction:"install",nextStep:"Reinstall the exact skill for a supported agent and scope before enabling enforced Guardian."},"Guardian enforce mode could not identify every supported local activation target.",n.json,"guardian_install_target_unavailable");for(let m of p){let h=l.find(v=>v.id===m);if(!h)return x({status:"blocked",reasonCode:"guardian_install_target_unavailable",skillSlug:i,materializationId:u.materializationId,agent:m,scope:d,nextAction:"install",nextStep:"Reinstall the exact skill for a supported agent and scope before enabling enforced Guardian."},"Guardian enforce mode found an unsupported local activation target.",n.json,"guardian_install_target_unavailable");let g=`${d}:${h.id}`;if(c.has(g))continue;c.add(g);let y=await Ya({backend:r,skillSlug:i,agentId:h.id,scope:d,flags:n,enforceRequired:!0});if(y)return y}}}await Eae(r,i,o)}return A(o,o.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,r)}async function zse(e,t,n){let r=k(t.skill)??k(e[1]),i;try{i=await OU(n,r)}catch(m){i={status:"unavailable",skillSlug:r,policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ve(m),nextAction:"guardian.status",nextStep:"Cloud Guardian policy could not be loaded. Local hook and preference posture are still shown below."}}let o=await zn(n),s=r?await $ae(n,r):void 0,a=f(i,"status")==="unavailable",l=f(o,"enforcementLayer")??"not_installed",d=l!=="not_installed"&&o.strictPreActionBlocking===!0?{status:"strict_installed",reasonCode:"guardian_hook_strict",enforcementLayer:l,strictPreActionBlocking:!0,nextAction:"guardian.check",nextStep:"Cloud Guardian policy is enforced when checked, and the local host hook can block supported risky actions before execution."}:l==="native_hook_candidate"?{status:"candidate_installed",reasonCode:"guardian_hook_candidate",enforcementLayer:l,strictPreActionBlocking:!1,nextAction:"guardian.hook.status",nextStep:"A Guardian candidate hook is installed, but strict pre-action blocking is not verified. Run `skills-layer guardian hook status --scope project` to inspect the current binding."}:{status:"not_installed",reasonCode:"guardian_hook_not_installed",enforcementLayer:"not_installed",strictPreActionBlocking:!1,nextAction:"guardian.hook.install",nextStep:"Cloud Guardian policy is enforced when checked, but local pre-action blocking is not installed for this host. Run `skills-layer guardian hook install --agent codex --scope global` or `skills-layer setup`."},p=await qse({backend:n,skillSlug:r,policy:i,hook:o,localPreference:s});return A(ie({status:a?"degraded":"ok",skillSlug:f(i,"skillSlug")??r,policy:i,localPreference:s,hook:o,cloudPolicy:{status:f(i,"effectiveMode")??f(i,"status")??"unknown",reasonCode:f(i,"reasonCode"),enforcementBoundary:"cloud_policy_when_checked",nextAction:f(i,"nextAction"),nextStep:f(i,"nextStep")},localEnforcement:d,measuredProtection:p,nextAction:f(d,"nextAction"),nextStep:f(d,"nextStep")}),a?"Guardian status loaded with limited Cloud policy data.":"Guardian status loaded.",t.json,n)}async function qse(e){let t=f(e.policy,"effectiveMode")??(e.localPreference?f(e.localPreference,"effectiveMode")??f(e.localPreference,"requestedPreference"):void 0),n=t==="warning_only"?"warning":t==="disabled"?"disabled":"enforce",r="active",i,o,s=[];if(e.skillSlug){o=(await Bi(e.backend,e.skillSlug)).installs[e.skillSlug],s=An(o);let b=s.map(w=>w.lifecycle?.state??"unreadable");b.some(w=>w==="active"||w==="pending_activation")||(b.includes("externally_removed")?r="externally_removed":b.includes("host_detached")?r="host_detached":b.includes("drifted")?r="drifted":b.length>0&&(r="unreadable")),i=o?f(o,"workspaceId")??f(o,"workingModeWorkspaceId"):void 0}let a=[],l=new Set;for(let v of["project","global"])try{a.push(...Object.values((await Vo(e.backend,v)).associations).filter(b=>!e.skillSlug||b.skillSlug===e.skillSlug))}catch{l.add(v)}let c=SM(a,l.size>0),d=(Be(e.hook,"hooks")?.filter(j)??[]).filter(v=>v.active===!0),p=s.flatMap(v=>{let b=f(v.record,"scope");if(b!=="project"&&b!=="global")return[];let w=o?gr(o,v):v.record,_=f(w,"workspaceId")??f(w,"workingModeWorkspaceId"),C=f(v.record,"receiptSha256"),P=v.lifecycle?.receipt.generation.generationId,N=Vse(v.lifecycle?.state);return mr(v.record).map(T=>{let X=wr(T),G=d.find(Ce=>f(Ce,"agent")===T&&f(Ce,"scope")===b),ee=a.filter(Ce=>Ce.agentId===T&&Ce.scope===b&&(!C||Ce.receiptSha256===C)&&(!P||Ce.generationId===P)),te=SM(ee,l.has(b)),Q=yl({evaluationContext:"runtime",requestedMode:n,workspacePolicy:_?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:X?.maximumTier==="strict_candidate",hookInstalled:!!G,strictHookVerified:G?.strictPreActionBlocking===!0,exactActivationVerified:G?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:te,materializationState:N});return{materializationId:v.materializationId,agent:T,scope:b,installedPath:v.lifecycle?.receipt.targetDir,receiptSha256:C,generationId:P,materializationState:N,associationState:te,activeAssociationCount:ee.filter(Ce=>Ce.state==="active").length,hookState:G?f(G,"hookState")??"active":"not_installed",evidenceCapability:G?.evidenceCapability??"unverified",exactActivationVerified:G?.exactActivationVerified===!0,activationRoute:G?.activationRoute??null,workspaceRequired:!!_,...Q}})}),m=yl({evaluationContext:"runtime",requestedMode:n,workspacePolicy:i?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:d.some(v=>wr(f(v,"agent")??"")?.maximumTier==="strict_candidate"),hookInstalled:d.length>0,strictHookVerified:d.some(v=>v.strictPreActionBlocking===!0),exactActivationVerified:d.some(v=>v.strictPreActionBlocking===!0&&v.exactActivationVerified===!0),completeWrapperVerified:!1,associationState:c,materializationState:r}),h=new Set(p.map(v=>v.label)),g=p.length===0?m:{label:h.size===1?p[0].label:"mixed",countedAsEnforced:p.every(v=>v.countedAsEnforced),activationAllowed:p.every(v=>v.activationAllowed),runtimeGuardian:p.every(v=>v.runtimeGuardian),reasonCode:h.size===1?p[0].reasonCode:"mixed_target_protection"},y=s.map(v=>({materializationId:v.materializationId,scope:f(v.record,"scope"),agent:f(v.record,"agent")??f(v.record,"targetAgent"),targetAgents:mr(v.record),installedPath:v.lifecycle?.receipt.targetDir,receiptSha256:f(v.record,"receiptSha256"),state:v.lifecycle?.state??"unreadable",protectionTargets:p.filter(b=>b.materializationId===v.materializationId)}));return{...g,requestedMode:n,workspaceRequired:!!i,associationState:c,materializationState:r,materializations:y,targets:p,targetCount:p.length,activeAssociationCount:a.filter(v=>v.state==="active").length}}function Vse(e){return e==="active"||e==="pending_activation"?"active":e==="externally_removed"||e==="host_detached"||e==="drifted"?e:"unreadable"}function SM(e,t){return t?"stale":e.some(n=>n.state==="active")?"active":e.some(n=>n.state==="externally_removed")?"externally_removed":e.some(n=>n.state==="host_detached")?"host_detached":e.some(n=>n.state==="stale")?"stale":e.some(n=>n.state==="pending_authority")?"pending_authority":"none"}async function OU(e,t){let n=t?await rd(e,t):void 0;return await D(e,"/api/v1/guardian/status",{method:"POST",headers:V(e.apiKey),body:JSON.stringify(ie({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function Gse(e){if(!e.apiKey)return{status:"unknown",policySource:"cloud",reasonCode:"login_required",nextAction:"skills-layer login",nextStep:"Sign in to read the Cloud Guardian policy that applies to your account."};try{return await OU(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ve(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function LU(e,t){let n=k(e.agent)??"codex",r=Xa(e.scope);if(r.status==="invalid")return R(r.message,e.json);let i=et(t.env,t.platform,t.cwd).find(m=>m.id===n);if(!i)return x({status:"error",reasonCode:"unknown_agent",agent:n,nextAction:"agents.list",nextStep:"Run `skills-layer agents list` to see supported agents, then retry Guardian hook install with a supported --agent value."},`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json,"unknown_agent");let o=Dae(i,r.scope,t,k(e.hostVersion)??i.installEvidence.hostVersion??"unverified");if(!o)return R(`Guardian ${r.scope} hooks are not available for ${i.displayName}.`,e.json);let s=ez(t,r.scope),a=OM(Bu(t.cwd,o.hookPath)),l=OM(Bu(t.cwd,o.configPath)),c=await tz(s),u=c.hooks.find(m=>f(m,"agent")===i.id&&f(m,"scope")===r.scope),d=await Tae(o,t,u),p=[...c.hooks.filter(m=>f(m,"agent")!==i.id||f(m,"scope")!==r.scope),{hookId:$t,hookName:xt,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:a.startsWith("..")?o.hookPath:a,configPath:l.startsWith("..")?o.configPath:l,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,hookFileOwnership:d.hookFileOwnership,...d.configEntryOwnership?{configEntryOwnership:d.configEntryOwnership}:{},...d.configEntryOwnerships?{configEntryOwnerships:d.configEntryOwnerships}:{},...d.activationConfigEntryOwnership?{activationConfigEntryOwnership:d.activationConfigEntryOwnership}:{},...d.configFileOwnership?{configFileOwnership:d.configFileOwnership}:{},absoluteCliPath:d.absoluteCliPath,hostVersion:o.hostVersion,adapterRevision:Gn(o.agent).adapterRevision,evidencePath:Oae(t,r.scope,o.agent,o.hostVersion),enabledAt:t.now()}];return await Ve(s,{version:1,hooks:p}),A({status:"enabled",hookId:$t,hookName:xt,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:o.hookPath,configPath:o.configPath,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,agentCommandMatrix:GC({purpose:"materialize_skill",command:"skills-layer install <skill-slug>",jsonCommand:"skills-layer install <skill-slug> --json"}),nextStep:"Guardian is installed into the selected host configuration. Installed hooks route host pre-tool events through the internal Guardian hook runtime. `skills-layer guardian check` and MCP `guardian.check` remain diagnostic; use `skills-layer guardian exec` for atomic guarded shell execution, while supported hooks call MCP/Cloud `guardian.enforce` before a mapped tool action.",warnings:["This hook is installed as a candidate integration and is not counted as strict Guardian enforcement until a real agent/platform allow/deny canary proves the exact adapter, script, config, and CLI binding."]},"Guardian hook enabled.",e.json,t)}async function Hse(e,t){let n=k(e.scope),r=n?Xa(n):null;if(r?.status==="invalid")return R(r.message,e.json);let i=await zn(t,r?.status==="valid"?r.scope:void 0);return A(i,"Guardian status loaded.",e.json,t)}async function Kse(e,t,n){let r=Xa(k(t.scope));if(r.status==="invalid")return R(r.message,t.json);let i=O(e[0]??t.skill,"guardian session bind requires a skill slug."),o=O(t.version,"guardian session bind requires --version."),s=k(t.agent);if(!s||!vr(s))return R("guardian session bind requires an agent with an implemented Guardian pre-tool adapter.",t.json);let a=O(t.hostVersion,"guardian session bind requires --host-version."),l=VU(k(t.guardianPreference)??k(t.mode));if(!l)return R("guardian session bind --mode must be enforce, warning-only, or disabled.",t.json);let c={version:1,scope:r.scope,skillSlug:i,skillVersion:o,...k(t.workspaceId)?{workspaceId:k(t.workspaceId)}:{},agentId:s,hostVersion:a,requestedPreference:l,boundAt:n.now()},u=qU(n,r.scope);return await Mo(Me(u),{recursive:!0,mode:448}),await Ve(u,c),await We(MP(n,r.scope),{force:!0}),A({status:"bound",binding:c,bindingPath:u,nextAction:"guardian.hook.run",nextStep:"Start the bound host session. The hook will obtain short-lived signed attribution for the exact Cloud generation."},"Guardian exact skill session bound.",t.json,n)}async function Wse(e,t,n){let r=O(e[0]??t.skill,"guardian launch requires a skill slug."),i=Xa(k(t.scope));if(i.status==="invalid")return R(i.message,t.json);let o=k(t.agent);if(o!=="codex"&&o!=="kiro-cli")return x({status:"blocked",reasonCode:"guardian_approved_launcher_unavailable",skillSlug:r,agent:o,supportedLauncherAgents:["codex","kiro-cli"],nextAction:"guardian.status",nextStep:"Use a host with verified native activation, or use the managed launcher for Codex or Kiro CLI. Cline and Cursor IDE processes do not expose a trustworthy inherited-session launcher boundary."},"A trustworthy managed Guardian launcher is unavailable for this host.",t.json,"guardian_approved_launcher_unavailable");let s=e[1];if(!s)return R("guardian launch requires `-- <codex|kiro-cli> [arguments]`.",t.json);if(!(o==="codex"?new Set(["codex","codex.exe"]):new Set(["kiro","kiro-cli","kiro.exe","kiro-cli.exe"])).has(ot(s).toLowerCase()))return x({status:"blocked",reasonCode:"guardian_launcher_executable_mismatch",agent:o,executable:ot(s),nextAction:"guardian.launch",nextStep:`Launch the real ${o} executable after --; arbitrary commands cannot receive a Guardian launch token.`},"Guardian refused to pass managed-session authority to a different executable.",t.json,"guardian_launcher_executable_mismatch");let l=(await Bi(n,r)).installs[r],c=qn(l,{scope:i.scope,agent:o}).filter(N=>N.lifecycle?.state==="active");if(c.length!==1||!c[0].lifecycle)return x({status:"blocked",reasonCode:c.length===0?"guardian_launch_install_not_found":"guardian_launch_install_ambiguous",skillSlug:r,agent:o,scope:i.scope,matchingMaterializationCount:c.length,nextAction:"installed",nextStep:"Keep exactly one active exact materialization for this agent and scope before launching a guarded session."},"Guardian could not resolve one exact installed generation for the managed launch.",t.json,c.length===0?"guardian_launch_install_not_found":"guardian_launch_install_ambiguous");let u=c[0].lifecycle,d=await Dr(u.receipt);if(d.status!=="verified")return x({status:"blocked",reasonCode:d.reasonCode,skillSlug:r,agent:o,scope:i.scope,nextAction:"install",nextStep:"Repair or reinstall the exact generation before starting a managed Guardian session."},"Guardian refused to launch from a stale or changed local generation.",t.json,d.reasonCode);let p=await Ya({backend:n,skillSlug:r,agentId:o,scope:i.scope,flags:t,enforceRequired:!0});if(p)return p;let m=await zn(n,i.scope),h=(Be(m,"hooks")??[]).filter(j).find(N=>f(N,"agent")===o&&f(N,"scope")===i.scope&&N.active===!0&&N.strictPreActionBlocking===!0&&N.exactActivationVerified===!0);if(!h)return x({status:"blocked",reasonCode:"guardian_launcher_route_unavailable",agent:o,nextAction:"guardian.hook.status",nextStep:"Install and verify the Guardian activation route before launching."},"Guardian refused to launch because the verified hook route is unavailable.",t.json,"guardian_launcher_route_unavailable");let g=k(t.hostVersion)??f(h,"hostVersion")??"unverified",y;try{y=await JU(s,n,fr(n.platform))}catch(N){return R(ve(N),t.json)}let v=Ge(32).toString("base64url"),b=n.now(),w={version:1,launchId:`guardian_launch_${Ge(12).toString("hex")}`,tokenSha256:`sha256:${Ue("sha256").update(v,"utf8").digest("hex")}`,scope:i.scope,agentId:o,hostVersion:g,skillSlug:r,generationId:u.receipt.generation.generationId,receiptSha256:Vr(u.receipt),status:"pending",createdAt:b,expiresAt:new Date(Date.parse(b)+15*6e4).toISOString()};await rae(n,i.scope,w);let _=await new Promise((N,T)=>{let X=UM(y,e.slice(2),{cwd:n.cwd,env:{...n.env,SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN:v,SKILLS_LAYER_GUARDIAN_LAUNCH_SCOPE:i.scope},stdio:"inherit"});X.once("error",T),X.once("exit",(G,ee)=>N({exitCode:G??1,signal:ee}))}).catch(async N=>{throw await IM(n,i.scope,w.launchId).catch(()=>{}),N}),P=(await UU(n,i.scope)).launches[w.launchId]?.status==="associated";return await IM(n,i.scope,w.launchId).catch(()=>{}),A({status:P?"managed_session_completed":"host_exited_before_association",launchId:w.launchId,skillSlug:r,agent:o,scope:i.scope,generationId:w.generationId,hostExitCode:_.exitCode,hostSignal:_.signal,associationObserved:P,nextAction:"guardian.status",nextStep:P?"The one-time launch authority was consumed by the exact host session; inspect per-target Guardian status for the resulting association.":"The host exited before its hook completed an exact active Guardian association. The one-time authority was discarded and is not strict-session evidence."},P?"Managed Guardian host session completed.":"The managed host exited without an observed Guardian session association.",t.json,n)}async function Zse(e,t){let n=Xa(k(e.scope)),r=k(e.agent);if(n.status==="invalid"||!r||!vr(r))return it(r&&vr(r)?r:"codex","deny","Guardian hook configuration is invalid.");let i=Re(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!i||i.length>512*1024)return it(r,"deny","Guardian could not read the bounded host event.");let o;try{o=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return it(r,"deny","Guardian could not parse the host event.")}let s=hd(r,o);if(s)return await xM({agentId:r,scope:n.scope,observation:s,rawPayload:o,flags:e,backend:t});let a=NU(r,o);if(!a)return it(r,"deny","Guardian could not bind this event to the host session.");let l=Re(t.env.SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN);if(l){let h=await iae(t,n.scope,l,r,t.now());if(!h)return it(r,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token.");let g=h.launch;if(h.disposition==="associated"){let y;try{y=await Vo(t,n.scope)}catch{return it(r,"deny","Guardian session association evidence is unreadable.")}let v=pl(y,{agentId:r,sessionId:a,asOf:t.now()}),b=v.associations.length===1?v.associations[0]:void 0;return!b||tt(b)!==g.associationKey?it(r,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token."):await FP({agentId:r,scope:n.scope,lookup:v,rawPayload:o,backend:t})}return await xM({agentId:r,scope:n.scope,observation:{sessionId:a,skillReference:g.skillSlug,referenceKind:"slug",source:"approved_launcher",evidence:`approved-launcher:${g.launchId}`},expectedReceiptSha256:g.receiptSha256,expectedGenerationId:g.generationId,managedLaunchId:g.launchId,qualificationCandidate:g.qualificationOnly===!0,rawPayload:o,flags:e,backend:t})}let c;try{c=await Vo(t,n.scope)}catch{return it(r,"deny","Guardian session association evidence is unreadable.")}let u=pl(c,{agentId:r,sessionId:a,asOf:t.now()});if(u.status!=="unrelated")return await FP({agentId:r,scope:n.scope,lookup:u,rawPayload:o,backend:t});let d=await ke(qU(t,n.scope));if(!d||d.version!==1||d.agentId!==r)return await sae(t,n.scope,r)?it(r,"deny",`Guardian requires \`skills-layer guardian launch <skill> --agent ${r} --scope ${n.scope} -- <host>\` because this host has no trustworthy native skill-activation signal.`):it(r,"allow","No Skills Layer skill session is bound; unrelated host activity remains outside Guardian.");let p=await ke(MP(t,n.scope));if(!Xse(p,d,a,t.now()))try{let h=await D(t,"/api/v1/guardian/sessions",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({skillSlug:d.skillSlug,version:d.skillVersion,...d.workspaceId?{workspaceId:d.workspaceId}:{},agentId:r,platform:t.platform,hostVersion:d.hostVersion,sessionId:a,requestedPreference:d.requestedPreference})}),g=L(h,"envelope"),y=GU(h,"publicKeys");if(!g||!y)throw new Error("Guardian session authority returned an invalid envelope.");p={version:1,envelope:g,publicKeys:y,savedAt:t.now()},await Ve(MP(t,n.scope),p)}catch{return it(r,"deny","Guardian could not obtain current signed skill-session authority.")}await Qse({binding:d,sessionId:a,cache:p,backend:t}).catch(()=>{});let m=await fy({agentId:r,platform:t.platform==="darwin"||t.platform==="linux"||t.platform==="win32"?t.platform:"linux",hostVersion:d.hostVersion,rawPayload:o,attributionEnvelope:p.envelope,attributionPublicKeys:p.publicKeys,now:t.now(),evaluate:async h=>jU(h,d,t)});return{exitCode:m.exitCode,stdout:m.stdout,stderr:m.stderr}}async function xM(e){let t;try{t=await eae(e.observation,e.agentId,e.backend)}catch(c){return Di(e.agentId,e.observation,"deny",ve(c))}let n=Vr(t.receipt);if(e.expectedReceiptSha256&&e.expectedReceiptSha256!==n||e.expectedGenerationId&&e.expectedGenerationId!==t.receipt.generation.generationId)return Di(e.agentId,e.observation,"deny","Guardian managed launch no longer matches the exact installed generation.");if(!t.workspaceId&&(t.requestedPreference===null||t.requestedPreference==="disabled"))return Di(e.agentId,e.observation,"allow","Guardian is not enabled for this Personal skill; no runtime association was created.");let r=t.requestedPreference??"enforce",i=Gn(e.agentId),o=tae(e.agentId,e.rawPayload,e.flags)??"unverified",s=e.backend.now(),a={version:2,revision:1,state:"pending_authority",scope:e.scope,agentId:e.agentId,hostVersion:o,sessionId:e.observation.sessionId,skillSlug:t.skillSlug,skillVersion:t.receipt.generation.semanticVersion,generationId:t.receipt.generation.generationId,receiptSha256:n,...t.workspaceId?{workspaceId:t.workspaceId}:{},requestedPreference:r,activationSource:e.observation.source,activationEvidence:e.observation.evidence,adapterRevision:i.adapterRevision,createdAt:s,updatedAt:s},l;try{l=await zU(e.backend,e.scope,a)}catch{return Di(e.agentId,e.observation,CM(a),"Guardian could not safely record this exact skill-session association.")}try{let c=await FU(l,e.backend),u=e.backend.now(),d=ul({envelope:c.cache.envelope,publicKeys:c.cache.publicKeys,expectedAgentId:e.agentId,expectedPlatform:fr(e.backend.platform),now:u});if(d.skillSlug!==l.skillSlug||d.version!==l.skillVersion||d.generationId!==l.generationId||d.sessionId!==l.sessionId||d.workspaceId!==l.workspaceId)throw new Error("Guardian Cloud authority did not match the exact local association.");let p=await zn(e.backend,e.scope),m=Be(p,"hooks")?.filter(j).find(_=>f(_,"agent")===e.agentId&&_.active===!0),h=l.requestedPreference==="warning_only"?"warning":l.requestedPreference,g=d.workspaceRequiredMode===null?null:{requiredMode:d.workspaceRequiredMode,revision:c.policyRevision,updatedBy:"skills-layer-cloud",updatedAt:d.issuedAt},y=Jse({enabled:e.qualificationCandidate===!0,managedLaunchId:e.managedLaunchId,agentId:e.agentId,exactHook:m,env:e.backend.env}),v=yl({evaluationContext:"activation_eligibility",requestedMode:h,workspacePolicy:g,hostSupported:wr(e.agentId)?.maximumTier==="strict_candidate",hookInstalled:!!m,strictHookVerified:y||m?.strictPreActionBlocking===!0,exactActivationVerified:y||m?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"pending_authority",materializationState:"active"});if(!v.activationAllowed)return await jo(e.backend,e.scope,tt(l),{state:"stale",reasonCode:v.reasonCode,updatedAt:s}),Di(e.agentId,e.observation,"deny",`Guardian refused activation because verified enforcement is unavailable (${v.reasonCode}).`);let b=await jo(e.backend,e.scope,tt(l),{state:"active",trustLedgerId:c.trustLedgerId,attributionExpiresAt:d.expiresAt,updatedAt:u}),w=tt(b);return await mA(e.backend,e.scope,w,c.cache),!e.managedLaunchId&&ls(e.backend.env)==="missing_attribution"?(await jo(e.backend,e.scope,w,{state:"stale",reasonCode:"phase149_missing_attribution_canary",updatedAt:u}),await lae(e.backend,e.scope,w),Di(e.agentId,e.observation,"allow","Guardian qualification removed signed attribution after exact activation.")):(e.managedLaunchId&&await oae(e.backend,e.scope,e.managedLaunchId,w),await hE(e.backend.env),e.managedLaunchId?await FP({agentId:e.agentId,scope:e.scope,lookup:{status:"active",associations:[b]},rawPayload:e.rawPayload,backend:e.backend}):Di(e.agentId,e.observation,"allow",v.label==="warning_only"?"Guardian warning-only activation is associated with this exact installed generation; it is not counted as strict enforcement.":"Guardian associated this host session with the exact installed generation."))}catch(c){return await jo(e.backend,e.scope,tt(l),{state:"pending_authority",reasonCode:"guardian_session_authority_unavailable",updatedAt:s}).catch(()=>{}),Di(e.agentId,e.observation,BP(c)?"deny":CM(l),l.requestedPreference==="warning_only"&&!l.workspaceId&&!BP(c)?"Guardian warning-only activation continued without runtime authority; protection is diagnostic only.":`Guardian could not establish exact skill-session authority (${ve(c)}).`)}}function Jse(e){if(!e.enabled||!e.managedLaunchId?.startsWith("guardian_launch_phase149_")||wr(e.agentId)?.automaticAssociation!=="approved_launcher_required"||e.exactHook?.active!==!0||e.exactHook.configActive!==!0||e.exactHook.evidenceCapability!=="unverified")return!1;let t=Be(e.exactHook,"evidenceReasons");return t?.length!==1||t[0]!=="live_canary_evidence_missing"?!1:ls(e.env)!==null}async function FP(e){if(e.lookup.status==="ambiguous")return it(e.agentId,"deny","Guardian found multiple active skill associations for this host session.");let t=e.lookup.associations[0];if(!t)return it(e.agentId,"deny","Guardian expected an exact association but could not load it.");if(e.lookup.status==="terminal")return it(e.agentId,"deny","Guardian blocked a session whose exact skill was removed or detached.");if(e.lookup.status==="expected_missing_authority")return it(e.agentId,t.requestedPreference==="warning_only"&&!t.workspaceId?"allow":"deny",t.requestedPreference==="warning_only"&&!t.workspaceId?"Guardian warning only: exact runtime authority is missing; this is not strict enforcement.":"Guardian blocked an expected skill session because exact runtime authority is missing.");let n=await nae(t,e.backend);if(n.status!=="verified")return await jo(e.backend,e.scope,tt(t),{state:n.state,reasonCode:n.reasonCode,updatedAt:e.backend.now()}).catch(()=>{}),it(e.agentId,"deny","Guardian blocked this session because the exact installed generation is no longer current.");let r=await cae(e.backend,e.scope,tt(t));if(e.lookup.status==="active_authority_stale"||!uae(r,t,e.backend.now()))try{let a=await FU(t,e.backend);r=a.cache;let l=ul({envelope:r.envelope,publicKeys:r.publicKeys,expectedAgentId:e.agentId,expectedPlatform:fr(e.backend.platform),now:e.backend.now()});await jo(e.backend,e.scope,tt(t),{state:"active",trustLedgerId:a.trustLedgerId,attributionExpiresAt:l.expiresAt,updatedAt:e.backend.now()}),await mA(e.backend,e.scope,tt(t),r)}catch(a){let l=t.requestedPreference==="warning_only"&&!t.workspaceId&&!BP(a);return it(e.agentId,l?"allow":"deny",l?"Guardian warning only: signed runtime authority could not be refreshed.":"Guardian blocked this action because signed runtime authority could not be refreshed.")}let i={version:1,scope:t.scope,skillSlug:t.skillSlug,skillVersion:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},agentId:e.agentId,hostVersion:t.hostVersion,requestedPreference:t.requestedPreference,boundAt:t.createdAt},o=!1,s=await fy({agentId:e.agentId,platform:fr(e.backend.platform),hostVersion:t.hostVersion,rawPayload:e.rawPayload,attributionEnvelope:r.envelope,attributionPublicKeys:r.publicKeys,now:e.backend.now(),evaluate:async a=>{let l=await jU(a,i,e.backend);return o=l.delegatedExecution===!0,l}});return o&&await yE({agentId:e.agentId,scope:e.scope,skillSlug:t.skillSlug,associationKey:tt(t),env:e.backend.env}),{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr,...o?{[TU]:!0}:{}}}async function jU(e,t,n){if(e.action.actionFamily==="shell_execution"||e.action.actionFamily==="generated_code_execution"){let i=await zn(n,t.scope),o=(Be(i,"hooks")??[]).filter(j).find(c=>f(c,"agent")===t.agentId&&f(c,"scope")===t.scope&&c.active===!0&&c.configActive===!0&&typeof f(c,"absoluteCliPath")=="string"),s=o?f(o,"absoluteCliPath"):void 0,a=ls(n.env)?kE:void 0;if(s&&e.action.command&&wE({command:e.action.command,cliPath:s,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:fr(n.platform),...a?{approvedEnvironmentKeys:a}:{}}))return{decision:"allow",reason:"Guardian delegated this exact shell action to the atomic guarded execution wrapper.",delegatedExecution:!0};let l=s?bE({cliPath:s,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:fr(n.platform),...a?{approvedEnvironmentKeys:a}:{}}):null;return{decision:"deny",reason:l&&l.length<=800?`Use the exact guarded command prefix: ${l} <command>`:"Use the exact Skills Layer Guardian execution wrapper for one-action guarded shell or generated-code execution."}}let r=Yse(e);if(r.length===0)return{decision:"deny",reason:"Guardian has no exact action mapping for this host event."};for(let i of r){let o=await D(n,"/api/v1/guardian/enforce",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({skillSlug:t.skillSlug,version:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},guardianPreference:t.requestedPreference,telemetryMode:(t.workspaceId,"cloud_managed"),action:i})});if(L(o,"enforcement")?.canExecute!==!0)return{decision:"deny",reason:`Guardian denied this exact action (${Ah(o)}).`}}return{decision:"allow",reason:"Guardian allowed the exact attributed host action."}}function Yse(e){let t={strictActionSha256:e.actionSha256,toolInputSha256:e.action.toolInputSha256,adapterRevision:e.adapterRevision,host:e.action.host};switch(e.action.actionFamily){case"filesystem_read":case"filesystem_write":return e.action.fileTargets.map(n=>({type:e.action.actionFamily==="filesystem_read"?"file_read":"file_write",path:n,metadata:t}));case"network_access":return e.action.networkTargets.map(n=>({type:"network_request",url:n,metadata:t}));case"browser_access":return[{type:"browser_action",target:e.action.toolName,metadata:t}];case"device_control":return[{type:"device_action",target:e.action.toolName,metadata:t}];case"api_access":return[{type:"api_call",target:e.action.toolName,metadata:t}];default:return[]}}function it(e,t,n){let r=ns(e,{decision:t,reason:n});return{exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}}function NU(e,t){if(!j(t))return null;let n=e==="cline"?t.taskId:e==="cursor"?t.conversation_id:e==="windsurf"?t.trajectory_id:e==="antigravity"||e==="antigravity-cli"?t.conversationId:t.session_id;return typeof n=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u.test(n)?n:null}function Xse(e,t,n,r){if(!e||e.version!==1||!j(e.envelope)||!j(e.envelope.claims))return!1;let i=e.envelope.claims;return i.agentId===t.agentId&&i.sessionId===n&&i.skillSlug===t.skillSlug&&i.version===t.skillVersion&&i.workspaceId===t.workspaceId&&typeof i.expiresAt=="string"&&Date.parse(i.expiresAt)>Date.parse(r)+5e3}async function Qse(e){let t=(await lt(e.backend)).installs[e.binding.skillSlug],n=qn(t,{scope:e.binding.scope,agent:e.binding.agentId}).filter(a=>a.lifecycle?.receipt.generation.semanticVersion===e.binding.skillVersion),r=n.length===1?n[0].lifecycle:null;if(!r||r.state!=="active"||r.receipt.generation.semanticVersion!==e.binding.skillVersion||(await Dr(r.receipt)).status!=="verified")return;let o=ul({envelope:e.cache.envelope,publicKeys:e.cache.publicKeys,expectedAgentId:e.binding.agentId,expectedPlatform:fr(e.backend.platform),now:e.backend.now()});if(o.sessionId!==e.sessionId||o.generationId!==r.receipt.generation.generationId||o.skillSlug!==e.binding.skillSlug||o.version!==e.binding.skillVersion)return;let s=await zU(e.backend,e.binding.scope,{version:2,revision:1,state:"active",scope:e.binding.scope,agentId:e.binding.agentId,hostVersion:e.binding.hostVersion,sessionId:e.sessionId,skillSlug:e.binding.skillSlug,skillVersion:e.binding.skillVersion,generationId:r.receipt.generation.generationId,receiptSha256:Vr(r.receipt),...e.binding.workspaceId?{workspaceId:e.binding.workspaceId}:{},requestedPreference:e.binding.requestedPreference,activationSource:"manual_recovery",activationEvidence:`legacy-bind:${e.binding.boundAt}`,adapterRevision:Gn(e.binding.agentId).adapterRevision,trustLedgerId:e.cache.envelope.version===2?e.cache.envelope.claims.trustLedgerId:"legacy_local",attributionExpiresAt:o.expiresAt,createdAt:e.binding.boundAt,updatedAt:e.backend.now()});await mA(e.backend,e.binding.scope,tt(s),e.cache)}async function eae(e,t,n){let r=await lt(n),i=Object.entries(r.installs).flatMap(([u,d])=>An(d).flatMap(p=>{let m=p.lifecycle;if(!m||m.state!=="active")return[];if(!mr(p.record).includes(t))return[];if(e.referenceKind==="slug"){if(e.skillReference!==u&&e.skillReference!==m.receipt.generation.skillSlug)return[]}else{let h=qo(m.receipt.targetDir),g=qo(e.skillReference),y=Bu(h,g);if(y.startsWith("..")||st.isAbsolute(y)||Lt.isAbsolute(y))return[]}return[{skillSlug:u,record:gr(d,p),lifecycle:m}]}));if(i.length!==1)throw new Error(i.length===0?"Guardian activation did not resolve to an owned exact installed generation.":"Guardian activation matched more than one installed generation.");let o=i[0],s=await Dr(o.lifecycle.receipt);if(s.status!=="verified")throw new Error(`Guardian activation receipt verification failed (${s.reasonCode}).`);let a=f(o.record,"workspaceId")??f(o.record,"workingModeWorkspaceId"),l=await rd(n,o.skillSlug),c=l===void 0?a?"enforce":null:VU(l);if(l!==void 0&&c===null)throw new Error("Guardian activation preference is invalid.");return{skillSlug:o.skillSlug,record:o.record,receipt:o.lifecycle.receipt,requestedPreference:c,...a?{workspaceId:a}:{}}}async function FU(e,t){let n=await D(t,"/api/v1/guardian/sessions",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({skillSlug:e.skillSlug,version:e.skillVersion,...e.workspaceId?{workspaceId:e.workspaceId}:{},agentId:e.agentId,platform:fr(t.platform),hostVersion:e.hostVersion,sessionId:e.sessionId,requestedPreference:e.requestedPreference})}),r=L(n,"envelope"),i=GU(n,"publicKeys"),o=L(n,"ledger"),s=o?f(o,"ledgerId"):void 0;if(!r||!i||!s)throw new Error("Guardian session authority returned an invalid exact-generation envelope.");return{cache:{version:1,envelope:r,publicKeys:i,savedAt:t.now()},trustLedgerId:s,policyRevision:r.version===2?r.claims.policyRevision:1}}function CM(e){return e.requestedPreference==="warning_only"&&!e.workspaceId?"allow":"deny"}function BP(e){return e instanceof Z?e.status<500:!ve(e).startsWith("Unable to reach ")}function Di(e,t,n,r){return t.source==="claude_user_prompt_expansion"?n==="deny"?{exitCode:2,stdout:"",stderr:r}:{exitCode:0,stdout:"",stderr:""}:it(e,n,r)}function tae(e,t,n){let r=k(n.hostVersion);if(r)return r;if(!j(t))return null;let i=e==="cline"?t.clineVersion:e==="cursor"?t.cursor_version:t.host_version;return typeof i=="string"&&/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u.test(i)?i:null}function fr(e){return e==="darwin"||e==="win32"?e:"linux"}async function nae(e,t){let n=(await lt(t)).installs[e.skillSlug],r=qn(n,{receiptSha256:e.receiptSha256}),i=r.length===1?r[0].lifecycle:null;if(!i)return{status:"invalid",state:"externally_removed",reasonCode:"exact_install_record_absent"};if(i.receipt.generation.semanticVersion!==e.skillVersion||i.receipt.generation.generationId!==e.generationId||Vr(i.receipt)!==e.receiptSha256)return{status:"invalid",state:"stale",reasonCode:"exact_generation_replaced"};try{await Xu(i.receipt.targetDir)}catch(s){return s.code==="ENOENT"?{status:"invalid",state:"externally_removed",reasonCode:"exact_target_absent"}:{status:"invalid",state:"stale",reasonCode:"exact_target_unreadable"}}let o=await Dr(i.receipt);return o.status==="verified"?{status:"verified"}:{status:"invalid",state:"stale",reasonCode:o.reasonCode}}function BU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-associations.json"):K(e.cwd,".skills-layer","guardian-session-associations.json")}function MU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-managed-launches.json"):K(e.cwd,".skills-layer","guardian-managed-launches.json")}async function UU(e,t){let n=await ke(MU(e,t));if(!j(n)||n.version!==1||!Number.isSafeInteger(n.revision)||Number(n.revision)<0||!j(n.launches))return{version:1,revision:0,launches:{}};let r=Object.fromEntries(Object.entries(n.launches).flatMap(([i,o])=>{if(!j(o))return[];let s=f(o,"agentId"),a=f(o,"scope"),l=f(o,"tokenSha256"),c=f(o,"receiptSha256"),u=f(o,"status"),d=o;return d.version!==1||d.launchId!==i||s!=="codex"&&s!=="kiro-cli"||a!==t||!l||!/^sha256:[a-f0-9]{64}$/u.test(l)||!c||!/^sha256:[a-f0-9]{64}$/u.test(c)||u!=="pending"&&u!=="claimed"&&u!=="associated"||o.qualificationOnly!==void 0&&o.qualificationOnly!==!0||!f(o,"hostVersion")||!f(o,"skillSlug")||!f(o,"generationId")||u==="associated"&&!f(o,"associationKey")||!f(o,"createdAt")||!f(o,"expiresAt")||!Number.isFinite(Date.parse(d.createdAt))||!Number.isFinite(Date.parse(d.expiresAt))?[]:[[i,d]]}));return{version:1,revision:Number(n.revision),launches:r}}async function td(e,t,n){let r=MU(e,t);await Zo(Me(r));let i=`${r}.lock`,o=null;for(let s=0;s<50&&!o;s+=1)try{o=await Uo(i,"wx",384)}catch(a){if(a.code!=="EEXIST"||s===49)throw a;await e.sleep(10)}if(!o)throw new Error("Guardian managed launch lock is unavailable.");try{let s=await UU(e,t),a=n(s);return await nd(r,a.store),a.value}finally{await o.close().catch(()=>{}),await We(i,{force:!0}).catch(()=>{})}}async function rae(e,t,n){await td(e,t,r=>({store:{version:1,revision:r.revision+1,launches:{...r.launches,[n.launchId]:n}},value:void 0}))}async function IM(e,t,n){await td(e,t,r=>{let i={...r.launches};return delete i[n],{store:{version:1,revision:r.revision+1,launches:i},value:void 0}})}async function iae(e,t,n,r,i){if(n.length<32||n.length>256||!/^[A-Za-z0-9_-]+$/u.test(n))return null;let o=`sha256:${Ue("sha256").update(n,"utf8").digest("hex")}`;return await td(e,t,s=>{let a=Object.values(s.launches).filter(d=>(d.status==="pending"||d.status==="associated")&&d.tokenSha256===o&&d.agentId===r&&(d.status==="associated"||Date.parse(d.expiresAt)>Date.parse(i))),l=a.length===1?a[0]:void 0,c=l?.status==="pending"?{...l,status:"claimed"}:l,u=Object.fromEntries(Object.entries(s.launches).flatMap(([d,p])=>p.status!=="associated"&&Date.parse(p.expiresAt)<=Date.parse(i)?[]:[[d,p.launchId===c?.launchId?c:p]]));return{store:{version:1,revision:s.revision+1,launches:u},value:c?{disposition:l?.status==="pending"?"claimed":"associated",launch:c}:null}})}async function oae(e,t,n,r){await td(e,t,i=>{let o=i.launches[n];if(!o||o.status!=="claimed")throw new Error("Guardian managed launch is not in the claimed state.");return{store:{version:1,revision:i.revision+1,launches:{...i.launches,[n]:{...o,status:"associated",associationKey:r}}},value:void 0}})}async function sae(e,t,n){if(wr(n)?.automaticAssociation!=="approved_launcher_required")return!1;let r=await lt(e);for(let[i,o]of Object.entries(r.installs)){let s=qn(o,{scope:t,agent:n});for(let a of s){if(a.lifecycle?.state!=="active"&&a.lifecycle?.state!=="pending_activation")continue;let l=gr(o,a);if(f(l,"workspaceId")??f(l,"workingModeWorkspaceId"))return!0;let u=await rd(e,i);if(u==="enforce"||u==="enabled")return!0}}return!1}function Oh(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-authorities.json"):K(e.cwd,".skills-layer","guardian-session-authorities.json")}async function Vo(e,t){let n=await ke(BU(e,t));return n===null?JR():YR(n)}async function fA(e,t,n){let r=BU(e,t);await Zo(Me(r));let i=`${r}.lock`,o=null;try{o=await Uo(i,"wx",384);let s=await Vo(e,t),a=n(s);return await nd(r,a.index),a.value}finally{await o?.close().catch(()=>{}),await We(i,{force:!0}).catch(()=>{})}}async function zU(e,t,n){return await fA(e,t,r=>{let i=XR(r,n,r.revision),o=i.associations[tt(n)];return{index:i,value:o}})}async function jo(e,t,n,r){return await fA(e,t,i=>{let o=QR(i,{key:n,expectedIndexRevision:i.revision,...r});return{index:o,value:o.associations[n]}})}async function aae(e,t){let n=0;for(let r of["project","global"]){let i=await fA(e,r,o=>{let s=eE(o,{...t,expectedIndexRevision:o.revision});return{index:s.index,value:s.removedKeys}});if(n+=i.length,i.length>0){let o=Oh(e,r),s=await Lh(e,r),a=new Set(i);await nd(o,{version:1,revision:s.revision+1,authorities:Object.fromEntries(Object.entries(s.authorities).filter(([l])=>!a.has(l)))})}await td(e,r,o=>({store:{version:1,revision:o.revision+1,launches:Object.fromEntries(Object.entries(o.launches).filter(([,s])=>s.skillSlug!==t.skillSlug||s.generationId!==t.generationId||s.receiptSha256!==t.receiptSha256))},value:void 0}))}return n}async function Lh(e,t){let n=await ke(Oh(e,t));return!j(n)||n.version!==1||!Number.isSafeInteger(n.revision)||!j(n.authorities)?{version:1,revision:0,authorities:{}}:{version:1,revision:Number(n.revision),authorities:Object.fromEntries(Object.entries(n.authorities).filter(r=>{let i=r[1];return j(i)&&i.version===1&&j(i.envelope)&&j(i.publicKeys)&&typeof i.savedAt=="string"}))}}async function mA(e,t,n,r){let i=Oh(e,t),o=await Lh(e,t);await nd(i,{version:1,revision:o.revision+1,authorities:{...o.authorities,[n]:r}})}async function lae(e,t,n){let r=Oh(e,t),i=await Lh(e,t),o={...i.authorities};delete o[n],await nd(r,{version:1,revision:i.revision+1,authorities:o})}async function cae(e,t,n){return(await Lh(e,t)).authorities[n]??null}function uae(e,t,n){if(!e||e.version!==1||!j(e.envelope)||!j(e.envelope.claims))return!1;let r=e.envelope.claims;return r.agentId===t.agentId&&r.sessionId===t.sessionId&&r.skillSlug===t.skillSlug&&r.version===t.skillVersion&&r.generationId===t.generationId&&r.workspaceId===t.workspaceId&&typeof r.expiresAt=="string"&&Date.parse(r.expiresAt)>Date.parse(n)+5e3}async function nd(e,t){let n=Me(e);await Zo(n);let r=K(n,`.${ot(e)}.${Ge(12).toString("hex")}.tmp`),i=null;try{i=await Uo(r,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
|
|
2167
|
-
`,"utf8"),await i.sync(),await i.close(),i=null,await zo(r,e),await Jo(e,384),await SA(n)}finally{await i?.close().catch(()=>{}),await We(r,{force:!0}).catch(()=>{})}}function qU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-binding.json"):K(e.cwd,".skills-layer","guardian-session-binding.json")}function MP(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session.json"):K(e.cwd,".skills-layer","guardian-session.json")}function VU(e){return!e||e==="enforce"||e==="enabled"?"enforce":e==="warning"||e==="warning-only"||e==="warning_only"?"warning_only":e==="disabled"||e==="off"?"disabled":null}function GU(e,t){let n=e[t];if(!j(n))return null;let r=Object.entries(n);return r.every(([,i])=>typeof i=="string")?Object.fromEntries(r):null}async function zn(e,t){let n=t?[t]:["project","global"],r=[],i=new Set;for(let l of n){let c=ez(e,l);if(i.has(c))continue;i.add(c);let u=await tz(c);for(let d of u.hooks){let p=f(d,"hookPath"),m=p?zP(e,l,p):null,h=f(d,"configPath"),g=h?zP(e,l,h):null,y=m?await pr(m):!1,v=g?await pr(g):null,b=y?v===!1?"active_missing_config":"active":"stale_missing_hook",w=await dae({backend:e,scope:l,hook:d,absoluteHookPath:m,absoluteConfigPath:g,hookActive:y,configActive:v});r.push({hookId:f(d,"hookId")??$t,hookName:f(d,"hookName")??xt,...d,scope:f(d,"scope")??l,hookPath:m??p??null,configPath:g??h??null,active:y,configActive:v,hookState:b,strictPreActionBlocking:w.capability==="strict",exactActivationVerified:w.exactActivationVerified,activationRoute:w.activationRoute,evidenceCapability:w.capability,evidenceReasons:w.reasons,nextStep:!y||v===!1?`Run skills-layer guardian hook install --agent ${String(d.agent)} --scope ${l}.`:w.capability!=="strict"?"This hook is installed but not strict-verified. Standard workspaces permit installation with a warning. For strict workspaces, ask your Admin for an adapter with current matching real-host canary evidence; hook install does not create that evidence.":"Strict host evidence is current. Install the approved skill using this exact agent and scope.",evidencePath:w.evidencePath,qualifiedHostExecutablePath:w.qualifiedHostExecutablePath,qualifiedHostExecutableSha256:w.qualifiedHostExecutableSha256})}}let o=r.filter(l=>l.active===!0).length,s=r.filter(l=>l.active===!1).length,a=o>0?0:s;return{status:"ok",enforcementLayer:r.some(l=>l.active===!0&&l.strictPreActionBlocking===!0)?"native_hook":o>0?"native_hook_candidate":"not_installed",strictPreActionBlocking:r.some(l=>l.active===!0&&l.strictPreActionBlocking===!0),exactActivationVerified:r.some(l=>l.active===!0&&l.strictPreActionBlocking===!0&&l.exactActivationVerified===!0),activeHookCount:o,missingHookCount:a,staleHookCount:s,hooks:r,setup:await hA(e),warnings:s>0?o>0?["One or more stale Guardian hook records were found, but an active Skills Layer Security Hook is installed."]:["One or more configured Guardian hooks are missing from disk. Run skills-layer guardian hook install --agent <agent> again to repair them."]:[]}}async function dae(e){let t=f(e.hook,"agent"),n=f(e.hook,"hostVersion"),r=f(e.hook,"adapterRevision"),i=f(e.hook,"absoluteCliPath"),o=f(e.hook,"evidencePath"),s=o?zP(e.backend,e.scope,o):null;if(!t||!vr(t))return{capability:"unverified",reasons:["strict_adapter_unavailable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(wr(t)?.maximumTier!=="strict_candidate")return{capability:"unverified",reasons:["host_strict_tier_unavailable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(!e.hookActive||e.configActive!==!0||!e.absoluteHookPath||!e.absoluteConfigPath)return{capability:"unverified",reasons:["hook_installation_incomplete"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(!n||!r||!i||!s)return{capability:"unverified",reasons:["hook_binding_metadata_missing"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};let a=await ke(s);if(!a)return{capability:"unverified",reasons:["live_canary_evidence_missing"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};try{let l=await pE({agentId:t,platform:fr(e.backend.platform),hostVersion:n,adapterRevision:r,hookConfigPath:e.absoluteConfigPath,hookScriptPath:e.absoluteHookPath,absoluteCliPath:i}),c=dE({evidence:a,currentBinding:l,asOf:e.backend.now()}),u=wr(t),d=c.capability==="strict"&&(u.automaticAssociation==="native_activation"?a.activationRoute==="native_activation":u.automaticAssociation==="approved_launcher_required"&&a.activationRoute==="approved_launcher");return{capability:d?c.capability:"unverified",reasons:d?c.reasons:[...c.reasons,"activation_route_does_not_match_host_capability"],evidencePath:s,exactActivationVerified:d,activationRoute:a.activationRoute,qualifiedHostExecutablePath:a.qualification.hostExecutablePath,qualifiedHostExecutableSha256:a.qualification.hostExecutableSha256}}catch{return{capability:"unverified",reasons:["current_installation_binding_unverifiable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null}}}async function HU(e,t){if(e.json){let c=await ke(t.paths.mcpConfigPath),u=c&&Array.isArray(c.clientIds)?c.clientIds.filter(p=>typeof p=="string"):c&&f(c,"clientId")?[f(c,"clientId")]:[],d=await az(t,u);return
|
|
2166
|
+
`))}function mP(e,t){return x({status:"not_found_or_forbidden",reasonCode:"workspace_not_found_or_forbidden",workspaceId:e,nextAction:"workspace.list",nextStep:"Run `skills-layer workspace list` to find a workspace you can access, then retry with that workspace id."},`Workspace ${e} was not found or you do not have access. Run \`skills-layer workspace list\` to inspect accessible workspaces.`,t.json,"workspace_not_found_or_forbidden")}function vM(e,t,n){let r={status:"approval_not_found",reasonCode:"workspace_skill_approval_not_found",workspaceId:e,skillSlug:t,nextAction:"workspace.approve",nextStep:`Run \`skills-layer workspace approve ${e} ${t}\` first, then run \`skills-layer workspace guide ${e} ${t}\` after the approval exists.`};return x(r,`Workspace approval not found for ${t}. Run \`skills-layer workspace approve ${e} ${t}\` first.`,n.json,"workspace_skill_approval_not_found")}function kM(e){let t=e.details??{},n=f(t,"reasonCode")?.toLowerCase(),r=`${f(t,"error")??e.message}`.toLowerCase();return n==="workspace_skill_approval_not_found"||r.includes("workspace")&&r.includes("approval")&&r.includes("not found")}function Ese(e){let t=e.details??{},n=f(t,"reasonCode")?.toLowerCase(),r=`${f(t,"error")??e.message}`.toLowerCase();return n==="skill_not_found"||r.includes("skill")&&r.includes("not found")}function $se(e,t,n,r){let i=r.details??{},o={status:"not_found",reasonCode:"skill_not_found",workspaceId:e,skillSlug:t,nextAction:"search",nextStep:f(i,"nextStep")??`Run \`skills-layer search ${t}\` to find the public skill before approving it for workspace ${e}.`};return x(o,`Skill ${t} was not found. Run \`skills-layer search ${t}\` before approving it for the workspace.`,n.json,"skill_not_found")}async function Dse(e,t,n){let r=O(e[0],"buy requires a skill slug."),i=Bie(t);if(i.failure)return i.failure;if(k(t.workspace))return x({reasonCode:"invalid_input"},"buy does not support --workspace; use skills-layer enterprise skill buy <enterprise-id> <skill-slug>.",t.json,"invalid_input");let o=await nA(n,{skillSlug:r,paymentMethod:i.value},t,"/api/v1/buy");if(fe(o))return o;if(o.status==="already_owned")return R(o,`You already own ${r}. Run \`skills-layer install ${r}\` to install or update it.`,t.json,n);if(t.noOpen&&o.status==="checkout_required"&&typeof o.checkoutUrl=="string")return R({...o,nextAction:"open_checkout_url",nextStep:`Open ${o.checkoutUrl} to complete payment, then run skills-layer install ${r}.`},`Payment is required for ${r}.`,t.json,n);if(t.json||t.noOpen||o.status!=="checkout_required"||typeof o.checkoutUrl!="string"||typeof o.purchaseId!="string")return R(o,`Purchase flow started for ${r}.`,t.json,n);n.emitInfo(`Opening checkout for ${r}. Complete the payment in your browser, then come back here.`),await n.openUrl(o.checkoutUrl)||n.emitInfo(`Open this checkout URL manually to continue: ${o.checkoutUrl}`),n.emitInfo("Waiting for payment confirmation...");let a=await Xae(o.purchaseId,n);return fe(a)?a:a.status!=="succeeded"?R({...o,purchaseStatus:a.status},`Checkout is still ${a.status} for ${r}. You can rerun install after payment reconciliation completes.`,t.json,n):(n.emitInfo("Payment confirmed. Continuing with install."),await Wa([r],t,n,{origin:"post_purchase",fallbackPolicy:"account_required"}))}async function Tse(e,t,n){let r=e[0]??"list";if(r==="list")return await me("/api/v1/purchases",t,n,"Purchases loaded.",{authenticated:!0});if(r==="spending")return await me("/api/v1/spending",t,n,"Spending loaded.",{authenticated:!0});let i=O(e[1],`purchases ${r} requires a purchase id.`);if(r==="status")return await me(`/api/v1/purchases/${encodeURIComponent(i)}`,t,n,"Purchase status loaded.",{authenticated:!0});if(r==="invoice")return await me(`/api/v1/purchases/${encodeURIComponent(i)}/invoice`,t,n,"Invoice loaded.",{authenticated:!0});if(r==="refund-quote"){let o=await D(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund-quote`,{headers:re(n.apiKey,n.authBlockedMessage)}),s=j(o.quote)?o.quote:o,a=l=>typeof l=="number"?`USD ${(l/100).toFixed(2)}`:"unavailable";return R(o,`Refundable: ${a(s.refundableAmountCents)}. Non-refundable: ${a(s.nonRefundableAmountCents)}. Refund window ends: ${String(s.refundWindowEndsAt??"unavailable")}.`,t.json,n)}if(r==="refund"){let o=await D(n,`/api/v1/purchases/${encodeURIComponent(i)}/refund`,{method:"POST",headers:V(n.apiKey),body:JSON.stringify(Ft(t,["reason"]))}),s=o.status==="refunded"?await ed(t,n):{warnings:[]};return R({...o,warnings:[...s.warnings,"Manually copied folders cannot be removed automatically; other machines check on sync, installed or update."]},o.status==="refunded"?"Refund completed.":"Refund requested.",t.json,n)}return E(`Unknown purchases command "${r}".`,t.json)}function DU(e,t,n,r){let i=typeof e.amountCents=="number"?` (USD ${(e.amountCents/100).toFixed(2)})`:"";return R({...e,status:"action_required",reasonCode:"purchase_required",nextAction:"buy",nextStep:`skills-layer buy ${t}`},`Purchase required${i}. Run \`skills-layer buy ${t}\`.`,n.json,r)}async function Ose(e,t,n){let r=e[0];if(r==="search"){let i=new URLSearchParams;return Ke(i,"query",e.slice(1).join(" ").trim()||k(t.query)),Ke(i,"limit",k(t.limit)),await me(`/api/v1/me/search${Qe(i)}`,t,n,"Authenticated library search complete.",{authenticated:!0})}if(r==="add"){let i=O(e[1],"library add requires a skill slug."),o=await nA(n,{skillSlug:i},t);return fe(o)?o:o.status==="purchase_required"?DU(o,i,t,n):R(o,"Skill added to library.",t.json,n)}return E(`Unknown library command "${r}".`,t.json)}async function Lse(e,t,n){let r=O(e[0],"export requires a skill slug.");if(t.showUrl&&k(t.output))return x({status:"error",reasonCode:"conflicting_export_output",nextAction:"export",nextStep:"Use either --show-url to inspect the signed URL or --output <file> to download the bundle, not both."},"export cannot use --show-url and --output together.",t.json,"conflicting_export_output");let i=new URLSearchParams,o=k(t.version);if(o&&!Th(o))return eA("export",o,t);Ke(i,"version",o);let s=await D(n,`/api/v1/me/library/${encodeURIComponent(r)}/export${Qe(i)}`,{headers:re(n.apiKey,n.authBlockedMessage)}),a=k(t.output);if(a){let l=await xh({backend:n,exportResult:s,flags:t,skillSlug:r});if(fe(l))return l;let c=Tt(n.cwd,a);await IA(c,l.bytes);let u={...s};return delete u.downloadUrl,R({...u,archiveSha256:l.archiveSha256,archiveSha256Meaning:"artifact_v1_exact_zip_bytes_sha256",downloadedArchiveSha256:l.archiveBytesSha256,downloadedFileSha256:l.archiveBytesSha256,archiveHashFormat:l.archiveHashFormat,generationId:l.envelope.generation.generationId,manifestSha256:l.envelope.manifest.sha256,outputPath:c,downloaded:!0},`Exported ${r} to ${c}. Downloaded file SHA-256: ${l.archiveBytesSha256}.`,t.json,n)}return R(s,a?`Exported ${r} to ${a}.`:"Export prepared.",t.json,n)}async function wM(e,t,n,r){if(e==="show"){let a=t[0]?.trim(),l=a?`?skillSlug=${encodeURIComponent(a)}`:"";return await me(`/api/v1/me/library/reviews${l}`,n,r,"Reviews loaded.",{authenticated:!0})}let i=O(t[0],"add-review requires a skill slug."),o=O(n.rating,"add-review requires --rating.");if(!/^[1-5]$/u.test(o))return x({status:"error",reasonCode:"invalid_rating",rating:o,acceptedValues:["1","2","3","4","5"],nextAction:"add-review",nextStep:"Use --rating with a whole number from 1 to 5."},`Invalid review rating "${o}". Use a whole number from 1 to 5.`,n.json,"invalid_rating");let s=Ft(n,["rating","feedback"]);if(typeof n.evalSummary=="string"){let a=await ke(qo(r.cwd,n.evalSummary));if(a===null)return x({status:"error",reasonCode:"invalid_eval_summary_file",path:n.evalSummary,nextAction:"add-review",nextStep:"Pass --eval-summary with a readable JSON redacted eval summary envelope."},`Could not read eval summary JSON from ${n.evalSummary}.`,n.json,"invalid_eval_summary_file");s.evalSummary=a}return await Oe(`/api/v1/me/library/${encodeURIComponent(i)}/review`,s,n,r,"Review added.")}async function bM(e,t,n,r){let i=O(t[0],`${e==="add"?"add-issue":"show-issues"} requires a skill slug.`);if(e==="show")return await me(`/api/v1/me/library/${encodeURIComponent(i)}/issues`,n,r,"Issues loaded.",{authenticated:!0});O(n.message,"add-issue requires --message.");let o=Mn("add-issue","issueType",n.issueType,_ie,n,"invalid_issue_type","issue-type");return o||await Oe(`/api/v1/me/library/${encodeURIComponent(i)}/report-issue`,Ft(n,["issueType","message"]),n,r,"Issue reported.")}async function jse(e,t,n){let r=e[0];if(r==="hook"){let i=e[1];if(i==="install")return await LU(t,n);if(i==="status")return await Hse(t,n);if(i==="run"){let o=await Zse(t,n),s=k(t.agent);if(s&&vr(s)){let a=ls(n.env);await by({agentId:s,associationState:a?await Fse(s,t,n):"unreadable",activationEvent:a?await Mse(s,n):!1,delegatedExecution:o[TU]===!0,env:n.env,rawPayloadBase64:Re(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64),result:o})}return o}return E(`Unknown guardian hook command "${i??""}".`,t.json)}if(r==="session"){let i=e[1];return i==="bind"?await Kse(e.slice(2),t,n):E(`Unknown guardian session command "${i??""}".`,t.json)}if(r==="enable")return e[1]||t.skill?await gP("enforce",e,t,n):E("guardian enable requires a skill slug.",t.json);if(r==="disable")return await gP("disabled",e,t,n);if(r==="enable-warnings-only")return await gP("warning_only",e,t,n);if(r==="status")return await zse(e,t,n);if(r==="launch")return await Wse(e.slice(1),t,n);if(r==="exec")try{let i=await Use(e,t,n);return await _M(i,e,t,n),i}catch(i){throw await _M({exitCode:1,stdout:"",stderr:ve(i)},e,t,n),i}if(r==="check"){let i=O(e[1]??t.skill,"guardian check requires a skill slug.");if((await ed({...t,dryRun:!0},n,i)).revokedSlugs.includes(i))return R({status:"blocked",decision:"block",reasonCode:"entitlement_revoked_refunded",skillSlug:i,nextStep:`Run skills-layer remove ${i}, or buy it again.`},"This skill was refunded; execution is blocked.",t.json,n);let s=LM(t,"check");if(t.grantJson.length>0)return x({status:"error",reasonCode:"caller_supplied_authorization_grants_rejected",nextAction:"guardian.approval.prepare",nextStep:"Use an authenticated one-action approval or `skills-layer guardian exec` for shell execution."},"Guardian enforcement does not accept caller-authored authorization grants.",t.json,"caller_supplied_authorization_grants_rejected");let a=xce(t.cloudTrustLedger);if(a.status==="invalid")return E(a.message,t.json);let l=UP(t.telemetryMode,a.policy==="off"?"local_only":"cloud_managed");if(l.status==="invalid")return E(l.message,t.json);let c=await KU({skillSlug:i,version:k(t.version),action:s,flags:t,backend:n,telemetryMode:l.mode});if(c.status!=="ok")return c.result;let u=c.context.installedPath,d=k(t.version)??c.context.version,p=ie({skillSlug:i,version:d,action:s,path:u,guardianPreference:await rd(n,i),unmanagedPolicy:c.context.unmanagedPolicy,allowUnmanagedOnce:t.allowUnmanagedOnce,telemetryMode:l.mode,localPreflight:qu(c.context)}),m=await D(n,"/api/v1/guardian/enforce",{method:"POST",headers:V(n.apiKey),body:JSON.stringify(p)});return await Ga(n,{skillSlug:i,version:d,action:s,decisionStatus:qP(m),reasonCode:Ah(m),telemetryMode:l.mode,path:u,authority:m}),R({...m,localPreflight:qu(c.context)},"Guardian check complete.",t.json,n)}if(r==="incident"){let i=O(e[1]??t.skill,"guardian incident requires a skill slug."),o=O(t.version,"guardian incident requires --version."),s=UP(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return E(s.message,t.json);let a=k(t.path);if(a&&!await pr(Tt(n.cwd,a)))return x({status:"error",reasonCode:"invalid_incident_path",path:a,nextAction:"guardian.incident",nextStep:"Use --path with an installed skill directory, or omit --path so Skills Layer resolves the local install record."},`Guardian incident path does not exist: ${a}`,t.json,"invalid_incident_path");let l=a??(await WU({skillSlug:i,flags:t,backend:n})).installedPath,c=LM(t,"incident"),u=ln(t.evidenceJson,"evidence-json"),d=s.mode==="cloud_managed"&&!n.apiKey?"local_only":s.mode,p=n.now(),m=ie({skillSlug:i,version:o,action:c,evidence:u,path:l,telemetryMode:d,incident:!0,reason:k(t.reason),generatedAt:p,...d==="cloud_managed"?{incidentIdempotencyKey:sle()}:{}});if(d==="local_only"){if(!l)return E("guardian incident --telemetry-mode local_only requires --path <installed-skill-path>.",t.json);let v=await $M({backend:n,skillSlug:i,version:o,installedPath:l,action:c,reason:k(t.reason)??"Guardian local-only incident"});if(f(v,"status")!=="quarantined"){let w=f(v,"reasonCode")??"guardian_exact_quarantine_failed";return x(v,`Guardian could not physically quarantine the exact installed generation for ${i}.`,t.json,w)}await Ga(n,{skillSlug:i,version:o,action:c,decisionStatus:"blocked",reasonCode:"incident_recorded",telemetryMode:d,path:l});let b=DM(n,i);return await BM(b,JSON.stringify({request:m,response:null,localResponse:v,savedAt:n.now()},null,2)),R({status:"written",skillSlug:i,version:o,telemetryMode:d,cloudTelemetry:n.apiKey?"not_requested":"login_required",localResponse:v,incidentStatePath:b,incidentPath:v.incidentPath},n.apiKey?"Guardian incident recorded locally.":"Guardian incident recorded locally. Log in to submit Cloud incident evidence.",t.json,n)}let h=await ale(n,m),g=l?await $M({backend:n,skillSlug:i,version:o,installedPath:l,action:c,reason:k(t.reason)??"Guardian Cloud-managed incident"}):null;if(g&&f(g,"status")!=="quarantined"){let v=f(g,"reasonCode")??"guardian_exact_quarantine_failed";return x({...g,cloudResponse:h},`Guardian recorded the Cloud incident but could not physically quarantine the exact local generation for ${i}.`,t.json,v)}await Mo(n.paths.incidentsDir,{recursive:!0});let y=DM(n,i);return await BM(y,JSON.stringify({request:m,response:h,localResponse:g,savedAt:n.now()},null,2)),await Ga(n,{skillSlug:i,version:o,action:c,decisionStatus:qP(h),reasonCode:Ah(h),telemetryMode:s.mode,path:l,authority:h}),R({...h,telemetryMode:s.mode,localResponse:g,incidentPath:y},"Guardian incident recorded.",t.json,n)}return E(`Unknown guardian command "${r??""}".`,t.json)}var TU=Symbol("guardian-delegated-execution");async function _M(e,t,n,r){if(!ls(r.env))return;let i=r.env.SKILLS_LAYER_GUARDIAN_CANARY_AGENT_ID,o=r.env.SKILLS_LAYER_GUARDIAN_CANARY_SCOPE;if(!i||!vr(i)||o!=="project"&&o!=="global")return;let s=k(n.skill)??t[1];s&&await by({agentId:i,associationState:await Nse(i,o,s,r),activationEvent:!1,env:r.env,rawPayloadBase64:Buffer.from(JSON.stringify({positionals:t,json:n.json})).toString("base64url"),reportingSource:"guarded_execution",result:e})}async function Nse(e,t,n,r){let i=await vE({agentId:e,scope:t,skillSlug:n,env:r.env});if(!i)return"unreadable";try{let o=await Vo(r,t),s=o.associations[i.associationKey];if(!s||s.agentId!==e||s.scope!==t||s.skillSlug!==n)return"missing";let a=pl(o,{agentId:e,sessionId:s.sessionId,asOf:r.now()});return a.associations.some(c=>tt(c)===i.associationKey)?a.status==="active"||a.status==="active_authority_stale"?"active":a.status==="terminal"?"terminal":a.status==="ambiguous"?"ambiguous":"missing":"missing"}catch{return"unreadable"}}async function Fse(e,t,n){let r=Xa(k(t.scope));return r.status==="invalid"?"unreadable":await Bse(e,r.scope,n)}async function Bse(e,t,n){let r=Re(n.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!r)return"unreadable";let i;try{i=JSON.parse(Buffer.from(r,"base64url").toString("utf8"))}catch{return"unreadable"}let o=hd(e,i)?.sessionId??NU(e,i);if(!o)return"unreadable";try{let s=await Vo(n,t),a=pl(s,{agentId:e,sessionId:o,asOf:n.now()});return a.status==="active"||a.status==="active_authority_stale"?"active":a.status==="unrelated"||a.status==="expected_missing_authority"?"missing":a.status}catch{return"unreadable"}}async function Mse(e,t){let n=Re(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!n)return!1;try{let r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));return hd(e,r)!==null}catch{return!1}}async function Use(e,t,n){let r=k(t.skill),i=O(r??e[1],"guardian exec requires a skill slug."),o=r?e.slice(1):e.slice(2);if(o.length===0)return E("guardian exec requires a command after --.",t.json);if(t.actionJson!==void 0)return x({status:"error",reasonCode:"caller_supplied_execution_action_rejected",nextAction:"guardian.execution.prepare",nextStep:"Guardian derives the canonical shell action from the exact command and execution plan."},"Guardian guarded execution does not accept a caller-authored action.",t.json,"caller_supplied_execution_action_rejected");if(t.grantJson.length>0)return x({status:"error",reasonCode:"caller_supplied_authorization_grants_rejected",nextAction:"guardian.execution.prepare",nextStep:"Use the authenticated atomic Guardian execution prepare flow."},"Guardian guarded execution does not accept caller-authored authorization grants.",t.json,"caller_supplied_authorization_grants_rejected");let s=UP(t.telemetryMode,"cloud_managed");if(s.status==="invalid")return E(s.message,t.json);let a=AM(o),l=await KU({skillSlug:i,version:k(t.version),action:a,flags:t,backend:n,telemetryMode:s.mode});if(l.status!=="ok")return l.result;let c=l.context.installedPath,u=k(t.version)??l.context.version;if(!u)return x({status:"blocked",reasonCode:"guardian_exact_version_required",skillSlug:i,nextStep:"Install the skill through Skills Layer or pass its exact --version before guarded execution."},"Guardian guarded execution requires an exact installed skill version.",t.json,"guardian_exact_version_required");let d=await wae({commandArgs:o,skillSlug:i,version:u,flags:t,backend:n,localContext:l.context});if(d.status==="blocked")return d.result;let p=AM(o,d.request),m=await D(n,"/api/v1/guardian/execution/prepare",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({request:d.request,...t.dryRun?{dryRun:!0}:{}})}),h=typeof f(m,"token")=="string"&&L(m,"plan")!==void 0&&L(m,"binding")!==void 0;if(!kae(m)&&!h){let C=Ah(m);return await Ga(n,{skillSlug:i,version:u,action:p,decisionStatus:"blocked",reasonCode:C,telemetryMode:s.mode,path:c,authority:m}),x({...m,status:"blocked",reasonCode:C,skillSlug:i},"Guardian blocked guarded execution.",t.json,C)}if(await Ga(n,{skillSlug:i,version:u,action:p,decisionStatus:"allowed",reasonCode:"within_contract",telemetryMode:s.mode,path:c,authority:m}),t.dryRun)return R({status:"allowed",skillSlug:i,guardian:m,localPreflight:qu(l.context),command:{executable:ot(d.request.executableRealPath),executableSha256:d.request.executableSha256,argvSha256:YU(d.request.argv),cwdRealPath:d.request.cwdRealPath,executed:!1,dryRun:!0}},"Guardian guarded execution allowed.",t.json,n);let g=m,y=f(g,"token"),v=L(g,"plan"),b=L(g,"binding");if(!y||!v||!b)return x({status:"blocked",reasonCode:"guardian_grant_response_invalid",skillSlug:i},"Guardian returned an invalid execution grant.",t.json,"guardian_grant_response_invalid");await D(n,"/api/v1/guardian/execution-grants/consume",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({token:y,plan:v,binding:b})});let w;try{w=await O2({plan:v,ambientEnvironment:n.env,approvedSecrets:d.approvedSecrets})}catch(C){let P=C instanceof $e?C.reasonCode:"guardian_process_failed";return x({status:"blocked",reasonCode:P,skillSlug:i,planHash:b.planHash},"Guardian refused the contained process launch.",t.json,P)}let _={executable:ot(v.executableRealPath),argsCount:v.argv.length,exitCode:w.exitCode??1,reason:w.reason,signal:w.signal,stdout:w.stdout,stderr:w.stderr,outputTruncated:w.outputTruncated,planHash:w.planHash};return{exitCode:_.exitCode,stdout:t.json?JSON.stringify({status:_.exitCode===0?"executed":"command_failed",summary:"Guardian guarded execution complete.",why:null,nextAction:null,nextStep:null,data:{skillSlug:i,guardian:m,localPreflight:qu(l.context),command:_},warnings:[],links:[],reasonCode:_.exitCode===0?null:"command_failed",handoff:null},null,2):Rae(_),stderr:_.stderr}}async function gP(e,t,n,r){let i=O(t[1]??n.skill,`guardian ${t[0]??"mode"} requires a skill slug.`),o=await D(r,"/api/v1/guardian/mode",{method:"POST",headers:V(r.apiKey),body:JSON.stringify({skillSlug:i,requestedPreference:e,source:"public-cli"})});if(o.preferenceAccepted===!0){if(f(o,"effectiveMode")==="enforce"){let s=(await Bi(r,i)).installs[i],a=An(s).filter(u=>u.lifecycle?.state==="active"||u.lifecycle?.state==="pending_activation"),l=et(r.env,r.platform,r.cwd),c=new Set;for(let u of a){let d=f(u.record,"scope"),p=mr(u.record);if(d!=="project"&&d!=="global"||p.length===0)return x({status:"blocked",reasonCode:"guardian_install_target_unavailable",skillSlug:i,materializationId:u.materializationId,scope:d,targetAgents:p,nextAction:"install",nextStep:"Reinstall the exact skill for a supported agent and scope before enabling enforced Guardian."},"Guardian enforce mode could not identify every supported local activation target.",n.json,"guardian_install_target_unavailable");for(let m of p){let h=l.find(v=>v.id===m);if(!h)return x({status:"blocked",reasonCode:"guardian_install_target_unavailable",skillSlug:i,materializationId:u.materializationId,agent:m,scope:d,nextAction:"install",nextStep:"Reinstall the exact skill for a supported agent and scope before enabling enforced Guardian."},"Guardian enforce mode found an unsupported local activation target.",n.json,"guardian_install_target_unavailable");let g=`${d}:${h.id}`;if(c.has(g))continue;c.add(g);let y=await Ya({backend:r,skillSlug:i,agentId:h.id,scope:d,flags:n,enforceRequired:!0});if(y)return y}}}await Eae(r,i,o)}return R(o,o.preferenceAccepted===!0?"Guardian mode updated.":"Guardian mode resolved by policy.",n.json,r)}async function zse(e,t,n){let r=k(t.skill)??k(e[1]),i;try{i=await OU(n,r)}catch(m){i={status:"unavailable",skillSlug:r,policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ve(m),nextAction:"guardian.status",nextStep:"Cloud Guardian policy could not be loaded. Local hook and preference posture are still shown below."}}let o=await zn(n),s=r?await $ae(n,r):void 0,a=f(i,"status")==="unavailable",l=f(o,"enforcementLayer")??"not_installed",d=l!=="not_installed"&&o.strictPreActionBlocking===!0?{status:"strict_installed",reasonCode:"guardian_hook_strict",enforcementLayer:l,strictPreActionBlocking:!0,nextAction:"guardian.check",nextStep:"Cloud Guardian policy is enforced when checked, and the local host hook can block supported risky actions before execution."}:l==="native_hook_candidate"?{status:"candidate_installed",reasonCode:"guardian_hook_candidate",enforcementLayer:l,strictPreActionBlocking:!1,nextAction:"guardian.hook.status",nextStep:"A Guardian candidate hook is installed, but strict pre-action blocking is not verified. Run `skills-layer guardian hook status --scope project` to inspect the current binding."}:{status:"not_installed",reasonCode:"guardian_hook_not_installed",enforcementLayer:"not_installed",strictPreActionBlocking:!1,nextAction:"guardian.hook.install",nextStep:"Cloud Guardian policy is enforced when checked, but local pre-action blocking is not installed for this host. Run `skills-layer guardian hook install --agent codex --scope global` or `skills-layer setup`."},p=await qse({backend:n,skillSlug:r,policy:i,hook:o,localPreference:s});return R(ie({status:a?"degraded":"ok",skillSlug:f(i,"skillSlug")??r,policy:i,localPreference:s,hook:o,cloudPolicy:{status:f(i,"effectiveMode")??f(i,"status")??"unknown",reasonCode:f(i,"reasonCode"),enforcementBoundary:"cloud_policy_when_checked",nextAction:f(i,"nextAction"),nextStep:f(i,"nextStep")},localEnforcement:d,measuredProtection:p,nextAction:f(d,"nextAction"),nextStep:f(d,"nextStep")}),a?"Guardian status loaded with limited Cloud policy data.":"Guardian status loaded.",t.json,n)}async function qse(e){let t=f(e.policy,"effectiveMode")??(e.localPreference?f(e.localPreference,"effectiveMode")??f(e.localPreference,"requestedPreference"):void 0),n=t==="warning_only"?"warning":t==="disabled"?"disabled":"enforce",r="active",i,o,s=[];if(e.skillSlug){o=(await Bi(e.backend,e.skillSlug)).installs[e.skillSlug],s=An(o);let b=s.map(w=>w.lifecycle?.state??"unreadable");b.some(w=>w==="active"||w==="pending_activation")||(b.includes("externally_removed")?r="externally_removed":b.includes("host_detached")?r="host_detached":b.includes("drifted")?r="drifted":b.length>0&&(r="unreadable")),i=o?f(o,"workspaceId")??f(o,"workingModeWorkspaceId"):void 0}let a=[],l=new Set;for(let v of["project","global"])try{a.push(...Object.values((await Vo(e.backend,v)).associations).filter(b=>!e.skillSlug||b.skillSlug===e.skillSlug))}catch{l.add(v)}let c=SM(a,l.size>0),d=(Be(e.hook,"hooks")?.filter(j)??[]).filter(v=>v.active===!0),p=s.flatMap(v=>{let b=f(v.record,"scope");if(b!=="project"&&b!=="global")return[];let w=o?gr(o,v):v.record,_=f(w,"workspaceId")??f(w,"workingModeWorkspaceId"),C=f(v.record,"receiptSha256"),P=v.lifecycle?.receipt.generation.generationId,N=Vse(v.lifecycle?.state);return mr(v.record).map(T=>{let X=wr(T),G=d.find(Ce=>f(Ce,"agent")===T&&f(Ce,"scope")===b),ee=a.filter(Ce=>Ce.agentId===T&&Ce.scope===b&&(!C||Ce.receiptSha256===C)&&(!P||Ce.generationId===P)),te=SM(ee,l.has(b)),Q=yl({evaluationContext:"runtime",requestedMode:n,workspacePolicy:_?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:X?.maximumTier==="strict_candidate",hookInstalled:!!G,strictHookVerified:G?.strictPreActionBlocking===!0,exactActivationVerified:G?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:te,materializationState:N});return{materializationId:v.materializationId,agent:T,scope:b,installedPath:v.lifecycle?.receipt.targetDir,receiptSha256:C,generationId:P,materializationState:N,associationState:te,activeAssociationCount:ee.filter(Ce=>Ce.state==="active").length,hookState:G?f(G,"hookState")??"active":"not_installed",evidenceCapability:G?.evidenceCapability??"unverified",exactActivationVerified:G?.exactActivationVerified===!0,activationRoute:G?.activationRoute??null,workspaceRequired:!!_,...Q}})}),m=yl({evaluationContext:"runtime",requestedMode:n,workspacePolicy:i?{requiredMode:"enforce",revision:1,updatedBy:"skills-layer-cloud",updatedAt:e.backend.now()}:null,hostSupported:d.some(v=>wr(f(v,"agent")??"")?.maximumTier==="strict_candidate"),hookInstalled:d.length>0,strictHookVerified:d.some(v=>v.strictPreActionBlocking===!0),exactActivationVerified:d.some(v=>v.strictPreActionBlocking===!0&&v.exactActivationVerified===!0),completeWrapperVerified:!1,associationState:c,materializationState:r}),h=new Set(p.map(v=>v.label)),g=p.length===0?m:{label:h.size===1?p[0].label:"mixed",countedAsEnforced:p.every(v=>v.countedAsEnforced),activationAllowed:p.every(v=>v.activationAllowed),runtimeGuardian:p.every(v=>v.runtimeGuardian),reasonCode:h.size===1?p[0].reasonCode:"mixed_target_protection"},y=s.map(v=>({materializationId:v.materializationId,scope:f(v.record,"scope"),agent:f(v.record,"agent")??f(v.record,"targetAgent"),targetAgents:mr(v.record),installedPath:v.lifecycle?.receipt.targetDir,receiptSha256:f(v.record,"receiptSha256"),state:v.lifecycle?.state??"unreadable",protectionTargets:p.filter(b=>b.materializationId===v.materializationId)}));return{...g,requestedMode:n,workspaceRequired:!!i,associationState:c,materializationState:r,materializations:y,targets:p,targetCount:p.length,activeAssociationCount:a.filter(v=>v.state==="active").length}}function Vse(e){return e==="active"||e==="pending_activation"?"active":e==="externally_removed"||e==="host_detached"||e==="drifted"?e:"unreadable"}function SM(e,t){return t?"stale":e.some(n=>n.state==="active")?"active":e.some(n=>n.state==="externally_removed")?"externally_removed":e.some(n=>n.state==="host_detached")?"host_detached":e.some(n=>n.state==="stale")?"stale":e.some(n=>n.state==="pending_authority")?"pending_authority":"none"}async function OU(e,t){let n=t?await rd(e,t):void 0;return await D(e,"/api/v1/guardian/status",{method:"POST",headers:V(e.apiKey),body:JSON.stringify(ie({skillSlug:t,requestedPreference:n,source:"public-cli"}))})}async function Gse(e){if(!e.apiKey)return{status:"unknown",policySource:"cloud",reasonCode:"login_required",nextAction:"skills-layer login",nextStep:"Sign in to read the Cloud Guardian policy that applies to your account."};try{return await OU(e)}catch(t){return{status:"unavailable",policySource:"cloud",reasonCode:"guardian_policy_status_unavailable",message:ve(t),nextAction:"skills-layer guardian status",nextStep:"Retry Guardian status after backend connectivity or authentication is healthy."}}}async function LU(e,t){let n=k(e.agent)??"codex",r=Xa(e.scope);if(r.status==="invalid")return E(r.message,e.json);let i=et(t.env,t.platform,t.cwd).find(m=>m.id===n);if(!i)return x({status:"error",reasonCode:"unknown_agent",agent:n,nextAction:"agents.list",nextStep:"Run `skills-layer agents list` to see supported agents, then retry Guardian hook install with a supported --agent value."},`Unsupported Guardian agent "${n}". Run skills-layer agents list to see supported agents.`,e.json,"unknown_agent");let o=Dae(i,r.scope,t,k(e.hostVersion)??i.installEvidence.hostVersion??"unverified");if(!o)return E(`Guardian ${r.scope} hooks are not available for ${i.displayName}.`,e.json);let s=ez(t,r.scope),a=OM(Bu(t.cwd,o.hookPath)),l=OM(Bu(t.cwd,o.configPath)),c=await tz(s),u=c.hooks.find(m=>f(m,"agent")===i.id&&f(m,"scope")===r.scope),d=await Tae(o,t,u),p=[...c.hooks.filter(m=>f(m,"agent")!==i.id||f(m,"scope")!==r.scope),{hookId:$t,hookName:xt,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:a.startsWith("..")?o.hookPath:a,configPath:l.startsWith("..")?o.configPath:l,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,hookFileOwnership:d.hookFileOwnership,...d.configEntryOwnership?{configEntryOwnership:d.configEntryOwnership}:{},...d.configEntryOwnerships?{configEntryOwnerships:d.configEntryOwnerships}:{},...d.activationConfigEntryOwnership?{activationConfigEntryOwnership:d.activationConfigEntryOwnership}:{},...d.configFileOwnership?{configFileOwnership:d.configFileOwnership}:{},absoluteCliPath:d.absoluteCliPath,hostVersion:o.hostVersion,adapterRevision:Gn(o.agent).adapterRevision,evidencePath:Oae(t,r.scope,o.agent,o.hostVersion),enabledAt:t.now()}];return await Ve(s,{version:1,hooks:p}),R({status:"enabled",hookId:$t,hookName:xt,agent:i.id,agentName:i.displayName,scope:r.scope,hookPath:o.hookPath,configPath:o.configPath,enforcementLayer:o.enforcementLayer,strictPreActionBlocking:o.strictPreActionBlocking,agentCommandMatrix:GC({purpose:"materialize_skill",command:"skills-layer install <skill-slug>",jsonCommand:"skills-layer install <skill-slug> --json"}),nextStep:"Guardian is installed into the selected host configuration. Installed hooks route host pre-tool events through the internal Guardian hook runtime. `skills-layer guardian check` and MCP `guardian.check` remain diagnostic; use `skills-layer guardian exec` for atomic guarded shell execution, while supported hooks call MCP/Cloud `guardian.enforce` before a mapped tool action.",warnings:["This hook is installed as a candidate integration and is not counted as strict Guardian enforcement until a real agent/platform allow/deny canary proves the exact adapter, script, config, and CLI binding."]},"Guardian hook enabled.",e.json,t)}async function Hse(e,t){let n=k(e.scope),r=n?Xa(n):null;if(r?.status==="invalid")return E(r.message,e.json);let i=await zn(t,r?.status==="valid"?r.scope:void 0);return R(i,"Guardian status loaded.",e.json,t)}async function Kse(e,t,n){let r=Xa(k(t.scope));if(r.status==="invalid")return E(r.message,t.json);let i=O(e[0]??t.skill,"guardian session bind requires a skill slug."),o=O(t.version,"guardian session bind requires --version."),s=k(t.agent);if(!s||!vr(s))return E("guardian session bind requires an agent with an implemented Guardian pre-tool adapter.",t.json);let a=O(t.hostVersion,"guardian session bind requires --host-version."),l=VU(k(t.guardianPreference)??k(t.mode));if(!l)return E("guardian session bind --mode must be enforce, warning-only, or disabled.",t.json);let c={version:1,scope:r.scope,skillSlug:i,skillVersion:o,...k(t.workspaceId)?{workspaceId:k(t.workspaceId)}:{},agentId:s,hostVersion:a,requestedPreference:l,boundAt:n.now()},u=qU(n,r.scope);return await Mo(Me(u),{recursive:!0,mode:448}),await Ve(u,c),await We(MP(n,r.scope),{force:!0}),R({status:"bound",binding:c,bindingPath:u,nextAction:"guardian.hook.run",nextStep:"Start the bound host session. The hook will obtain short-lived signed attribution for the exact Cloud generation."},"Guardian exact skill session bound.",t.json,n)}async function Wse(e,t,n){let r=O(e[0]??t.skill,"guardian launch requires a skill slug."),i=Xa(k(t.scope));if(i.status==="invalid")return E(i.message,t.json);let o=k(t.agent);if(o!=="codex"&&o!=="kiro-cli")return x({status:"blocked",reasonCode:"guardian_approved_launcher_unavailable",skillSlug:r,agent:o,supportedLauncherAgents:["codex","kiro-cli"],nextAction:"guardian.status",nextStep:"Use a host with verified native activation, or use the managed launcher for Codex or Kiro CLI. Cline and Cursor IDE processes do not expose a trustworthy inherited-session launcher boundary."},"A trustworthy managed Guardian launcher is unavailable for this host.",t.json,"guardian_approved_launcher_unavailable");let s=e[1];if(!s)return E("guardian launch requires `-- <codex|kiro-cli> [arguments]`.",t.json);if(!(o==="codex"?new Set(["codex","codex.exe"]):new Set(["kiro","kiro-cli","kiro.exe","kiro-cli.exe"])).has(ot(s).toLowerCase()))return x({status:"blocked",reasonCode:"guardian_launcher_executable_mismatch",agent:o,executable:ot(s),nextAction:"guardian.launch",nextStep:`Launch the real ${o} executable after --; arbitrary commands cannot receive a Guardian launch token.`},"Guardian refused to pass managed-session authority to a different executable.",t.json,"guardian_launcher_executable_mismatch");let l=(await Bi(n,r)).installs[r],c=qn(l,{scope:i.scope,agent:o}).filter(N=>N.lifecycle?.state==="active");if(c.length!==1||!c[0].lifecycle)return x({status:"blocked",reasonCode:c.length===0?"guardian_launch_install_not_found":"guardian_launch_install_ambiguous",skillSlug:r,agent:o,scope:i.scope,matchingMaterializationCount:c.length,nextAction:"installed",nextStep:"Keep exactly one active exact materialization for this agent and scope before launching a guarded session."},"Guardian could not resolve one exact installed generation for the managed launch.",t.json,c.length===0?"guardian_launch_install_not_found":"guardian_launch_install_ambiguous");let u=c[0].lifecycle,d=await Dr(u.receipt);if(d.status!=="verified")return x({status:"blocked",reasonCode:d.reasonCode,skillSlug:r,agent:o,scope:i.scope,nextAction:"install",nextStep:"Repair or reinstall the exact generation before starting a managed Guardian session."},"Guardian refused to launch from a stale or changed local generation.",t.json,d.reasonCode);let p=await Ya({backend:n,skillSlug:r,agentId:o,scope:i.scope,flags:t,enforceRequired:!0});if(p)return p;let m=await zn(n,i.scope),h=(Be(m,"hooks")??[]).filter(j).find(N=>f(N,"agent")===o&&f(N,"scope")===i.scope&&N.active===!0&&N.strictPreActionBlocking===!0&&N.exactActivationVerified===!0);if(!h)return x({status:"blocked",reasonCode:"guardian_launcher_route_unavailable",agent:o,nextAction:"guardian.hook.status",nextStep:"Install and verify the Guardian activation route before launching."},"Guardian refused to launch because the verified hook route is unavailable.",t.json,"guardian_launcher_route_unavailable");let g=k(t.hostVersion)??f(h,"hostVersion")??"unverified",y;try{y=await JU(s,n,fr(n.platform))}catch(N){return E(ve(N),t.json)}let v=Ge(32).toString("base64url"),b=n.now(),w={version:1,launchId:`guardian_launch_${Ge(12).toString("hex")}`,tokenSha256:`sha256:${Ue("sha256").update(v,"utf8").digest("hex")}`,scope:i.scope,agentId:o,hostVersion:g,skillSlug:r,generationId:u.receipt.generation.generationId,receiptSha256:Vr(u.receipt),status:"pending",createdAt:b,expiresAt:new Date(Date.parse(b)+15*6e4).toISOString()};await rae(n,i.scope,w);let _=await new Promise((N,T)=>{let X=UM(y,e.slice(2),{cwd:n.cwd,env:{...n.env,SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN:v,SKILLS_LAYER_GUARDIAN_LAUNCH_SCOPE:i.scope},stdio:"inherit"});X.once("error",T),X.once("exit",(G,ee)=>N({exitCode:G??1,signal:ee}))}).catch(async N=>{throw await IM(n,i.scope,w.launchId).catch(()=>{}),N}),P=(await UU(n,i.scope)).launches[w.launchId]?.status==="associated";return await IM(n,i.scope,w.launchId).catch(()=>{}),R({status:P?"managed_session_completed":"host_exited_before_association",launchId:w.launchId,skillSlug:r,agent:o,scope:i.scope,generationId:w.generationId,hostExitCode:_.exitCode,hostSignal:_.signal,associationObserved:P,nextAction:"guardian.status",nextStep:P?"The one-time launch authority was consumed by the exact host session; inspect per-target Guardian status for the resulting association.":"The host exited before its hook completed an exact active Guardian association. The one-time authority was discarded and is not strict-session evidence."},P?"Managed Guardian host session completed.":"The managed host exited without an observed Guardian session association.",t.json,n)}async function Zse(e,t){let n=Xa(k(e.scope)),r=k(e.agent);if(n.status==="invalid"||!r||!vr(r))return it(r&&vr(r)?r:"codex","deny","Guardian hook configuration is invalid.");let i=Re(t.env.SKILLS_LAYER_GUARDIAN_HOOK_PAYLOAD_BASE64);if(!i||i.length>512*1024)return it(r,"deny","Guardian could not read the bounded host event.");let o;try{o=JSON.parse(Buffer.from(i,"base64url").toString("utf8"))}catch{return it(r,"deny","Guardian could not parse the host event.")}let s=hd(r,o);if(s)return await xM({agentId:r,scope:n.scope,observation:s,rawPayload:o,flags:e,backend:t});let a=NU(r,o);if(!a)return it(r,"deny","Guardian could not bind this event to the host session.");let l=Re(t.env.SKILLS_LAYER_GUARDIAN_LAUNCH_TOKEN);if(l){let h=await iae(t,n.scope,l,r,t.now());if(!h)return it(r,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token.");let g=h.launch;if(h.disposition==="associated"){let y;try{y=await Vo(t,n.scope)}catch{return it(r,"deny","Guardian session association evidence is unreadable.")}let v=pl(y,{agentId:r,sessionId:a,asOf:t.now()}),b=v.associations.length===1?v.associations[0]:void 0;return!b||tt(b)!==g.associationKey?it(r,"deny","Guardian rejected an invalid, expired, replayed, or host-mismatched managed launch token."):await FP({agentId:r,scope:n.scope,lookup:v,rawPayload:o,backend:t})}return await xM({agentId:r,scope:n.scope,observation:{sessionId:a,skillReference:g.skillSlug,referenceKind:"slug",source:"approved_launcher",evidence:`approved-launcher:${g.launchId}`},expectedReceiptSha256:g.receiptSha256,expectedGenerationId:g.generationId,managedLaunchId:g.launchId,qualificationCandidate:g.qualificationOnly===!0,rawPayload:o,flags:e,backend:t})}let c;try{c=await Vo(t,n.scope)}catch{return it(r,"deny","Guardian session association evidence is unreadable.")}let u=pl(c,{agentId:r,sessionId:a,asOf:t.now()});if(u.status!=="unrelated")return await FP({agentId:r,scope:n.scope,lookup:u,rawPayload:o,backend:t});let d=await ke(qU(t,n.scope));if(!d||d.version!==1||d.agentId!==r)return await sae(t,n.scope,r)?it(r,"deny",`Guardian requires \`skills-layer guardian launch <skill> --agent ${r} --scope ${n.scope} -- <host>\` because this host has no trustworthy native skill-activation signal.`):it(r,"allow","No Skills Layer skill session is bound; unrelated host activity remains outside Guardian.");let p=await ke(MP(t,n.scope));if(!Xse(p,d,a,t.now()))try{let h=await D(t,"/api/v1/guardian/sessions",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({skillSlug:d.skillSlug,version:d.skillVersion,...d.workspaceId?{workspaceId:d.workspaceId}:{},agentId:r,platform:t.platform,hostVersion:d.hostVersion,sessionId:a,requestedPreference:d.requestedPreference})}),g=L(h,"envelope"),y=GU(h,"publicKeys");if(!g||!y)throw new Error("Guardian session authority returned an invalid envelope.");p={version:1,envelope:g,publicKeys:y,savedAt:t.now()},await Ve(MP(t,n.scope),p)}catch{return it(r,"deny","Guardian could not obtain current signed skill-session authority.")}await Qse({binding:d,sessionId:a,cache:p,backend:t}).catch(()=>{});let m=await fy({agentId:r,platform:t.platform==="darwin"||t.platform==="linux"||t.platform==="win32"?t.platform:"linux",hostVersion:d.hostVersion,rawPayload:o,attributionEnvelope:p.envelope,attributionPublicKeys:p.publicKeys,now:t.now(),evaluate:async h=>jU(h,d,t)});return{exitCode:m.exitCode,stdout:m.stdout,stderr:m.stderr}}async function xM(e){let t;try{t=await eae(e.observation,e.agentId,e.backend)}catch(c){return Di(e.agentId,e.observation,"deny",ve(c))}let n=Vr(t.receipt);if(e.expectedReceiptSha256&&e.expectedReceiptSha256!==n||e.expectedGenerationId&&e.expectedGenerationId!==t.receipt.generation.generationId)return Di(e.agentId,e.observation,"deny","Guardian managed launch no longer matches the exact installed generation.");if(!t.workspaceId&&(t.requestedPreference===null||t.requestedPreference==="disabled"))return Di(e.agentId,e.observation,"allow","Guardian is not enabled for this Personal skill; no runtime association was created.");let r=t.requestedPreference??"enforce",i=Gn(e.agentId),o=tae(e.agentId,e.rawPayload,e.flags)??"unverified",s=e.backend.now(),a={version:2,revision:1,state:"pending_authority",scope:e.scope,agentId:e.agentId,hostVersion:o,sessionId:e.observation.sessionId,skillSlug:t.skillSlug,skillVersion:t.receipt.generation.semanticVersion,generationId:t.receipt.generation.generationId,receiptSha256:n,...t.workspaceId?{workspaceId:t.workspaceId}:{},requestedPreference:r,activationSource:e.observation.source,activationEvidence:e.observation.evidence,adapterRevision:i.adapterRevision,createdAt:s,updatedAt:s},l;try{l=await zU(e.backend,e.scope,a)}catch{return Di(e.agentId,e.observation,CM(a),"Guardian could not safely record this exact skill-session association.")}try{let c=await FU(l,e.backend),u=e.backend.now(),d=ul({envelope:c.cache.envelope,publicKeys:c.cache.publicKeys,expectedAgentId:e.agentId,expectedPlatform:fr(e.backend.platform),now:u});if(d.skillSlug!==l.skillSlug||d.version!==l.skillVersion||d.generationId!==l.generationId||d.sessionId!==l.sessionId||d.workspaceId!==l.workspaceId)throw new Error("Guardian Cloud authority did not match the exact local association.");let p=await zn(e.backend,e.scope),m=Be(p,"hooks")?.filter(j).find(_=>f(_,"agent")===e.agentId&&_.active===!0),h=l.requestedPreference==="warning_only"?"warning":l.requestedPreference,g=d.workspaceRequiredMode===null?null:{requiredMode:d.workspaceRequiredMode,revision:c.policyRevision,updatedBy:"skills-layer-cloud",updatedAt:d.issuedAt},y=Jse({enabled:e.qualificationCandidate===!0,managedLaunchId:e.managedLaunchId,agentId:e.agentId,exactHook:m,env:e.backend.env}),v=yl({evaluationContext:"activation_eligibility",requestedMode:h,workspacePolicy:g,hostSupported:wr(e.agentId)?.maximumTier==="strict_candidate",hookInstalled:!!m,strictHookVerified:y||m?.strictPreActionBlocking===!0,exactActivationVerified:y||m?.exactActivationVerified===!0,completeWrapperVerified:!1,associationState:"pending_authority",materializationState:"active"});if(!v.activationAllowed)return await jo(e.backend,e.scope,tt(l),{state:"stale",reasonCode:v.reasonCode,updatedAt:s}),Di(e.agentId,e.observation,"deny",`Guardian refused activation because verified enforcement is unavailable (${v.reasonCode}).`);let b=await jo(e.backend,e.scope,tt(l),{state:"active",trustLedgerId:c.trustLedgerId,attributionExpiresAt:d.expiresAt,updatedAt:u}),w=tt(b);return await mA(e.backend,e.scope,w,c.cache),!e.managedLaunchId&&ls(e.backend.env)==="missing_attribution"?(await jo(e.backend,e.scope,w,{state:"stale",reasonCode:"phase149_missing_attribution_canary",updatedAt:u}),await lae(e.backend,e.scope,w),Di(e.agentId,e.observation,"allow","Guardian qualification removed signed attribution after exact activation.")):(e.managedLaunchId&&await oae(e.backend,e.scope,e.managedLaunchId,w),await hE(e.backend.env),e.managedLaunchId?await FP({agentId:e.agentId,scope:e.scope,lookup:{status:"active",associations:[b]},rawPayload:e.rawPayload,backend:e.backend}):Di(e.agentId,e.observation,"allow",v.label==="warning_only"?"Guardian warning-only activation is associated with this exact installed generation; it is not counted as strict enforcement.":"Guardian associated this host session with the exact installed generation."))}catch(c){return await jo(e.backend,e.scope,tt(l),{state:"pending_authority",reasonCode:"guardian_session_authority_unavailable",updatedAt:s}).catch(()=>{}),Di(e.agentId,e.observation,BP(c)?"deny":CM(l),l.requestedPreference==="warning_only"&&!l.workspaceId&&!BP(c)?"Guardian warning-only activation continued without runtime authority; protection is diagnostic only.":`Guardian could not establish exact skill-session authority (${ve(c)}).`)}}function Jse(e){if(!e.enabled||!e.managedLaunchId?.startsWith("guardian_launch_phase149_")||wr(e.agentId)?.automaticAssociation!=="approved_launcher_required"||e.exactHook?.active!==!0||e.exactHook.configActive!==!0||e.exactHook.evidenceCapability!=="unverified")return!1;let t=Be(e.exactHook,"evidenceReasons");return t?.length!==1||t[0]!=="live_canary_evidence_missing"?!1:ls(e.env)!==null}async function FP(e){if(e.lookup.status==="ambiguous")return it(e.agentId,"deny","Guardian found multiple active skill associations for this host session.");let t=e.lookup.associations[0];if(!t)return it(e.agentId,"deny","Guardian expected an exact association but could not load it.");if(e.lookup.status==="terminal")return it(e.agentId,"deny","Guardian blocked a session whose exact skill was removed or detached.");if(e.lookup.status==="expected_missing_authority")return it(e.agentId,t.requestedPreference==="warning_only"&&!t.workspaceId?"allow":"deny",t.requestedPreference==="warning_only"&&!t.workspaceId?"Guardian warning only: exact runtime authority is missing; this is not strict enforcement.":"Guardian blocked an expected skill session because exact runtime authority is missing.");let n=await nae(t,e.backend);if(n.status!=="verified")return await jo(e.backend,e.scope,tt(t),{state:n.state,reasonCode:n.reasonCode,updatedAt:e.backend.now()}).catch(()=>{}),it(e.agentId,"deny","Guardian blocked this session because the exact installed generation is no longer current.");let r=await cae(e.backend,e.scope,tt(t));if(e.lookup.status==="active_authority_stale"||!uae(r,t,e.backend.now()))try{let a=await FU(t,e.backend);r=a.cache;let l=ul({envelope:r.envelope,publicKeys:r.publicKeys,expectedAgentId:e.agentId,expectedPlatform:fr(e.backend.platform),now:e.backend.now()});await jo(e.backend,e.scope,tt(t),{state:"active",trustLedgerId:a.trustLedgerId,attributionExpiresAt:l.expiresAt,updatedAt:e.backend.now()}),await mA(e.backend,e.scope,tt(t),r)}catch(a){let l=t.requestedPreference==="warning_only"&&!t.workspaceId&&!BP(a);return it(e.agentId,l?"allow":"deny",l?"Guardian warning only: signed runtime authority could not be refreshed.":"Guardian blocked this action because signed runtime authority could not be refreshed.")}let i={version:1,scope:t.scope,skillSlug:t.skillSlug,skillVersion:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},agentId:e.agentId,hostVersion:t.hostVersion,requestedPreference:t.requestedPreference,boundAt:t.createdAt},o=!1,s=await fy({agentId:e.agentId,platform:fr(e.backend.platform),hostVersion:t.hostVersion,rawPayload:e.rawPayload,attributionEnvelope:r.envelope,attributionPublicKeys:r.publicKeys,now:e.backend.now(),evaluate:async a=>{let l=await jU(a,i,e.backend);return o=l.delegatedExecution===!0,l}});return o&&await yE({agentId:e.agentId,scope:e.scope,skillSlug:t.skillSlug,associationKey:tt(t),env:e.backend.env}),{exitCode:s.exitCode,stdout:s.stdout,stderr:s.stderr,...o?{[TU]:!0}:{}}}async function jU(e,t,n){if(e.action.actionFamily==="shell_execution"||e.action.actionFamily==="generated_code_execution"){let i=await zn(n,t.scope),o=(Be(i,"hooks")??[]).filter(j).find(c=>f(c,"agent")===t.agentId&&f(c,"scope")===t.scope&&c.active===!0&&c.configActive===!0&&typeof f(c,"absoluteCliPath")=="string"),s=o?f(o,"absoluteCliPath"):void 0,a=ls(n.env)?kE:void 0;if(s&&e.action.command&&wE({command:e.action.command,cliPath:s,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:fr(n.platform),...a?{approvedEnvironmentKeys:a}:{}}))return{decision:"allow",reason:"Guardian delegated this exact shell action to the atomic guarded execution wrapper.",delegatedExecution:!0};let l=s?bE({cliPath:s,runtimeExecutablePath:process.execPath,skillSlug:t.skillSlug,platform:fr(n.platform),...a?{approvedEnvironmentKeys:a}:{}}):null;return{decision:"deny",reason:l&&l.length<=800?`Use the exact guarded command prefix: ${l} <command>`:"Use the exact Skills Layer Guardian execution wrapper for one-action guarded shell or generated-code execution."}}let r=Yse(e);if(r.length===0)return{decision:"deny",reason:"Guardian has no exact action mapping for this host event."};for(let i of r){let o=await D(n,"/api/v1/guardian/enforce",{method:"POST",headers:V(n.apiKey,n.authBlockedMessage),signal:AbortSignal.timeout(7500),body:JSON.stringify({skillSlug:t.skillSlug,version:t.skillVersion,...t.workspaceId?{workspaceId:t.workspaceId}:{},guardianPreference:t.requestedPreference,telemetryMode:(t.workspaceId,"cloud_managed"),action:i})});if(L(o,"enforcement")?.canExecute!==!0)return{decision:"deny",reason:`Guardian denied this exact action (${Ah(o)}).`}}return{decision:"allow",reason:"Guardian allowed the exact attributed host action."}}function Yse(e){let t={strictActionSha256:e.actionSha256,toolInputSha256:e.action.toolInputSha256,adapterRevision:e.adapterRevision,host:e.action.host};switch(e.action.actionFamily){case"filesystem_read":case"filesystem_write":return e.action.fileTargets.map(n=>({type:e.action.actionFamily==="filesystem_read"?"file_read":"file_write",path:n,metadata:t}));case"network_access":return e.action.networkTargets.map(n=>({type:"network_request",url:n,metadata:t}));case"browser_access":return[{type:"browser_action",target:e.action.toolName,metadata:t}];case"device_control":return[{type:"device_action",target:e.action.toolName,metadata:t}];case"api_access":return[{type:"api_call",target:e.action.toolName,metadata:t}];default:return[]}}function it(e,t,n){let r=ns(e,{decision:t,reason:n});return{exitCode:r.exitCode,stdout:r.stdout,stderr:r.stderr}}function NU(e,t){if(!j(t))return null;let n=e==="cline"?t.taskId:e==="cursor"?t.conversation_id:e==="windsurf"?t.trajectory_id:e==="antigravity"||e==="antigravity-cli"?t.conversationId:t.session_id;return typeof n=="string"&&/^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,255}$/u.test(n)?n:null}function Xse(e,t,n,r){if(!e||e.version!==1||!j(e.envelope)||!j(e.envelope.claims))return!1;let i=e.envelope.claims;return i.agentId===t.agentId&&i.sessionId===n&&i.skillSlug===t.skillSlug&&i.version===t.skillVersion&&i.workspaceId===t.workspaceId&&typeof i.expiresAt=="string"&&Date.parse(i.expiresAt)>Date.parse(r)+5e3}async function Qse(e){let t=(await lt(e.backend)).installs[e.binding.skillSlug],n=qn(t,{scope:e.binding.scope,agent:e.binding.agentId}).filter(a=>a.lifecycle?.receipt.generation.semanticVersion===e.binding.skillVersion),r=n.length===1?n[0].lifecycle:null;if(!r||r.state!=="active"||r.receipt.generation.semanticVersion!==e.binding.skillVersion||(await Dr(r.receipt)).status!=="verified")return;let o=ul({envelope:e.cache.envelope,publicKeys:e.cache.publicKeys,expectedAgentId:e.binding.agentId,expectedPlatform:fr(e.backend.platform),now:e.backend.now()});if(o.sessionId!==e.sessionId||o.generationId!==r.receipt.generation.generationId||o.skillSlug!==e.binding.skillSlug||o.version!==e.binding.skillVersion)return;let s=await zU(e.backend,e.binding.scope,{version:2,revision:1,state:"active",scope:e.binding.scope,agentId:e.binding.agentId,hostVersion:e.binding.hostVersion,sessionId:e.sessionId,skillSlug:e.binding.skillSlug,skillVersion:e.binding.skillVersion,generationId:r.receipt.generation.generationId,receiptSha256:Vr(r.receipt),...e.binding.workspaceId?{workspaceId:e.binding.workspaceId}:{},requestedPreference:e.binding.requestedPreference,activationSource:"manual_recovery",activationEvidence:`legacy-bind:${e.binding.boundAt}`,adapterRevision:Gn(e.binding.agentId).adapterRevision,trustLedgerId:e.cache.envelope.version===2?e.cache.envelope.claims.trustLedgerId:"legacy_local",attributionExpiresAt:o.expiresAt,createdAt:e.binding.boundAt,updatedAt:e.backend.now()});await mA(e.backend,e.binding.scope,tt(s),e.cache)}async function eae(e,t,n){let r=await lt(n),i=Object.entries(r.installs).flatMap(([u,d])=>An(d).flatMap(p=>{let m=p.lifecycle;if(!m||m.state!=="active")return[];if(!mr(p.record).includes(t))return[];if(e.referenceKind==="slug"){if(e.skillReference!==u&&e.skillReference!==m.receipt.generation.skillSlug)return[]}else{let h=qo(m.receipt.targetDir),g=qo(e.skillReference),y=Bu(h,g);if(y.startsWith("..")||st.isAbsolute(y)||Lt.isAbsolute(y))return[]}return[{skillSlug:u,record:gr(d,p),lifecycle:m}]}));if(i.length!==1)throw new Error(i.length===0?"Guardian activation did not resolve to an owned exact installed generation.":"Guardian activation matched more than one installed generation.");let o=i[0],s=await Dr(o.lifecycle.receipt);if(s.status!=="verified")throw new Error(`Guardian activation receipt verification failed (${s.reasonCode}).`);let a=f(o.record,"workspaceId")??f(o.record,"workingModeWorkspaceId"),l=await rd(n,o.skillSlug),c=l===void 0?a?"enforce":null:VU(l);if(l!==void 0&&c===null)throw new Error("Guardian activation preference is invalid.");return{skillSlug:o.skillSlug,record:o.record,receipt:o.lifecycle.receipt,requestedPreference:c,...a?{workspaceId:a}:{}}}async function FU(e,t){let n=await D(t,"/api/v1/guardian/sessions",{method:"POST",headers:V(t.apiKey,t.authBlockedMessage),body:JSON.stringify({skillSlug:e.skillSlug,version:e.skillVersion,...e.workspaceId?{workspaceId:e.workspaceId}:{},agentId:e.agentId,platform:fr(t.platform),hostVersion:e.hostVersion,sessionId:e.sessionId,requestedPreference:e.requestedPreference})}),r=L(n,"envelope"),i=GU(n,"publicKeys"),o=L(n,"ledger"),s=o?f(o,"ledgerId"):void 0;if(!r||!i||!s)throw new Error("Guardian session authority returned an invalid exact-generation envelope.");return{cache:{version:1,envelope:r,publicKeys:i,savedAt:t.now()},trustLedgerId:s,policyRevision:r.version===2?r.claims.policyRevision:1}}function CM(e){return e.requestedPreference==="warning_only"&&!e.workspaceId?"allow":"deny"}function BP(e){return e instanceof Z?e.status<500:!ve(e).startsWith("Unable to reach ")}function Di(e,t,n,r){return t.source==="claude_user_prompt_expansion"?n==="deny"?{exitCode:2,stdout:"",stderr:r}:{exitCode:0,stdout:"",stderr:""}:it(e,n,r)}function tae(e,t,n){let r=k(n.hostVersion);if(r)return r;if(!j(t))return null;let i=e==="cline"?t.clineVersion:e==="cursor"?t.cursor_version:t.host_version;return typeof i=="string"&&/^[0-9A-Za-z][0-9A-Za-z.+_-]{0,127}$/u.test(i)?i:null}function fr(e){return e==="darwin"||e==="win32"?e:"linux"}async function nae(e,t){let n=(await lt(t)).installs[e.skillSlug],r=qn(n,{receiptSha256:e.receiptSha256}),i=r.length===1?r[0].lifecycle:null;if(!i)return{status:"invalid",state:"externally_removed",reasonCode:"exact_install_record_absent"};if(i.receipt.generation.semanticVersion!==e.skillVersion||i.receipt.generation.generationId!==e.generationId||Vr(i.receipt)!==e.receiptSha256)return{status:"invalid",state:"stale",reasonCode:"exact_generation_replaced"};try{await Xu(i.receipt.targetDir)}catch(s){return s.code==="ENOENT"?{status:"invalid",state:"externally_removed",reasonCode:"exact_target_absent"}:{status:"invalid",state:"stale",reasonCode:"exact_target_unreadable"}}let o=await Dr(i.receipt);return o.status==="verified"?{status:"verified"}:{status:"invalid",state:"stale",reasonCode:o.reasonCode}}function BU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-associations.json"):K(e.cwd,".skills-layer","guardian-session-associations.json")}function MU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-managed-launches.json"):K(e.cwd,".skills-layer","guardian-managed-launches.json")}async function UU(e,t){let n=await ke(MU(e,t));if(!j(n)||n.version!==1||!Number.isSafeInteger(n.revision)||Number(n.revision)<0||!j(n.launches))return{version:1,revision:0,launches:{}};let r=Object.fromEntries(Object.entries(n.launches).flatMap(([i,o])=>{if(!j(o))return[];let s=f(o,"agentId"),a=f(o,"scope"),l=f(o,"tokenSha256"),c=f(o,"receiptSha256"),u=f(o,"status"),d=o;return d.version!==1||d.launchId!==i||s!=="codex"&&s!=="kiro-cli"||a!==t||!l||!/^sha256:[a-f0-9]{64}$/u.test(l)||!c||!/^sha256:[a-f0-9]{64}$/u.test(c)||u!=="pending"&&u!=="claimed"&&u!=="associated"||o.qualificationOnly!==void 0&&o.qualificationOnly!==!0||!f(o,"hostVersion")||!f(o,"skillSlug")||!f(o,"generationId")||u==="associated"&&!f(o,"associationKey")||!f(o,"createdAt")||!f(o,"expiresAt")||!Number.isFinite(Date.parse(d.createdAt))||!Number.isFinite(Date.parse(d.expiresAt))?[]:[[i,d]]}));return{version:1,revision:Number(n.revision),launches:r}}async function td(e,t,n){let r=MU(e,t);await Zo(Me(r));let i=`${r}.lock`,o=null;for(let s=0;s<50&&!o;s+=1)try{o=await Uo(i,"wx",384)}catch(a){if(a.code!=="EEXIST"||s===49)throw a;await e.sleep(10)}if(!o)throw new Error("Guardian managed launch lock is unavailable.");try{let s=await UU(e,t),a=n(s);return await nd(r,a.store),a.value}finally{await o.close().catch(()=>{}),await We(i,{force:!0}).catch(()=>{})}}async function rae(e,t,n){await td(e,t,r=>({store:{version:1,revision:r.revision+1,launches:{...r.launches,[n.launchId]:n}},value:void 0}))}async function IM(e,t,n){await td(e,t,r=>{let i={...r.launches};return delete i[n],{store:{version:1,revision:r.revision+1,launches:i},value:void 0}})}async function iae(e,t,n,r,i){if(n.length<32||n.length>256||!/^[A-Za-z0-9_-]+$/u.test(n))return null;let o=`sha256:${Ue("sha256").update(n,"utf8").digest("hex")}`;return await td(e,t,s=>{let a=Object.values(s.launches).filter(d=>(d.status==="pending"||d.status==="associated")&&d.tokenSha256===o&&d.agentId===r&&(d.status==="associated"||Date.parse(d.expiresAt)>Date.parse(i))),l=a.length===1?a[0]:void 0,c=l?.status==="pending"?{...l,status:"claimed"}:l,u=Object.fromEntries(Object.entries(s.launches).flatMap(([d,p])=>p.status!=="associated"&&Date.parse(p.expiresAt)<=Date.parse(i)?[]:[[d,p.launchId===c?.launchId?c:p]]));return{store:{version:1,revision:s.revision+1,launches:u},value:c?{disposition:l?.status==="pending"?"claimed":"associated",launch:c}:null}})}async function oae(e,t,n,r){await td(e,t,i=>{let o=i.launches[n];if(!o||o.status!=="claimed")throw new Error("Guardian managed launch is not in the claimed state.");return{store:{version:1,revision:i.revision+1,launches:{...i.launches,[n]:{...o,status:"associated",associationKey:r}}},value:void 0}})}async function sae(e,t,n){if(wr(n)?.automaticAssociation!=="approved_launcher_required")return!1;let r=await lt(e);for(let[i,o]of Object.entries(r.installs)){let s=qn(o,{scope:t,agent:n});for(let a of s){if(a.lifecycle?.state!=="active"&&a.lifecycle?.state!=="pending_activation")continue;let l=gr(o,a);if(f(l,"workspaceId")??f(l,"workingModeWorkspaceId"))return!0;let u=await rd(e,i);if(u==="enforce"||u==="enabled")return!0}}return!1}function Oh(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-authorities.json"):K(e.cwd,".skills-layer","guardian-session-authorities.json")}async function Vo(e,t){let n=await ke(BU(e,t));return n===null?JR():YR(n)}async function fA(e,t,n){let r=BU(e,t);await Zo(Me(r));let i=`${r}.lock`,o=null;try{o=await Uo(i,"wx",384);let s=await Vo(e,t),a=n(s);return await nd(r,a.index),a.value}finally{await o?.close().catch(()=>{}),await We(i,{force:!0}).catch(()=>{})}}async function zU(e,t,n){return await fA(e,t,r=>{let i=XR(r,n,r.revision),o=i.associations[tt(n)];return{index:i,value:o}})}async function jo(e,t,n,r){return await fA(e,t,i=>{let o=QR(i,{key:n,expectedIndexRevision:i.revision,...r});return{index:o,value:o.associations[n]}})}async function aae(e,t){let n=0;for(let r of["project","global"]){let i=await fA(e,r,o=>{let s=eE(o,{...t,expectedIndexRevision:o.revision});return{index:s.index,value:s.removedKeys}});if(n+=i.length,i.length>0){let o=Oh(e,r),s=await Lh(e,r),a=new Set(i);await nd(o,{version:1,revision:s.revision+1,authorities:Object.fromEntries(Object.entries(s.authorities).filter(([l])=>!a.has(l)))})}await td(e,r,o=>({store:{version:1,revision:o.revision+1,launches:Object.fromEntries(Object.entries(o.launches).filter(([,s])=>s.skillSlug!==t.skillSlug||s.generationId!==t.generationId||s.receiptSha256!==t.receiptSha256))},value:void 0}))}return n}async function Lh(e,t){let n=await ke(Oh(e,t));return!j(n)||n.version!==1||!Number.isSafeInteger(n.revision)||!j(n.authorities)?{version:1,revision:0,authorities:{}}:{version:1,revision:Number(n.revision),authorities:Object.fromEntries(Object.entries(n.authorities).filter(r=>{let i=r[1];return j(i)&&i.version===1&&j(i.envelope)&&j(i.publicKeys)&&typeof i.savedAt=="string"}))}}async function mA(e,t,n,r){let i=Oh(e,t),o=await Lh(e,t);await nd(i,{version:1,revision:o.revision+1,authorities:{...o.authorities,[n]:r}})}async function lae(e,t,n){let r=Oh(e,t),i=await Lh(e,t),o={...i.authorities};delete o[n],await nd(r,{version:1,revision:i.revision+1,authorities:o})}async function cae(e,t,n){return(await Lh(e,t)).authorities[n]??null}function uae(e,t,n){if(!e||e.version!==1||!j(e.envelope)||!j(e.envelope.claims))return!1;let r=e.envelope.claims;return r.agentId===t.agentId&&r.sessionId===t.sessionId&&r.skillSlug===t.skillSlug&&r.version===t.skillVersion&&r.generationId===t.generationId&&r.workspaceId===t.workspaceId&&typeof r.expiresAt=="string"&&Date.parse(r.expiresAt)>Date.parse(n)+5e3}async function nd(e,t){let n=Me(e);await Zo(n);let r=K(n,`.${ot(e)}.${Ge(12).toString("hex")}.tmp`),i=null;try{i=await Uo(r,"wx",384),await i.writeFile(`${JSON.stringify(t,null,2)}
|
|
2167
|
+
`,"utf8"),await i.sync(),await i.close(),i=null,await zo(r,e),await Jo(e,384),await SA(n)}finally{await i?.close().catch(()=>{}),await We(r,{force:!0}).catch(()=>{})}}function qU(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session-binding.json"):K(e.cwd,".skills-layer","guardian-session-binding.json")}function MP(e,t){return t==="global"?K(e.paths.stateDir,"guardian-session.json"):K(e.cwd,".skills-layer","guardian-session.json")}function VU(e){return!e||e==="enforce"||e==="enabled"?"enforce":e==="warning"||e==="warning-only"||e==="warning_only"?"warning_only":e==="disabled"||e==="off"?"disabled":null}function GU(e,t){let n=e[t];if(!j(n))return null;let r=Object.entries(n);return r.every(([,i])=>typeof i=="string")?Object.fromEntries(r):null}async function zn(e,t){let n=t?[t]:["project","global"],r=[],i=new Set;for(let l of n){let c=ez(e,l);if(i.has(c))continue;i.add(c);let u=await tz(c);for(let d of u.hooks){let p=f(d,"hookPath"),m=p?zP(e,l,p):null,h=f(d,"configPath"),g=h?zP(e,l,h):null,y=m?await pr(m):!1,v=g?await pr(g):null,b=y?v===!1?"active_missing_config":"active":"stale_missing_hook",w=await dae({backend:e,scope:l,hook:d,absoluteHookPath:m,absoluteConfigPath:g,hookActive:y,configActive:v});r.push({hookId:f(d,"hookId")??$t,hookName:f(d,"hookName")??xt,...d,scope:f(d,"scope")??l,hookPath:m??p??null,configPath:g??h??null,active:y,configActive:v,hookState:b,strictPreActionBlocking:w.capability==="strict",exactActivationVerified:w.exactActivationVerified,activationRoute:w.activationRoute,evidenceCapability:w.capability,evidenceReasons:w.reasons,nextStep:!y||v===!1?`Run skills-layer guardian hook install --agent ${String(d.agent)} --scope ${l}.`:w.capability!=="strict"?"This hook is installed but not strict-verified. Standard workspaces permit installation with a warning. For strict workspaces, ask your Admin for an adapter with current matching real-host canary evidence; hook install does not create that evidence.":"Strict host evidence is current. Install the approved skill using this exact agent and scope.",evidencePath:w.evidencePath,qualifiedHostExecutablePath:w.qualifiedHostExecutablePath,qualifiedHostExecutableSha256:w.qualifiedHostExecutableSha256})}}let o=r.filter(l=>l.active===!0).length,s=r.filter(l=>l.active===!1).length,a=o>0?0:s;return{status:"ok",enforcementLayer:r.some(l=>l.active===!0&&l.strictPreActionBlocking===!0)?"native_hook":o>0?"native_hook_candidate":"not_installed",strictPreActionBlocking:r.some(l=>l.active===!0&&l.strictPreActionBlocking===!0),exactActivationVerified:r.some(l=>l.active===!0&&l.strictPreActionBlocking===!0&&l.exactActivationVerified===!0),activeHookCount:o,missingHookCount:a,staleHookCount:s,hooks:r,setup:await hA(e),warnings:s>0?o>0?["One or more stale Guardian hook records were found, but an active Skills Layer Security Hook is installed."]:["One or more configured Guardian hooks are missing from disk. Run skills-layer guardian hook install --agent <agent> again to repair them."]:[]}}async function dae(e){let t=f(e.hook,"agent"),n=f(e.hook,"hostVersion"),r=f(e.hook,"adapterRevision"),i=f(e.hook,"absoluteCliPath"),o=f(e.hook,"evidencePath"),s=o?zP(e.backend,e.scope,o):null;if(!t||!vr(t))return{capability:"unverified",reasons:["strict_adapter_unavailable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(wr(t)?.maximumTier!=="strict_candidate")return{capability:"unverified",reasons:["host_strict_tier_unavailable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(!e.hookActive||e.configActive!==!0||!e.absoluteHookPath||!e.absoluteConfigPath)return{capability:"unverified",reasons:["hook_installation_incomplete"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};if(!n||!r||!i||!s)return{capability:"unverified",reasons:["hook_binding_metadata_missing"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};let a=await ke(s);if(!a)return{capability:"unverified",reasons:["live_canary_evidence_missing"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null};try{let l=await pE({agentId:t,platform:fr(e.backend.platform),hostVersion:n,adapterRevision:r,hookConfigPath:e.absoluteConfigPath,hookScriptPath:e.absoluteHookPath,absoluteCliPath:i}),c=dE({evidence:a,currentBinding:l,asOf:e.backend.now()}),u=wr(t),d=c.capability==="strict"&&(u.automaticAssociation==="native_activation"?a.activationRoute==="native_activation":u.automaticAssociation==="approved_launcher_required"&&a.activationRoute==="approved_launcher");return{capability:d?c.capability:"unverified",reasons:d?c.reasons:[...c.reasons,"activation_route_does_not_match_host_capability"],evidencePath:s,exactActivationVerified:d,activationRoute:a.activationRoute,qualifiedHostExecutablePath:a.qualification.hostExecutablePath,qualifiedHostExecutableSha256:a.qualification.hostExecutableSha256}}catch{return{capability:"unverified",reasons:["current_installation_binding_unverifiable"],evidencePath:s,exactActivationVerified:!1,activationRoute:null,qualifiedHostExecutablePath:null,qualifiedHostExecutableSha256:null}}}async function HU(e,t){if(e.json){let c=await ke(t.paths.mcpConfigPath),u=c&&Array.isArray(c.clientIds)?c.clientIds.filter(p=>typeof p=="string"):c&&f(c,"clientId")?[f(c,"clientId")]:[],d=await az(t,u);return R({setup:await hA(t),mcp:{status:c?"mcp_configured":"mcp_not_configured",configured:!!c,clientId:u[0],clientIds:u,hosts:d,mcpUrl:c?f(c,"mcpUrl"):void 0,readiness:c?{status:"configured_needs_agent_reload",verifyCommand:u.length===1?`skills-layer mcp verify --client ${u[0]}`:"skills-layer mcp verify",nextStep:"Open a fresh agent session if Skills Layer tools are not visible yet."}:void 0,nextCommand:c?"skills-layer mcp verify":"skills-layer mcp setup"},guardian:await zn(t)},"Setup status loaded.",!0,t)}if(!t.stdoutIsTty)return R({status:"setup_needs_terminal",mcp:{nextCommand:"skills-layer mcp setup"},security:{nextCommand:"skills-layer guardian hook install --agent codex --scope project"}},"Setup needs an interactive terminal. Run `skills-layer setup`, or use `skills-layer mcp setup` and `skills-layer guardian hook install --agent codex --scope project`.",!1,t);let n=await t.promptSelect("Set up Skills Layer on this machine?",[{value:"mcp",label:"Setup Skills-Layer MCP",description:"Configure Skills Layer MCP for AI tools"},{value:"security",label:"Setup Skills-Layer Security Guardian",description:"Install Guardian hooks for this workspace"},{value:"both",label:"Setup both - MCP & Security Guardian",description:"Connect supported AI tools and install Guardian hooks"},{value:"not_now",label:"Remind me Later",description:"Skip setup for now; you can run skills-layer setup later"}]);if(n==="not_now"){let c={version:1,setupChoice:"not_now",mcpChoice:"not_now",mcpPromptedAt:t.now(),guardianHookChoice:"not_now",guardianHookPromptedAt:t.now(),remindAfter:mae(t.now(),7)};return await RM(t,c),R({status:"setup_skipped",mcp:{status:"not_configured",nextCommand:"skills-layer mcp setup"},security:{status:"not_configured",nextCommand:"skills-layer guardian hook install --agent codex --scope project"}},"Skills Layer setup skipped for now. Run `skills-layer setup` when you want MCP and Security hooks on this machine.",!1,t)}if(n!=="both"&&n!=="mcp"&&n!=="security")return E(`Unknown setup option "${n}".`,e.json);let r=n==="both"||n==="mcp",i=n==="both"||n==="security",o={status:"setup_complete",setupChoice:n},s={version:1,setupChoice:n,mcpChoice:r?"configured":"not_requested",mcpPromptedAt:t.now(),guardianHookChoice:i?k(e.scope)??"project":"not_requested",guardianHookPromptedAt:t.now()};if(r)if(!t.apiKey)o.mcp={status:"login_required",configured:!1,nextCommand:"skills-layer login"},s.mcpChoice="login_required";else{let c=await XP(e,t);if(fe(c))return c;o.mcp=c}if(i){let c={...e,json:!0,scope:k(e.scope)??"project",agent:k(e.agent)??"codex"},u=await LU(c,t);if(u.exitCode!==0)return u;let d=Wae(u.stdout),p=j(d)?d:{status:"enabled",agent:k(c.agent),scope:k(c.scope)};o.security=p,o.agent=f(p,"agent")??k(c.agent),o.scope=f(p,"scope")??k(c.scope),o.enforcementLayer=f(p,"enforcementLayer")??"native_hook_candidate",o.strictPreActionBlocking=p.strictPreActionBlocking===!0,o.hookPath=f(p,"hookPath"),o.configPath=f(p,"configPath"),o.nextAction="guardian.hook.status",o.nextStep=`Run \`skills-layer guardian hook status --scope ${f(p,"scope")??"project"}\` to inspect the candidate binding. Strict pre-action blocking remains unverified until real host allow/deny canaries pass.`}await RM(t,s);let l=(j(o.mcp)?f(o.mcp,"status"):void 0)==="login_required"?"Skills Layer Security setup complete. MCP setup needs login; run `skills-layer login`, then `skills-layer setup`.":n==="security"?"Skills Layer Security Guardian setup complete.":n==="mcp"?"Skills Layer MCP setup complete. Open a fresh agent session if MCP tools are not visible yet.":"Skills Layer MCP and Security Guardian setup complete. Open a fresh agent session if MCP tools are not visible yet.";return R(o,l,e.json,t)}async function pae(e,t){let n=await zn(t),r=await hA(t),i=J(n,"activeHookCount")??0;if(t.stdoutIsTty&&i===0&&!r)return await HU(e,t);let o=i>0?"Guardian host hooks are already configured. Run `skills-layer guardian hook status` to inspect them.":"Guardian is enabled for Skills Layer runtime checks. Run `skills-layer setup` when you want MCP and Security hooks on this machine.";return{exitCode:0,stdout:`${Lo(t.renderMode)}
|
|
2168
2168
|
|
|
2169
|
-
${o}`,stderr:""}}function fae(e,t){let n=J(e,"activeHookCount")??0,r=J(e,"missingHookCount")??0,i=f(t,"status")??"unknown",o=f(t,"effectiveMode"),s=f(t,"adminPolicy"),a=f(t,"nextAction"),l=f(t,"nextStep"),c=e.strictPreActionBlocking===!0;return n>0&&r===0&&c?{id:"guardian-local-hook",title:"Guardian local hook",status:"pass",summary:`Guardian native hook active count: ${n}.`,enforcementLayer:f(e,"enforcementLayer")??"native_hook",strictPreActionBlocking:c,measuredProtection:"verified_strict",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook status"}:n>0&&r===0?{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian candidate hook active count: ${n}; live strict evidence is not current.`,enforcementLayer:f(e,"enforcementLayer")??"native_hook_candidate",strictPreActionBlocking:!1,measuredProtection:"candidate_unverified",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook status",nextStep:"Run the agent/platform live canaries and inspect Guardian hook status before relying on enforced protection."}:{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian native hook setup needs attention. Active hooks: ${n}; missing hooks: ${r}.`,enforcementLayer:f(e,"enforcementLayer")??"not_installed",strictPreActionBlocking:c,measuredProtection:"unavailable",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook install --agent codex --scope project",nextStep:"Install a Guardian host hook for automatic checks, or route risky shell actions through `skills-layer guardian exec` for strict pre-execution blocking."}}function mae(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?e:(n.setUTCDate(n.getUTCDate()+t),n.toISOString())}async function KU(e){let t=ZU(k(e.flags.unmanagedPolicy)??e.backend.env.SKILLS_LAYER_UNMANAGED_SKILL_POLICY);if(t.status==="invalid")return{status:"invalid",result:R(t.message,e.flags.json)};let n=await WU({skillSlug:e.skillSlug,flags:e.flags,backend:e.backend,unmanagedPolicy:t.policy});if(n.reasonCode==="local_install_target_selection_required")return To({...e,context:n,reasonCode:n.reasonCode,message:"Guardian needs one exact local skill target before it can make an execution decision.",why:"This skill is installed in more than one target and the command did not identify which materialization is active.",nextAction:"guardian.check",nextStep:"Repeat the command with --agent, --scope, or --path so Guardian can bind the decision to one exact installed target."});if(n.unmanaged&&(n.unmanagedPolicy==="allow"||n.allowUnmanagedOnce))return To({...e,context:n,reasonCode:"guardian_unmanaged_atomic_execution_required",message:"Guardian check cannot authorize unmanaged execution.",why:"A diagnostic check cannot safely bind a one-use decision to the exact local process that would consume it.",nextAction:"install",nextStep:"Install or import the exact skill generation, then use `skills-layer guardian exec <skill-slug> -- <command>` for atomic guarded execution."});if(n.unmanaged&&n.unmanagedPolicy==="block")return To({...e,context:n,reasonCode:"unmanaged_skill_blocked",message:"Guardian blocked unmanaged local skill execution.",why:"The skill path is not backed by a public install index or lockfile entry and unmanaged policy is block.",nextAction:"install",nextStep:"Install or import the exact skill generation before requesting a Guardian execution decision."});let r=n.record?Jt(n.record):null;if(r&&r.state!=="active"){let s=r.state==="quarantined"?"skill_quarantined":r.state==="restore_pending"?"skill_restore_pending":r.state==="externally_removed"?"skill_externally_removed":r.state==="host_detached"?"skill_host_detached":r.state==="unreadable"?"skill_target_unreadable":r.state==="drifted"?"installed_artifact_changed":"skill_activation_pending";return To({...e,context:n,reasonCode:s,message:"Guardian blocked the action because this exact local generation is not active.",why:`The atomic local lifecycle state is ${r.state}.`,nextAction:r.state==="quarantined"?"guardian.incident.review":"installed",nextStep:r.state==="quarantined"?"Review the quarantine evidence and request a fresh exact-generation restore approval before re-enabling the skill.":r.state==="externally_removed"?"Reinstall the exact skill generation, or explicitly remove the retained tombstone after reviewing it.":"Complete or repair the local lifecycle transaction before running this skill."})}if(!n.installedPath)return{status:"ok",context:n};if(await qae(n.installedPath))return To({...e,context:n,reasonCode:"skill_disabled",message:"Guardian blocked the action because this local skill is disabled.",why:"A local Guardian incident marker is present for this skill.",nextAction:"guardian.incident.review",nextStep:"Review the local incident report before running this skill again."});if(n.unmanaged)return{status:"ok",context:n};let i=await yae(e.skillSlug,n.installedPath);if(n.identityAssessment=i,i.reattestationRequired===!0)return To({...e,context:n,reasonCode:f(i,"reasonCode")??"skill_identity_mismatch",message:"Guardian blocked the action because the installed skill identity changed.",why:"The visible SKILL.md identity no longer matches the installed skill record.",nextStep:"Reinstall or re-attest the skill before running it again."});let o=await vae(e.skillSlug,n.installedPath,e.backend,n.record);return n.driftAssessment=o,o.reattestationRequired===!0?To({...e,context:n,reasonCode:f(o,"reasonCode")??"installed_artifact_changed",message:"Guardian blocked the action because local runtime metadata detected installed artifact drift.",why:"The installed SKILL.md hash no longer matches the materialized runtime metadata.",nextStep:"Reinstall or re-attest the skill before running it again."}):{status:"ok",context:n}}async function To(e){return await Ga(e.backend,{skillSlug:e.skillSlug,version:e.version??e.context.version,action:e.action,decisionStatus:"blocked",reasonCode:e.reasonCode,telemetryMode:e.telemetryMode,path:e.context.installedPath}),{status:"blocked",result:x({status:"blocked",skillSlug:e.skillSlug,version:e.version??e.context.version,reasonCode:e.reasonCode,localPreflight:qu(e.context),unmanaged:e.context.unmanaged,unmanagedPolicy:e.context.unmanagedPolicy,allowUnmanagedOnce:e.context.allowUnmanagedOnce,why:e.why,nextAction:e.nextAction,nextStep:e.nextStep},e.message,e.flags.json,e.reasonCode)}}async function WU(e){let t=ZU(k(e.flags.unmanagedPolicy)),n=e.unmanagedPolicy??(t.status==="valid"?t.policy:"warn"),r=k(e.flags.path),i=r?Tt(e.backend.cwd,r):void 0,o=await gae(e.skillSlug,e.backend,{scope:k(e.flags.scope),agent:k(e.flags.agent),installedPath:i}),s=i??o?.installedPath;return{source:r?"explicit_path":o?.source??"install_index",status:r?"ok":o?.status,reasonCode:r?void 0:o?.reasonCode,installedPath:s,archivePath:r?void 0:o?.archivePath,installedPathSource:r?"explicit_path":o?.installedPathSource,version:k(e.flags.version)??o?.version,record:o?.record,unmanaged:!!(r&&!o),unmanagedPolicy:n,allowUnmanagedOnce:e.flags.allowUnmanagedOnce}}async function gae(e,t,n={}){let i=(await Bi(t,e)).installs[e];if(i){let o=qn(i,{...n,platform:t.platform});if(o.length>1)return{source:"install_index",status:"degraded",reasonCode:"local_install_target_selection_required",version:f(i,"version"),record:i};if(o.length===0)return null;let s=gr(i,o[0]),a=PM(s,t);return{source:"install_index",installedPath:a.installedPath,archivePath:a.archivePath,installedPathSource:a.installedPathSource,status:a.status,reasonCode:a.reasonCode,version:f(s,"version"),record:s}}for(let o of hae(t)){let s=await ke(o);if(!j(s)||!j(s.installs))continue;let a=s.installs[e];if(j(a)){let l=PM(a,t);return{source:"lockfile",installedPath:l.installedPath,archivePath:l.archivePath,installedPathSource:l.installedPathSource,status:l.status,reasonCode:l.reasonCode,version:f(a,"version"),record:a}}}return null}function hae(e){return Array.from(new Set([K(e.cwd,"skills-layer-lock.json"),K(e.paths.stateDir,"skills-layer-lock.json")]))}function PM(e,t){let n=f(e,"materializedSkillRoot");if(n)return{installedPath:ph(Tt(t.cwd,n)),installedPathSource:"materializedSkillRoot",status:"ok"};let r=f(e,"canonicalPath");if(r)return{installedPath:ph(Tt(t.cwd,r)),installedPathSource:"canonicalPath",status:"ok"};let i=f(e,"path");if(i)return{installedPath:ph(Tt(t.cwd,i)),installedPathSource:"path",status:"ok"};let o=f(e,"materializedPath")??f(e,"bundlePath");if(o){let c=Tt(t.cwd,o),u=ot(c).toLowerCase()==="bundle.zip"||c.toLowerCase().endsWith(".zip");return{installedPath:u?Me(Me(c)):ph(c),archivePath:u?c:void 0,installedPathSource:f(e,"materializedPath")?"materializedPath":"bundlePath",status:u?"degraded":"ok",reasonCode:u?"installed_skill_root_missing":void 0}}let a=(Array.isArray(e.materializedWrites)?e.materializedWrites.filter(j):[]).find(c=>{let u=f(c,"path");return u?.toLowerCase().endsWith("/skill.md")||u?.toLowerCase()==="skill.md"}),l=a?f(a,"path"):void 0;return{installedPath:l?Me(Tt(t.cwd,l)):void 0,installedPathSource:l?"materializedWrites":void 0,status:l?"ok":void 0}}function ph(e){return ot(e).toLowerCase()==="skill.md"?Me(e):e}async function yae(e,t){let n=K(t,"SKILL.md");if(!await pr(n))return{status:"not_checked",reasonCode:"skill_document_unavailable",expectedSkillSlug:e,reattestationRequired:!1};try{let r=wU(await Fi(n,"utf8"));return r?r!==e?{status:"mismatch",reasonCode:"skill_identity_mismatch",expectedSkillSlug:e,observedSkillName:r,skillDocumentPath:n,reattestationRequired:!0}:{status:"matched",expectedSkillSlug:e,observedSkillName:r,skillDocumentPath:n,reattestationRequired:!1}:{status:"not_checked",reasonCode:"skill_identity_metadata_unavailable",expectedSkillSlug:e,skillDocumentPath:n,reattestationRequired:!1}}catch(r){return{status:"invalid",reasonCode:"skill_identity_unreadable",expectedSkillSlug:e,skillDocumentPath:n,message:ve(r),reattestationRequired:!0}}}async function vae(e,t,n,r){let i=r?Jt(r):null;if(i){let p=await Dr(i.receipt);return p.status==="verified"?{status:"unchanged",reasonCode:"installed_tree_manifest_matches",skillSlug:e,generationId:i.receipt.generation.generationId,manifestSha256:i.receipt.manifestSha256,reattestationRequired:!1}:{status:"changed",reasonCode:p.reasonCode,skillSlug:e,generationId:i.receipt.generation.generationId,manifestSha256:i.receipt.manifestSha256,reattestationRequired:!0}}let o=K(t,".skills-layer-runtime.json"),s=await ke(o),a=s?L(s,"materialization"):void 0,l=a?f(a,"skillDocumentSha256"):void 0;if(!s||!l)return{status:"not_checked",reasonCode:"runtime_metadata_unavailable",skillSlug:e,reattestationRequired:!0};let c=K(t,"SKILL.md");if(!await pr(c))return{status:"changed",reasonCode:"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:l,reattestationRequired:!0};let u=oz(await Fi(c,"utf8")),d=u===l;return{status:d?"unchanged":"changed",reasonCode:d?"installed_artifact_matches":"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:l,observedSkillDocumentSha256:u,reattestationRequired:!d}}function qu(e){return ie({source:e.source,status:e.status,reasonCode:e.reasonCode,installedPath:e.installedPath,archivePath:e.archivePath,installedPathSource:e.installedPathSource,version:e.version,unmanaged:e.unmanaged,unmanagedPolicy:e.unmanagedPolicy,allowUnmanagedOnce:e.allowUnmanagedOnce,identityAssessment:e.identityAssessment,driftAssessment:e.driftAssessment})}function ZU(e){if(e===void 0||e.trim()==="")return{status:"valid",policy:"warn"};let t=e.trim().toLowerCase();return t==="allow"||t==="warn"||t==="block"?{status:"valid",policy:t}:{status:"invalid",message:"guardian check --unmanaged-policy must be one of: allow, warn, block."}}function UP(e,t){let n=k(e)??t;return n==="cloud_managed"||n==="local_only"?{status:"valid",mode:n}:{status:"invalid",message:"guardian --telemetry-mode must be one of: cloud_managed, local_only."}}function AM(e,t){return{type:"shell_command",command:ot(t?.executableRealPath??e[0]??"command"),...t?{metadata:{executableRealPath:t.executableRealPath,executableSha256:t.executableSha256,argvSha256:YU(t.argv),cwdRealPath:t.cwdRealPath,fileTargets:t.fileTargets,networkTargets:t.networkTargets,environmentKeys:t.environmentKeys,callerActionJsonIgnored:!0,callerGrantJsonIgnored:!0}}:{}}}function kae(e){let t=L(e,"enforcement");return typeof t?.canExecute=="boolean"?t.canExecute:qP(e)!=="blocked"}async function wae(e){let t=bae(e.backend.platform);if(!t)return Ou(e,"guardian_platform_unsupported","Guardian guarded execution is unavailable on this platform.");if(t==="win32")return Ou(e,"windows_process_tree_isolation_unavailable","Guardian strict execution on Windows requires a verified Job Object process-tree adapter.");if(e.commandArgs.some(Aae))return Ou(e,"guardian_secret_in_argv","Guardian refuses likely credentials in command arguments; pass only explicitly brokered named environment secrets.");try{let[n,r]=await Promise.all([JU(e.commandArgs[0],e.backend,t),Fu(e.backend.cwd)]),i=await Ja(n);if(!i.isFile()||i.size<=0||i.size>256*1024*1024)return Ou(e,"guardian_executable_invalid","Guardian requires a bounded regular executable file.");let o=`sha256:${Ue("sha256").update(await Fi(n)).digest("hex")}`,s=Iae(e.flags,e.backend.env),a=await Sae(e.commandArgs.slice(1),r,e.backend,t),l=k(e.flags.agent)??(e.localContext.record?f(e.localContext.record,"agent")??f(e.localContext.record,"targetAgent"):void 0)??Re(e.backend.config?.lastSelectedAgent)??"skills-layer-cli";return{status:"ok",approvedSecrets:s,request:{platform:t,actionFamily:"shell_execution",executableRealPath:n,executableSha256:o,argv:e.commandArgs.slice(1),cwdRealPath:r,fileTargets:a.fileTargets,networkTargets:a.networkTargets,immutableInputs:a.immutableInputs,environmentKeys:Pae(t,Object.keys(s)),skillSlug:e.skillSlug,version:e.version,...k(e.flags.workspaceId)?{workspaceId:k(e.flags.workspaceId)}:{},agentId:l,hostVersion:So,sessionId:`guardian_session_${Ge(16).toString("hex")}`}}}catch(n){let r=n instanceof $e?n.reasonCode:"guardian_plan_resolution_failed";return Ou(e,r,`Guardian could not resolve the exact execution plan: ${ve(n)}`)}}function Ou(e,t,n){return{status:"blocked",result:x({status:"blocked",reasonCode:t,skillSlug:e.skillSlug},n,e.flags.json,t)}}function bae(e){return e==="darwin"||e==="linux"||e==="win32"?e:null}async function JU(e,t,n){if(!e||/[\u0000-\u001f\u007f]/u.test(e))throw new Error("Executable name is invalid.");let r=n==="win32"?st:Lt,o=r.isAbsolute(e)||e.includes("/")||e.includes("\\")?[r.isAbsolute(e)?e:r.resolve(t.cwd,e)]:_ae(e,t,n);for(let s of o.slice(0,128))try{await zM(s,n==="win32"?RB.F_OK:RB.X_OK);let a=await Fu(s);if((await Ja(a)).isFile())return a}catch{}throw new Error(`Executable ${ot(e)} was not found as an accessible regular file.`)}function _ae(e,t,n){let r=n==="win32"?st:Lt,o=(Re(t.env.PATH)??(n==="win32"?"C:\\Windows\\System32":"/usr/local/bin:/usr/bin:/bin")).split(n==="win32"?";":":").filter(Boolean).slice(0,64),s=n==="win32"&&!st.extname(e)?(Re(t.env.PATHEXT)??".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean).slice(0,8):[""];return o.flatMap(a=>s.map(l=>r.join(a,`${e}${l}`)))}async function Sae(e,t,n,r){let i=new Set,o=new Set,s=new Map;for(let[a,l]of e.entries()){let c=l.startsWith("--")&&l.includes("=")?l.slice(l.indexOf("=")+1):l;if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(c)){let p=new URL(c);if(p.protocol!=="https:")throw new Error("Guardian network targets must use HTTPS.");o.add(p.toString());continue}if(!xae(c,r))continue;let u=await Cae(c,t,n,r);i.add(u);let d=await Ja(u).catch(()=>null);if(d?.isFile()){let p=s.get(u);p?p.argumentIndexes.push(a):s.set(u,{path:u,sha256:`sha256:${Ue("sha256").update(await Fi(u)).digest("hex")}`,size:d.size,argumentIndexes:[a]})}}return{fileTargets:[...i].sort(vh),networkTargets:[...o].sort(vh),immutableInputs:[...s.values()].sort((a,l)=>vh(a.path,l.path))}}function xae(e,t){return!e||e.startsWith("-")?!1:(t==="win32"?st:Lt).isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.startsWith("~/")||e.includes("/")||e.includes("\\")}async function Cae(e,t,n,r){let i=r==="win32"?st:Lt,o=r==="win32"?Re(n.env.USERPROFILE)??Re(n.env.HOME):Re(n.env.HOME),s=e.startsWith("~/")&&o?i.join(o,e.slice(2)):e,a=i.normalize(i.isAbsolute(s)?s:i.resolve(t,s));try{return await Fu(a)}catch{let l=await Fu(i.dirname(a));return i.join(l,i.basename(a))}}function Iae(e,t){let n=Array.isArray(e.secretEnv)?e.secretEnv:typeof e.secretEnv=="string"?[e.secretEnv]:[],r={};for(let i of[...new Set(n)]){if(!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u.test(i))throw new Error(`Secret environment key ${i} is invalid.`);let o=t[i];if(typeof o!="string"||o.length===0)throw new Error(`Secret environment key ${i} is unavailable.`);r[i]=o}return r}function Pae(e,t){let n=e==="win32"?["PATH","SystemRoot","TEMP","TMP","USERPROFILE"]:["HOME","PATH","TMPDIR"];return[...new Set([...n,...t])].sort(vh)}function Aae(e){return/(?:mktplace_|slg_exec_|github_pat_|gh[opusr]_|sk-)[A-Za-z0-9_-]{8,}/u.test(e)||/(?:password|passwd|secret|token|api[_-]?key)\s*[=:]\s*[^\s]+/iu.test(e)||/-----BEGIN [^-\r\n]{1,64} PRIVATE KEY-----/u.test(e)}function YU(e){return`sha256:${Ue("sha256").update(JSON.stringify(e),"utf8").digest("hex")}`}function vh(e,t){return e<t?-1:e>t?1:0}function Rae(e){let t=[e.exitCode===0?"OK Guardian guarded execution complete.":"Guardian guarded execution finished with a command error.","","Command",` executable: ${e.executable}`,` args count: ${e.argsCount}`,` exit code: ${e.exitCode}`];return e.stdout&&t.push("","Stdout",e.stdout),e.stderr&&t.push("","Stderr",e.stderr),t.join(`
|
|
2169
|
+
${o}`,stderr:""}}function fae(e,t){let n=J(e,"activeHookCount")??0,r=J(e,"missingHookCount")??0,i=f(t,"status")??"unknown",o=f(t,"effectiveMode"),s=f(t,"adminPolicy"),a=f(t,"nextAction"),l=f(t,"nextStep"),c=e.strictPreActionBlocking===!0;return n>0&&r===0&&c?{id:"guardian-local-hook",title:"Guardian local hook",status:"pass",summary:`Guardian native hook active count: ${n}.`,enforcementLayer:f(e,"enforcementLayer")??"native_hook",strictPreActionBlocking:c,measuredProtection:"verified_strict",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook status"}:n>0&&r===0?{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian candidate hook active count: ${n}; live strict evidence is not current.`,enforcementLayer:f(e,"enforcementLayer")??"native_hook_candidate",strictPreActionBlocking:!1,measuredProtection:"candidate_unverified",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook status",nextStep:"Run the agent/platform live canaries and inspect Guardian hook status before relying on enforced protection."}:{id:"guardian-local-hook",title:"Guardian local hook",status:"warn",summary:`Guardian native hook setup needs attention. Active hooks: ${n}; missing hooks: ${r}.`,enforcementLayer:f(e,"enforcementLayer")??"not_installed",strictPreActionBlocking:c,measuredProtection:"unavailable",policyStatus:i,adminPolicy:s,effectiveMode:o,policyNextAction:a,policyNextStep:l,recommendedCommand:"skills-layer guardian hook install --agent codex --scope project",nextStep:"Install a Guardian host hook for automatic checks, or route risky shell actions through `skills-layer guardian exec` for strict pre-execution blocking."}}function mae(e,t){let n=new Date(e);return Number.isNaN(n.getTime())?e:(n.setUTCDate(n.getUTCDate()+t),n.toISOString())}async function KU(e){let t=ZU(k(e.flags.unmanagedPolicy)??e.backend.env.SKILLS_LAYER_UNMANAGED_SKILL_POLICY);if(t.status==="invalid")return{status:"invalid",result:E(t.message,e.flags.json)};let n=await WU({skillSlug:e.skillSlug,flags:e.flags,backend:e.backend,unmanagedPolicy:t.policy});if(n.reasonCode==="local_install_target_selection_required")return To({...e,context:n,reasonCode:n.reasonCode,message:"Guardian needs one exact local skill target before it can make an execution decision.",why:"This skill is installed in more than one target and the command did not identify which materialization is active.",nextAction:"guardian.check",nextStep:"Repeat the command with --agent, --scope, or --path so Guardian can bind the decision to one exact installed target."});if(n.unmanaged&&(n.unmanagedPolicy==="allow"||n.allowUnmanagedOnce))return To({...e,context:n,reasonCode:"guardian_unmanaged_atomic_execution_required",message:"Guardian check cannot authorize unmanaged execution.",why:"A diagnostic check cannot safely bind a one-use decision to the exact local process that would consume it.",nextAction:"install",nextStep:"Install or import the exact skill generation, then use `skills-layer guardian exec <skill-slug> -- <command>` for atomic guarded execution."});if(n.unmanaged&&n.unmanagedPolicy==="block")return To({...e,context:n,reasonCode:"unmanaged_skill_blocked",message:"Guardian blocked unmanaged local skill execution.",why:"The skill path is not backed by a public install index or lockfile entry and unmanaged policy is block.",nextAction:"install",nextStep:"Install or import the exact skill generation before requesting a Guardian execution decision."});let r=n.record?Jt(n.record):null;if(r&&r.state!=="active"){let s=r.state==="quarantined"?"skill_quarantined":r.state==="restore_pending"?"skill_restore_pending":r.state==="externally_removed"?"skill_externally_removed":r.state==="host_detached"?"skill_host_detached":r.state==="unreadable"?"skill_target_unreadable":r.state==="drifted"?"installed_artifact_changed":"skill_activation_pending";return To({...e,context:n,reasonCode:s,message:"Guardian blocked the action because this exact local generation is not active.",why:`The atomic local lifecycle state is ${r.state}.`,nextAction:r.state==="quarantined"?"guardian.incident.review":"installed",nextStep:r.state==="quarantined"?"Review the quarantine evidence and request a fresh exact-generation restore approval before re-enabling the skill.":r.state==="externally_removed"?"Reinstall the exact skill generation, or explicitly remove the retained tombstone after reviewing it.":"Complete or repair the local lifecycle transaction before running this skill."})}if(!n.installedPath)return{status:"ok",context:n};if(await qae(n.installedPath))return To({...e,context:n,reasonCode:"skill_disabled",message:"Guardian blocked the action because this local skill is disabled.",why:"A local Guardian incident marker is present for this skill.",nextAction:"guardian.incident.review",nextStep:"Review the local incident report before running this skill again."});if(n.unmanaged)return{status:"ok",context:n};let i=await yae(e.skillSlug,n.installedPath);if(n.identityAssessment=i,i.reattestationRequired===!0)return To({...e,context:n,reasonCode:f(i,"reasonCode")??"skill_identity_mismatch",message:"Guardian blocked the action because the installed skill identity changed.",why:"The visible SKILL.md identity no longer matches the installed skill record.",nextStep:"Reinstall or re-attest the skill before running it again."});let o=await vae(e.skillSlug,n.installedPath,e.backend,n.record);return n.driftAssessment=o,o.reattestationRequired===!0?To({...e,context:n,reasonCode:f(o,"reasonCode")??"installed_artifact_changed",message:"Guardian blocked the action because local runtime metadata detected installed artifact drift.",why:"The installed SKILL.md hash no longer matches the materialized runtime metadata.",nextStep:"Reinstall or re-attest the skill before running it again."}):{status:"ok",context:n}}async function To(e){return await Ga(e.backend,{skillSlug:e.skillSlug,version:e.version??e.context.version,action:e.action,decisionStatus:"blocked",reasonCode:e.reasonCode,telemetryMode:e.telemetryMode,path:e.context.installedPath}),{status:"blocked",result:x({status:"blocked",skillSlug:e.skillSlug,version:e.version??e.context.version,reasonCode:e.reasonCode,localPreflight:qu(e.context),unmanaged:e.context.unmanaged,unmanagedPolicy:e.context.unmanagedPolicy,allowUnmanagedOnce:e.context.allowUnmanagedOnce,why:e.why,nextAction:e.nextAction,nextStep:e.nextStep},e.message,e.flags.json,e.reasonCode)}}async function WU(e){let t=ZU(k(e.flags.unmanagedPolicy)),n=e.unmanagedPolicy??(t.status==="valid"?t.policy:"warn"),r=k(e.flags.path),i=r?Tt(e.backend.cwd,r):void 0,o=await gae(e.skillSlug,e.backend,{scope:k(e.flags.scope),agent:k(e.flags.agent),installedPath:i}),s=i??o?.installedPath;return{source:r?"explicit_path":o?.source??"install_index",status:r?"ok":o?.status,reasonCode:r?void 0:o?.reasonCode,installedPath:s,archivePath:r?void 0:o?.archivePath,installedPathSource:r?"explicit_path":o?.installedPathSource,version:k(e.flags.version)??o?.version,record:o?.record,unmanaged:!!(r&&!o),unmanagedPolicy:n,allowUnmanagedOnce:e.flags.allowUnmanagedOnce}}async function gae(e,t,n={}){let i=(await Bi(t,e)).installs[e];if(i){let o=qn(i,{...n,platform:t.platform});if(o.length>1)return{source:"install_index",status:"degraded",reasonCode:"local_install_target_selection_required",version:f(i,"version"),record:i};if(o.length===0)return null;let s=gr(i,o[0]),a=PM(s,t);return{source:"install_index",installedPath:a.installedPath,archivePath:a.archivePath,installedPathSource:a.installedPathSource,status:a.status,reasonCode:a.reasonCode,version:f(s,"version"),record:s}}for(let o of hae(t)){let s=await ke(o);if(!j(s)||!j(s.installs))continue;let a=s.installs[e];if(j(a)){let l=PM(a,t);return{source:"lockfile",installedPath:l.installedPath,archivePath:l.archivePath,installedPathSource:l.installedPathSource,status:l.status,reasonCode:l.reasonCode,version:f(a,"version"),record:a}}}return null}function hae(e){return Array.from(new Set([K(e.cwd,"skills-layer-lock.json"),K(e.paths.stateDir,"skills-layer-lock.json")]))}function PM(e,t){let n=f(e,"materializedSkillRoot");if(n)return{installedPath:ph(Tt(t.cwd,n)),installedPathSource:"materializedSkillRoot",status:"ok"};let r=f(e,"canonicalPath");if(r)return{installedPath:ph(Tt(t.cwd,r)),installedPathSource:"canonicalPath",status:"ok"};let i=f(e,"path");if(i)return{installedPath:ph(Tt(t.cwd,i)),installedPathSource:"path",status:"ok"};let o=f(e,"materializedPath")??f(e,"bundlePath");if(o){let c=Tt(t.cwd,o),u=ot(c).toLowerCase()==="bundle.zip"||c.toLowerCase().endsWith(".zip");return{installedPath:u?Me(Me(c)):ph(c),archivePath:u?c:void 0,installedPathSource:f(e,"materializedPath")?"materializedPath":"bundlePath",status:u?"degraded":"ok",reasonCode:u?"installed_skill_root_missing":void 0}}let a=(Array.isArray(e.materializedWrites)?e.materializedWrites.filter(j):[]).find(c=>{let u=f(c,"path");return u?.toLowerCase().endsWith("/skill.md")||u?.toLowerCase()==="skill.md"}),l=a?f(a,"path"):void 0;return{installedPath:l?Me(Tt(t.cwd,l)):void 0,installedPathSource:l?"materializedWrites":void 0,status:l?"ok":void 0}}function ph(e){return ot(e).toLowerCase()==="skill.md"?Me(e):e}async function yae(e,t){let n=K(t,"SKILL.md");if(!await pr(n))return{status:"not_checked",reasonCode:"skill_document_unavailable",expectedSkillSlug:e,reattestationRequired:!1};try{let r=wU(await Fi(n,"utf8"));return r?r!==e?{status:"mismatch",reasonCode:"skill_identity_mismatch",expectedSkillSlug:e,observedSkillName:r,skillDocumentPath:n,reattestationRequired:!0}:{status:"matched",expectedSkillSlug:e,observedSkillName:r,skillDocumentPath:n,reattestationRequired:!1}:{status:"not_checked",reasonCode:"skill_identity_metadata_unavailable",expectedSkillSlug:e,skillDocumentPath:n,reattestationRequired:!1}}catch(r){return{status:"invalid",reasonCode:"skill_identity_unreadable",expectedSkillSlug:e,skillDocumentPath:n,message:ve(r),reattestationRequired:!0}}}async function vae(e,t,n,r){let i=r?Jt(r):null;if(i){let p=await Dr(i.receipt);return p.status==="verified"?{status:"unchanged",reasonCode:"installed_tree_manifest_matches",skillSlug:e,generationId:i.receipt.generation.generationId,manifestSha256:i.receipt.manifestSha256,reattestationRequired:!1}:{status:"changed",reasonCode:p.reasonCode,skillSlug:e,generationId:i.receipt.generation.generationId,manifestSha256:i.receipt.manifestSha256,reattestationRequired:!0}}let o=K(t,".skills-layer-runtime.json"),s=await ke(o),a=s?L(s,"materialization"):void 0,l=a?f(a,"skillDocumentSha256"):void 0;if(!s||!l)return{status:"not_checked",reasonCode:"runtime_metadata_unavailable",skillSlug:e,reattestationRequired:!0};let c=K(t,"SKILL.md");if(!await pr(c))return{status:"changed",reasonCode:"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:l,reattestationRequired:!0};let u=oz(await Fi(c,"utf8")),d=u===l;return{status:d?"unchanged":"changed",reasonCode:d?"installed_artifact_matches":"installed_artifact_changed",skillSlug:e,expectedSkillDocumentSha256:l,observedSkillDocumentSha256:u,reattestationRequired:!d}}function qu(e){return ie({source:e.source,status:e.status,reasonCode:e.reasonCode,installedPath:e.installedPath,archivePath:e.archivePath,installedPathSource:e.installedPathSource,version:e.version,unmanaged:e.unmanaged,unmanagedPolicy:e.unmanagedPolicy,allowUnmanagedOnce:e.allowUnmanagedOnce,identityAssessment:e.identityAssessment,driftAssessment:e.driftAssessment})}function ZU(e){if(e===void 0||e.trim()==="")return{status:"valid",policy:"warn"};let t=e.trim().toLowerCase();return t==="allow"||t==="warn"||t==="block"?{status:"valid",policy:t}:{status:"invalid",message:"guardian check --unmanaged-policy must be one of: allow, warn, block."}}function UP(e,t){let n=k(e)??t;return n==="cloud_managed"||n==="local_only"?{status:"valid",mode:n}:{status:"invalid",message:"guardian --telemetry-mode must be one of: cloud_managed, local_only."}}function AM(e,t){return{type:"shell_command",command:ot(t?.executableRealPath??e[0]??"command"),...t?{metadata:{executableRealPath:t.executableRealPath,executableSha256:t.executableSha256,argvSha256:YU(t.argv),cwdRealPath:t.cwdRealPath,fileTargets:t.fileTargets,networkTargets:t.networkTargets,environmentKeys:t.environmentKeys,callerActionJsonIgnored:!0,callerGrantJsonIgnored:!0}}:{}}}function kae(e){let t=L(e,"enforcement");return typeof t?.canExecute=="boolean"?t.canExecute:qP(e)!=="blocked"}async function wae(e){let t=bae(e.backend.platform);if(!t)return Ou(e,"guardian_platform_unsupported","Guardian guarded execution is unavailable on this platform.");if(t==="win32")return Ou(e,"windows_process_tree_isolation_unavailable","Guardian strict execution on Windows requires a verified Job Object process-tree adapter.");if(e.commandArgs.some(Aae))return Ou(e,"guardian_secret_in_argv","Guardian refuses likely credentials in command arguments; pass only explicitly brokered named environment secrets.");try{let[n,r]=await Promise.all([JU(e.commandArgs[0],e.backend,t),Fu(e.backend.cwd)]),i=await Ja(n);if(!i.isFile()||i.size<=0||i.size>256*1024*1024)return Ou(e,"guardian_executable_invalid","Guardian requires a bounded regular executable file.");let o=`sha256:${Ue("sha256").update(await Fi(n)).digest("hex")}`,s=Iae(e.flags,e.backend.env),a=await Sae(e.commandArgs.slice(1),r,e.backend,t),l=k(e.flags.agent)??(e.localContext.record?f(e.localContext.record,"agent")??f(e.localContext.record,"targetAgent"):void 0)??Re(e.backend.config?.lastSelectedAgent)??"skills-layer-cli";return{status:"ok",approvedSecrets:s,request:{platform:t,actionFamily:"shell_execution",executableRealPath:n,executableSha256:o,argv:e.commandArgs.slice(1),cwdRealPath:r,fileTargets:a.fileTargets,networkTargets:a.networkTargets,immutableInputs:a.immutableInputs,environmentKeys:Pae(t,Object.keys(s)),skillSlug:e.skillSlug,version:e.version,...k(e.flags.workspaceId)?{workspaceId:k(e.flags.workspaceId)}:{},agentId:l,hostVersion:So,sessionId:`guardian_session_${Ge(16).toString("hex")}`}}}catch(n){let r=n instanceof $e?n.reasonCode:"guardian_plan_resolution_failed";return Ou(e,r,`Guardian could not resolve the exact execution plan: ${ve(n)}`)}}function Ou(e,t,n){return{status:"blocked",result:x({status:"blocked",reasonCode:t,skillSlug:e.skillSlug},n,e.flags.json,t)}}function bae(e){return e==="darwin"||e==="linux"||e==="win32"?e:null}async function JU(e,t,n){if(!e||/[\u0000-\u001f\u007f]/u.test(e))throw new Error("Executable name is invalid.");let r=n==="win32"?st:Lt,o=r.isAbsolute(e)||e.includes("/")||e.includes("\\")?[r.isAbsolute(e)?e:r.resolve(t.cwd,e)]:_ae(e,t,n);for(let s of o.slice(0,128))try{await zM(s,n==="win32"?RB.F_OK:RB.X_OK);let a=await Fu(s);if((await Ja(a)).isFile())return a}catch{}throw new Error(`Executable ${ot(e)} was not found as an accessible regular file.`)}function _ae(e,t,n){let r=n==="win32"?st:Lt,o=(Re(t.env.PATH)??(n==="win32"?"C:\\Windows\\System32":"/usr/local/bin:/usr/bin:/bin")).split(n==="win32"?";":":").filter(Boolean).slice(0,64),s=n==="win32"&&!st.extname(e)?(Re(t.env.PATHEXT)??".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean).slice(0,8):[""];return o.flatMap(a=>s.map(l=>r.join(a,`${e}${l}`)))}async function Sae(e,t,n,r){let i=new Set,o=new Set,s=new Map;for(let[a,l]of e.entries()){let c=l.startsWith("--")&&l.includes("=")?l.slice(l.indexOf("=")+1):l;if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(c)){let p=new URL(c);if(p.protocol!=="https:")throw new Error("Guardian network targets must use HTTPS.");o.add(p.toString());continue}if(!xae(c,r))continue;let u=await Cae(c,t,n,r);i.add(u);let d=await Ja(u).catch(()=>null);if(d?.isFile()){let p=s.get(u);p?p.argumentIndexes.push(a):s.set(u,{path:u,sha256:`sha256:${Ue("sha256").update(await Fi(u)).digest("hex")}`,size:d.size,argumentIndexes:[a]})}}return{fileTargets:[...i].sort(vh),networkTargets:[...o].sort(vh),immutableInputs:[...s.values()].sort((a,l)=>vh(a.path,l.path))}}function xae(e,t){return!e||e.startsWith("-")?!1:(t==="win32"?st:Lt).isAbsolute(e)||e.startsWith("./")||e.startsWith("../")||e.startsWith("~/")||e.includes("/")||e.includes("\\")}async function Cae(e,t,n,r){let i=r==="win32"?st:Lt,o=r==="win32"?Re(n.env.USERPROFILE)??Re(n.env.HOME):Re(n.env.HOME),s=e.startsWith("~/")&&o?i.join(o,e.slice(2)):e,a=i.normalize(i.isAbsolute(s)?s:i.resolve(t,s));try{return await Fu(a)}catch{let l=await Fu(i.dirname(a));return i.join(l,i.basename(a))}}function Iae(e,t){let n=Array.isArray(e.secretEnv)?e.secretEnv:typeof e.secretEnv=="string"?[e.secretEnv]:[],r={};for(let i of[...new Set(n)]){if(!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/u.test(i))throw new Error(`Secret environment key ${i} is invalid.`);let o=t[i];if(typeof o!="string"||o.length===0)throw new Error(`Secret environment key ${i} is unavailable.`);r[i]=o}return r}function Pae(e,t){let n=e==="win32"?["PATH","SystemRoot","TEMP","TMP","USERPROFILE"]:["HOME","PATH","TMPDIR"];return[...new Set([...n,...t])].sort(vh)}function Aae(e){return/(?:mktplace_|slg_exec_|github_pat_|gh[opusr]_|sk-)[A-Za-z0-9_-]{8,}/u.test(e)||/(?:password|passwd|secret|token|api[_-]?key)\s*[=:]\s*[^\s]+/iu.test(e)||/-----BEGIN [^-\r\n]{1,64} PRIVATE KEY-----/u.test(e)}function YU(e){return`sha256:${Ue("sha256").update(JSON.stringify(e),"utf8").digest("hex")}`}function vh(e,t){return e<t?-1:e>t?1:0}function Rae(e){let t=[e.exitCode===0?"OK Guardian guarded execution complete.":"Guardian guarded execution finished with a command error.","","Command",` executable: ${e.executable}`,` args count: ${e.argsCount}`,` exit code: ${e.exitCode}`];return e.stdout&&t.push("","Stdout",e.stdout),e.stderr&&t.push("","Stderr",e.stderr),t.join(`
|
|
2170
2170
|
`)}function Xa(e){let t=k(e)??"project";return t==="project"||t==="global"?{status:"valid",scope:t}:{status:"invalid",message:"guardian hooks --scope must be one of: project, global."}}function XU(e){return K(e.paths.stateDir,"guardian-modes.json")}function QU(e){return K(e.paths.stateDir,"setup-state.json")}async function gA(e){let t=await ke(XU(e));return{version:1,skills:j(t?.skills)?t.skills:{}}}async function Eae(e,t,n){let r=await gA(e);await Ve(XU(e),{version:1,skills:{...r.skills,[t]:{requestedPreference:f(n,"requestedPreference")??"enforce",effectiveMode:f(n,"effectiveMode")??"enforce",reasonCode:f(n,"reasonCode"),auditId:f(n,"auditId"),updatedAt:e.now()}}})}async function rd(e,t){let r=(await gA(e)).skills[t];return r?f(r,"requestedPreference"):void 0}async function $ae(e,t){return(await gA(e)).skills[t]}async function hA(e){let t=await ke(QU(e));return j(t)?{version:1,setupChoice:f(t,"setupChoice"),mcpChoice:f(t,"mcpChoice"),mcpPromptedAt:f(t,"mcpPromptedAt"),guardianHookChoice:f(t,"guardianHookChoice"),guardianHookPromptedAt:f(t,"guardianHookPromptedAt"),remindAfter:f(t,"remindAfter")}:null}async function RM(e,t){await Ve(QU(e),t)}function Dae(e,t,n,r){let i=t==="global"?e.targets.globalRoot:e.targets.projectRoot;if(!i)return null;if(e.id==="codex")return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"hooks.json"),hookPath:K(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="claude-code")return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"settings.json"),hookPath:K(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="cline")return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"guardian-hooks.json"),hookPath:K(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="gemini-cli"){let o=t==="project"?K(n.cwd,".gemini"):i;return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(o,"settings.json"),hookPath:K(o,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r}}if(e.id==="cursor")return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"hooks.json"),hookPath:K(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="github-copilot"){let o=t==="project"?K(n.cwd,".github","hooks"):K(i,"hooks");return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(o,"skills-layer-guardian.json"),hookPath:K(o,"skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r}}if(e.id==="opencode")return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"skills-layer-guardian.json"),hookPath:K(i,"plugins","skills-layer-guardian.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="windsurf")return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"hooks.json"),hookPath:K(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r};if(e.id==="antigravity"||e.id==="antigravity-cli"){let o=t==="project"?K(n.cwd,".agents"):K(Me(i),"config");return{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(o,"hooks.json"),hookPath:K(o,"hooks",`skills-layer-guardian-${e.id}.mjs`),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r}}return e.id==="kiro-cli"?{agent:e.id,agentName:e.displayName,scope:t,hookId:$t,hookName:xt,configPath:K(i,"hooks","skills-layer-guardian.json"),hookPath:K(i,"hooks","skills-layer-guardian-hook.mjs"),enforcementLayer:"native_hook_candidate",strictPreActionBlocking:!1,hostVersion:r}:null}async function Tae(e,t,n){await Mo(Me(e.hookPath),{recursive:!0,mode:448}),await Mo(Me(e.configPath),{recursive:!0,mode:448});let r=EM(n?.hookFileOwnership),i=await Uae(t),o=await Py({operation:r?"update":"install",filePath:e.hookPath,content:e.agent==="opencode"?Bae(e,i,process.execPath):Mae(e.agent,e.scope,i,e.hostVersion),...r?{previousOwnership:r}:{}});if(e.agent==="windsurf"){let l=e.agent,c=["pre_read_code","pre_write_code","pre_run_command","pre_mcp_tool_use"],u=Array.isArray(n?.configEntryOwnerships)?n.configEntryOwnerships.flatMap(p=>{for(let m of c){let h=hP(p,l,m);if(h)return[h]}return[]}):[],d=[];for(let p of c){let m=u.find(g=>g.eventName===p),h=await xd({configPath:e.configPath,update:{operation:m?"update":"install",agentId:l,eventName:p,absoluteScriptPath:e.hookPath,...m?{previousOwnership:m}:{}}});d.push(h.ownership)}return{hookFileOwnership:o.ownership,configEntryOwnerships:d,absoluteCliPath:i}}if(e.agent==="codex"||e.agent==="claude-code"||e.agent==="gemini-cli"||e.agent==="cursor"||e.agent==="antigravity"||e.agent==="antigravity-cli"){let l=e.agent==="gemini-cli"?"BeforeTool":e.agent==="cursor"?"preToolUse":"PreToolUse",c=hP(n?.configEntryOwnership,e.agent,l),u=await xd({configPath:e.configPath,update:{operation:c?"update":"install",agentId:e.agent,eventName:l,absoluteScriptPath:e.hookPath,...c?{previousOwnership:c}:{}}}),d;if(e.agent==="claude-code"){let p=hP(n?.activationConfigEntryOwnership,e.agent,"UserPromptExpansion");d=(await xd({configPath:e.configPath,update:{operation:p?"update":"install",agentId:e.agent,eventName:"UserPromptExpansion",absoluteScriptPath:e.hookPath,...p?{previousOwnership:p}:{}}})).ownership}return{hookFileOwnership:o.ownership,configEntryOwnership:u.ownership,...d?{activationConfigEntryOwnership:d}:{},absoluteCliPath:i}}let s=EM(n?.configFileOwnership),a=await Py({operation:s?"update":"install",filePath:e.configPath,content:`${JSON.stringify(e.agent==="kiro-cli"?jae(e):e.agent==="github-copilot"?Nae(e,process.execPath):e.agent==="opencode"?Fae(e):Lae(e,t),null,2)}
|
|
2171
2171
|
`,...s?{previousOwnership:s}:{}});return{hookFileOwnership:o.ownership,configFileOwnership:a.ownership,absoluteCliPath:i}}function ez(e,t){return t==="global"?K(e.paths.stateDir,"guardian-hooks.json"):K(e.cwd,".skills-layer","guardian-hooks.json")}function Oae(e,t,n,r){let i=t==="global"?e.paths.stateDir:K(e.cwd,".skills-layer");return K(i,"guardian-hook-evidence",`${n}-${r}-${fr(e.platform)}.json`)}async function tz(e){let t=await ke(e);return{version:1,hooks:Array.isArray(t?.hooks)?t.hooks.filter(j):[]}}function zP(e,t,n){return st.isAbsolute(n)||n.startsWith("/")?n:qo(t==="global"?e.paths.stateDir:e.cwd,n)}function Lae(e,t){return{version:1,hookId:$t,hookName:xt,agent:e.agent,agentName:e.agentName,scope:e.scope,enforcementLayer:e.enforcementLayer,strictPreActionBlocking:e.strictPreActionBlocking,installedAt:t.now(),hooks:[{name:xt,id:$t,event:"PreToolUse",command:`node ${nz(e.hookPath)}`,status:"candidate"}]}}function jae(e){return{version:"v1",hooks:[{name:xt,description:"Skills Layer Guardian pre-tool authorization",trigger:"PreToolUse",matcher:".*",action:{type:"command",command:`node ${nz(e.hookPath)}`},timeout:0,enabled:!0}]}}function Nae(e,t){return{version:1,hooks:{PreToolUse:[{type:"command",matcher:"*",exec:t,args:[e.hookPath],timeoutSec:10}]}}}function Fae(e){return{version:1,agent:"opencode",scope:e.scope,hostVersion:e.hostVersion,hookEvent:"tool.execute.before",hookPath:e.hookPath,enabled:!0}}function Bae(e,t,n){return`import { spawnSync } from "node:child_process";
|
|
2172
2172
|
import { readFileSync } from "node:fs";
|
|
@@ -2269,12 +2269,12 @@ process.exit(${e==="windsurf"||e==="github-copilot"?"result.status === 0 ? 0 : 2
|
|
|
2269
2269
|
`);return await Zo(Me(u)),await ZP(u,`${m}
|
|
2270
2270
|
`,{encoding:"utf8",mode:384}),await Jo(u,384),{status:"quarantined",generatedAt:t,incidentPath:u,evidencePath:d,quarantineDir:l.quarantine.quarantineDir,localLifecycle:l.lifecycle,writtenFiles:[u,d]}}function yA(e,t,n){let r=n==="win32"?st:Lt,i=r.resolve(e).normalize("NFC"),o=r.resolve(t).normalize("NFC");return n==="linux"?i===o:i.toLocaleLowerCase("en-US")===o.toLocaleLowerCase("en-US")}function DM(e,t){let n=e.now().replace(/[:.]/gu,"-");return K(e.paths.incidentsDir,`${t}-${n}.json`)}async function Ga(e,t){let n=K(e.paths.stateDir,"guardian-audit.jsonl");await Zo(Me(n));let r=await Vae(n),i=t.authority?L(t.authority,"exactGeneration"):void 0,o=t.authority?L(t.authority,"guardianMode"):void 0,s=ie({version:2,generatedAt:e.now(),skillSlug:t.skillSlug,...t.version?{skillVersion:t.version}:{},actionType:f(t.action,"type")??"unknown",actionDigest:`sha256:${Ue("sha256").update(Ph(t.action)).digest("hex")}`,actionTarget:Hae(t.action),decisionStatus:t.decisionStatus,reasonCode:t.reasonCode,telemetryMode:t.telemetryMode,telemetryDelivery:t.authority?f(t.authority,"telemetryDelivery")??t.telemetryMode:t.telemetryMode,...i?{generationId:f(i,"generationId"),archiveSha256:f(i,"archiveSha256"),servingRevision:i.servingRevision}:{},...o?{effectiveMode:f(o,"effectiveMode")}:{},...r?{previousEntryHash:r}:{},...t.path?{localPath:iz(t.path)}:{}}),a=`sha256:${Ue("sha256").update(Ph(s)).digest("hex")}`,l=`${JSON.stringify({...s,entryHash:a})}
|
|
2271
2271
|
`;await Gae(n,Buffer.byteLength(l)),await ire(n,l,{encoding:"utf8",mode:384}),await Jo(n,384)}var rz=1048576,TM=3;async function Vae(e){let t=await Ja(e).catch(()=>null);if(!t?.isFile()||t.size===0||t.size>rz)return;let r=(await Fi(e,"utf8")).trimEnd().split(`
|
|
2272
|
-
`).at(-1);if(r)try{let i=JSON.parse(r),o=f(i,"entryHash");return o&&/^sha256:[a-f0-9]{64}$/u.test(o)?o:void 0}catch{return}}async function Gae(e,t){let n=await Ja(e).catch(()=>null);if(!(!n?.isFile()||n.size+t<=rz)){await We(`${e}.${TM}`,{force:!0});for(let r=TM-1;r>=1;r-=1)await zo(`${e}.${r}`,`${e}.${r+1}`).catch(i=>{if(i.code!=="ENOENT")throw i});await zo(e,`${e}.1`)}}function Ph(e){if(Array.isArray(e))return`[${e.map(Ph).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Ph(t[n])}`).join(",")}}`}return JSON.stringify(e)??"null"}function qP(e){let t=L(e,"decision"),n=L(e,"enforcement"),r=f(t??{},"status")??f(n??{},"status")??f(e,"status");return r==="allowed"||r==="advisory"?r:"blocked"}function Ah(e){let t=L(e,"decision");return f(t??{},"reasonCode")??f(e,"reasonCode")??f(e,"status")??"cloud_guardian_decision"}function Hae(e){let t=f(e,"type");if(t==="secret_read")return"redacted_secret";if(t==="shell_command")return"redacted_command";let n=f(e,"url");if(n)try{return new URL(n).origin}catch{return"redacted_url"}let r=f(e,"target");if(r)return VP(r);let i=f(e,"path");return i?iz(i):null}function iz(e){let t=ot(e.trim());return t?`<local-path>/${t}`:"<local-path>"}function VP(e){return e.replace(/sk-[A-Za-z0-9_-]+/gu,"[redacted-secret]").replace(/[A-Z0-9_]*SECRET[A-Z0-9_]*/gu,"[redacted-secret]").replace(/[A-Z0-9_]*TOKEN[A-Z0-9_]*/gu,"[redacted-token]").replace(/[A-Z0-9_]*KEY[A-Z0-9_]*/gu,"[redacted-key]")}function OM(e){return e.split(/[\\/]+/u).join("/")}function oz(e){return Ue("sha256").update(e).digest("hex")}async function vA(e,t,n,r,i){let o=Ho(),s=k(n.mfaCode),a=k(n.recoveryCode),l=()=>D(r,"/api/v1/verify",{method:"POST",headers:V(),body:JSON.stringify({email:e,code:t,handoffCodeHash:o.authorizationCodeHash,handoffCodeChallenge:o.codeChallenge,...s?{mfaCode:s}:{},...a?{recoveryCode:a}:{}})}),c;try{c=await l()}catch(d){if(!(d instanceof Z)||d.details?.reasonCode!=="login_mfa_required"||n.json||r.nonInteractive||!r.stdoutIsTty)throw d;let p=await r.promptSelect("Complete MFA to finish email login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),m=(await r.promptSecret(p==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();p==="recovery_code"?a=m:s=m,c=await l()}if(f(c,"status")!=="verified")return
|
|
2272
|
+
`).at(-1);if(r)try{let i=JSON.parse(r),o=f(i,"entryHash");return o&&/^sha256:[a-f0-9]{64}$/u.test(o)?o:void 0}catch{return}}async function Gae(e,t){let n=await Ja(e).catch(()=>null);if(!(!n?.isFile()||n.size+t<=rz)){await We(`${e}.${TM}`,{force:!0});for(let r=TM-1;r>=1;r-=1)await zo(`${e}.${r}`,`${e}.${r+1}`).catch(i=>{if(i.code!=="ENOENT")throw i});await zo(e,`${e}.1`)}}function Ph(e){if(Array.isArray(e))return`[${e.map(Ph).join(",")}]`;if(e&&typeof e=="object"){let t=e;return`{${Object.keys(t).sort().map(n=>`${JSON.stringify(n)}:${Ph(t[n])}`).join(",")}}`}return JSON.stringify(e)??"null"}function qP(e){let t=L(e,"decision"),n=L(e,"enforcement"),r=f(t??{},"status")??f(n??{},"status")??f(e,"status");return r==="allowed"||r==="advisory"?r:"blocked"}function Ah(e){let t=L(e,"decision");return f(t??{},"reasonCode")??f(e,"reasonCode")??f(e,"status")??"cloud_guardian_decision"}function Hae(e){let t=f(e,"type");if(t==="secret_read")return"redacted_secret";if(t==="shell_command")return"redacted_command";let n=f(e,"url");if(n)try{return new URL(n).origin}catch{return"redacted_url"}let r=f(e,"target");if(r)return VP(r);let i=f(e,"path");return i?iz(i):null}function iz(e){let t=ot(e.trim());return t?`<local-path>/${t}`:"<local-path>"}function VP(e){return e.replace(/sk-[A-Za-z0-9_-]+/gu,"[redacted-secret]").replace(/[A-Z0-9_]*SECRET[A-Z0-9_]*/gu,"[redacted-secret]").replace(/[A-Z0-9_]*TOKEN[A-Z0-9_]*/gu,"[redacted-token]").replace(/[A-Z0-9_]*KEY[A-Z0-9_]*/gu,"[redacted-key]")}function OM(e){return e.split(/[\\/]+/u).join("/")}function oz(e){return Ue("sha256").update(e).digest("hex")}async function vA(e,t,n,r,i){let o=Ho(),s=k(n.mfaCode),a=k(n.recoveryCode),l=()=>D(r,"/api/v1/verify",{method:"POST",headers:V(),body:JSON.stringify({email:e,code:t,handoffCodeHash:o.authorizationCodeHash,handoffCodeChallenge:o.codeChallenge,...s?{mfaCode:s}:{},...a?{recoveryCode:a}:{}})}),c;try{c=await l()}catch(d){if(!(d instanceof Z)||d.details?.reasonCode!=="login_mfa_required"||n.json||r.nonInteractive||!r.stdoutIsTty)throw d;let p=await r.promptSelect("Complete MFA to finish email login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),m=(await r.promptSecret(p==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();p==="recovery_code"?a=m:s=m,c=await l()}if(f(c,"status")!=="verified")return E("Email verification did not prepare a secure credential handoff. Restart verification.",n.json);let u=await D(r,"/api/v1/identity/credential-handoff/exchange",{method:"POST",headers:V(),body:JSON.stringify({authorizationCode:o.authorizationCode,codeVerifier:o.codeVerifier})});if(f(u,"status")!=="exchanged"||!f(u,"email")||!f(u,"role")||!f(u,"apiKey"))return E("Email verification credential handoff failed closed. Restart verification.",n.json);if(n.json){let d=f(u,"apiKey");if(d){let p=await Vu(r,d,{expectedEmail:e,knownEmail:f(u,"email")??e,knownRole:f(u,"role")??"user",knownRoles:Un(u,"roles"),knownUserId:f(u,"userId"),knownSessionCredentialId:f(u,"id")}),m=await wh(n,{...r,config:p,apiKey:d});return fe(m)?m:R(Nt({...u,loggedIn:!0,...m.data?{workspaceSelection:m.data}:{}}),["Email verified and login completed.",m.message??""].filter(Boolean).join(" "),!0,r)}return R(Nt({...u,email:e,loggedIn:!1,nextCommand:`skills-layer login --method email --email ${e}`,nextAction:"login"}),"Email verified. Login still needs to be completed.",!0,r)}return await kA(e,u,n,r,i)}async function kA(e,t,n,r,i){let o=f(t,"apiKey"),s=f(t,"role")??"user",a=Un(t,"roles"),l=f(t,"userId"),c=o;if(!c&&n.json)return R(Nt({...t,email:e,role:s,...a?{roles:a}:{},loggedIn:!1}),`${i} Login still needs to be completed through a human handoff.`,!0,r);if(!c)try{c=(await r.promptSecret(`Enter the API key emailed to ${e} (check spam/junk folder if missing): `)).trim()}catch{return R(Nt({...t,email:e,role:s,...a?{roles:a}:{},loggedIn:!1}),`${i} Check your email (including spam/junk folder) for the API key, then run \`skills-layer login\` to finish signing in.`,n.json,r)}if(!c)return E("No API key was entered. Run `skills-layer login` once you have the emailed key.",n.json);let u=await Vu(r,c,{expectedEmail:e,knownEmail:e,knownRole:s,knownRoles:a,knownUserId:l,knownSessionCredentialId:f(t,"id"),forceProfileValidation:!o}),d=await wh(n,{...r,config:u,apiKey:c});if(fe(d))return d;let p=await xP(n,{...r,config:u,apiKey:c});if(fe(p))return p;let m=p.data?.status==="mcp_not_configured";return R(Nt(CP({...t,status:m?"partial_success":f(t,"status")??"verified",email:u.email,role:u.role,...u.roles?{roles:u.roles}:{},loggedIn:!0,...d.data?{workingMode:d.data}:{},...p.data?{mcp:p.data}:{},...m?{warnings:[p.data]}:{}},p.data)),[`${i} Logged in as ${u.email}.`,d.message??"",p.message??""].filter(Boolean).join(" "),n.json,r)}function Ho(){let e=`social_handoff_${Ge(32).toString("base64url")}`,t=Ge(48).toString("base64url");return{authorizationCode:e,codeVerifier:t,authorizationCodeHash:Ue("sha256").update(e).digest("base64url"),codeChallenge:Ue("sha256").update(t).digest("base64url")}}async function wA(e){if(!e.backend.nonInteractive)return null;if(!e.backend.credentialStore)return No(e.flags,e.backend);let t=`social_${Ge(18).toString("base64url")}`,n=`skills-layer-social-continuation:${t}`,r={version:1,reference:t,baseUrl:e.backend.baseUrl,provider:e.provider,mode:e.mode,authorizationCode:e.credentialHandoff.authorizationCode,codeVerifier:e.credentialHandoff.codeVerifier,authorizationCodeHash:e.credentialHandoff.authorizationCodeHash,codeChallenge:e.credentialHandoff.codeChallenge,createdAt:e.backend.now()},i={...r,integrityDigest:bA(r)};try{let o=JSON.stringify(i);if(await e.backend.credentialStore.set(je,n,o),await e.backend.credentialStore.get(je,n)!==o)return await e.backend.credentialStore.delete(je,n),No(e.flags,e.backend)}catch{return await e.backend.credentialStore.delete(je,n).catch(()=>{}),No(e.flags,e.backend)}return{reference:t,account:n,secret:i}}function No(e,t){return x({status:"security_unavailable",reasonCode:"social_secure_continuation_unavailable",unchanged:!0,nextAction:"login.interactive",nextStep:"Run the same command in an interactive human terminal with OS-secure credential storage available."},"Secure social continuation is unavailable. No browser login was started.",e.json,"social_secure_continuation_unavailable")}async function Kae(e,t,n){if(!n.credentialStore)return!1;let r=f(t,"state"),i=f(t,"expiresAt");if(!r||!i)return await n.credentialStore.delete(je,e.account).catch(()=>{}),!1;let o={version:e.secret.version,reference:e.secret.reference,baseUrl:e.secret.baseUrl,provider:e.secret.provider,mode:e.secret.mode,authorizationCode:e.secret.authorizationCode,codeVerifier:e.secret.codeVerifier,authorizationCodeHash:e.secret.authorizationCodeHash,codeChallenge:e.secret.codeChallenge,createdAt:e.secret.createdAt,state:r,expiresAt:i},s={...o,integrityDigest:bA(o)};try{let a=JSON.stringify(s);return await n.credentialStore.set(je,e.account,a),await n.credentialStore.get(je,e.account)===a}catch{return await n.credentialStore.delete(je,e.account).catch(()=>{}),!1}}function bA(e){return Ue("sha256").update(JSON.stringify([e.version,e.reference,e.baseUrl,e.provider,e.mode,e.authorizationCode,e.codeVerifier,e.authorizationCodeHash,e.codeChallenge,e.createdAt,e.state??null,e.expiresAt??null])).digest("base64url")}async function jh(e,t,n,r,i,o,s="/api/v1/identity/social/status",a=null){let l=f(t,"authorizationUrl"),c=O(f(t,"state"),"Social auth did not return a state."),u=Cz(e);if(i.nonInteractive)return!a||!await Kae(a,t,i)?No(r,i):R({status:"human_action_required",reasonCode:"social_auth_browser_handoff",provider:e,mode:o,authorizationUrl:l,reference:a.reference,expiresAt:f(t,"expiresAt"),nextAction:"identity.continue",nextStep:`Complete the browser sign-in, then run \`skills-layer identity continue --reference ${a.reference}\`.`},`${u} browser sign-in is ready. Complete it, then continue with the returned non-secret reference.`,r.json,i);if(l){let p=r.noOpen?!1:await i.openUrl(l);r.json||i.emitInfo(o==="recovery"?p?`${u} recovery started. Finish the verification in your browser, then come back here. Waiting for browser recovery to finish...`:`${u} recovery started. Open this URL in your browser, then come back here once it is done:
|
|
2273
2273
|
${l}
|
|
2274
2274
|
Waiting for browser recovery to finish...`:p?`${u} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`:`${u} sign-in started. Open this URL in your browser, then come back here once it is done:
|
|
2275
2275
|
${l}
|
|
2276
|
-
Waiting for browser sign-in to finish...`)}else r.json||i.emitInfo(o==="recovery"?`${u} recovery started. Finish the verification in your browser, then come back here. Waiting for browser recovery to finish...`:`${u} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`);let d=await Jae(c,i,s);if(fe(d))return d;if(d.status==="verified"||d.status==="recovered")return await kh(u,n,r,i,o);if(d.status==="mfa_required"){if(!n)return R("Login MFA handoff is unavailable. Start login again.",r.json);let p=k(r.mfaCode),m=k(r.recoveryCode);if(!p&&!m&&!r.json&&i.stdoutIsTty){let g=await i.promptSelect("Complete MFA to finish login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),y=(await i.promptSecret(g==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();g==="recovery_code"?m=y:p=y}if(!p&&!m)return x({status:"human_action_required",reasonCode:"login_mfa_required",methods:["authenticator","recovery_code"],nextAction:"account.login.mfa",nextStep:"Re-run login in a human terminal and complete MFA."},"MFA is required to finish login.",r.json,"login_mfa_required");let h=await D(i,"/api/v1/identity/login/mfa/verify",{method:"POST",headers:V(),body:JSON.stringify({state:c,authorizationCode:n.authorizationCode,codeVerifier:n.codeVerifier,...p?{mfaCode:p}:{},...m?{recoveryCode:m}:{}})});return f(h,"status")!=="verified"||f(h,"credentialHandoff")!=="ready"?R("MFA verification did not authorize the login credential. Start login again.",r.json):await kh(u,n,r,i,o)}if(d.status==="already_registered"||d.status==="link_required"){let p=GF(e,!!i.apiKey&&!i.authBlockedMessage);return x({...p},p.summary,r.json,"social_identity_link_required")}if(d.status==="registration_confirmation_required"){if(!r.json&&i.stdoutIsTty){let m=await i.promptSelect(`Create a new Skills Layer account using your verified ${u} identity?`,[{value:"create",label:"Yes, create my account",description:"Create one account, connect this sign-in, and log in"},{value:"cancel",label:"No",description:"Create nothing and leave Skills Layer unchanged"}])==="create",h=await D(i,"/api/v1/identity/social/registration/confirm",{method:"POST",headers:V(),body:JSON.stringify({state:c,createAccount:m})});return!m||f(h,"status")==="registration_cancelled"?A({status:"registration_cancelled",changed:!1},"Registration cancelled. No Skills Layer account was created.",!1,i):f(h,"status")!=="verified"||f(h,"credentialHandoff")!=="ready"?R("Account creation could not be confirmed safely. Start registration again.",!1):await kh(u,n,r,i,"register")}return x({status:"registration_confirmation_required",reasonCode:"registration_confirmation_required",nextAction:"account.registration.confirm",nextStep:r.createAccount?"Provider verification finished, but account creation still needs confirmation. Start registration again.":"Re-run registration with --create-account after confirming that you want to create this account."},"Account creation needs explicit confirmation.",r.json,"registration_confirmation_required")}return d.status==="linked"?A(d,`${u} sign-in is now connected.`,r.json,i):Zae(d)?R(tle(d),r.json):R("Social auth completed with an unexpected response.",r.json)}async function kh(e,t,n,r,i){if(!t)return R("Social credential handoff is unavailable. Start the login flow again.",n.json);let o=await D(r,"/api/v1/identity/social/exchange",{method:"POST",headers:V(),body:JSON.stringify({authorizationCode:t.authorizationCode,codeVerifier:t.codeVerifier})});if(f(o,"status")!=="exchanged"||!f(o,"email")||!f(o,"role")||!f(o,"apiKey"))return R("Social credential handoff failed closed. Start the login flow again.",n.json);let s=f(o,"email");return await kA(s,o,n,r,i==="recovery"?`Recovered access for ${s} through ${e}.`:`Verified ${s} through ${e}.`)}function Ko(e){return e==="google"||e==="github"||e==="gitlab"||e==="microsoft"}function fe(e){return j(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function Wae(e){try{let t=JSON.parse(e);return j(t)?t.data:void 0}catch{return}}function Zae(e){return e.status==="registration_required"||e.status==="state_expired"||e.status==="provider_mismatch"||e.status==="identity_conflict"||e.status==="email_required"||e.status==="failed"}async function Jae(e,t,n="/api/v1/identity/social/status"){for(let r=0;r<120;r+=1)try{let i=await D(t,`${n}/${encodeURIComponent(e)}`,n.includes("/identity/connect/")?{headers:re(t.apiKey,t.authBlockedMessage)}:void 0),o=f(i,"status")??"failed";if(o==="pending"){await t.sleep(1500);continue}return(o==="verified"||o==="recovered")&&f(i,"credentialHandoff")==="ready"?{status:o,credentialHandoff:"ready"}:o==="already_registered"||o==="link_required"?{status:o}:o==="linked"?{status:o}:o==="registration_confirmation_required"?{status:o}:o==="mfa_required"?{status:o}:o==="registration_required"||o==="state_expired"||o==="provider_mismatch"||o==="identity_conflict"||o==="email_required"||o==="failed"?{status:o,error:f(i,"error")}:R("Social auth completed with an unexpected response.",!1)}catch(i){if(i instanceof Z&&(i.status===404||i.status===429)){await t.sleep(1500);continue}return R(ve(i),!1)}return R("Timed out while waiting for social auth to complete.",!1)}async function Yae(e,t){let n=`/api/v1/identity/mfa/recovery-codes/operations/${encodeURIComponent(e)}`;for(let r=0;r<210;r+=1)try{let i=await D(t,n,{headers:re(t.apiKey,t.authBlockedMessage)}),o=f(i,"status"),s=L(i,"data");if(o==="pending"||o==="finalizing"){await t.sleep(1500);continue}if(o==="completed")return{...i,completedAt:f(i,"completedAt")??(s?f(s,"completedAt"):void 0)};if(o==="locked"){let a=f(i,"retryAt")??(s?f(s,"retryAt"):void 0);return x({status:"locked",reasonCode:"mfa_challenge_locked",retryAt:a,nextAction:"wait",nextStep:a?`Retry after ${a}.`:"Wait for the MFA verification lock to expire, then retry."},"Recovery-code verification is temporarily locked after too many invalid attempts.",!1)}return o==="failed"?x({status:"failed",reasonCode:"mfa_recovery_codes_failed",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"Recovery codes were not replaced.",!1):o==="expired"?x({status:"expired",reasonCode:"mfa_recovery_codes_expired",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"The recovery-code browser session expired before completion.",!1):R("Recovery-code verification completed with an unexpected response.",!1)}catch(i){if(i instanceof Z&&i.status===429){let o=i.details??{},s=f(o,"reasonCode"),a=f(o,"retryAt");if(s==="mfa_challenge_locked")return x({status:"locked",reasonCode:s,retryAt:a,nextAction:"wait",nextStep:a?`Retry after ${a}.`:"Wait for the MFA verification lock to expire, then retry."},"Recovery-code verification is temporarily locked after too many invalid attempts.",!1);let l=J(o,"retryAfterSeconds"),c=l===void 0?1500:Math.min(6e4,Math.max(1500,l*1e3));await t.sleep(c);continue}return R(ve(i),!1)}return x({status:"expired",reasonCode:"mfa_recovery_codes_expired",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"Timed out while waiting for recovery-code verification.",!1)}async function Xae(e,t){for(let n=0;n<120;n+=1)try{let r=await D(t,`/api/v1/purchases/${encodeURIComponent(e)}`,{headers:re(t.apiKey,t.authBlockedMessage)});if(!r?.status||r.status==="pending"||r.status==="requires_action"){await t.sleep(1500);continue}return{status:r.status,purchaseId:e}}catch(r){if(r instanceof Z&&r.status===429){await t.sleep(1500);continue}return R(ve(r),!1)}return R("Timed out while waiting for purchase confirmation.",!1)}async function Qae(e,t,n){let r=null;for(let i=0;i<120;i+=1)try{let o=await D(n,e,{headers:re(n.apiKey,n.authBlockedMessage)});r=o;let s=f(o,"status");if(!s||s==="checkout_required"||s==="pending"||s==="requires_action"||s==="payment_received"||s==="provisioning"||s==="finalizing"){await n.sleep(1500);continue}return o}catch(o){if(o instanceof Z&&o.status===429){await n.sleep(1500);continue}return R(ve(o),!1)}try{let i=await D(n,e,{headers:re(n.apiKey,n.authBlockedMessage)}),o=f(i,"status");if(o&&!["checkout_required","pending","requires_action","payment_received","provisioning","finalizing"].includes(o))return i;r=i}catch{}return{...r??{},status:"completion_pending",reasonCode:"enterprise_checkout_completion_pending",checkoutId:t,statusPath:e,retrySafe:!0,nextAction:"check_checkout_status",nextStep:"Check this checkout status again. Do not start a second checkout."}}async function ele(e,t){for(let n=0;n<120;n+=1)try{let r=await D(t,`/api/v1/me/private-skill-charges/${encodeURIComponent(e)}`,{headers:re(t.apiKey,t.authBlockedMessage)}),i=f(r,"status");if(!i||i==="checkout_required"||i==="pending"||i==="requires_action"){await t.sleep(1500);continue}return{...r,status:i}}catch(r){if(r instanceof Z&&r.status===429){await t.sleep(1500);continue}return R(ve(r),!1)}return R("Timed out while waiting for payment confirmation.",!1)}function sz(e){let t=L(e,"accountLink");return(t?f(t,"url"):void 0)??f(e,"url")??f(e,"setupUrl")}function tle(e){return e.status==="registration_confirmation_required"?"Account creation requires explicit confirmation.":e.status==="registration_required"?e.error??"No verified account exists for this social identity. Use `skills-layer register` first.":e.status==="state_expired"?"Social auth expired before completion. Start the flow again.":e.status==="provider_mismatch"?"The browser completed a different social provider than the one the CLI started.":e.status==="identity_conflict"?e.error??"This social identity is already linked to another account.":e.status==="email_required"?e.error??"This social profile did not provide an email address.":e.error??"Social auth could not be completed."}async function Vu(e,t,n={}){let i=n.forceProfileValidation===!0||!n.knownEmail||!n.knownRole?await D({...e,apiKey:t},"/api/v1/me",{headers:{...re(t),...n.notifyLogin?{"x-skills-layer-session-intent":"login"}:{}}}):{userId:n.knownUserId,sessionCredentialId:n.knownSessionCredentialId,email:n.knownEmail,role:n.knownRole,roles:n.knownRoles},o=f(i,"email")??n.knownEmail??"unknown";if(n.expectedEmail&&o.toLowerCase()!==n.expectedEmail.toLowerCase())throw new Error(`The entered API key belongs to ${o}, not ${n.expectedEmail}. Use the API key emailed to ${n.expectedEmail}.`);let s=await D({...e,apiKey:t},"/api/v1/capabilities",{headers:re(t)}),a={version:are,baseUrl:e.baseUrl,apiKey:t,edition:f(s,"edition")??f(i,"edition")??"saas",userId:f(i,"userId")??n.knownUserId,sessionCredentialId:f(i,"sessionCredentialId")??n.knownSessionCredentialId,email:o,role:f(i,"role")??n.knownRole??"user",roles:Un(i,"roles")??n.knownRoles,lastSelectedAgent:e.config?.lastSelectedAgent,savedAt:e.now()};return await CA(e.paths.configPath,a,e),await yce(e,a),await Ve(e.paths.backendPreferencePath,{version:JP,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),a}function LM(e,t){let n=ln(e.actionJson,"action-json");if(n&&typeof n=="object"&&!Array.isArray(n))return n;let r=k(e.action);return t==="incident"?{type:"file_write",path:k(e.path)??".skills-layer/incidents/guardian-incident.json"}:r==="file_read"||r==="file_write"?{type:r,path:k(e.path)??"."}:r==="shell_command"?{type:"shell_command",command:"unspecified"}:{type:"api_call",...r?{target:r}:{}}}async function me(e,t,n,r,i={}){let o=i.authenticated?re(n.apiKey,n.authBlockedMessage):Wo(n.apiKey);return await Gu(e,{headers:o},t,n,r)}async function nle(e,t){let[n,r,i]=await Promise.all([D(t,"/api/v1/status",{headers:Wo(t.apiKey)}),zn(t),Nh(t)]),o={guardian:r,mcp:i.publicState};return A({...n,localRuntime:o},"Status loaded.",e.json,t)}async function az(e,t){let n=new Set(t);return(await Wh({env:e.env,platform:e.platform,cwd:e.cwd,pathExists:e.pathExists})).map(r=>({...r,managedConfigured:n.has(r.hostId)}))}async function Nh(e){let t=await ke(e.paths.mcpConfigPath),n=t&&Array.isArray(t.clientIds)?t.clientIds.filter(d=>typeof d=="string"&&Ot(d)!==null):t&&f(t,"clientId")&&Ot(f(t,"clientId"))?[f(t,"clientId")]:[],r=await az(e,n),i=r.filter(d=>d.installed),o=r.filter(d=>d.configured),s=r.filter(d=>d.managedConfigured),a=!!t,l=!a&&i.length>0,c=a?"mcp_configured":l?"mcp_hosts_detected_unmanaged":"mcp_not_configured",u=a?`Skills Layer MCP is configured for ${n.length} managed host${n.length===1?"":"s"}.`:l?"MCP-capable hosts or host configuration were detected, but the Skills Layer managed bridge is not configured.":"No MCP-capable host or Skills Layer managed bridge was detected on this machine.";return{config:t,configuredClientIds:n,hosts:r,summary:u,publicState:{status:c,configured:a,managedConfigured:a,hostDetected:i.length>0,hostConfigured:o.length>0,clientId:n[0]??null,clientIds:n,detectedHostIds:i.map(d=>d.hostId),hostConfiguredIds:o.map(d=>d.hostId),hosts:r,detectedHostCount:i.length,hostConfiguredCount:o.length,managedConfiguredHostCount:s.length,verifiedHostCount:0,configPath:e.paths.mcpConfigPath,nextCommand:a?"skills-layer mcp verify":"skills-layer mcp setup",verifyCommand:a?n.length===1?`skills-layer mcp verify --client ${n[0]}`:"skills-layer mcp verify":"skills-layer mcp setup",nextAction:a?"mcp.verify":"mcp.setup",nextStep:a?"Verify the Skills Layer managed bridge from a fresh agent session.":l?"Run `skills-layer mcp setup` to connect Skills Layer to a detected MCP-capable host.":"Run `skills-layer mcp setup` to connect Skills Layer to an AI client."}}}async function rle(e,t){if(e.deep)return await ile(e,t);let n=await D(t,"/api/v1/doctor",{headers:Wo(t.apiKey)}),[r,i,o]=await Promise.all([zn(t),Gse(t),Nh(t)]),s=[...vz(n),fae(r,i)];return A({...n,guardian:{...r,policy:i},mcp:o.publicState,checks:s},"Doctor checks loaded.",e.json,t)}async function ile(e,t){let n;try{let c=await D(t,"/api/v1/status",{headers:Wo(t.apiKey)});n=cr("ok","backend_reachable","status","Backend status loaded.",{baseUrl:t.baseUrl,edition:f(c,"edition"),capabilityCount:Array.isArray(c.capabilities)?c.capabilities.length:void 0})}catch(c){n=cr("error","backend_unreachable","backend.status","Selected backend could not be reached.",{baseUrl:t.baseUrl,error:ve(c)})}let r=t.config?.credentialStorage??(t.apiKey?"local_file_locked":"none"),i=await Nh(t),o=i.config,s=await zn(t),a=et(t.env,t.platform,t.cwd).map(c=>({id:c.id,displayName:c.displayName,capabilities:c.capabilities})),l={backend:n,auth:t.apiKey?cr("ok","authenticated","whoami","A local session is available for the selected backend.",{email:t.config?.email,role:t.config?.role,savedLoginMatchesSelectedBackend:!0}):cr("login_required","login_required","login","No usable local session is available for the selected backend.",{savedLoginMatchesSelectedBackend:t.config?.baseUrl?Yu(t.config.baseUrl,t.baseUrl):!0}),credentialStorage:cr(r==="none"?"not_configured":"ok",r==="none"?"credential_storage_not_configured":"credential_storage_ready",r==="none"?"login":"auth.status",r==="none"?"Run `skills-layer login` to create a secure local session.":"Credential storage metadata is present.",{credentialStorage:r,configPath:t.paths.configPath}),mcp:o?cr("configured","mcp_configured","mcp.verify","MCP is configured locally; verify from a fresh agent session if tools are not visible.",{...i.publicState,mcpUrl:f(o,"mcpUrl")}):cr(i.publicState.hostDetected?"detected_unmanaged":"not_configured",i.publicState.status,"mcp.setup",i.summary,{...i.publicState}),guardianHooks:cr(f(s,"enforcementLayer")==="not_installed"?"not_installed":s.strictPreActionBlocking===!0?"ok":"warn",f(s,"enforcementLayer")==="not_installed"?"guardian_hook_not_installed":s.strictPreActionBlocking===!0?"guardian_hook_verified_strict":"guardian_hook_candidate_unverified","guardian.hook.status",f(s,"enforcementLayer")==="not_installed"?"Cloud Guardian checks work when called, but local pre-action hooks are not installed.":s.strictPreActionBlocking===!0?"At least one Skills Layer Security Hook has current matching live-canary evidence.":"A Skills Layer Security Hook is installed, but current live-canary evidence has not verified strict enforcement.",s),localPaths:cr("ok","local_paths_resolved","doctor.deep","Local Skills Layer paths resolved.",{stateDir:t.paths.stateDir,configPath:t.paths.configPath,installsPath:t.paths.installsPath,mcpConfigPath:t.paths.mcpConfigPath}),agentTargets:cr("ok","agent_targets_loaded","agents.list","Supported local agent targets loaded.",{count:a.length,results:a})};return A({status:"ok",deep:!0,sections:l,nextAction:t.apiKey?"status":"login",nextStep:t.apiKey?"Run `skills-layer status --json` for Cloud journey readiness.":"Run `skills-layer login` to sign in, then rerun `skills-layer doctor --deep --json`."},"Deep doctor diagnostics loaded.",e.json,t)}function cr(e,t,n,r,i={}){return ie({status:e,reasonCode:t,nextAction:n,nextStep:r,...i})}async function Oe(e,t,n,r,i,o={}){return await Gu(e,{method:"POST",headers:{...V(r.apiKey),...o},body:JSON.stringify(ie(t))},n,r,i)}function ole(){return`payout_request_${Ge(24).toString("base64url")}`}function sle(){return`guardian_incident_${Ge(24).toString("base64url")}`}async function ale(e,t){for(let n=0;n<2;n+=1)try{return await D(e,"/api/v1/guardian/enforce",{method:"POST",headers:V(e.apiKey),body:JSON.stringify(t)})}catch(r){if(!(r instanceof Z?[500,502,503,504].includes(r.status):r instanceof Error&&r.message.startsWith("Unable to reach "))||n===1)throw r;await e.sleep(250)}throw new Error("Guardian incident retry limit was exhausted.")}async function Li(e,t,n,r,i){return await Gu(e,{method:"PATCH",headers:V(r.apiKey),body:JSON.stringify(ie(t))},n,r,i)}async function Gu(e,t,n,r,i){let o=await D(r,e,t);return A(o,i,n.json,r)}async function D(e,t,n={}){tl(e.baseUrl);let r=await e.fetchFn(`${e.baseUrl}${t}`,{...n,redirect:"error"}).catch(s=>{throw new Error(`Unable to reach ${e.baseUrl}. ${ve(s)}`)});if(!r.ok)throw await lle(r);let i=await r.text();if(!i)return{};let o=JSON.parse(i);return o&&typeof o=="object"&&!Array.isArray(o)&&o.schemaVersion!=="skills-layer.creator.operation.v1"&&"data"in o?o.data:o}async function lle(e){let t=await e.text();if(t)try{let n=JSON.parse(t);return new Z(e.status,f(n,"error")??f(n,"summary")??(e.statusText||"Request failed"),n)}catch{return new Z(e.status,t)}return new Z(e.status,e.statusText||"Request failed")}function re(e,t){if(t)throw new Z(401,t,{error:t,nextAction:"backend.status",nextStep:t});if(!e)throw new Z(401,"Login required.",{error:"Login required.",nextAction:"login",nextStep:"Run `skills-layer login` to sign in, then retry this command."});return{authorization:`Bearer ${e}`}}function Wo(e){return e?{authorization:`Bearer ${e}`}:{}}function V(e,t){return{"content-type":"application/json",...e||t?re(e,t):{}}}async function Hu(e,t){if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(e)||/^[a-z][a-z0-9+.-]*:(?![\\/])/iu.test(e))return;let n=Tt(t,e);try{await Xu(n)}catch{return}let r=await ma({cwd:t,sourcePath:e,limits:yo});return{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:r.files}}var Ku=class extends Error{constructor(){super("Local Installation Ledger changed concurrently; retry the exact target operation."),this.name="InstallIndexRevisionConflictError"}},Fo=/^sha256:[a-f0-9]{64}$/u;function Wu(e){return{version:1,state:e.state,operationId:e.operationId,receipt:e.receipt,...e.quarantine?{quarantine:e.quarantine}:{},updatedAt:e.backend.now()}}function Jt(e){let t=L(e,"localLifecycle");if(!t||t.version!==1)return null;let n=f(t,"state"),r=f(t,"operationId"),i=f(t,"updatedAt"),o=pz(t.receipt);if(!n||!["pending_activation","active","quarantined","restore_pending","externally_removed","unreadable","drifted","host_detached"].includes(n)||!r||!i||!o)return null;let s=t.quarantine===void 0?void 0:dle(t.quarantine);return(n==="quarantined"||n==="restore_pending")&&!s?null:{version:1,state:n,operationId:r,receipt:o,...s?{quarantine:s}:{},updatedAt:i}}var cle=new Set(["agent","atomicActivation","guardianRuntimeMetadata","guardianEnforcement","guardianActivationReceipt","harnessUninstalledAt","hostRegistrationState","localLifecycle","materializationId","materializedPath","materializedSkillRoot","materializedWrites","receiptSha256","reconciliation","scope","targetAgent","targetAgents","targetGroup"]);function Zu(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!cle.has(t)))}function Bo(e,t){let r=(t==="win32"?st:Lt).resolve(e).normalize("NFC");return t==="linux"?r:r.toLocaleLowerCase("en-US")}function lz(e){let t=`${e.scope}\0${Bo(e.targetDir,e.platform)}`;return`materialization_${Ue("sha256").update(t).digest("hex").slice(0,24)}`}function Yt(e){let t=e?L(e,"materializations"):void 0;return t?Object.fromEntries(Object.entries(t).flatMap(([n,r])=>j(r)?[[n,r]]:[])):{}}function An(e){return Object.entries(Yt(e)).map(([t,n])=>({materializationId:t,record:n,lifecycle:Jt(n)}))}function mr(e){return Array.from(new Set([...Un(e,"targetAgents")??[],...[f(e,"agent"),f(e,"targetAgent")].filter(t=>!!t)])).sort()}function Fr(e){let t=Jt(e.materialization),n=f(e.materialization,"scope");if(!t||n!=="project"&&n!=="global")throw new Error("Local Installation Ledger materialization requires an exact lifecycle and project/global scope.");let r=f(e.materialization,"materializationId")??lz({scope:n,targetDir:t.receipt.targetDir,platform:e.backend.platform}),i=Yt(e.existing)[r],o=Array.from(new Set([...mr(i??{}),...mr(e.materialization)])).sort(),s={...e.materialization,materializationId:r,targetAgents:o,...o.length>1?{targetGroup:`shared:${n}:${o.join(",")}`}:{},receiptSha256:Vr(t.receipt),savedAt:e.backend.now()},a={...Yt(e.existing),[r]:s},l=Object.keys(a).length===1?s:{};return{...Zu(e.existing??{}),...l,skillSlug:e.skillSlug,materializations:a,materializationCount:Object.keys(a).length,savedAt:e.backend.now()}}function cz(e){let t=Yt(e.existing);if(delete t[e.materializationId],Object.keys(t).length===0)return;let n=Object.values(t);return{...Zu(e.existing),...n.length===1?n[0]:{},materializations:t,materializationCount:Object.keys(t).length,savedAt:e.backend.now()}}function qn(e,t={}){return An(e).filter(n=>{let r=f(n.record,"scope");if(t.scope&&r!==t.scope||t.agent&&!mr(n.record).includes(t.agent)||t.receiptSha256&&f(n.record,"receiptSha256")!==t.receiptSha256)return!1;if(t.installedPath){let i=n.lifecycle?.receipt.targetDir;if(!i||!yA(t.installedPath,i,t.platform??process.platform))return!1}return!0})}function ule(e){let t=e.backend.platform==="win32"?st:Lt,n=new Set;for(let r of et(e.backend.env,e.backend.platform,e.backend.cwd))if(!(e.agent&&r.id!==e.agent))for(let i of new Set([e.skillSlug,Mr(e.skillSlug)]))(!e.scope||e.scope==="project")&&n.add(Bo(t.join(r.targets.projectSkillsPath,i),e.backend.platform)),(!e.scope||e.scope==="global")&&r.targets.globalSkillsPath&&n.add(Bo(t.join(r.targets.globalSkillsPath,i),e.backend.platform));return e.materializations.filter(r=>{let i=r.lifecycle?.receipt.targetDir;return!!(i&&n.has(Bo(i,e.backend.platform)))})}function gr(e,t){return{...Zu(e),...t.record,materializationId:t.materializationId}}function uz(e){return Object.values(e.installs).flatMap(t=>{let n=An(t);return n.length>0?n.map(r=>gr(t,r)):[t]})}function dz(e){let t=L(e,"cachedArtifact"),n=t?L(t,"generation"):void 0,r=t?f(t,"state"):void 0,i=t?f(t,"bundlePath"):void 0,o=n?f(n,"skillSlug"):void 0,s=n?f(n,"semanticVersion"):void 0,a=n?f(n,"generationId"):void 0,l=t?f(t,"archiveSha256"):void 0,c=t?f(t,"manifestSha256"):void 0,u=t?f(t,"savedAt"):void 0;return r!=="verified"||!i||!o||!s||!a||!l||!Fo.test(l)||!c||!Fo.test(c)||!u?null:{state:"verified",bundlePath:i,generation:{skillSlug:o,semanticVersion:s,generationId:a},archiveSha256:l,manifestSha256:c,savedAt:u}}function pz(e){if(!j(e))return null;let t=f(e,"targetDir"),n=L(e,"generation"),r=n?f(n,"skillSlug"):void 0,i=n?f(n,"semanticVersion"):void 0,o=n?f(n,"generationId"):void 0,s=f(e,"archiveSha256"),a=f(e,"manifestSha256"),l=Be(e,"files");if(!t||!r||!i||!o||!s||!Fo.test(s)||!a||!Fo.test(a)||!l||l.length===0)return null;let c=l.flatMap(u=>{if(!j(u))return[];let d=f(u,"path"),p=J(u,"sizeBytes"),m=f(u,"sha256");return d&&Number.isSafeInteger(p)&&p>=0&&m&&Fo.test(m)?[{path:d,sizeBytes:p,sha256:m}]:[]});return c.length!==l.length?null:{targetDir:t,generation:{skillSlug:r,semanticVersion:i,generationId:o},archiveSha256:s,manifestSha256:a,files:c}}function fz(e){if(!j(e)||e.status!=="authorized")return null;let t=f(e,"authorizationId"),n=f(e,"purpose"),r=L(e,"generation"),i=r?f(r,"skillSlug"):void 0,o=r?f(r,"semanticVersion"):void 0,s=r?f(r,"generationId"):void 0,a=f(e,"archiveSha256"),l=f(e,"manifestSha256");return!t||!n||!["quarantine_blocked","quarantine_revoked","restore_fresh_approval","purge_quarantined"].includes(n)||!i||!o||!s||!a||!Fo.test(a)||!l||!Fo.test(l)?null:{status:"authorized",authorizationId:t,purpose:n,generation:{skillSlug:i,semanticVersion:o,generationId:s},archiveSha256:a,manifestSha256:l}}function dle(e){if(!j(e)||e.status!=="quarantined")return null;let t=f(e,"reasonCode"),n=f(e,"targetDir"),r=f(e,"quarantineRoot"),i=f(e,"quarantineDir"),o=Un(e,"discoveryRoots"),s=fz(e.quarantineAuthorization),a=pz(e.receipt);return!t||!n||!r||!i||!o||o.length===0||!s||!a?null:{status:"quarantined",reasonCode:t,targetDir:n,quarantineRoot:r,quarantineDir:i,discoveryRoots:o,quarantineAuthorization:s,receipt:a}}async function lt(e){let t=await ke(e.paths.installsPath);return!j(t)||t.version!==hh||!j(t.installs)?{version:hh,revision:0,installs:{}}:{version:hh,revision:Number.isSafeInteger(t.revision)&&Number(t.revision)>=0?Number(t.revision):0,installs:gle(t.installs)}}async function _A(e,t){let n=e.paths.installsPath,r=Me(n);await Zo(r);let i=`${n}.lock`,o,s=Date.now()+5e3;for(;!o;)try{o=await Uo(i,"wx",384)}catch(c){if(c.code!=="EEXIST"||Date.now()>=s)throw c;await new Promise(u=>setTimeout(u,10))}let a=K(r,`.${ot(n)}.${Ge(12).toString("hex")}.tmp`),l;try{let c=await ke(n),u=j(c)&&c.version===hh&&Number.isSafeInteger(c.revision)&&Number(c.revision)>=0?Number(c.revision):0;if(u!==t.revision)throw new Ku;let d={...t,revision:u+1};l=await Uo(a,"wx",384),await l.writeFile(`${JSON.stringify(d,null,2)}
|
|
2277
|
-
`,"utf8"),await l.sync(),await l.close(),l=void 0,await zo(a,n),await Jo(n,384),await SA(r),t.revision=d.revision}catch(c){throw await l?.close().catch(()=>{}),await We(a,{force:!0}).catch(()=>{}),c}finally{await o.close().catch(()=>{}),await We(i,{force:!0}).catch(()=>{})}}async function Br(e,t){for(let n=0;n<8;n+=1){let r=await lt(e);await t(r);try{return await _A(e,r),r}catch(i){if(!(i instanceof Ku)||n===7)throw i}}throw new Ku}async function Bi(e,t){let n=await lt(e),r=!1,i=[];for(let[o,s]of Object.entries(n.installs)){if(t&&o!==t)continue;let a=s;for(let l of An(s)){let c=l.lifecycle;if(!c||c.state!=="active")continue;let u=await ple(l.record,c);if(u.state==="active")continue;let d=u.state;a=Fr({existing:a,skillSlug:o,materialization:{...l.record,status:u.state,reconciliation:{version:1,state:u.state,reasonCode:u.reasonCode,observedAt:e.now(),recoverable:u.recoverable},localLifecycle:{...c,state:d,updatedAt:e.now()},savedAt:e.now()},backend:e}),r=!0,i.push({skillSlug:o,generationId:c.receipt.generation.generationId,receiptSha256:Vr(c.receipt),state:u.state==="externally_removed"?"externally_removed":u.state==="host_detached"?"host_detached":"stale",reasonCode:u.reasonCode})}n.installs[o]=a}r&&await _A(e,n);for(let o of i)await fle(e,o).catch(()=>{});return n}async function ple(e,t){let n;try{let o=await Xu(t.receipt.targetDir);n=o.isDirectory()&&!o.isSymbolicLink()?"present_directory":"replaced_type"}catch(o){n=o.code==="ENOENT"?"absent":"unreadable"}let r=n==="present_directory"?(await Dr(t.receipt)).status==="verified"?"verified":"changed":"unchecked",i=e.hostRegistrationState==="detached"||typeof e.harnessUninstalledAt=="string"?"detached":"unknown";return g2({pathState:n,receiptState:r,hostState:i})}async function fle(e,t){for(let n of["project","global"]){let r;try{r=await Vo(e,n)}catch{continue}let i=Object.entries(r.associations).filter(([,o])=>o.skillSlug===t.skillSlug&&o.generationId===t.generationId&&o.receiptSha256===t.receiptSha256&&o.state!=="externally_removed"&&o.state!=="host_detached");for(let[o]of i)await jo(e,n,o,{state:t.state,reasonCode:t.reasonCode,updatedAt:e.now()})}}async function SA(e){if(process.platform!=="win32")try{let t=await Uo(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function mle(e){await Br(e.backend,t=>{let n=t.installs[e.skillSlug];if(!n)return;let r=Yt(n)[e.materializationId],i=r?Jt(r):null;if(!i||i.operationId!==e.operationId)return;if(e.baselineMaterialization){t.installs[e.skillSlug]=Fr({existing:n,skillSlug:e.skillSlug,materialization:e.baselineMaterialization,backend:e.backend});return}let o=cz({existing:n,materializationId:e.materializationId,backend:e.backend});o?t.installs[e.skillSlug]=o:delete t.installs[e.skillSlug]})}async function Ha(e,t,n){let r=f(t,"skillSlug")??f(t,"slug")??n,i=Array.isArray(t.materializationResults)?t.materializationResults.filter(j):Jt(t)?[t]:[],o=i.length>0?Zu(t):t;await Br(e,s=>{let a={...Zu(s.installs[r]??{}),...o,...t.acquisitionMode==="authenticated_account"?{acquisitionBaseUrl:e.baseUrl,acquiredByUserId:e.config?.userId}:{},skillSlug:r,materializations:Yt(s.installs[r]),savedAt:e.now()};for(let l of i)a=Fr({existing:a,skillSlug:r,materialization:{...l,...t.acquisitionMode==="authenticated_account"?{acquisitionMode:t.acquisitionMode,acquisitionBaseUrl:e.baseUrl,acquiredByUserId:e.config?.userId,entitlementId:t.entitlementId}:{}},backend:e});s.installs[r]=a})}function gle(e){let t={};for(let[n,r]of Object.entries(e))t[n]=j(r)?r:{skillSlug:n,value:r};return t}var at=5;function mz(e){if(!j(e))return null;let t=f(e,"reasonCode"),n=t==="commercial_rights_declaration_required"||t==="commercial_rights_declaration_invalid";if(!n&&t!=="paid_to_free_confirmation_required")return null;let r=n?"Confirm your rights to distribute this skill.":"Confirm that this paid skill should become free.";return{...e,status:"action_required",error:r,message:r,nextAction:"retry",nextStep:n?"Repeat with --attest-rights --rights-basis self_authored after confirming your rights. For submit or submit-version, also add --distribution-scope commercial_distribution.":"To make this paid skill free, repeat with --price-cents 0 --confirm-free. The generic --yes flag does not confirm this change."}}function
|
|
2276
|
+
Waiting for browser sign-in to finish...`)}else r.json||i.emitInfo(o==="recovery"?`${u} recovery started. Finish the verification in your browser, then come back here. Waiting for browser recovery to finish...`:`${u} sign-in started. Finish the login in your browser, then come back here. Waiting for browser sign-in to finish...`);let d=await Jae(c,i,s);if(fe(d))return d;if(d.status==="verified"||d.status==="recovered")return await kh(u,n,r,i,o);if(d.status==="mfa_required"){if(!n)return E("Login MFA handoff is unavailable. Start login again.",r.json);let p=k(r.mfaCode),m=k(r.recoveryCode);if(!p&&!m&&!r.json&&i.stdoutIsTty){let g=await i.promptSelect("Complete MFA to finish login:",[{value:"authenticator",label:"Authenticator code",description:"Use the current 6-digit code"},{value:"recovery_code",label:"Recovery code",description:"Use one unused one-time recovery code"}]),y=(await i.promptSecret(g==="recovery_code"?"Enter one unused MFA recovery code: ":"Enter the 6-digit authenticator code: ")).trim();g==="recovery_code"?m=y:p=y}if(!p&&!m)return x({status:"human_action_required",reasonCode:"login_mfa_required",methods:["authenticator","recovery_code"],nextAction:"account.login.mfa",nextStep:"Re-run login in a human terminal and complete MFA."},"MFA is required to finish login.",r.json,"login_mfa_required");let h=await D(i,"/api/v1/identity/login/mfa/verify",{method:"POST",headers:V(),body:JSON.stringify({state:c,authorizationCode:n.authorizationCode,codeVerifier:n.codeVerifier,...p?{mfaCode:p}:{},...m?{recoveryCode:m}:{}})});return f(h,"status")!=="verified"||f(h,"credentialHandoff")!=="ready"?E("MFA verification did not authorize the login credential. Start login again.",r.json):await kh(u,n,r,i,o)}if(d.status==="already_registered"||d.status==="link_required"){let p=GF(e,!!i.apiKey&&!i.authBlockedMessage);return x({...p},p.summary,r.json,"social_identity_link_required")}if(d.status==="registration_confirmation_required"){if(!r.json&&i.stdoutIsTty){let m=await i.promptSelect(`Create a new Skills Layer account using your verified ${u} identity?`,[{value:"create",label:"Yes, create my account",description:"Create one account, connect this sign-in, and log in"},{value:"cancel",label:"No",description:"Create nothing and leave Skills Layer unchanged"}])==="create",h=await D(i,"/api/v1/identity/social/registration/confirm",{method:"POST",headers:V(),body:JSON.stringify({state:c,createAccount:m})});return!m||f(h,"status")==="registration_cancelled"?R({status:"registration_cancelled",changed:!1},"Registration cancelled. No Skills Layer account was created.",!1,i):f(h,"status")!=="verified"||f(h,"credentialHandoff")!=="ready"?E("Account creation could not be confirmed safely. Start registration again.",!1):await kh(u,n,r,i,"register")}return x({status:"registration_confirmation_required",reasonCode:"registration_confirmation_required",nextAction:"account.registration.confirm",nextStep:r.createAccount?"Provider verification finished, but account creation still needs confirmation. Start registration again.":"Re-run registration with --create-account after confirming that you want to create this account."},"Account creation needs explicit confirmation.",r.json,"registration_confirmation_required")}return d.status==="linked"?R(d,`${u} sign-in is now connected.`,r.json,i):Zae(d)?E(tle(d),r.json):E("Social auth completed with an unexpected response.",r.json)}async function kh(e,t,n,r,i){if(!t)return E("Social credential handoff is unavailable. Start the login flow again.",n.json);let o=await D(r,"/api/v1/identity/social/exchange",{method:"POST",headers:V(),body:JSON.stringify({authorizationCode:t.authorizationCode,codeVerifier:t.codeVerifier})});if(f(o,"status")!=="exchanged"||!f(o,"email")||!f(o,"role")||!f(o,"apiKey"))return E("Social credential handoff failed closed. Start the login flow again.",n.json);let s=f(o,"email");return await kA(s,o,n,r,i==="recovery"?`Recovered access for ${s} through ${e}.`:`Verified ${s} through ${e}.`)}function Ko(e){return e==="google"||e==="github"||e==="gitlab"||e==="microsoft"}function fe(e){return j(e)&&typeof e.exitCode=="number"&&typeof e.stdout=="string"&&typeof e.stderr=="string"}function Wae(e){try{let t=JSON.parse(e);return j(t)?t.data:void 0}catch{return}}function Zae(e){return e.status==="registration_required"||e.status==="state_expired"||e.status==="provider_mismatch"||e.status==="identity_conflict"||e.status==="email_required"||e.status==="failed"}async function Jae(e,t,n="/api/v1/identity/social/status"){for(let r=0;r<120;r+=1)try{let i=await D(t,`${n}/${encodeURIComponent(e)}`,n.includes("/identity/connect/")?{headers:re(t.apiKey,t.authBlockedMessage)}:void 0),o=f(i,"status")??"failed";if(o==="pending"){await t.sleep(1500);continue}return(o==="verified"||o==="recovered")&&f(i,"credentialHandoff")==="ready"?{status:o,credentialHandoff:"ready"}:o==="already_registered"||o==="link_required"?{status:o}:o==="linked"?{status:o}:o==="registration_confirmation_required"?{status:o}:o==="mfa_required"?{status:o}:o==="registration_required"||o==="state_expired"||o==="provider_mismatch"||o==="identity_conflict"||o==="email_required"||o==="failed"?{status:o,error:f(i,"error")}:E("Social auth completed with an unexpected response.",!1)}catch(i){if(i instanceof Z&&(i.status===404||i.status===429)){await t.sleep(1500);continue}return E(ve(i),!1)}return E("Timed out while waiting for social auth to complete.",!1)}async function Yae(e,t){let n=`/api/v1/identity/mfa/recovery-codes/operations/${encodeURIComponent(e)}`;for(let r=0;r<210;r+=1)try{let i=await D(t,n,{headers:re(t.apiKey,t.authBlockedMessage)}),o=f(i,"status"),s=L(i,"data");if(o==="pending"||o==="finalizing"){await t.sleep(1500);continue}if(o==="completed")return{...i,completedAt:f(i,"completedAt")??(s?f(s,"completedAt"):void 0)};if(o==="locked"){let a=f(i,"retryAt")??(s?f(s,"retryAt"):void 0);return x({status:"locked",reasonCode:"mfa_challenge_locked",retryAt:a,nextAction:"wait",nextStep:a?`Retry after ${a}.`:"Wait for the MFA verification lock to expire, then retry."},"Recovery-code verification is temporarily locked after too many invalid attempts.",!1)}return o==="failed"?x({status:"failed",reasonCode:"mfa_recovery_codes_failed",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"Recovery codes were not replaced.",!1):o==="expired"?x({status:"expired",reasonCode:"mfa_recovery_codes_expired",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"The recovery-code browser session expired before completion.",!1):E("Recovery-code verification completed with an unexpected response.",!1)}catch(i){if(i instanceof Z&&i.status===429){let o=i.details??{},s=f(o,"reasonCode"),a=f(o,"retryAt");if(s==="mfa_challenge_locked")return x({status:"locked",reasonCode:s,retryAt:a,nextAction:"wait",nextStep:a?`Retry after ${a}.`:"Wait for the MFA verification lock to expire, then retry."},"Recovery-code verification is temporarily locked after too many invalid attempts.",!1);let l=J(o,"retryAfterSeconds"),c=l===void 0?1500:Math.min(6e4,Math.max(1500,l*1e3));await t.sleep(c);continue}return E(ve(i),!1)}return x({status:"expired",reasonCode:"mfa_recovery_codes_expired",nextAction:"retry",nextStep:"Run `skills-layer auth mfa recovery-codes` again."},"Timed out while waiting for recovery-code verification.",!1)}async function Xae(e,t){for(let n=0;n<120;n+=1)try{let r=await D(t,`/api/v1/purchases/${encodeURIComponent(e)}`,{headers:re(t.apiKey,t.authBlockedMessage)});if(!r?.status||r.status==="pending"||r.status==="requires_action"){await t.sleep(1500);continue}return{status:r.status,purchaseId:e}}catch(r){if(r instanceof Z&&r.status===429){await t.sleep(1500);continue}return E(ve(r),!1)}return E("Timed out while waiting for purchase confirmation.",!1)}async function Qae(e,t,n){let r=null;for(let i=0;i<120;i+=1)try{let o=await D(n,e,{headers:re(n.apiKey,n.authBlockedMessage)});r=o;let s=f(o,"status");if(!s||s==="checkout_required"||s==="pending"||s==="requires_action"||s==="payment_received"||s==="provisioning"||s==="finalizing"){await n.sleep(1500);continue}return o}catch(o){if(o instanceof Z&&o.status===429){await n.sleep(1500);continue}return E(ve(o),!1)}try{let i=await D(n,e,{headers:re(n.apiKey,n.authBlockedMessage)}),o=f(i,"status");if(o&&!["checkout_required","pending","requires_action","payment_received","provisioning","finalizing"].includes(o))return i;r=i}catch{}return{...r??{},status:"completion_pending",reasonCode:"enterprise_checkout_completion_pending",checkoutId:t,statusPath:e,retrySafe:!0,nextAction:"check_checkout_status",nextStep:"Check this checkout status again. Do not start a second checkout."}}async function ele(e,t){for(let n=0;n<120;n+=1)try{let r=await D(t,`/api/v1/me/private-skill-charges/${encodeURIComponent(e)}`,{headers:re(t.apiKey,t.authBlockedMessage)}),i=f(r,"status");if(!i||i==="checkout_required"||i==="pending"||i==="requires_action"){await t.sleep(1500);continue}return{...r,status:i}}catch(r){if(r instanceof Z&&r.status===429){await t.sleep(1500);continue}return E(ve(r),!1)}return E("Timed out while waiting for payment confirmation.",!1)}function sz(e){let t=L(e,"accountLink");return(t?f(t,"url"):void 0)??f(e,"url")??f(e,"setupUrl")}function tle(e){return e.status==="registration_confirmation_required"?"Account creation requires explicit confirmation.":e.status==="registration_required"?e.error??"No verified account exists for this social identity. Use `skills-layer register` first.":e.status==="state_expired"?"Social auth expired before completion. Start the flow again.":e.status==="provider_mismatch"?"The browser completed a different social provider than the one the CLI started.":e.status==="identity_conflict"?e.error??"This social identity is already linked to another account.":e.status==="email_required"?e.error??"This social profile did not provide an email address.":e.error??"Social auth could not be completed."}async function Vu(e,t,n={}){let i=n.forceProfileValidation===!0||!n.knownEmail||!n.knownRole?await D({...e,apiKey:t},"/api/v1/me",{headers:{...re(t),...n.notifyLogin?{"x-skills-layer-session-intent":"login"}:{}}}):{userId:n.knownUserId,sessionCredentialId:n.knownSessionCredentialId,email:n.knownEmail,role:n.knownRole,roles:n.knownRoles},o=f(i,"email")??n.knownEmail??"unknown";if(n.expectedEmail&&o.toLowerCase()!==n.expectedEmail.toLowerCase())throw new Error(`The entered API key belongs to ${o}, not ${n.expectedEmail}. Use the API key emailed to ${n.expectedEmail}.`);let s=await D({...e,apiKey:t},"/api/v1/capabilities",{headers:re(t)}),a={version:are,baseUrl:e.baseUrl,apiKey:t,edition:f(s,"edition")??f(i,"edition")??"saas",userId:f(i,"userId")??n.knownUserId,sessionCredentialId:f(i,"sessionCredentialId")??n.knownSessionCredentialId,email:o,role:f(i,"role")??n.knownRole??"user",roles:Un(i,"roles")??n.knownRoles,lastSelectedAgent:e.config?.lastSelectedAgent,savedAt:e.now()};return await CA(e.paths.configPath,a,e),await yce(e,a),await Ve(e.paths.backendPreferencePath,{version:JP,preferredBaseUrl:e.baseUrl,savedAt:e.now()}),a}function LM(e,t){let n=ln(e.actionJson,"action-json");if(n&&typeof n=="object"&&!Array.isArray(n))return n;let r=k(e.action);return t==="incident"?{type:"file_write",path:k(e.path)??".skills-layer/incidents/guardian-incident.json"}:r==="file_read"||r==="file_write"?{type:r,path:k(e.path)??"."}:r==="shell_command"?{type:"shell_command",command:"unspecified"}:{type:"api_call",...r?{target:r}:{}}}async function me(e,t,n,r,i={}){let o=i.authenticated?re(n.apiKey,n.authBlockedMessage):Wo(n.apiKey);return await Gu(e,{headers:o},t,n,r)}async function nle(e,t){let[n,r,i]=await Promise.all([D(t,"/api/v1/status",{headers:Wo(t.apiKey)}),zn(t),Nh(t)]),o={guardian:r,mcp:i.publicState};return R({...n,localRuntime:o},"Status loaded.",e.json,t)}async function az(e,t){let n=new Set(t);return(await Wh({env:e.env,platform:e.platform,cwd:e.cwd,pathExists:e.pathExists})).map(r=>({...r,managedConfigured:n.has(r.hostId)}))}async function Nh(e){let t=await ke(e.paths.mcpConfigPath),n=t&&Array.isArray(t.clientIds)?t.clientIds.filter(d=>typeof d=="string"&&Ot(d)!==null):t&&f(t,"clientId")&&Ot(f(t,"clientId"))?[f(t,"clientId")]:[],r=await az(e,n),i=r.filter(d=>d.installed),o=r.filter(d=>d.configured),s=r.filter(d=>d.managedConfigured),a=!!t,l=!a&&i.length>0,c=a?"mcp_configured":l?"mcp_hosts_detected_unmanaged":"mcp_not_configured",u=a?`Skills Layer MCP is configured for ${n.length} managed host${n.length===1?"":"s"}.`:l?"MCP-capable hosts or host configuration were detected, but the Skills Layer managed bridge is not configured.":"No MCP-capable host or Skills Layer managed bridge was detected on this machine.";return{config:t,configuredClientIds:n,hosts:r,summary:u,publicState:{status:c,configured:a,managedConfigured:a,hostDetected:i.length>0,hostConfigured:o.length>0,clientId:n[0]??null,clientIds:n,detectedHostIds:i.map(d=>d.hostId),hostConfiguredIds:o.map(d=>d.hostId),hosts:r,detectedHostCount:i.length,hostConfiguredCount:o.length,managedConfiguredHostCount:s.length,verifiedHostCount:0,configPath:e.paths.mcpConfigPath,nextCommand:a?"skills-layer mcp verify":"skills-layer mcp setup",verifyCommand:a?n.length===1?`skills-layer mcp verify --client ${n[0]}`:"skills-layer mcp verify":"skills-layer mcp setup",nextAction:a?"mcp.verify":"mcp.setup",nextStep:a?"Verify the Skills Layer managed bridge from a fresh agent session.":l?"Run `skills-layer mcp setup` to connect Skills Layer to a detected MCP-capable host.":"Run `skills-layer mcp setup` to connect Skills Layer to an AI client."}}}async function rle(e,t){if(e.deep)return await ile(e,t);let n=await D(t,"/api/v1/doctor",{headers:Wo(t.apiKey)}),[r,i,o]=await Promise.all([zn(t),Gse(t),Nh(t)]),s=[...vz(n),fae(r,i)];return R({...n,guardian:{...r,policy:i},mcp:o.publicState,checks:s},"Doctor checks loaded.",e.json,t)}async function ile(e,t){let n;try{let c=await D(t,"/api/v1/status",{headers:Wo(t.apiKey)});n=cr("ok","backend_reachable","status","Backend status loaded.",{baseUrl:t.baseUrl,edition:f(c,"edition"),capabilityCount:Array.isArray(c.capabilities)?c.capabilities.length:void 0})}catch(c){n=cr("error","backend_unreachable","backend.status","Selected backend could not be reached.",{baseUrl:t.baseUrl,error:ve(c)})}let r=t.config?.credentialStorage??(t.apiKey?"local_file_locked":"none"),i=await Nh(t),o=i.config,s=await zn(t),a=et(t.env,t.platform,t.cwd).map(c=>({id:c.id,displayName:c.displayName,capabilities:c.capabilities})),l={backend:n,auth:t.apiKey?cr("ok","authenticated","whoami","A local session is available for the selected backend.",{email:t.config?.email,role:t.config?.role,savedLoginMatchesSelectedBackend:!0}):cr("login_required","login_required","login","No usable local session is available for the selected backend.",{savedLoginMatchesSelectedBackend:t.config?.baseUrl?Yu(t.config.baseUrl,t.baseUrl):!0}),credentialStorage:cr(r==="none"?"not_configured":"ok",r==="none"?"credential_storage_not_configured":"credential_storage_ready",r==="none"?"login":"auth.status",r==="none"?"Run `skills-layer login` to create a secure local session.":"Credential storage metadata is present.",{credentialStorage:r,configPath:t.paths.configPath}),mcp:o?cr("configured","mcp_configured","mcp.verify","MCP is configured locally; verify from a fresh agent session if tools are not visible.",{...i.publicState,mcpUrl:f(o,"mcpUrl")}):cr(i.publicState.hostDetected?"detected_unmanaged":"not_configured",i.publicState.status,"mcp.setup",i.summary,{...i.publicState}),guardianHooks:cr(f(s,"enforcementLayer")==="not_installed"?"not_installed":s.strictPreActionBlocking===!0?"ok":"warn",f(s,"enforcementLayer")==="not_installed"?"guardian_hook_not_installed":s.strictPreActionBlocking===!0?"guardian_hook_verified_strict":"guardian_hook_candidate_unverified","guardian.hook.status",f(s,"enforcementLayer")==="not_installed"?"Cloud Guardian checks work when called, but local pre-action hooks are not installed.":s.strictPreActionBlocking===!0?"At least one Skills Layer Security Hook has current matching live-canary evidence.":"A Skills Layer Security Hook is installed, but current live-canary evidence has not verified strict enforcement.",s),localPaths:cr("ok","local_paths_resolved","doctor.deep","Local Skills Layer paths resolved.",{stateDir:t.paths.stateDir,configPath:t.paths.configPath,installsPath:t.paths.installsPath,mcpConfigPath:t.paths.mcpConfigPath}),agentTargets:cr("ok","agent_targets_loaded","agents.list","Supported local agent targets loaded.",{count:a.length,results:a})};return R({status:"ok",deep:!0,sections:l,nextAction:t.apiKey?"status":"login",nextStep:t.apiKey?"Run `skills-layer status --json` for Cloud journey readiness.":"Run `skills-layer login` to sign in, then rerun `skills-layer doctor --deep --json`."},"Deep doctor diagnostics loaded.",e.json,t)}function cr(e,t,n,r,i={}){return ie({status:e,reasonCode:t,nextAction:n,nextStep:r,...i})}async function Oe(e,t,n,r,i,o={}){return await Gu(e,{method:"POST",headers:{...V(r.apiKey),...o},body:JSON.stringify(ie(t))},n,r,i)}function ole(){return`payout_request_${Ge(24).toString("base64url")}`}function sle(){return`guardian_incident_${Ge(24).toString("base64url")}`}async function ale(e,t){for(let n=0;n<2;n+=1)try{return await D(e,"/api/v1/guardian/enforce",{method:"POST",headers:V(e.apiKey),body:JSON.stringify(t)})}catch(r){if(!(r instanceof Z?[500,502,503,504].includes(r.status):r instanceof Error&&r.message.startsWith("Unable to reach "))||n===1)throw r;await e.sleep(250)}throw new Error("Guardian incident retry limit was exhausted.")}async function Li(e,t,n,r,i){return await Gu(e,{method:"PATCH",headers:V(r.apiKey),body:JSON.stringify(ie(t))},n,r,i)}async function Gu(e,t,n,r,i){let o=await D(r,e,t);return R(o,i,n.json,r)}async function D(e,t,n={}){tl(e.baseUrl);let r=await e.fetchFn(`${e.baseUrl}${t}`,{...n,redirect:"error"}).catch(s=>{throw new Error(`Unable to reach ${e.baseUrl}. ${ve(s)}`)});if(!r.ok)throw await lle(r);let i=await r.text();if(!i)return{};let o=JSON.parse(i);return o&&typeof o=="object"&&!Array.isArray(o)&&o.schemaVersion!=="skills-layer.creator.operation.v1"&&"data"in o?o.data:o}async function lle(e){let t=await e.text();if(t)try{let n=JSON.parse(t);return new Z(e.status,f(n,"error")??f(n,"summary")??(e.statusText||"Request failed"),n)}catch{return new Z(e.status,t)}return new Z(e.status,e.statusText||"Request failed")}function re(e,t){if(t)throw new Z(401,t,{error:t,nextAction:"backend.status",nextStep:t});if(!e)throw new Z(401,"Login required.",{error:"Login required.",nextAction:"login",nextStep:"Run `skills-layer login` to sign in, then retry this command."});return{authorization:`Bearer ${e}`}}function Wo(e){return e?{authorization:`Bearer ${e}`}:{}}function V(e,t){return{"content-type":"application/json",...e||t?re(e,t):{}}}async function Hu(e,t){if(/^[a-z][a-z0-9+.-]*:\/\//iu.test(e)||/^[a-z][a-z0-9+.-]*:(?![\\/])/iu.test(e))return;let n=Tt(t,e);try{await Xu(n)}catch{return}let r=await ma({cwd:t,sourcePath:e,limits:yo});return{sourceMetadata:{kind:"local",input:e,canonicalSource:`local:${e}`},files:r.files}}var Ku=class extends Error{constructor(){super("Local Installation Ledger changed concurrently; retry the exact target operation."),this.name="InstallIndexRevisionConflictError"}},Fo=/^sha256:[a-f0-9]{64}$/u;function Wu(e){return{version:1,state:e.state,operationId:e.operationId,receipt:e.receipt,...e.quarantine?{quarantine:e.quarantine}:{},updatedAt:e.backend.now()}}function Jt(e){let t=L(e,"localLifecycle");if(!t||t.version!==1)return null;let n=f(t,"state"),r=f(t,"operationId"),i=f(t,"updatedAt"),o=pz(t.receipt);if(!n||!["pending_activation","active","quarantined","restore_pending","externally_removed","unreadable","drifted","host_detached"].includes(n)||!r||!i||!o)return null;let s=t.quarantine===void 0?void 0:dle(t.quarantine);return(n==="quarantined"||n==="restore_pending")&&!s?null:{version:1,state:n,operationId:r,receipt:o,...s?{quarantine:s}:{},updatedAt:i}}var cle=new Set(["agent","atomicActivation","guardianRuntimeMetadata","guardianEnforcement","guardianActivationReceipt","harnessUninstalledAt","hostRegistrationState","localLifecycle","materializationId","materializedPath","materializedSkillRoot","materializedWrites","receiptSha256","reconciliation","scope","targetAgent","targetAgents","targetGroup"]);function Zu(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!cle.has(t)))}function Bo(e,t){let r=(t==="win32"?st:Lt).resolve(e).normalize("NFC");return t==="linux"?r:r.toLocaleLowerCase("en-US")}function lz(e){let t=`${e.scope}\0${Bo(e.targetDir,e.platform)}`;return`materialization_${Ue("sha256").update(t).digest("hex").slice(0,24)}`}function Yt(e){let t=e?L(e,"materializations"):void 0;return t?Object.fromEntries(Object.entries(t).flatMap(([n,r])=>j(r)?[[n,r]]:[])):{}}function An(e){return Object.entries(Yt(e)).map(([t,n])=>({materializationId:t,record:n,lifecycle:Jt(n)}))}function mr(e){return Array.from(new Set([...Un(e,"targetAgents")??[],...[f(e,"agent"),f(e,"targetAgent")].filter(t=>!!t)])).sort()}function Fr(e){let t=Jt(e.materialization),n=f(e.materialization,"scope");if(!t||n!=="project"&&n!=="global")throw new Error("Local Installation Ledger materialization requires an exact lifecycle and project/global scope.");let r=f(e.materialization,"materializationId")??lz({scope:n,targetDir:t.receipt.targetDir,platform:e.backend.platform}),i=Yt(e.existing)[r],o=Array.from(new Set([...mr(i??{}),...mr(e.materialization)])).sort(),s={...e.materialization,materializationId:r,targetAgents:o,...o.length>1?{targetGroup:`shared:${n}:${o.join(",")}`}:{},receiptSha256:Vr(t.receipt),savedAt:e.backend.now()},a={...Yt(e.existing),[r]:s},l=Object.keys(a).length===1?s:{};return{...Zu(e.existing??{}),...l,skillSlug:e.skillSlug,materializations:a,materializationCount:Object.keys(a).length,savedAt:e.backend.now()}}function cz(e){let t=Yt(e.existing);if(delete t[e.materializationId],Object.keys(t).length===0)return;let n=Object.values(t);return{...Zu(e.existing),...n.length===1?n[0]:{},materializations:t,materializationCount:Object.keys(t).length,savedAt:e.backend.now()}}function qn(e,t={}){return An(e).filter(n=>{let r=f(n.record,"scope");if(t.scope&&r!==t.scope||t.agent&&!mr(n.record).includes(t.agent)||t.receiptSha256&&f(n.record,"receiptSha256")!==t.receiptSha256)return!1;if(t.installedPath){let i=n.lifecycle?.receipt.targetDir;if(!i||!yA(t.installedPath,i,t.platform??process.platform))return!1}return!0})}function ule(e){let t=e.backend.platform==="win32"?st:Lt,n=new Set;for(let r of et(e.backend.env,e.backend.platform,e.backend.cwd))if(!(e.agent&&r.id!==e.agent))for(let i of new Set([e.skillSlug,Mr(e.skillSlug)]))(!e.scope||e.scope==="project")&&n.add(Bo(t.join(r.targets.projectSkillsPath,i),e.backend.platform)),(!e.scope||e.scope==="global")&&r.targets.globalSkillsPath&&n.add(Bo(t.join(r.targets.globalSkillsPath,i),e.backend.platform));return e.materializations.filter(r=>{let i=r.lifecycle?.receipt.targetDir;return!!(i&&n.has(Bo(i,e.backend.platform)))})}function gr(e,t){return{...Zu(e),...t.record,materializationId:t.materializationId}}function uz(e){return Object.values(e.installs).flatMap(t=>{let n=An(t);return n.length>0?n.map(r=>gr(t,r)):[t]})}function dz(e){let t=L(e,"cachedArtifact"),n=t?L(t,"generation"):void 0,r=t?f(t,"state"):void 0,i=t?f(t,"bundlePath"):void 0,o=n?f(n,"skillSlug"):void 0,s=n?f(n,"semanticVersion"):void 0,a=n?f(n,"generationId"):void 0,l=t?f(t,"archiveSha256"):void 0,c=t?f(t,"manifestSha256"):void 0,u=t?f(t,"savedAt"):void 0;return r!=="verified"||!i||!o||!s||!a||!l||!Fo.test(l)||!c||!Fo.test(c)||!u?null:{state:"verified",bundlePath:i,generation:{skillSlug:o,semanticVersion:s,generationId:a},archiveSha256:l,manifestSha256:c,savedAt:u}}function pz(e){if(!j(e))return null;let t=f(e,"targetDir"),n=L(e,"generation"),r=n?f(n,"skillSlug"):void 0,i=n?f(n,"semanticVersion"):void 0,o=n?f(n,"generationId"):void 0,s=f(e,"archiveSha256"),a=f(e,"manifestSha256"),l=Be(e,"files");if(!t||!r||!i||!o||!s||!Fo.test(s)||!a||!Fo.test(a)||!l||l.length===0)return null;let c=l.flatMap(u=>{if(!j(u))return[];let d=f(u,"path"),p=J(u,"sizeBytes"),m=f(u,"sha256");return d&&Number.isSafeInteger(p)&&p>=0&&m&&Fo.test(m)?[{path:d,sizeBytes:p,sha256:m}]:[]});return c.length!==l.length?null:{targetDir:t,generation:{skillSlug:r,semanticVersion:i,generationId:o},archiveSha256:s,manifestSha256:a,files:c}}function fz(e){if(!j(e)||e.status!=="authorized")return null;let t=f(e,"authorizationId"),n=f(e,"purpose"),r=L(e,"generation"),i=r?f(r,"skillSlug"):void 0,o=r?f(r,"semanticVersion"):void 0,s=r?f(r,"generationId"):void 0,a=f(e,"archiveSha256"),l=f(e,"manifestSha256");return!t||!n||!["quarantine_blocked","quarantine_revoked","restore_fresh_approval","purge_quarantined"].includes(n)||!i||!o||!s||!a||!Fo.test(a)||!l||!Fo.test(l)?null:{status:"authorized",authorizationId:t,purpose:n,generation:{skillSlug:i,semanticVersion:o,generationId:s},archiveSha256:a,manifestSha256:l}}function dle(e){if(!j(e)||e.status!=="quarantined")return null;let t=f(e,"reasonCode"),n=f(e,"targetDir"),r=f(e,"quarantineRoot"),i=f(e,"quarantineDir"),o=Un(e,"discoveryRoots"),s=fz(e.quarantineAuthorization),a=pz(e.receipt);return!t||!n||!r||!i||!o||o.length===0||!s||!a?null:{status:"quarantined",reasonCode:t,targetDir:n,quarantineRoot:r,quarantineDir:i,discoveryRoots:o,quarantineAuthorization:s,receipt:a}}async function lt(e){let t=await ke(e.paths.installsPath);return!j(t)||t.version!==hh||!j(t.installs)?{version:hh,revision:0,installs:{}}:{version:hh,revision:Number.isSafeInteger(t.revision)&&Number(t.revision)>=0?Number(t.revision):0,installs:gle(t.installs)}}async function _A(e,t){let n=e.paths.installsPath,r=Me(n);await Zo(r);let i=`${n}.lock`,o,s=Date.now()+5e3;for(;!o;)try{o=await Uo(i,"wx",384)}catch(c){if(c.code!=="EEXIST"||Date.now()>=s)throw c;await new Promise(u=>setTimeout(u,10))}let a=K(r,`.${ot(n)}.${Ge(12).toString("hex")}.tmp`),l;try{let c=await ke(n),u=j(c)&&c.version===hh&&Number.isSafeInteger(c.revision)&&Number(c.revision)>=0?Number(c.revision):0;if(u!==t.revision)throw new Ku;let d={...t,revision:u+1};l=await Uo(a,"wx",384),await l.writeFile(`${JSON.stringify(d,null,2)}
|
|
2277
|
+
`,"utf8"),await l.sync(),await l.close(),l=void 0,await zo(a,n),await Jo(n,384),await SA(r),t.revision=d.revision}catch(c){throw await l?.close().catch(()=>{}),await We(a,{force:!0}).catch(()=>{}),c}finally{await o.close().catch(()=>{}),await We(i,{force:!0}).catch(()=>{})}}async function Br(e,t){for(let n=0;n<8;n+=1){let r=await lt(e);await t(r);try{return await _A(e,r),r}catch(i){if(!(i instanceof Ku)||n===7)throw i}}throw new Ku}async function Bi(e,t){let n=await lt(e),r=!1,i=[];for(let[o,s]of Object.entries(n.installs)){if(t&&o!==t)continue;let a=s;for(let l of An(s)){let c=l.lifecycle;if(!c||c.state!=="active")continue;let u=await ple(l.record,c);if(u.state==="active")continue;let d=u.state;a=Fr({existing:a,skillSlug:o,materialization:{...l.record,status:u.state,reconciliation:{version:1,state:u.state,reasonCode:u.reasonCode,observedAt:e.now(),recoverable:u.recoverable},localLifecycle:{...c,state:d,updatedAt:e.now()},savedAt:e.now()},backend:e}),r=!0,i.push({skillSlug:o,generationId:c.receipt.generation.generationId,receiptSha256:Vr(c.receipt),state:u.state==="externally_removed"?"externally_removed":u.state==="host_detached"?"host_detached":"stale",reasonCode:u.reasonCode})}n.installs[o]=a}r&&await _A(e,n);for(let o of i)await fle(e,o).catch(()=>{});return n}async function ple(e,t){let n;try{let o=await Xu(t.receipt.targetDir);n=o.isDirectory()&&!o.isSymbolicLink()?"present_directory":"replaced_type"}catch(o){n=o.code==="ENOENT"?"absent":"unreadable"}let r=n==="present_directory"?(await Dr(t.receipt)).status==="verified"?"verified":"changed":"unchecked",i=e.hostRegistrationState==="detached"||typeof e.harnessUninstalledAt=="string"?"detached":"unknown";return g2({pathState:n,receiptState:r,hostState:i})}async function fle(e,t){for(let n of["project","global"]){let r;try{r=await Vo(e,n)}catch{continue}let i=Object.entries(r.associations).filter(([,o])=>o.skillSlug===t.skillSlug&&o.generationId===t.generationId&&o.receiptSha256===t.receiptSha256&&o.state!=="externally_removed"&&o.state!=="host_detached");for(let[o]of i)await jo(e,n,o,{state:t.state,reasonCode:t.reasonCode,updatedAt:e.now()})}}async function SA(e){if(process.platform!=="win32")try{let t=await Uo(e,"r");try{await t.sync()}finally{await t.close()}}catch{}}async function mle(e){await Br(e.backend,t=>{let n=t.installs[e.skillSlug];if(!n)return;let r=Yt(n)[e.materializationId],i=r?Jt(r):null;if(!i||i.operationId!==e.operationId)return;if(e.baselineMaterialization){t.installs[e.skillSlug]=Fr({existing:n,skillSlug:e.skillSlug,materialization:e.baselineMaterialization,backend:e.backend});return}let o=cz({existing:n,materializationId:e.materializationId,backend:e.backend});o?t.installs[e.skillSlug]=o:delete t.installs[e.skillSlug]})}async function Ha(e,t,n){let r=f(t,"skillSlug")??f(t,"slug")??n,i=Array.isArray(t.materializationResults)?t.materializationResults.filter(j):Jt(t)?[t]:[],o=i.length>0?Zu(t):t;await Br(e,s=>{let a={...Zu(s.installs[r]??{}),...o,...t.acquisitionMode==="authenticated_account"?{acquisitionBaseUrl:e.baseUrl,acquiredByUserId:e.config?.userId}:{},skillSlug:r,materializations:Yt(s.installs[r]),savedAt:e.now()};for(let l of i)a=Fr({existing:a,skillSlug:r,materialization:{...l,...t.acquisitionMode==="authenticated_account"?{acquisitionMode:t.acquisitionMode,acquisitionBaseUrl:e.baseUrl,acquiredByUserId:e.config?.userId,entitlementId:t.entitlementId}:{}},backend:e});s.installs[r]=a})}function gle(e){let t={};for(let[n,r]of Object.entries(e))t[n]=j(r)?r:{skillSlug:n,value:r};return t}var at=5;function mz(e){if(!j(e))return null;let t=f(e,"reasonCode"),n=t==="commercial_rights_declaration_required"||t==="commercial_rights_declaration_invalid";if(!n&&t!=="paid_to_free_confirmation_required")return null;let r=n?"Confirm your rights to distribute this skill.":"Confirm that this paid skill should become free.";return{...e,status:"action_required",error:r,message:r,nextAction:"retry",nextStep:n?"Repeat with --attest-rights --rights-basis self_authored after confirming your rights. For submit or submit-version, also add --distribution-scope commercial_distribution.":"To make this paid skill free, repeat with --price-cents 0 --confirm-free. The generic --yes flag does not confirm this change."}}function R(e,t,n,r,i){let o=mz(e);o&&(e=o,t=String(o.message));let s=e&&typeof e=="object"&&!Array.isArray(e)&&typeof e.status=="string"?String(e.status):"ok",a=Rh(e),l=n&&i?gz(a,r?.renderMode.detail??"standard",i):a,c=j(a)?a:void 0,u={schemaVersion:VM,status:s,statusFamily:kle(s,a),summary:t,why:c?f(c,"why")??null:null,nextAction:c?f(c,"nextAction")??null:null,nextStep:c?f(c,"nextStep")??null:null,data:l,warnings:c&&Array.isArray(c.warnings)?c.warnings:[],links:c&&Array.isArray(c.links)?c.links:[],reasonCode:c?f(c,"reasonCode")??null:null,handoff:c?.handoff??null};return{exitCode:0,stdout:n?JSON.stringify(u,null,2):St(_le(a,t,r)),stderr:""}}function gz(e,t,n){return t==="full"||!j(e)?e:n==="installed"?yle(e,t):vle(e,t)}var hz=["skillSlug","version","scope","agent","status"],hle=[...hz,"targetAgent","source","sourceKind","installMode","installedAt","savedAt","updatedAt","generationId","installedPathSource","localLifecycle"];function yle(e,t){let n=un(e.results),r=t==="concise"?3:5,i=t==="concise"?hz:hle,o=n.slice(0,r).map(s=>Ua(s,i));return{status:f(e,"status")??"ok",resultCount:n.length,returnedResultCount:o.length,warnings:e.warnings,omittedResultCount:Math.max(0,n.length-o.length),results:o}}function vle(e,t){let n=t==="concise"?3:5,r=L(e,"parsedSkill"),i=r?L(r,"frontmatter"):void 0,o=L(e,"license"),s=[yP("skill.body",r?.body),yP("skill.frontmatter",r?.rawFrontmatter),yP("license.text",o?.text)].filter(d=>d!==void 0),a=jM(e.issues,n),l=jM(e.licenseIssues,n),c=L(e,"evalReadiness"),u=L(e,"aiReview");return ie({status:e.status,profile:e.profile,ingestible:e.ingestible,valid:e.valid,stats:e.stats,skill:i?Ua(i,t==="concise"?["name"]:["name","description","compatibility","license"]):void 0,license:o?Ua(o,t==="concise"?["status","identifier"]:["status","identifier","detectedIdentifier","declarationSource","filePath","textSha256"]):void 0,issueCount:Array.isArray(e.issues)?e.issues.length:0,returnedIssueCount:a.length,omittedIssueCount:Math.max(0,(Array.isArray(e.issues)?e.issues.length:0)-a.length),issues:a,licenseIssues:l.length>0?l:void 0,evalReadiness:c?Ua(c,t==="concise"?["status","label","origin","confidence","evidenceFileCount","nextAction"]:["schemaVersion","status","label","origin","confidence","creatorReviewed","evidenceFileCount","runtimeFileCount","artifactDigest","score","summaryEnvelope","improvements","recommendedCommands","nextAction"]):void 0,securityReport:e.securityReport,aiReview:u?Ua(u,["status","reasonCode","message","nextAction","nextStep"]):void 0,rawContent:s})}function jM(e,t){return Array.isArray(e)?e.slice(0,t).map(n=>j(n)?Ua(n,["severity","code","message","path","nextAction","nextStep"]):n):[]}function yP(e,t){if(typeof t=="string")return{field:e,characterCount:t.length,sha256:`sha256:${Ue("sha256").update(t).digest("hex")}`}}function Ua(e,t){let n={};for(let r of t)e[r]!==void 0&&(n[r]=e[r]);return n}function kle(e,t){let n=e.toLowerCase();return n==="pass"||n.includes("dry")?"dry_run_passed":n.includes("created")?"created":n.includes("updated")||n.includes("configured")||n.includes("synced")?"updated":n.includes("revoked")||n.includes("removed")||n.includes("disconnected")?"removed":n.includes("approval")||n.includes("handoff")||j(t)&&t.handoff?"human_handoff":"ok"}var wle="<redacted>";function Rh(e){if(typeof e=="string")return H(e);if(Array.isArray(e))return e.map(n=>Rh(n));if(!j(e))return e;let t={};for(let[n,r]of Object.entries(e))t[n]=ble(n)?wle:Rh(r);return t}function ble(e){let t=e.replace(/[^a-z0-9]/giu,"").toLowerCase();return t==="devicecode"||t==="usercode"||t==="verificationcode"||t==="recoverycode"||t==="onetimecode"||t==="password"||t==="clientsecret"||t==="privatekey"||t==="apikey"||t==="rawapikey"||t==="accesstoken"||t==="refreshtoken"||t==="bearertoken"||t==="mcptoken"||t.endsWith("secret")?!0:t.endsWith("token")&&t!=="tokenprefix"}function _le(e,t,n){let r=n?.renderMode??Aa([],{},{stdinIsTty:!1,stdoutIsTty:!1,stderrIsTty:!1}).mode,i=Pe(n);if(j(e)){if(J(e,"pendingPrice")!==void 0)return["Price change pending admin review",`Live price: ${Le(J(e,"priceCents")??0,"usd")}`,`Pending price: ${Le(J(e,"pendingPrice"),"usd")}`,f(e,"reasonCode"),f(e,"nextStep")].filter(Boolean).join(`
|
|
2278
2278
|
`);if(t==="Spending loaded."){let l=f(e,"currency")??"usd",c=[`Total spent: ${Le(J(e,"totalSpentCents")??0,l)}`,`Refunded: ${Le(J(e,"refundedCents")??0,l)} (${J(e,"refundedCount")??0})`,`Successful purchases: ${J(e,"successfulPurchaseCount")??0}`],u=L(e,"spentByCurrency"),d=Object.entries(u??{}).filter(p=>typeof p[1]=="number"&&p[1]!==0);if(d.length>1){c.push("By currency");for(let[p,m]of d)c.push(`${p.toUpperCase()}: ${Le(m,p)}`)}return c.join(`
|
|
2279
2279
|
`)}if(["Purchases loaded.","Purchase status loaded.","Invoice loaded."].includes(t))return Sle(e,t,i,r.detail==="full");if(t==="Skill loaded.")return VF(e,r);if(t==="Status loaded."&&NM(e))return Rle(e,t,i);if(t==="Doctor checks loaded."&&NM(e))return Ele(e,t,i);if(t==="Withdrawal requested.")return DA(e);if(t==="Payout setup link created."){let l=sz(e);if(l)return OA(l,L(e,"accountLink")?.expiresAt)}if(t==="Creator payout profile loaded.")return Jle(e,t,i);if(t==="Creator earnings loaded."||t==="Earnings loaded.")return Yle(e,"Creator earnings loaded.",i);if(t==="Creator payouts loaded."||t==="Payouts loaded.")return Xle(e,"Creator payouts loaded.",i);if(t==="Guardian check complete.")return Ple(e,t,i);if(t==="Reviews loaded.")return Ile(e,t,i);if(t==="Categories loaded.")return Cle(e,t,i)}let o=j(e)?f(e,"status")??"ok":"ok",s=NN({status:o,summary:t,data:e,next:j(e)?xle(e):[],links:[],warnings:j(e)&&Array.isArray(e.warnings)?e.warnings.filter(l=>typeof l=="string"):[]},r),a=j(e)?L(e,"submission")??L(e,"analytics")??e:null;return a?.listingStatus==="delisted"?`${s}
|
|
2280
2280
|
|
|
@@ -2286,7 +2286,7 @@ Delisted on ${f(a,"delistedAt")??"an unrecorded date"}; existing buyers keep acc
|
|
|
2286
2286
|
`)}function Nu(e,t){if(j(e))return typeof e[t]=="boolean"?e[t]:void 0}function qe(e,t){return j(e)?f(e,t):void 0}function Ale(e){return e.split(/[_-]+/u).filter(Boolean).map(t=>`${t[0]?.toUpperCase()??""}${t.slice(1)}`).join(" ")}function NM(e){return!!(L(e,"backend")&&L(e,"auth")&&Array.isArray(e.checks))}function Rle(e,t,n){let r=[`${n.ok("OK")} ${t}`,"",n.section("Readiness")],i=f(e,"summary");i&&r.push(` ${i}`);let o=L(e,"backend"),s=o?Ole(o):void 0;s&&r.push(` ${n.label("Backend")}: ${s}`);let a=L(e,"auth"),l=a?Lle(a):void 0;l&&r.push(` ${n.label("Account")}: ${l}`);let c=a?J(a,"personalModeCount"):void 0,u=a?J(a,"enterpriseWorkspaceCount")??J(a,"workspaceCount"):void 0,d=a?J(a,"availableWorkingModeCount"):void 0;c!==void 0&&r.push(` ${n.label("Personal modes")}: ${c}`),u!==void 0&&r.push(` ${n.label("Enterprise workspaces")}: ${u}`),d!==void 0&&r.push(` ${n.label("Available workspace choices")}: ${d}`);let p=a?J(a,"libraryCount"):void 0;p!==void 0&&r.push(` ${n.label("Owned skills")}: ${p}`);let m=L(e,"localRuntime"),h=m?L(m,"guardian"):void 0,g=m?L(m,"mcp"):void 0;(h||g)&&(r.push("",n.section("Local runtime")),h&&r.push(` ${n.label("Guardian")}: ${qe(h,"enforcementLayer")??"not_installed"}`,` ${n.label("Strict pre-action blocking")}: ${Nu(h,"strictPreActionBlocking")===!0?"yes":"no"}`),g&&r.push(` ${n.label("MCP")}: ${Nu(g,"configured")===!0?"configured":"not configured"}`));let y=yz(e);return y.length>0&&r.push("",n.section("Next"),...y.map(v=>` ${n.arrow} ${v}`)),r.push(` ${n.arrow} Run \`skills-layer doctor\` for diagnostics.`),r.join(`
|
|
2287
2287
|
`)}function Ele(e,t,n){let r=[`${n.ok("OK")} ${t}`,"",n.section("Diagnostics")],i=f(e,"summary");i&&r.push(` ${i}`);let o=f(e,"status");o&&r.push(` ${n.label("Status")}: ${o}`);let s=vz(e),a=s.filter(u=>jle(f(u,"status"))),l=s.filter(u=>f(u,"status")!=="pass");r.push(a.length===0?" No blocking issues found.":` ${a.length} check${a.length===1?"":"s"} need attention.`),a.length===0&&l.length>0&&r.push(` Advisory checks needing attention: ${l.length}.`),r.push("",n.section(`Checks (${s.length})`)),s.length===0&&r.push(` ${n.muted("No checks returned by the backend.")}`),s.forEach((u,d)=>{let p=f(u,"status")??"unknown",m=f(u,"title")??f(u,"id")??`Check ${d+1}`;r.push(`${d+1}. ${n.label(`[${p}] ${m}`)}`);let h=f(u,"summary");h&&r.push(` ${h}`);let g=f(u,"why");if(g&&r.push(` ${n.label("Why")}: ${g}`),p!=="pass"){let y=f(u,"nextStep");y&&r.push(` ${n.label("Fix")}: ${y}`);let v=f(u,"recommendedCommand");v&&r.push(` ${n.label("Try")}: ${v}`)}});let c=yz(e);return c.length>0&&r.push("",n.section(a.length>0?"Recommended Fix":"Next"),...c.map(u=>` ${n.arrow} ${u}`)),r.join(`
|
|
2288
2288
|
`)}function $le(e,t,n,r){let i=[`${n.ok("OK")} ${t}`],o=Un(e,"requestedSlugs");o&&o.length>0&&i.push("",n.section("Requested"),` ${o.join(", ")}`);let s=un(e.results);i.push("",n.section(`Comparison (${s.length})`)),s.length===0&&i.push(` ${n.muted("No comparable skills returned.")}`),s.forEach((u,d)=>{let p=HP(u)??`Skill ${d+1}`;i.push(`${d+1}. ${p}`);let m=Dle(u);m&&i.push(` ${m}`);let h=_z(u);h&&i.push(` ${n.label("summary")}: ${r?h.replace(/\s+/gu," ").trim():Za(h)}`)});let a=un(e.missing);a.length>0&&(i.push("",n.section(`Missing (${a.length})`)),a.forEach((u,d)=>{let p=f(u,"slug")??f(u,"skillSlug")??HP(u)??`Entry ${d+1}`,m=f(u,"reason")??f(u,"status");i.push(`${d+1}. ${m?`${p} - ${m}`:p}`)}));let l=Un(e,"guidance")??Ka(e.guidance);l.length>0&&i.push("",n.section("Guidance"),...l.slice(0,3).map(u=>` ${n.arrow} ${Za(u)}`));let c=Tle(s);return c.length>0&&i.push("",n.section("Next"),...c.map(u=>` ${n.arrow} ${u}`)),i.join(`
|
|
2289
|
-
`)}function Dle(e){let t=L(e,"securityPosture"),n=f(e,"trust")??f(e,"trustStatus")??f(e,"trustLabel")??(t?f(t,"label"):void 0),r=e.score??e.securityScore??(t?t.securityScore:void 0),i=f(e,"risk")??f(e,"runtimeRisk")??(t?f(t,"runtimeRisk"):void 0);return[["slug",f(e,"slug")??f(e,"skillSlug")],["version",f(e,"version")??f(e,"currentVersion")],["category",f(e,"category")],["type",f(e,"type")??f(e,"skillType")],["trust",n],["score",r],["risk",i]].flatMap(([s,a])=>a==null||a===""?[]:[`${s}: ${dn(String(s),a)}`]).join("; ")}function Tle(e){let t=[];for(let n of e.slice(0,5)){let r=f(n,"slug")??f(n,"skillSlug");r&&t.push(`skills-layer show ${r}`,`skills-layer trust ${r}`,`skills-layer install ${r}`)}return t}function Ole(e){let t=f(e,"edition"),n=f(e,"baseUrl");return t&&n?`${t} at ${n}`:t??n}function Lle(e){let t=f(e,"state");if(t&&t!=="authenticated")return t==="anonymous"?"not signed in":t;let n=f(e,"email"),r=Un(e,"roles");return n&&r&&r.length>0?`${n} (${r.join(", ")})`:n??f(e,"role")}function yz(e){let t=[],n=f(e,"recommendedCommand");n&&t.push(n);let r=f(e,"nextStep");return r&&t.push(r),t}function vz(e){return Array.isArray(e.checks)?e.checks.filter(j):[]}function jle(e){return e!==void 0&&e!=="pass"&&e!=="warn"&&e!=="advisory"}function un(e){return Array.isArray(e)?e.filter(j):[]}function Ka(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Nle(e){let t=e.commerce===!0;return{status:t?"available":"unavailable",summary:t?"Marketplace purchases, invoices, refunds, and creator commerce flows are available.":"Marketplace commerce is not available on this backend.",availableWorkflows:t?["Browse skills with `skills-layer featured` or `skills-layer search <query>`.","Start purchase handoff with `skills-layer buy <skill-slug>`.","Review account purchases with `skills-layer purchases list`."]:["Browse and install available free skills.","Use `skills-layer help topic install` for install guidance."]}}var Fle={"core.identity":"Account and sign-in","core.catalog":"Catalog discovery","core.validation":"Creator validation","core.creator":"Creator submissions","core.library":"Owned skills","core.workspace":"Workspace rollout","core.guardian":"Runtime trust checks","core.source":"Source installs","core.discovery":"Catalog discovery","marketplace.commerce":"Marketplace commerce","marketplace.reviews":"Reviews and issues","marketplace.payouts":"Creator earnings"};function Ble(e){let t=Ka(e.capabilities);return{status:"ok",edition:f(e,"edition")??"unknown",summary:"Public product capabilities available on the selected backend.",capabilities:t.map(n=>({name:Fle[n]??Fh(n.replace(/^[^.]+\./u,"").replace(/[._-]+/gu," ")),available:!0})),count:t.length}}function Mle(e,t){let n=k(e);if(!n)return;let r=Number(n);return!Number.isInteger(r)||r<=0?
|
|
2289
|
+
`)}function Dle(e){let t=L(e,"securityPosture"),n=f(e,"trust")??f(e,"trustStatus")??f(e,"trustLabel")??(t?f(t,"label"):void 0),r=e.score??e.securityScore??(t?t.securityScore:void 0),i=f(e,"risk")??f(e,"runtimeRisk")??(t?f(t,"runtimeRisk"):void 0);return[["slug",f(e,"slug")??f(e,"skillSlug")],["version",f(e,"version")??f(e,"currentVersion")],["category",f(e,"category")],["type",f(e,"type")??f(e,"skillType")],["trust",n],["score",r],["risk",i]].flatMap(([s,a])=>a==null||a===""?[]:[`${s}: ${dn(String(s),a)}`]).join("; ")}function Tle(e){let t=[];for(let n of e.slice(0,5)){let r=f(n,"slug")??f(n,"skillSlug");r&&t.push(`skills-layer show ${r}`,`skills-layer trust ${r}`,`skills-layer install ${r}`)}return t}function Ole(e){let t=f(e,"edition"),n=f(e,"baseUrl");return t&&n?`${t} at ${n}`:t??n}function Lle(e){let t=f(e,"state");if(t&&t!=="authenticated")return t==="anonymous"?"not signed in":t;let n=f(e,"email"),r=Un(e,"roles");return n&&r&&r.length>0?`${n} (${r.join(", ")})`:n??f(e,"role")}function yz(e){let t=[],n=f(e,"recommendedCommand");n&&t.push(n);let r=f(e,"nextStep");return r&&t.push(r),t}function vz(e){return Array.isArray(e.checks)?e.checks.filter(j):[]}function jle(e){return e!==void 0&&e!=="pass"&&e!=="warn"&&e!=="advisory"}function un(e){return Array.isArray(e)?e.filter(j):[]}function Ka(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Nle(e){let t=e.commerce===!0;return{status:t?"available":"unavailable",summary:t?"Marketplace purchases, invoices, refunds, and creator commerce flows are available.":"Marketplace commerce is not available on this backend.",availableWorkflows:t?["Browse skills with `skills-layer featured` or `skills-layer search <query>`.","Start purchase handoff with `skills-layer buy <skill-slug>`.","Review account purchases with `skills-layer purchases list`."]:["Browse and install available free skills.","Use `skills-layer help topic install` for install guidance."]}}var Fle={"core.identity":"Account and sign-in","core.catalog":"Catalog discovery","core.validation":"Creator validation","core.creator":"Creator submissions","core.library":"Owned skills","core.workspace":"Workspace rollout","core.guardian":"Runtime trust checks","core.source":"Source installs","core.discovery":"Catalog discovery","marketplace.commerce":"Marketplace commerce","marketplace.reviews":"Reviews and issues","marketplace.payouts":"Creator earnings"};function Ble(e){let t=Ka(e.capabilities);return{status:"ok",edition:f(e,"edition")??"unknown",summary:"Public product capabilities available on the selected backend.",capabilities:t.map(n=>({name:Fle[n]??Fh(n.replace(/^[^.]+\./u,"").replace(/[._-]+/gu," ")),available:!0})),count:t.length}}function Mle(e,t){let n=k(e);if(!n)return;let r=Number(n);return!Number.isInteger(r)||r<=0?E("help optimize-tokens --max-characters must be a positive integer.",t):r<120||r>4e3?E("help optimize-tokens --max-characters must be between 120 and 4000.",t):r}function Ule(e,t,n){let r=Pe(n),i=L(e,"validation")??e,o=L(i,"parsedSkill")??L(e,"parsedSkill"),s=o?L(o,"frontmatter"):void 0,a=f(e,"skillSlug")??(s?f(s,"name"):void 0),l=i.valid===!0||e.valid===!0,c=vP(i,e,"issues"),u=vP(i,e,"warnings"),d=vP(i,e,"advice"),p=L(i,"stats")??L(e,"stats"),m=[l?`${r.ok("OK")} Validation complete.`:"Validation failed.","",r.section("Bundle")];m.push(` ${r.label("Path")}: ${t}`),a&&m.push(` ${r.label("Skill")}: ${a}`),m.push(` ${r.label("Readiness")}: ${l?"ready for dry-run submission":"needs changes before submission"}`),m.push("",r.section("Checks")),m.push(` ${r.arrow} SKILL.md structure and frontmatter`),m.push(` ${r.arrow} Required bundle files and supported directories`),m.push(` ${r.arrow} Secret hygiene, unsafe script signals, and trust-review readiness`),m.push(` ${r.arrow} Trigger quality inputs for should-trigger / should-not-trigger testing`);let h=L(e,"evalReadiness");if(h){let v=L(h,"summaryEnvelope"),b=Array.isArray(v?.statuses)?v.statuses.map(P=>String(P)).join(", "):void 0,w=L(h,"score"),_=w?J(w,"effectiveScorePercent"):void 0,C=w?J(w,"overallScore"):void 0;m.push("",r.section("Effectiveness Eval")),m.push(` ${r.label("Posture")}: ${f(h,"label")??f(h,"status")??"limited"}`),m.push(` ${r.label("Origin")}: ${f(h,"origin")??"inferred"}`),_!==void 0?m.push(` ${r.label("Effective score")}: ${Eh(_)}`):C!==void 0&&m.push(` ${r.label("Effective score")}: ${Eh(C*100)}`),m.push(` ${r.label("Artifact digest")}: ${f(h,"artifactDigest")??"unavailable"}`),h.runtimeFileCount!==void 0&&m.push(` ${r.label("Runtime files")}: ${dn("runtimeFileCount",h.runtimeFileCount)}`),h.evidenceFileCount!==void 0&&m.push(` ${r.label("Evidence files excluded")}: ${dn("evidenceFileCount",h.evidenceFileCount)}`),m.push(` ${r.label("Submit envelope")}: mandatory${b?` (${b})`:""}`)}if(p){let v=p.fileCount??p.files??e.fileCount,b=p.bodyWordCount??p.bodyWords??e.bodyWordCount;m.push("",r.section("File Summary")),v!==void 0&&m.push(` ${r.label("File count")}: ${dn("fileCount",v)}`),b!==void 0&&m.push(` ${r.label("Body words")}: ${dn("bodyWordCount",b)}`)}let g=L(e,"securityReport");g&&(m.push("",r.section("Security")),m.push(` ${r.label("Recommendation")}: ${f(g,"recommendation")??"unknown"}`),m.push(...fh("Findings",Array.isArray(g.findings)?g.findings:[],r,"No security findings returned.")));let y=L(e,"aiReview");if(y){m.push("",r.section("AI Review")),m.push(` ${r.label("Status")}: ${f(y,"status")??"unknown"}`);let v=f(y,"message");v&&m.push(` ${v}`);let b=f(y,"nextStep");b&&m.push(` ${r.arrow} ${b}`)}return m.push("",...fh("Issues",c,r,"No blocking issues found.")),m.push("",...fh("Warnings",u,r,"No warnings returned.")),m.push("",...fh("Advice",d,r,"No extra advice returned.")),m.push("",r.section("Next")),l?(m.push(` ${r.arrow} skills-layer preview-trigger ${t} --should-trigger "<prompt>" --should-not-trigger "<prompt>"`),m.push(` ${r.arrow} skills-layer creator submit ${t} --dry-run`)):m.push(` ${r.arrow} Fix the listed issues, then run skills-layer validate ${t}`),m.join(`
|
|
2290
2290
|
`)}function vP(e,t,n){let r=Array.isArray(e[n])?e[n]:[],i=Array.isArray(t[n])?t[n]:[];return r.length>0?r:i}function fh(e,t,n,r){let i=[n.section(`${e} (${t.length})`)];return t.length===0?(i.push(` ${n.muted(r)}`),i):(t.slice(0,at).forEach((o,s)=>{i.push(`${s+1}. ${kz(o)}`)}),i)}function kz(e){return j(e)?(f(e,"message")??f(e,"title")??f(e,"code")??f(e,"path")??Ju(e))||"Details available with --json":dn("",e)}function zle(e,t,n){let r=Pe(n),i=qle(e),o=Vle(e),s=[`${r.ok("OK")} Trigger preview complete.`,"",r.section("Bundle"),` ${r.label("Path")}: ${t}`],a=f(e,"skillSlug")??f(e,"slug");return a&&s.push(` ${r.label("Skill")}: ${a}`),s.push("",r.section(`Prompt Results (${i.length})`)),i.length===0&&s.push(` ${r.muted("No prompt results returned. Use --json to inspect the raw backend response.")}`),i.slice(0,at).forEach((l,c)=>{s.push(`${c+1}. ${Gle(l,c)}`)}),s.push("",r.section(`Guidance (${o.length})`)),o.length===0&&s.push(` ${r.muted("No extra trigger guidance returned.")}`),o.slice(0,at).forEach((l,c)=>{s.push(`${c+1}. ${l}`)}),s.push("",r.section("Next")),s.push(` ${r.arrow} skills-layer validate ${t}`),s.push(` ${r.arrow} skills-layer creator submit ${t} --dry-run`),s.join(`
|
|
2291
2291
|
`)}function qle(e){return[...un(e.promptResults),...un(e.results),...un(e.shouldTriggerResults),...un(e.shouldNotTriggerResults),...un(e.paraphraseResults)]}function Vle(e){let t=Ka(e.guidance),n=un(e.guidance).map(r=>kz(r));return[...t,...n]}function Gle(e,t){let n=f(e,"prompt")??f(e,"text")??f(e,"input")??`Prompt ${t+1}`,r=Hle(e),i=Kle(e),o=Wle(e),s=e.score??e.confidence,a=f(e,"reason")??f(e,"explanation")??f(e,"message");return[`"${Za(n)}"`,r?`expected: ${r}`:void 0,i?`actual: ${i}`:void 0,o,s!==void 0?`score: ${dn("score",s)}`:void 0,a?`reason: ${Za(a)}`:void 0].filter(l=>!!l).join("; ")}function Hle(e){return typeof e.shouldTrigger=="boolean"?e.shouldTrigger?"should trigger":"should not trigger":typeof e.expectedTrigger=="boolean"?e.expectedTrigger?"should trigger":"should not trigger":f(e,"expected")??f(e,"kind")??f(e,"type")}function Kle(e){return typeof e.triggered=="boolean"?e.triggered?"triggered":"did not trigger":typeof e.actualTrigger=="boolean"?e.actualTrigger?"triggered":"did not trigger":f(e,"actual")??f(e,"classification")??f(e,"decision")}function Wle(e){return typeof e.passed=="boolean"?e.passed?"pass":"fail":typeof e.pass=="boolean"?e.pass?"pass":"fail":f(e,"status")}function Zle(e,t,n,r){let i=Pe(r),o=f(e,"skillSlug")??ot(t),s=[`${i.ok("OK")} Created ${n}.`,"",i.section("Local Skill")];s.push(` ${i.label("Path")}: ${n}`),s.push(` ${i.label("Skill")}: ${o}`);let a=f(e,"skillType"),l=f(e,"category");return a&&s.push(` ${i.label("Type")}: ${a}`),l&&s.push(` ${i.label("Category")}: ${l}`),s.push(` ${i.label("Evaluation")}: not run`),s.push("",i.section("Next")),s.push(` ${i.arrow} Edit ${n}`),s.push(` ${i.arrow} skills-layer validate ${t}`),s.push(` ${i.arrow} skills-layer preview-trigger ${t} --should-trigger "<prompt>" --should-not-trigger "<prompt>"`),s.push(` ${i.arrow} skills-layer creator submit ${t} --dry-run`),s.join(`
|
|
2292
2292
|
`)}function Jle(e,t,n){let r=L(e,"profile")??e,i=kP(r,"requirementsCurrentlyDue"),o=kP(r,"requirementsPastDue"),s=kP(r,"requirementsPendingVerification"),a=["payouts","Enabled"].join(""),l=r.readyForPayouts??r[a],c=l===!0,u=[`${n.ok("OK")} ${t}`,"",n.section("Payout Profile")];return u.push(` ${n.label("Status")}: ${gh(f(r,"status"))}`),u.push(` ${n.label("Ready for payouts")}: ${FM(l)}`),u.push(` ${n.label("Account details submitted")}: ${FM(r.detailsSubmitted)}`),u.push(` ${n.label("Currency")}: ${gh(f(r,"currency")?.toUpperCase())}`),u.push(` ${n.label("Country")}: ${gh(f(r,"country")?.toUpperCase())}`),u.push(` ${n.label("Minimum withdrawal")}: ${Qle(r)}`),u.push(` ${n.label("Updated at")}: ${gh(f(r,"updatedAt"))}`),u.push("",n.section("Requirements")),u.push(` ${n.label("Currently due")}: ${wP(i)}`),u.push(` ${n.label("Past due")}: ${wP(o)}`),u.push(` ${n.label("Pending verification")}: ${wP(s)}`),u.push("",n.section("Next")),c?(u.push(` ${n.arrow} skills-layer creator earnings`),u.push(` ${n.arrow} skills-layer creator withdraw --amount-cents <amount>`),u.push(` ${n.arrow} skills-layer creator payouts`)):(u.push(` ${n.arrow} skills-layer creator payout-link`),u.push(` ${n.arrow} skills-layer creator earnings`)),u.join(`
|
|
@@ -2294,9 +2294,9 @@ Delisted on ${f(a,"delistedAt")??"an unrecorded date"}; existing buyers keep acc
|
|
|
2294
2294
|
`)}function Xle(e,t,n){let r=Array.isArray(e.results)?e.results:[],i=GP(e,r),o=Fe(e,"withdrawableBalanceCents"),s=[`${n.ok("OK")} ${t}`,"",n.section("Payout History")];return s.push(` ${n.label("Withdrawable now")}: ${mh(e,"withdrawableBalanceCents",i)}`),s.push(` ${n.label("Pending payouts")}: ${mh(e,"pendingPayoutCents",i)}`),s.push(` ${n.label("Completed payouts")}: ${mh(e,"completedPayoutCents",i)}`),s.push("",n.section(`Requests (${r.length})`)),r.length===0?s.push(` ${n.muted("No payout requests yet.")}`):(r.slice(0,at).forEach((a,l)=>{if(!j(a)){s.push(`${l+1}. ${dn("",a)}`);return}let c=GP(a,void 0,i),u=f(a,"payoutId")??f(a,"id")??`Payout ${l+1}`,d=f(a,"status")??"unknown",p=mh(a,"amountCents",c),m=f(a,"requestedAt"),h=f(a,"completedAt"),g=f(a,"reason");s.push(`${l+1}. ${u}`),s.push(` ${n.label("Amount")}: ${p}; ${n.label("Status")}: ${d}`),m&&s.push(` ${n.label("Requested")}: ${m}`),h&&s.push(` ${n.label("Completed")}: ${h}`),g&&s.push(` ${n.label("Reason")}: ${g}`)}),r.length>at&&s.push(` ${n.muted(`... ${r.length-at} more`)}`)),s.push("",n.section("Guidance")),r.length===0?s.push("1. Payouts appear here after you request a withdrawal."):s.push("1. Use this history to track requested, processing, paid, or failed payouts."),s.push("2. Check payout profile if setup or verification looks incomplete."),s.push("",n.section("Next")),o>0&&s.push(` ${n.arrow} skills-layer creator withdraw --amount-cents ${o}`),s.push(` ${n.arrow} skills-layer creator earnings`),s.push(` ${n.arrow} skills-layer creator payout-profile`),s.join(`
|
|
2295
2295
|
`)}function GP(e,t,n="USD"){let r=f(e,"currency");if(r)return r.toUpperCase();let i=t?.find(j);if(i){let o=f(i,"currency");if(o)return o.toUpperCase()}return n}function Fe(e,t){return J(e,t)??0}function Oo(e,t){return J(e,t)??0}function mh(e,t,n){return Le(Fe(e,t),n)}function kP(e,t){return(Un(e,t)??[]).map(n=>n.replace(/[._-]+/gu," "))}function wP(e){return e.length>0?e.join(", "):"none"}function FM(e){return e===!0?"yes":e===!1?"no":"unknown"}function gh(e){return e??"none"}function Qle(e){let t=J(e,"minimumWithdrawalAmountCents"),n=f(e,"currency")?.toUpperCase()??"minor units";return t===void 0?"none":`${ece(t)} ${n}`}function ece(e){return(e/100).toFixed(2).replace(/\.00$/u,"").replace(/(\.\d)0$/u,"$1")}function Pe(e){let t=e?.renderMode??Aa([],{},{stdinIsTty:!1,stdoutIsTty:!1,stderrIsTty:!1}).mode,n=an(t);return{ok:n.success,section:n.heading,label:n.label,muted:n.muted,arrow:n.info("->")}}function tce(e,t){let n=[],r=ice(e,t);r.length>0&&n.push(...r);let i=nce(e,t);i.length>0&&n.push(...i);for(let[o,s]of ace(e))if(Array.isArray(s))n.push(...rce(o,s,t));else if(j(s)){let a=Ju(s);a&&n.push(` ${t.label(KP(o))}: ${a}`)}else n.push(` ${t.label(KP(o))}: ${dn(o,s)}`);return n}function nce(e,t){let n=L(e,"effectiveness");if(!n)return[];let r=f(n,"label"),i=f(n,"latestSummaryStatus"),o=J(n,"evidenceCount"),s=L(n,"score"),a=s?J(s,"overallScore"):void 0,l=s?J(s,"effectiveScorePercent"):void 0,c=s?L(s,"components"):void 0,u=c?J(c,"passRate"):void 0,d=c?J(c,"coverageRatio"):void 0;if(!r&&i===void 0&&o===void 0&&a===void 0)return[];let p=[t.section("Effectiveness")];if(r&&p.push(` ${t.label("Label")}: ${r}`),i&&p.push(` ${t.label("Latest summary")}: ${i}`),o!==void 0&&p.push(` ${t.label("Evidence count")}: ${o}`),Array.isArray(n.assessmentCoverage))for(let m of n.assessmentCoverage)j(m)&&typeof m.assessedRanges=="number"&&typeof m.availableRanges=="number"&&typeof m.untestedRanges=="number"&&p.push(` ${t.label("Assessment scope")}: ${m.assessedRanges} of ${m.availableRanges} source ranges assessed; ${m.untestedRanges} untested. Score applies to the sample.`);return l!==void 0?p.push(` ${t.label("Effective score")}: ${Eh(l)}`):a!==void 0&&p.push(` ${t.label("Effective score")}: ${Eh(a*100)}`),u!==void 0&&p.push(` ${t.label("Pass rate")}: ${u}`),d!==void 0&&p.push(` ${t.label("Coverage")}: ${d}`),p}function Eh(e){let t=Math.round(e*10)/10;return`${Number.isInteger(t)?t.toFixed(0):t.toFixed(1)}%`}function rce(e,t,n){let r=lce(e),i=[n.section(`${r} (${t.length})`)];return t.length===0?(i.push(` ${n.muted("No entries.")}`),i):(t.slice(0,at).forEach((o,s)=>{i.push(...wz(o,s,n))}),t.length>at&&i.push(` ${n.muted(`... ${t.length-at} more`)}`),i)}function wz(e,t,n){if(!j(e))return[`${t+1}. ${dn("",e)}`];let r=HP(e)??Re(Ju(e))??`Item ${t+1}`,i=[`${t+1}. ${r}`],o=_z(e);o&&i.push(` ${o}`);let s=Ju(e);return s&&i.push(` ${s}`),i}function ice(e,t){let n=tse(e,t);if(n.length>0)return n;let r=L(e,"capabilityProfile"),i=r?f(r,"runtimeRisk"):void 0;return i?[t.section("Trust"),` ${t.label("Runtime risk")}: ${i}`]:[]}function oce(e,t,n){let r=Pe(n),i=f(e,"skillSlug")??t,o=f(e,"runtimeRisk")??(L(e,"capabilityProfile")?f(L(e,"capabilityProfile"),"runtimeRisk"):void 0),s=[`${r.ok("OK")} Creator security report loaded.`,"",r.section("Creator Security")];o&&s.push(` ${r.label("Runtime risk")}: ${o}`);let a=f(e,"recommendation");a&&s.push(` ${r.label("Recommendation")}: ${a}`),s.push(` ${r.label("Skill")}: ${i}`);let l=f(e,"version");l&&s.push(` ${r.label("Version")}: ${l}`);let c=["semantic","review","no","reviewable","findings"].join("_"),u=Ka(e.reviewDegradedReasons).includes(c),d=Ka(e.trustBadges).filter(h=>h==="capability-mismatch"),p=Ka(e.trustBadges).filter(h=>h!=="capability-mismatch");(u||d.length>0)&&(s.push("",r.section("Creator Notes")),u&&s.push("1. Semantic review was not needed because there were no reviewable findings."),d.forEach((h,g)=>{s.push(`${u?g+2:g+1}. ${h==="capability-mismatch"?"Capability declaration needs review.":h}`)})),p.length>0&&(s.push("",r.section(`Trust badges (${p.length})`)),p.slice(0,at).forEach((h,g)=>s.push(`${g+1}. ${h}`)));let m=Array.isArray(e.findings)?e.findings:[];return s.push("",r.section(`Findings (${m.length})`)),m.length===0?s.push(` ${r.muted("No entries.")}`):m.slice(0,at).forEach((h,g)=>{s.push(...wz(h,g,r))}),s.push("",r.section("Next")),s.push(` ${r.arrow} skills-layer creator rescan-security ${i}`),s.push(` ${r.arrow} skills-layer creator status ${i}`),s.push(` ${r.arrow} skills-layer trust ${i}`),s.join(`
|
|
2296
2296
|
`)}function sce(e,t,n){let i=L(e,"report")??e,o=Pe(n),s=i.securityScore,a=f(i,"generatedAt")??f(i,"reportGeneratedAt"),l=Array.isArray(i.findings)?i.findings:void 0,c=[`${o.ok("OK")} Security rescan requested.`,"",o.section("Creator Security")];return c.push(` ${o.label("Skill")}: ${f(i,"skillSlug")??t}`),l&&c.push(` ${o.label("Findings")}: ${l.length}`),a&&c.push(` ${o.label("Generated at")}: ${a}`),c.push("",o.section("Next")),c.push(` ${o.arrow} skills-layer creator security-report ${t}`),c.push(` ${o.arrow} skills-layer creator status ${t}`),c.join(`
|
|
2297
|
-
`)}function ace(e){return Object.entries(e).filter(([t,n])=>bz(t,n))}function bz(e,t){let n=e.toLowerCase();return n==="status"||n==="securityscore"||n==="recommendation"||n==="capabilityprofile"||n==="securityposture"||n==="trust"||n==="effectiveness"||n.includes("apikey")||n.includes("secret")||n.includes("token")||n==="content"?!1:t!==void 0}function Ju(e){let n=[["id","id"],["name","name"],["keyPrefix","prefix"],["slug","slug"],["skillSlug","skill"],["currentVersion","version"],["version","version"],["category","category"],["skillType","type"],["type","type"],["visibility","visibility"],["status","status"],["count","count"],["email","email"],["role","role"],["selectedBackend","backend"],["selectedBaseUrl","base url"],["path","path"],["downloadUrl","download url"],["authorizationUrl","authorization url"],["checkoutUrl","checkout url"],["url","url"],["issueId","issue"],["reviewId","review"],["purchaseId","purchase"],["workspaceId","workspace"],["clientId","client"],["environment","environment"],["expiresAt","expires"],["lastUsedAt","last used on (UTC day)"],["revocable","revocable"],["revokeCommand","revoke"],["approvalId","approval"],["source","source"],["scope","scope"],["agent","agent"],["bytes","bytes"],["fileCount","file count"],["bodyWordCount","body words"]].flatMap(([i,o])=>{if(!bz(i,e[i]))return[];let s=e[i];return s===void 0?[]:[`${o}: ${dn(i,s)}`]}),r=L(e,"securityPosture");if(r){let i=f(r,"label"),o=f(r,"runtimeRisk");i&&n.push(`trust: ${i}`),o&&n.push(`risk: ${o}`)}return n.join("; ")}function _z(e){return f(e,"shortDescription")??f(e,"summary")??f(e,"description")??f(e,"message")}function HP(e){return f(e,"displayName")??f(e,"name")??f(e,"title")??f(e,"slug")??f(e,"skillSlug")??f(e,"code")??f(e,"id")}function dn(e,t){return e==="lastUsedAt"&&typeof t=="string"?t.slice(0,10):e==="downloadUrl"?"<hidden; use --json or --output>":typeof t=="string"?e.toLowerCase()==="category"?Sz(t):Za(t):typeof t=="number"||typeof t=="boolean"?String(t):t===null?"none":Array.isArray(t)?`${t.length} item${t.length===1?"":"s"}`:j(t)?Ju(t)||"details available with --json":String(t)}function Sz(e){return y0(e)}function Za(e){let t=e.replace(/\s+/gu," ").trim();return t.length>160?`${t.slice(0,157)}...`:t}function lce(e){return Fh(KP(e))}function KP(e){return e.replace(/([a-z0-9])([A-Z])/gu,"$1 $2").replace(/[_-]+/gu," ").toLowerCase()}function cce(e){if(e.verificationStatus==="unverified"&&e.publiclyDiscoverable===!1)return["Review the locally installed files before use; they remain Unverified / Unscored.","A public listing requires successful evaluation and final publication authority; held reviews are not automatic approval."];let t=uce(e),n=t?[`skills-layer show ${t}`,`skills-layer trust ${t}`,`skills-layer install ${t}`]:[],r=typeof e.downloadUrl=="string",i=Array.isArray(e.materializedWrites)&&e.materializedWrites.length>0;return r&&n.push("Use --output <path> to write exports without printing temporary download URLs"),i&&n.push("Review the materialized files in this workspace"),e.valid===!0&&n.push("skills-layer creator submit <path> --dry-run"),n}function uce(e){let t=f(e,"skillSlug")??f(e,"slug");if(t)return t;let n=e.results;if(Array.isArray(n)){for(let r of n)if(j(r)){let i=f(r,"skillSlug")??f(r,"slug");if(i)return i}}}function j(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function
|
|
2297
|
+
`)}function ace(e){return Object.entries(e).filter(([t,n])=>bz(t,n))}function bz(e,t){let n=e.toLowerCase();return n==="status"||n==="securityscore"||n==="recommendation"||n==="capabilityprofile"||n==="securityposture"||n==="trust"||n==="effectiveness"||n.includes("apikey")||n.includes("secret")||n.includes("token")||n==="content"?!1:t!==void 0}function Ju(e){let n=[["id","id"],["name","name"],["keyPrefix","prefix"],["slug","slug"],["skillSlug","skill"],["currentVersion","version"],["version","version"],["category","category"],["skillType","type"],["type","type"],["visibility","visibility"],["status","status"],["count","count"],["email","email"],["role","role"],["selectedBackend","backend"],["selectedBaseUrl","base url"],["path","path"],["downloadUrl","download url"],["authorizationUrl","authorization url"],["checkoutUrl","checkout url"],["url","url"],["issueId","issue"],["reviewId","review"],["purchaseId","purchase"],["workspaceId","workspace"],["clientId","client"],["environment","environment"],["expiresAt","expires"],["lastUsedAt","last used on (UTC day)"],["revocable","revocable"],["revokeCommand","revoke"],["approvalId","approval"],["source","source"],["scope","scope"],["agent","agent"],["bytes","bytes"],["fileCount","file count"],["bodyWordCount","body words"]].flatMap(([i,o])=>{if(!bz(i,e[i]))return[];let s=e[i];return s===void 0?[]:[`${o}: ${dn(i,s)}`]}),r=L(e,"securityPosture");if(r){let i=f(r,"label"),o=f(r,"runtimeRisk");i&&n.push(`trust: ${i}`),o&&n.push(`risk: ${o}`)}return n.join("; ")}function _z(e){return f(e,"shortDescription")??f(e,"summary")??f(e,"description")??f(e,"message")}function HP(e){return f(e,"displayName")??f(e,"name")??f(e,"title")??f(e,"slug")??f(e,"skillSlug")??f(e,"code")??f(e,"id")}function dn(e,t){return e==="lastUsedAt"&&typeof t=="string"?t.slice(0,10):e==="downloadUrl"?"<hidden; use --json or --output>":typeof t=="string"?e.toLowerCase()==="category"?Sz(t):Za(t):typeof t=="number"||typeof t=="boolean"?String(t):t===null?"none":Array.isArray(t)?`${t.length} item${t.length===1?"":"s"}`:j(t)?Ju(t)||"details available with --json":String(t)}function Sz(e){return y0(e)}function Za(e){let t=e.replace(/\s+/gu," ").trim();return t.length>160?`${t.slice(0,157)}...`:t}function lce(e){return Fh(KP(e))}function KP(e){return e.replace(/([a-z0-9])([A-Z])/gu,"$1 $2").replace(/[_-]+/gu," ").toLowerCase()}function cce(e){if(e.verificationStatus==="unverified"&&e.publiclyDiscoverable===!1)return["Review the locally installed files before use; they remain Unverified / Unscored.","A public listing requires successful evaluation and final publication authority; held reviews are not automatic approval."];let t=uce(e),n=t?[`skills-layer show ${t}`,`skills-layer trust ${t}`,`skills-layer install ${t}`]:[],r=typeof e.downloadUrl=="string",i=Array.isArray(e.materializedWrites)&&e.materializedWrites.length>0;return r&&n.push("Use --output <path> to write exports without printing temporary download URLs"),i&&n.push("Review the materialized files in this workspace"),e.valid===!0&&n.push("skills-layer creator submit <path> --dry-run"),n}function uce(e){let t=f(e,"skillSlug")??f(e,"slug");if(t)return t;let n=e.results;if(Array.isArray(n)){for(let r of n)if(j(r)){let i=f(r,"skillSlug")??f(r,"slug");if(i)return i}}}function j(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function E(e,t){e=H(e);let n=dce(e);return n?x(n.payload,e,t,n.reasonCode):t?x({status:"error",reasonCode:"command_failed",error:e},e,t,"command_failed"):{exitCode:1,stdout:"",stderr:St(e)}}function dce(e){if(/Local bundle rejected \(canonical_bundle_rejected\)/iu.test(e))return{reasonCode:"canonical_bundle_rejected",payload:{status:"error",reasonCode:"canonical_bundle_rejected",nextAction:"bundle.fix",nextStep:"Correct the listed bundle issues and run `skills-layer validate <path>`."}};if(/Invalid or expired recovery code/iu.test(e))return{reasonCode:"recovery_code_invalid_or_expired",payload:{status:"error",reasonCode:"recovery_code_invalid_or_expired",nextAction:"auth.recover",nextStep:"Request a fresh recovery code and complete recovery before it expires."}};let t=/^(?<provider>google|github|gitlab|microsoft) auth is not configured$/iu.exec(e);if(t?.groups?.provider)return{reasonCode:"social_provider_not_configured",payload:{status:"error",reasonCode:"social_provider_not_configured",provider:t.groups.provider.toLowerCase(),nextAction:"login",nextStep:"Choose a configured sign-in method or ask the platform operator to configure this provider."}};if(/^Search results do not include /u.test(e))return{reasonCode:"search_selection_not_found",payload:{status:"not_found",reasonCode:"search_selection_not_found",nextAction:"search",nextStep:"Run search again with a matching query or choose one of the returned skill slugs."}};if(/^workspace installs require --workspace <workspace-id>\.$/u.test(e))return{reasonCode:"workspace_required",payload:{status:"error",error:e,reasonCode:"workspace_required",nextAction:"workspace.current",nextStep:"Pass --workspace <workspace-id> using an accessible workspace."}};let n=/^Unsupported skill type "(?<skillType>[^"]+)"\./u.exec(e);if(n?.groups?.skillType)return{reasonCode:"unsupported_skill_type",payload:{status:"error",reasonCode:"unsupported_skill_type",providedSkillType:n.groups.skillType,acceptedValues:["standalone","workflow","workflow_automation","mcp_enhanced"],nextAction:"creator.init",nextStep:"Choose one of the supported skill types."}};let r=/^(?<code>EACCES|EPERM|EROFS):\s*(?<detail>.+)$/iu.exec(e);if(r?.groups){let h=r.groups.code.toUpperCase(),g=/'(?<path>[^']+)'/u.exec(e)?.groups?.path;return{reasonCode:"local_filesystem_permission_denied",payload:{status:"error",reasonCode:"local_filesystem_permission_denied",code:h,...g?{path:g}:{},nextAction:"check_local_permissions",nextStep:"Check the local path permissions, choose a writable installed skill directory, or rerun the command from a workspace you can write to."}}}let i=/^--(?<flag>[a-z0-9-]+) must be valid JSON\.$/iu.exec(e);if(i?.groups){let h=i.groups.flag;return{reasonCode:"invalid_json",payload:{status:"error",reasonCode:"invalid_json",flag:h,nextAction:"fix_json_flag",nextStep:`Provide valid JSON for --${h}.`}}}let o=/^Unknown flag --(?<flag>[a-z0-9-]+)\.$/iu.exec(e);if(o?.groups)return{reasonCode:"unknown_flag",payload:{status:"error",reasonCode:"unknown_flag",flag:o.groups.flag,nextAction:"help",nextStep:"Run `skills-layer <command> --help` to see supported flags for that command."}};let s=/^(?<command>.+?) --(?<flag>[a-z0-9-]+) must be one of: (?<accepted>.+?)\.$/iu.exec(e);if(s?.groups){let h=s.groups.flag,g=s.groups.accepted.split(",").map(y=>y.trim()).filter(Boolean);return{reasonCode:`invalid_${h.replace(/-/gu,"_")}`,payload:{status:"error",reasonCode:`invalid_${h.replace(/-/gu,"_")}`,command:s.groups.command,flag:h,acceptedValues:g,nextAction:s.groups.command.replace(/\s+/gu,"."),nextStep:`Use --${h} with one of: ${g.join(", ")}.`}}}let a=/^Unknown (?<namespace>.+?) command "(?<subcommand>.*?)"\.$/u.exec(e);if(a?.groups){let h=a.groups.namespace.trim(),g=a.groups.subcommand;return{reasonCode:"unknown_subcommand",payload:{status:"error",reasonCode:"unknown_subcommand",namespace:h,subcommand:g,nextAction:`${h.replace(/\s+/gu,".")}.help`,nextStep:`Run \`skills-layer ${h} --help\` to see supported ${h} commands.`}}}if(e.startsWith("Flag --"))return{reasonCode:"flag_value_missing",payload:{status:"error",reasonCode:"flag_value_missing",nextStep:"Supply a value for the flag. To clear a profile field, use its --clear-<field> option."}};let l=/^(?<command>.+?) requires (?<argument>.+?)\.$/u.exec(e);if(!l?.groups)return;let c=l.groups.command.trim(),u=l.groups.argument.trim(),d=pce(u),p=/--(?<name>[a-z0-9-]+)/iu.exec(u)?.groups?.name,m=p?`--${p} <value>`:`<${d}>`;return{reasonCode:"missing_required_argument",payload:{status:"error",reasonCode:"missing_required_argument",command:c,argument:d,nextAction:c.replace(/\s+/gu,"."),nextStep:`Run \`skills-layer ${c} ${m}\`.`}}}function pce(e){let t=e.replace(/^(?:a|an|the)\s+/iu,"");if(/^two or more skill slugs$/iu.test(t))return"two-or-more-skill-slugs";let n=/--(?<name>[a-z0-9-]+)/iu.exec(t)?.groups?.name;return n||(/<(?<name>[^>]+)>/u.exec(t)?.groups?.name??t).replace(/\s+or\s+.*$/iu,"").replace(/[^a-z0-9]+/giu,"-").replace(/^-+|-+$/gu,"").toLowerCase()||"argument"}function x(e,t,n,r){let i=Rh(e),o=Og(r??f(i,"reasonCode")),s={schemaVersion:VM,status:fce(f(i,"status"),o.defaultStatus),summary:t,why:f(i,"why")??null,nextAction:f(i,"nextAction")??null,nextStep:f(i,"nextStep")??null,data:i,warnings:Array.isArray(i.warnings)?i.warnings:[],links:Array.isArray(i.links)?i.links:[],reasonCode:o.reasonCode,reasonFamily:o.family,handoff:i.handoff??null};return{exitCode:1,stdout:"",stderr:n?JSON.stringify(s,null,2):St(mce(s,t))}}function fce(e,t){return!e||!/^[a-z][a-z0-9_]*$/u.test(e)||e==="approved"||e==="published"?t:e}function mce(e,t){let n=f(e,"summary")??t,r=f(e,"reasonCode"),i=f(e,"why"),o=f(e,"nextStep"),s=L(e,"data"),a=s?f(s,"requestId")??f(s,"operationId"):void 0,l=gce(r,n),c=[l];l!==n&&c.push(n),c.push("","Unchanged"," No Skills Layer state was changed by this failed command."),i&&i!==n&&c.push("","Why",` ${i}`);let d=(s&&Array.isArray(s.blockingFindings)?s.blockingFindings:[]).flatMap(p=>{if(!j(p)||typeof p.code!="string"||!/^[A-Za-z0-9_-]{1,128}$/u.test(p.code))return[];let m=typeof p.path=="string"?p.path.replace(/[\p{Cc}\p{Cf}]/gu,"").slice(0,256):"",h=Number.isSafeInteger(p.lineNumber)&&Number(p.lineNumber)>0?`:${p.lineNumber}`:"";return[` ${p.code}${m?` \u2014 ${m}${h}`:""}`]}).slice(0,12);if(d.length>0&&c.push("","Blocking checks",...d),o){let p=/`(?<command>skills-layer(?: [^`]+)?)`/u.exec(o)?.groups?.command;c.push("","Next",` ${p??o}`)}else{let p=/`(?<command>skills-layer(?: [^`]+)?)`/u.exec(n)?.groups?.command;c.push("","Next",` ${p??"skills-layer --help"}`)}return a&&c.push("",`Reference ${a}`),c.join(`
|
|
2298
2298
|
`)}function gce(e,t){if(e==="missing_required_argument")return"Required information is missing";if(e==="unknown_flag")return"That option is not supported";if(e==="invalid_json")return"That JSON value could not be read";if(e==="local_filesystem_permission_denied")return"Skills Layer cannot write to that location";if(e==="login_required")return"Sign in required";if(e==="social_identity_link_required")return"Secure account connection required";let n=t.split(`
|
|
2299
|
-
`,1)[0]?.trim();return n&&n.length<=72?n:"Skills Layer could not complete the command"}function Go(e,t){let n=mz(e.details);if(n)return
|
|
2299
|
+
`,1)[0]?.trim();return n&&n.length<=72?n:"Skills Layer could not complete the command"}function Go(e,t){let n=mz(e.details);if(n)return R(n,String(n.message),t);let r=e.details??{};if(e.status===401&&!f(r,"reasonCode")){let a=f(r,"error")??"Login required.",l=f(r,"nextAction")??"login",c=f(r,"nextStep")??"Run `skills-layer login` to sign in, then retry this command.",u=/[.!?]$/u.test(a)?a:`${a}.`;return x({status:"login_required",reasonCode:"login_required",error:a,nextAction:l,nextStep:c},`${u} ${c}`,t,"login_required")}let i=f(r,"reasonCode");if(i){let a=j(r.data)?r.data:null,c=a!==null&&("summary"in r||"data"in r)?a:r,u=f(c,"error")??f(r,"error")??f(r,"summary")??e.message,d=Og(i,{httpStatus:e.status}),p=u==="Request failed"||u==="Request failed."?d.safeSummary:u;return x({...c,status:f(r,"status")??f(c,"status")??(e.status===404?"not_found":"error"),nextAction:f(c,"nextAction")??f(r,"nextAction"),nextStep:f(c,"nextStep")??f(r,"nextStep"),warnings:Array.isArray(c.warnings)?c.warnings:r.warnings,links:Array.isArray(c.links)?c.links:r.links,handoff:c.handoff??r.handoff,reasonCode:i},[p,$A(c.eligibleAt??r.eligibleAt)].filter(Boolean).join(`
|
|
2300
2300
|
`),t,i)}let o=hce(e);if(o)return x(o.payload,o.message,t,o.reasonCode);let s=Og(null,{httpStatus:e.status});return x({status:s.defaultStatus,reasonCode:s.reasonCode,error:f(r,"error")??e.message,...Array.isArray(r.issues)?{issues:r.issues}:{},...j(r.validation)?{validation:r.validation}:{},nextAction:e.status===404?"help":null,nextStep:e.status===404?"Check the identifier or list the resources visible to this account.":null},f(r,"error")??e.message,t,s.reasonCode)}function hce(e){let t=f(e.details??{},"error")??e.message,n=t.toLowerCase();return n.includes("invalid or expired recovery code")?{reasonCode:"recovery_code_invalid_or_expired",message:"The recovery code is invalid or expired.",payload:{status:"error",reasonCode:"recovery_code_invalid_or_expired",nextAction:"auth.recover",nextStep:"Request a fresh recovery code and complete recovery before it expires."}}:/^(?:google|github|gitlab|microsoft) auth is not configured$/u.test(n)?{reasonCode:"social_provider_not_configured",message:"The selected social provider is not configured.",payload:{status:"error",reasonCode:"social_provider_not_configured",nextAction:"login",nextStep:"Choose a configured sign-in method or ask the platform operator to configure this provider."}}:e.status===403?{reasonCode:"permission_denied",message:"This credential cannot access the requested resource.",payload:{status:"error",reasonCode:"permission_denied",nextAction:null,nextStep:null}}:e.status===404&&n.includes("source connection")?{reasonCode:"source_connection_not_found",message:"Source connection not found.",payload:{status:"not_found",error:t,reasonCode:"source_connection_not_found",nextAction:"source.connection.start",nextStep:"Check the source connection id, or start a new source connection."}}:e.status===404&&n.includes("approval request")?{reasonCode:"approval_request_not_found",message:"Approval request not found.",payload:{status:"not_found",error:t,reasonCode:"approval_request_not_found",nextAction:"approval.request.status",nextStep:"Check the approval request id, or rerun the workflow that created the approval request."}}:e.status===404&&(n.includes("purchase")||n.includes("invoice"))?{reasonCode:"purchase_not_found",message:"Purchase not found.",payload:{status:"not_found",error:t,reasonCode:"purchase_not_found",nextAction:"purchases.list",nextStep:"Run `skills-layer purchases list` to find a valid purchase id."}}:e.status===404&&(n.includes("security report")||n.includes("trust report"))?{reasonCode:"trust_report_not_found",message:"Platform Score report not found.",payload:{status:"not_found",error:t,reasonCode:"trust_report_not_found",nextAction:"trust",nextStep:"Run `skills-layer show <skill-slug>` to confirm the skill exists, then retry trust after the Platform Score report is generated."}}:e.status===404&&n.includes("help topic")?{reasonCode:"help_topic_not_found",message:"Help topic not found.",payload:{status:"not_found",error:t,reasonCode:"help_topic_not_found",nextAction:"help",nextStep:"Run `skills-layer help full` or `skills-layer --help` to see available topics."}}:e.status===404&&n.includes("skill")?{reasonCode:"skill_not_found",message:"Skill not found.",payload:{status:"not_found",error:t,reasonCode:"skill_not_found",nextAction:"search",nextStep:"Run `skills-layer search <query>` to find a valid skill slug before retrying."}}:e.status===404?n.includes("download exported bundle")?{reasonCode:"resource_not_found",message:t,payload:{status:"not_found",error:t,reasonCode:"resource_not_found",nextAction:"export",nextStep:"Request a fresh export URL and retry the download."}}:{reasonCode:"resource_not_found",message:"The requested resource was not found.",payload:{status:"not_found",reasonCode:"resource_not_found",nextAction:"help",nextStep:"Check the identifier or list the resources visible to this account."}}:null}async function ke(e){try{return JSON.parse(await Fi(e,"utf8"))}catch{return null}}async function xA(e,t){try{let n=qC(await ke(e.paths.pendingRevocationsPath)),r=_g(t);return await Ve(e.paths.pendingRevocationsPath,VC(U2(n,r))),!0}catch{return!1}}async function yce(e,t){let n=await ke(e.paths.pendingRevocationsPath),r=qC(n);if(r.length===0)return n!==null&&await We(e.paths.pendingRevocationsPath,{force:!0}),{attempted:0,completed:0,remaining:0};let i=r.filter(a=>a.baseUrl===t.baseUrl&&a.userId===t.userId),o=r.filter(a=>a.baseUrl!==t.baseUrl||a.userId!==t.userId),s=0;for(let a of i)try{await D({...e,baseUrl:a.baseUrl,apiKey:t.apiKey},"/api/v1/me/session/revoke",{method:"POST",headers:V(t.apiKey),body:JSON.stringify(z2(a))}),s+=1}catch{o.push(a)}return o.length===0?await We(e.paths.pendingRevocationsPath,{force:!0}):await Ve(e.paths.pendingRevocationsPath,VC(o)),{attempted:i.length,completed:s,remaining:o.length}}async function vce(e,t){let n=await ke(e);return n?N2(n,{env:t.env,platform:t.platform,store:t.credentialStore}):null}async function CA(e,t,n){let r=await j2(t,{env:n.env,platform:n.platform,store:n.credentialStore});await Ve(e,r)}async function Ve(e,t){await Zo(Me(e)),await ZP(e,`${JSON.stringify(t,null,2)}
|
|
2301
2301
|
`,{encoding:"utf8",mode:384}),await Jo(e,384)}async function Zo(e){await Mo(e,{recursive:!0,mode:448}),await Jo(e,448)}async function Jo(e,t){if(process.platform!=="win32")try{await ore(e,t)}catch{}}async function BM(e,t){await Mo(Me(e),{recursive:!0}),await ZP(e,t,"utf8")}async function IA(e,t){let n=Me(e);await Mo(n,{recursive:!0});let r=K(n,`.${ot(e)}.tmp-${Ge(12).toString("hex")}`),i;try{i=await Uo(r,"wx",384),await i.writeFile(t),await i.sync(),await i.close(),i=void 0,await zo(r,e),await Jo(e,384),await SA(n)}catch(o){throw await i?.close().catch(()=>{}),await We(r,{force:!0}).catch(()=>{}),o}}function kce(e=process.stdin,t=process.stdout,n=qM){return async r=>{if(!e.isTTY||!t.isTTY)throw new Error("Interactive prompt is not available in this environment.");let i=n({input:e,output:t});try{return(await i.question(r)).trim()}finally{i.close()}}}function wce(e=process.stdin,t=process.stdout,n=qM){return async r=>{if(!e.isTTY||!t.isTTY)throw new Error("Interactive secret prompt is not available in this environment.");if(typeof e.setRawMode=="function"&&typeof e.on=="function"&&typeof e.off=="function")return new Promise((o,s)=>{let a=e,l=a.isRaw===!0,c="",u=!1,d=m=>{u||(u=!0,a.off("data",p),a.setRawMode(l),a.pause?.(),t.write(`
|
|
2302
2302
|
`),m())},p=m=>{let h=typeof m=="string"?m:m.toString("utf8");for(let g of h){if(g==="\r"||g===`
|