@humain/humain-code 0.8.5 → 0.8.7
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/CHANGELOG.md +27 -2
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/{anthropic-messages-42CGJCSR.js → anthropic-messages-QMSJV4J5.js} +3 -3
- package/dist/bundle/chunks/{ask-VH7GNX75.js → ask-VVSJA5VG.js} +2 -2
- package/dist/bundle/chunks/{azure-openai-responses-DOKKMBUN.js → azure-openai-responses-P57ZD6XP.js} +3 -3
- package/dist/bundle/chunks/chunk-2QVKRSKH.js +4 -0
- package/dist/bundle/chunks/{chunk-SASR4VNV.js → chunk-3BZUQ54Z.js} +1 -1
- package/dist/bundle/chunks/{chunk-XGOJCV6Z.js → chunk-4K6ISLTX.js} +1 -1
- package/dist/bundle/chunks/{chunk-BNZZJ4LO.js → chunk-4QVJYVS5.js} +1 -1
- package/dist/bundle/chunks/{chunk-MXF3KYLZ.js → chunk-4UXFF4IH.js} +1 -1
- package/dist/bundle/chunks/{chunk-53DWQSBC.js → chunk-6PJEPQBW.js} +2 -2
- package/dist/bundle/chunks/{chunk-4SL6URR3.js → chunk-7X7QN6MX.js} +5 -3
- package/dist/bundle/chunks/{chunk-N3W4ALAM.js → chunk-A7AH3VMJ.js} +69 -66
- package/dist/bundle/chunks/{chunk-H35P7ROY.js → chunk-B345VDHB.js} +9 -7
- package/dist/bundle/chunks/{chunk-A5ZMBTTM.js → chunk-B57IK7TV.js} +2 -2
- package/dist/bundle/chunks/{chunk-KJ3QRSSY.js → chunk-BVBEJBVY.js} +1 -1
- package/dist/bundle/chunks/{chunk-AER66CNP.js → chunk-BXDTDGHH.js} +1 -1
- package/dist/bundle/chunks/chunk-CDLUE6BJ.js +4 -0
- package/dist/bundle/chunks/{chunk-FLWO3H5J.js → chunk-DBC6XUKA.js} +1 -1
- package/dist/bundle/chunks/{chunk-BDNX23GT.js → chunk-EB2ZJYOO.js} +268 -232
- package/dist/bundle/chunks/{chunk-2RXTZK2V.js → chunk-EK4QE622.js} +147 -37
- package/dist/bundle/chunks/{chunk-K5EFEIFP.js → chunk-H6CKS7HC.js} +1 -1
- package/dist/bundle/chunks/{chunk-UTRUALFN.js → chunk-HV25WMNO.js} +1 -1
- package/dist/bundle/chunks/{chunk-7XRMMCKG.js → chunk-IP7R6BIN.js} +935 -529
- package/dist/bundle/chunks/{chunk-HRNYDRL7.js → chunk-J5R2BQJS.js} +1 -1
- package/dist/bundle/chunks/{chunk-5C5K4EVJ.js → chunk-JNSFJADB.js} +1 -1
- package/dist/bundle/chunks/{chunk-CG43CMFH.js → chunk-KBIPIIKE.js} +1 -1
- package/dist/bundle/chunks/{chunk-3OOOEJV4.js → chunk-MS3SLC2V.js} +10 -10
- package/dist/bundle/chunks/{chunk-WCKS2DPT.js → chunk-NO6T6CDO.js} +1 -1
- package/dist/bundle/chunks/{chunk-VWUEKLRH.js → chunk-NSSJ6OJK.js} +141 -225
- package/dist/bundle/chunks/{chunk-MZYHSWHX.js → chunk-OR3ORXP3.js} +2 -2
- package/dist/bundle/chunks/{chunk-MLOUZAVZ.js → chunk-PU7SKUJ6.js} +2 -2
- package/dist/bundle/chunks/{chunk-QZXLTW7V.js → chunk-RRGJHRKF.js} +1 -1
- package/dist/bundle/chunks/{chunk-625QJSFJ.js → chunk-SDPK3KZ3.js} +1 -1
- package/dist/bundle/chunks/{chunk-ZFFDBTG3.js → chunk-SPLJOIKL.js} +1 -1
- package/dist/bundle/chunks/{chunk-O44A4E4K.js → chunk-TNKPCYIM.js} +1 -1
- package/dist/bundle/chunks/{chunk-5KUCY54O.js → chunk-UY5TOBH2.js} +1 -1
- package/dist/bundle/chunks/{chunk-FHP5BULR.js → chunk-VFPA5KPR.js} +1 -1
- package/dist/bundle/chunks/chunk-VP27C46J.js +23 -0
- package/dist/bundle/chunks/{chunk-B3FT6L6S.js → chunk-XZJT5U3V.js} +1 -1
- package/dist/bundle/chunks/{chunk-UOSJTMCL.js → chunk-YCGPXBJP.js} +1 -1
- package/dist/bundle/chunks/{chunk-COZTJAOY.js → chunk-YRSNKHEF.js} +384 -781
- package/dist/bundle/chunks/{chunk-MQYR4Q6X.js → chunk-YSRWNEZW.js} +1 -1
- package/dist/bundle/chunks/{chunk-EWPEY4F4.js → chunk-ZAO4KC6J.js} +884 -898
- package/dist/bundle/chunks/{chunk-V2HTCZRF.js → chunk-ZXOTVZUX.js} +1 -1
- package/dist/bundle/chunks/{chunk-T5WECB2D.js → chunk-ZZNGVD5Q.js} +1 -1
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-ZAZW4M4B.js → cloudflare-workers-ai-system-one-4BO66KHO.js} +1 -1
- package/dist/bundle/chunks/{compat-2RC4CJNV.js → compat-EOHVO2W3.js} +4 -4
- package/dist/bundle/chunks/{curator-server-MW645JI3.js → curator-server-72V7LMHQ.js} +1 -1
- package/dist/bundle/chunks/{dist-3DAGUOYC.js → dist-FW7ELRQH.js} +1 -1
- package/dist/bundle/chunks/{dist-K4QIXV5O.js → dist-YEVRRTWL.js} +8 -8
- package/dist/bundle/chunks/{dist-VXQT3DQY.js → dist-ZRUKAVTU.js} +3 -3
- package/dist/bundle/chunks/{doctor-EH7X36SK.js → doctor-HJKC434Y.js} +29 -28
- package/dist/bundle/chunks/{easter-egg-3d-Z24JLXD4.js → easter-egg-3d-M37PJBL5.js} +1 -1
- package/dist/bundle/chunks/entry-M5TRX7N4.js +2 -0
- package/dist/bundle/chunks/{execute-C4BZQRPQ.js → execute-MIXK3CFW.js} +2 -2
- package/dist/bundle/chunks/{extract-XVQCIS7D.js → extract-WB6Y6ISY.js} +2 -2
- package/dist/bundle/chunks/{flow-implementer-J6QTLBTH.js → flow-implementer-ZNK5KVOG.js} +5 -5
- package/dist/bundle/chunks/github-copilot.js +1 -1
- package/dist/bundle/chunks/{google-generative-ai-P2P45MYP.js → google-generative-ai-B2BT7X4W.js} +3 -3
- package/dist/bundle/chunks/{google-vertex-SHY4IS5F.js → google-vertex-PCFDFRHY.js} +3 -3
- package/dist/bundle/chunks/{host-YESS2VAB.js → host-RF6R6GLZ.js} +1 -1
- package/dist/bundle/chunks/{inprocess-OHNEKTFB.js → inprocess-6MLIANGV.js} +6 -6
- package/dist/bundle/chunks/interactive-mode-QKREO5BH.js +6 -0
- package/dist/bundle/chunks/{llama-cpp-classify-RSRH4KV2.js → llama-cpp-classify-DMJSUUAD.js} +1 -1
- package/dist/bundle/chunks/{mistral-conversations-YTMJKHHI.js → mistral-conversations-OXWTIYWX.js} +2 -2
- package/dist/bundle/chunks/{openai-codex-responses-NUCJOJSZ.js → openai-codex-responses-YGXOZKWL.js} +3 -3
- package/dist/bundle/chunks/{openai-completions-E5NRJUHA.js → openai-completions-WDVOHMN6.js} +4 -4
- package/dist/bundle/chunks/{openai-decisions-342J5ZYG.js → openai-decisions-45LGQAD5.js} +1 -1
- package/dist/bundle/chunks/{openai-responses-BN5Z4HFI.js → openai-responses-OZDPUN4M.js} +3 -3
- package/dist/bundle/chunks/{openrouter-images-7RNG3JVF.js → openrouter-images-2IKRVRTZ.js} +2 -2
- package/dist/bundle/chunks/{pi-messages-2L7FV5OK.js → pi-messages-VZOJLMWW.js} +2 -2
- package/dist/bundle/chunks/{questionnaire-session-XEVAK7JS.js → questionnaire-session-RSZE5I3P.js} +2 -2
- package/dist/bundle/chunks/{session-picker-666KJIVM.js → session-picker-EUPZJEFF.js} +2 -2
- package/dist/bundle/chunks/{startup-ui-INEVSNGK.js → startup-ui-RTSTUGUC.js} +2 -2
- package/dist/bundle/chunks/{typesafe-system-one-UJUNSZG4.js → typesafe-system-one-IVWD24CQ.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-6FVRJTM3.js → virtual-modules-LS3DOCYU.js} +8 -8
- package/dist/bundle/cli-runtime.js +5 -5
- package/dist/bundle/flow/package.json +1 -1
- package/dist/bundle/index.js +11 -11
- package/dist/bundle/rpc-entry.js +5 -5
- package/dist/coordination/adapter/delivery.d.ts +6 -0
- package/dist/coordination/adapter/delivery.d.ts.map +1 -1
- package/dist/coordination/adapter/delivery.js +39 -4
- package/dist/coordination/adapter/delivery.js.map +1 -1
- package/dist/coordination/adapter/index.d.ts +2 -0
- package/dist/coordination/adapter/index.d.ts.map +1 -1
- package/dist/coordination/adapter/index.js +26 -0
- package/dist/coordination/adapter/index.js.map +1 -1
- package/dist/coordination/adapter/tool.js +3 -3
- package/dist/coordination/adapter/tool.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts +2 -0
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +4 -0
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/keybindings.d.ts +16 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +2 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +5 -0
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +2 -0
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager.d.ts +10 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +31 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +5 -0
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +8 -0
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/forge-build-token.d.ts +3 -0
- package/dist/forge-build-token.d.ts.map +1 -0
- package/dist/forge-build-token.js +17 -0
- package/dist/forge-build-token.js.map +1 -0
- package/dist/humain/checklist/vendor/commands.d.ts +7 -0
- package/dist/humain/checklist/vendor/commands.d.ts.map +1 -1
- package/dist/humain/checklist/vendor/commands.js +65 -13
- package/dist/humain/checklist/vendor/commands.js.map +1 -1
- package/dist/humain/checklist/vendor/index.d.ts.map +1 -1
- package/dist/humain/checklist/vendor/index.js +4 -3
- package/dist/humain/checklist/vendor/index.js.map +1 -1
- package/dist/humain/hcode/build-token.d.ts +35 -0
- package/dist/humain/hcode/build-token.d.ts.map +1 -0
- package/dist/humain/hcode/build-token.js +406 -0
- package/dist/humain/hcode/build-token.js.map +1 -0
- package/dist/humain/hcode/contracts.d.ts +3 -1
- package/dist/humain/hcode/contracts.d.ts.map +1 -1
- package/dist/humain/hcode/contracts.js +7 -4
- package/dist/humain/hcode/contracts.js.map +1 -1
- package/dist/humain/hcode/notices.d.ts +5 -0
- package/dist/humain/hcode/notices.d.ts.map +1 -1
- package/dist/humain/hcode/notices.js +5 -0
- package/dist/humain/hcode/notices.js.map +1 -1
- package/dist/humain/hcode/provider.d.ts.map +1 -1
- package/dist/humain/hcode/provider.js +1 -1
- package/dist/humain/hcode/provider.js.map +1 -1
- package/dist/humain/hcode/run-credential.d.ts +3 -1
- package/dist/humain/hcode/run-credential.d.ts.map +1 -1
- package/dist/humain/hcode/run-credential.js +123 -19
- package/dist/humain/hcode/run-credential.js.map +1 -1
- package/dist/humain/hcode/sandbox.d.ts.map +1 -1
- package/dist/humain/hcode/sandbox.js +10 -4
- package/dist/humain/hcode/sandbox.js.map +1 -1
- package/dist/modes/interactive/chat-viewport.d.ts +4 -0
- package/dist/modes/interactive/chat-viewport.d.ts.map +1 -1
- package/dist/modes/interactive/chat-viewport.js +29 -5
- package/dist/modes/interactive/chat-viewport.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +2 -0
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +29 -12
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +6 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +20 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/status-line.js +2 -2
- package/dist/modes/interactive/components/status-line.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +18 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +91 -3
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tool-group.d.ts +22 -0
- package/dist/modes/interactive/components/tool-group.d.ts.map +1 -0
- package/dist/modes/interactive/components/tool-group.js +117 -0
- package/dist/modes/interactive/components/tool-group.js.map +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts +12 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +155 -6
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/sidebar/git-work.d.ts +18 -0
- package/dist/modes/interactive/sidebar/git-work.d.ts.map +1 -0
- package/dist/modes/interactive/sidebar/git-work.js +56 -0
- package/dist/modes/interactive/sidebar/git-work.js.map +1 -0
- package/dist/modes/interactive/sidebar/sidebar-component.d.ts +13 -0
- package/dist/modes/interactive/sidebar/sidebar-component.d.ts.map +1 -0
- package/dist/modes/interactive/sidebar/sidebar-component.js +61 -0
- package/dist/modes/interactive/sidebar/sidebar-component.js.map +1 -0
- package/dist/modes/interactive/sidebar/sidebar-model.d.ts +69 -0
- package/dist/modes/interactive/sidebar/sidebar-model.d.ts.map +1 -0
- package/dist/modes/interactive/sidebar/sidebar-model.js +217 -0
- package/dist/modes/interactive/sidebar/sidebar-model.js.map +1 -0
- package/dist/modes/interactive/tool-grouping.d.ts +11 -0
- package/dist/modes/interactive/tool-grouping.d.ts.map +1 -0
- package/dist/modes/interactive/tool-grouping.js +32 -0
- package/dist/modes/interactive/tool-grouping.js.map +1 -0
- package/docs/coordination.md +7 -3
- package/docs/environment-variables.md +14 -0
- package/docs/forge-run-bootstrap.md +77 -42
- package/docs/keybindings.md +2 -0
- package/docs/providers.md +14 -0
- package/docs/settings.md +16 -1
- package/docs/slash-commands.md +3 -0
- package/examples/sdk/12-full-control.ts +1 -1
- package/npm-shrinkwrap.json +7 -6
- package/package.json +3 -2
- package/schemas/keybindings.schema.json +8 -0
- package/schemas/settings.schema.json +29 -0
- package/src/humain/caveman/UPSTREAM.md +15 -3
- package/src/humain/caveman/upstream.json +2 -2
- package/dist/bundle/chunks/chunk-HWFAAGYK.js +0 -23
- package/dist/bundle/chunks/chunk-RP6MWUAP.js +0 -4
- package/dist/bundle/chunks/entry-3EL6GOWK.js +0 -2
- package/dist/bundle/chunks/interactive-mode-ZREVRX7W.js +0 -5
- /package/dist/bundle/chunks/{chunk-T7F2TEIS.js → chunk-3IX4NEXK.js} +0 -0
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{ANTHROPIC_USAGE_PROVIDER_ID,
|
|
3
|
-
import{
|
|
4
|
-
|
|
2
|
+
import{ANTHROPIC_USAGE_PROVIDER_ID,COORDINATION_MESSAGE_TYPE,CoordinationClient,CoordinationRequestError,CoordinationSessionHeldError,InboundDelivery,MAX_ID_CHARS,MAX_NAME_CHARS,MAX_WORKTREE_CHARS,TASK_ID_ENV,WakeBudget,cleanMeta,createClientBackend,createCoordinationToolDefinition,createIntegrationBackend,currentSubagentDepth,inspectAttempt,parseAnthropicSubscriptionUsage,peerLabel,readGitBranch,renderPeerMessage,resolveGitRepositoryIdentity,resolveToCwd,runGit,tokenMatch}from"./chunk-IP7R6BIN.js";
|
|
3
|
+
import{ensureBroker}from"./chunk-MA2WCMSN.js";import{ID_IN_USE_DETAIL,MAX_ARTIFACT_BYTES,MAX_EVIDENCE_CHARS,MAX_SESSION_FIELD_CHARS,isOwnershipMode,isRecordKey,isSha256Hex,truncateChars}from"./chunk-S2US54IU.js";import{TOOL_SEARCH_TOOL_NAME}from"./chunk-4QVJYVS5.js";import{CODEMODE_TOOL_NAME,VisualLinePreview,addUsageToTotals,createUsageTotals,formatToolCallWithArgs,getSessionUsage,getTextOutput,replaceTabs,stripAnsi,writeOutputFile}from"./chunk-PU7SKUJ6.js";import{HCODE_PROVIDER,
|
|
4
|
+
getCodexAvailability,parseSubscriptionCreditAmount}from"./chunk-A7AH3VMJ.js";import{loadMcpConfig,updateMcpServerConfig}from"./chunk-J64VNQ6D.js";import{openBrowser}from"./chunk-IWZQ25I3.js";import{createMcpResultSchema,limitMcpContent,normalizeMcpInputSchema,toMcpModelContent}from"./chunk-QZWUXGY7.js";import{LIST_MCP_RESOURCES_TOOL,LIST_MCP_RESOURCE_TEMPLATES_TOOL,READ_MCP_RESOURCE_TOOL,getMcpToolExposure,mcpNamespace,raceWithAbortSignal}from"./chunk-GMPJWLZS.js";import{
|
|
5
|
+
killTrackedDetachedChildrenAsync}from"./chunk-PYX6ZCC7.js";import{areExperimentalFeaturesEnabled}from"./chunk-VP27C46J.js";import{DynamicBorder}from"./chunk-4K6ISLTX.js";import{keyHint,keyText}from"./chunk-4UXFF4IH.js";import{getSelectListTheme,getThemeInstance,theme}from"./chunk-DBC6XUKA.js";import{hcodeDisplayName,isWSL}from"./chunk-OADQOW67.js";import{Container,Input,SelectList,Spacer,Text,getNativeClipboard,hyperlink,sanitizeTerminalText,truncateToWidth,visibleWidth,
|
|
6
|
+
wrapTextWithAnsi}from"./chunk-B345VDHB.js";import{COORDINATION_FILE_MODE,resolveCoordinationRuntimePaths}from"./chunk-B47PNNLL.js";import{ENV_PREFIX,getAgentDir}from"./chunk-CKFLQGJN.js";var HCODE_LOGIN_MISMATCH_DETAILS="HUMAIN Code's sign-in settings (/api/cli/config or issuer discovery) don't match what this CLI version accepts. Update the CLI with `humain-code update`, or ask the HUMAIN Code platform team to check the server's CLI sign-in configuration.",EMPTY_REASONS={no_cli_models_approved:{reason:"no model is approved for CLI",fix:"Ask an admin to set a model to Web + CLI or CLI only in Settings > Model Access."},provider_key_not_cli_enabled:{reason:"the provider key isn't\
|
|
5
7
|
enabled for CLI",fix:"Ask an admin to enable CLI on the key in Settings > Provider Keys."},cli_capacity_unconfigured:{reason:"CLI capacity hasn't been configured",fix:"Ask the HUMAIN Code platform team to check the deployment's CLI capacity limits."},provider_key_not_dedicated:{reason:"the provider key is shared or isn't approved for CLI use",fix:"Ask an admin to configure a dedicated key for HUMAIN Code CLI."},models_not_qualified:{reason:"this server hasn't finished CLI setup for the approved\
|
|
6
8
|
models",fix:"Ask an admin to report it to the HUMAIN Code platform team."}};function hcodeEmptyCatalogMessage(reason){if(!reason)return"Your admin hasn't enabled CLI models yet.";let{reason:why,fix}=EMPTY_REASONS[reason];return`No models are available in the CLI: ${why}. ${fix}`}function hcodeEmptyCatalogReason(cause){return cause.kind==="failed"?{reason:"the model list couldn't be loaded",fix:"Check your network, VPN or Zscaler."}:cause.reason?EMPTY_REASONS[cause.reason]:{reason:"your admin ha\
|
|
7
9
|
sn't enabled CLI models yet",fix:"Ask an admin to enable a model for CLI."}}function hcodeEmptyCatalogNotice(environmentId,email,cause){let{reason,fix}=hcodeEmptyCatalogReason(cause);return[`\u2713 Signed in to ${hcodeDisplayName(environmentId)}${email?` as ${email}`:""}`,` No models available in the CLI yet: ${reason}.`,` ${fix}`," You can keep using your other providers. I'll check again automatically."," /model to retry \xB7 /login status for details"].join(`
|
|
8
10
|
`)}function hcodeLoginAvailability(readiness){if(!readiness)return{state:"pending",text:"checking connection\u2026"};switch(readiness.kind){case"ready":return{state:"ready",text:"connected"};case"unreachable":return{state:"failed",text:`Can't reach ${readiness.host}: check VPN/Zscaler [Retry]`};case"not-configured":return{state:"failed",text:`HUMAIN Code isn't available on ${readiness.environmentId} yet (server: hcode_unavailable). Try another environment or contact support. [Retry]`};case"http-\
|
|
9
11
|
error":return{state:"failed",text:`Sign-in server returned HTTP ${readiness.status}${readiness.message?`: ${readiness.message}`:"."} [Retry]`};case"mismatch":return{state:"failed",text:"Server sign-in settings don't match this CLI version [Details]"};case"unavailable":return{state:"failed",text:"Sign-in is not available in this environment [Retry]"}}}function hcodeSignedInElsewhereNotice(environmentId,elsewhere){let other=elsewhere[0];if(other)return`${hcodeDisplayName(environmentId)}: not signe\
|
|
10
|
-
d in. HUMAIN Code now defaults to production. Your saved sign-in is for ${hcodeDisplayName(other)} and was not moved: start humain-code with --env ${other} to use it, or /login to sign in here.`}import{randomUUID}from"node:crypto";import{unlinkSync,writeFileSync}from"node:fs";import{platform,tmpdir}from"node:os";import{join}from"node:path";import{spawn}from"node:child_process";function runClipboardCommand(command,args,options){return new Promise(
|
|
12
|
+
d in. HUMAIN Code now defaults to production. Your saved sign-in is for ${hcodeDisplayName(other)} and was not moved: start humain-code with --env ${other} to use it, or /login to sign in here.`}import{randomUUID}from"node:crypto";import{unlinkSync,writeFileSync}from"node:fs";import{platform,tmpdir}from"node:os";import{join}from"node:path";import{spawn}from"node:child_process";function runClipboardCommand(command,args,options){return new Promise(resolve4=>{let child=spawn(command,args,{stdio:["pipe",options?.input===void 0?"pipe":"ignore","ignore"],cwd:"/",detached:process.platform!=="win32",windowsHide:!0}),chunks=[],length=0,settled=!1,finish=result=>{settled||(settled=!0,clearTimeout(timer),resolve4(result))},abort=()=>{child.kill("SIGKILL"),child.stdout?.destroy(),child.stdin?.destroy(),finish(void 0)},timer=setTimeout(abort,options?.
|
|
11
13
|
timeoutMs??3e3);child.on("error",()=>finish(void 0)),child.on("close",code=>{settled||finish(code===0?Buffer.concat(chunks,length):void 0)}),child.stdout?.on("data",chunk=>{settled||(length+=chunk.length,length>(options?.maxBufferBytes??50*1024*1024)?abort():chunks.push(chunk))}),child.stdin?.on("error",()=>{}),child.stdin?.end(options?.input)})}var MAX_OSC52_ENCODED_LENGTH=1e5;function isRemoteSession(env){return!!(env.SSH_CONNECTION||env.SSH_CLIENT||env.MOSH_CONNECTION||env.HUMAIN_TERMINAL_CLIPBOARD_OSC52==="1")}function emitOsc52(text){let encoded=Buffer.from(text).toString("base64");return encoded.length>MAX_OSC52_ENCODED_LENGTH?!1:(process.stdout.write(`\x1B]52;c;${encoded}\x07`),!0)}async function copyViaWindowsClipboard(text){let tmpFile=join(tmpdir(),`pi-wsl-clip-${randomUUID()}.txt`);try{writeFileSync(tmpFile,text,{encoding:"ut\
|
|
12
14
|
f8",mode:384});let winPath=(await runClipboardCommand("wslpath",["-w",tmpFile],{timeoutMs:1e3}))?.toString("utf8").trim();if(!winPath)return!1;let script=`Set-Clipboard -Value ([System.IO.File]::ReadAllText('${winPath.replaceAll("'","''")}', [System.Text.Encoding]::UTF8))`;return await runClipboardCommand("powershell.exe",["-NoProfile","-Command",script],{timeoutMs:5e3})!==void 0}catch{return!1}finally{try{unlinkSync(tmpFile)}catch{}}}async function readClipboardText(){let commands=[];process.env.
|
|
13
15
|
TERMUX_VERSION&&commands.push(["termux-clipboard-get",[]]),platform()==="linux"&&(process.env.WAYLAND_DISPLAY&&commands.push(["wl-paste",["--no-newline","--type","text"]]),process.env.DISPLAY&&commands.push(["xclip",["-selection","clipboard","-out"]],["xsel",["--clipboard","--output"]]));for(let[command,args]of commands){let bytes=await runClipboardCommand(command,args,{timeoutMs:5e3});if(bytes!==void 0)return bytes.toString("utf8")||null}try{return await getNativeClipboard()?.getText()||null}catch{
|
|
@@ -41,10 +43,10 @@ length>0?converted:[{type:"text",text:`Resource ${uri} is empty.`}]),contents=re
|
|
|
41
43
|
requestRender()}async copy(){try{await copyToClipboard(this.url),this.setHint(theme.fg("success","Copied URL to clipboard"))}catch(error){this.setHint(theme.fg("error",error instanceof Error?error.message:String(error)))}}};function frame(theme2,title,body,footer){let container=new Container;container.addChild(new DynamicBorder(text=>theme2.fg("accent",text))),container.addChild(new Text(theme2.fg("accent",theme2.bold(sanitizeTerminalText(title))),1,0));for(let child of body)container.addChild(child);return footer&&(container.addChild(new Spacer(1)),container.addChild(new Text(theme2.fg("dim",footer),1,0))),container.addChild(new DynamicBorder(text=>theme2.fg("accent",text))),container}var MAX_VISIBLE_ITEMS=12;function sanitizeMenu(menu){
|
|
42
44
|
let text=value=>value===void 0?void 0:sanitizeTerminalText(value);return{...menu,title:sanitizeTerminalText(menu.title),details:text(menu.details),error:text(menu.error),empty:text(menu.empty),items:menu.items.map(item=>({...item,label:sanitizeTerminalText(item.label),description:text(item.description)}))}}var McpManagerView=class{tui;theme;keybindings;content;inputHandler;inputTarget;_focused=!1;constructor(tui,theme2,keybindings){this.tui=tui,this.theme=theme2,this.keybindings=keybindings,this.
|
|
43
45
|
content=frame(theme2,"MCP servers",[new Text(theme2.fg("muted","Loading\u2026"),1,1)])}get focused(){return this._focused}set focused(value){this._focused=value,this.inputTarget&&(this.inputTarget.focused=value)}get capturesViewportInput(){return this.inputHandler?.capturesViewportInput===!0}setContent(content,inputHandler,inputTarget){this.inputTarget&&(this.inputTarget.focused=!1),this.content=content,this.inputHandler=inputHandler,this.inputTarget=inputTarget,this.inputTarget&&(this.inputTarget.
|
|
44
|
-
focused=this._focused),this.tui.requestRender()}menu(build,subscribe){return new Promise(
|
|
46
|
+
focused=this._focused),this.tui.requestRender()}menu(build,subscribe){return new Promise(resolve4=>{let unsubscribe,settled=!1,finish=value=>{settled||(settled=!0,unsubscribe?.(),resolve4(value))},selected,render=()=>{let menu=sanitizeMenu(build()),wanted=selected??menu.selected,body=[];menu.details&&body.push(new Text(this.theme.fg("muted",menu.details),1,0)),menu.error&&body.push(new Text(this.theme.fg("error",menu.error),1,0)),body.push(new Spacer(1));let footer=`${keyHint("tui.select.confirm",
|
|
45
47
|
menu.confirmLabel)} \u2022 ${keyHint("tui.select.cancel",menu.cancelLabel)}`;if(menu.items.length===0){body.push(new Text(this.theme.fg("muted",menu.empty??"Nothing to show."),1,0)),this.setContent(frame(this.theme,menu.title,body,keyHint("tui.select.cancel",menu.cancelLabel)),{handleInput:data=>{this.keybindings.matches(data,"tui.select.cancel")&&finish(void 0)}});return}let list=new SelectList(menu.items,Math.min(menu.items.length,MAX_VISIBLE_ITEMS),getSelectListTheme()),index=menu.items.findIndex(
|
|
46
48
|
item=>item.value===wanted);index!==-1&&list.setSelectedIndex(index),selected=list.getSelectedItem()?.value,list.onSelectionChange=item=>{selected=item.value},list.onSelect=item=>finish(item.value),list.onCancel=()=>finish(void 0),body.push(list),this.setContent(frame(this.theme,menu.title,body,footer),list)};render(),unsubscribe=subscribe?.(()=>{settled||render()})})}status(title,message,onCancel){let body=[new Spacer(1),new Text(this.theme.fg("muted",sanitizeTerminalText(message)),1,0)];if(!onCancel){
|
|
47
|
-
this.setContent(frame(this.theme,title,body));return}this.setContent(frame(this.theme,title,body,keyHint("tui.select.cancel","cancel")),{handleInput:data=>{this.keybindings.matches(data,"tui.select.cancel")&&onCancel()}})}redirectUrl(title,authorizationUrl,signal){return new Promise(
|
|
49
|
+
this.setContent(frame(this.theme,title,body));return}this.setContent(frame(this.theme,title,body,keyHint("tui.select.cancel","cancel")),{handleInput:data=>{this.keybindings.matches(data,"tui.select.cancel")&&onCancel()}})}redirectUrl(title,authorizationUrl,signal){return new Promise(resolve4=>{let settled=!1,finish=value=>{settled||(settled=!0,signal.removeEventListener("abort",onAbort),resolve4(value))},onAbort=()=>finish(void 0);if(signal.aborted){finish(void 0);return}signal.addEventListener(
|
|
48
50
|
"abort",onAbort,{once:!0});let input=new Input,link=new AuthUrlComponent(this.tui,authorizationUrl),body=[new Spacer(1),new Text(this.theme.fg("muted","Approve access in your browser. If it did not open, visit:"),1,0),link,new Spacer(1),new Text(this.theme.fg("muted","If the browser runs on another machine, paste the URL it was redirected to:"),1,0),input];this.setContent(frame(this.theme,title,body,`${keyHint("tui.select.confirm","submit")} \u2022 ${keyHint("tui.select.cancel","cancel")}`),{handleInput:data=>{
|
|
49
51
|
if(this.keybindings.matches(data,"tui.select.confirm")){let value=input.getValue().trim();value&&finish(value);return}if(this.keybindings.matches(data,"tui.select.cancel")){finish(void 0);return}if(this.keybindings.matches(data,"app.message.copy")){link.copy();return}input.handleInput(data)}},input)})}handleInput(data){this.inputHandler?.handleInput?.(data),this.tui.requestRender()}render(width){return this.content.render(width).map(line=>visibleWidth(line)>width?truncateToWidth(line,width,""):line)}invalidate(){
|
|
50
52
|
this.content.invalidate()}};async function showMcpManager(ctx,manage){await ctx.ui.custom((tui,theme2,keybindings,done)=>{let view=new McpManagerView(tui,theme2,keybindings);return manage(view).then(()=>done(),error=>{ctx.ui.notify(error instanceof Error?error.message:String(error),"error"),done()}),view})}var statusProviders=new WeakMap;function getMcpStatus(sessionManager){return statusProviders.get(sessionManager)?.()}var DEFAULT_STARTUP_WAIT_MS=1e4,RESOURCE_TOOL_NAMES=new Set([LIST_MCP_RESOURCES_TOOL,LIST_MCP_RESOURCE_TEMPLATES_TOOL,READ_MCP_RESOURCE_TOOL]),EXPOSURE_DESCRIPTIONS={codemode:"called from codemode scripts, which find them with searchTools()",deferred:"not declared until tool_search loads them, then called directly; no codemode needed",direct:"declared to the model like built-in to\
|
|
@@ -73,7 +75,7 @@ CODEMODE_TOOL_NAME)||hasToolSearch&&reachable.includes(TOOL_SEARCH_TOOL_NAME)||w
|
|
|
73
75
|
connection.name,url)??null):"null"},onConnectionChange=connection=>{connection.state!=="needs-auth"?tokensAtSignIn.delete(connection):tokensAtSignIn.has(connection)||tokensAtSignIn.set(connection,storedTokens(connection)),emitChange()},reconnectSignedIn=async ctx=>{let signedIn=[...tokensAtSignIn].filter(([connection,tokens])=>storedTokens(connection)!==tokens);if(signedIn.length!==0){for(let[connection]of signedIn)tokensAtSignIn.delete(connection);await Promise.allSettled(signedIn.map(([connection])=>connection.
|
|
74
76
|
reconnect())),ensureDiscoveryActive(ctx)}},createConnection=async(server,isCurrent)=>{let runtime=await loadMcpRuntime();if(!isCurrent())return;let connection=new runtime.McpServerConnection({entry:server.entry,cwd:sessionCwd,createTransport:options.createTransport??runtime.createDefaultTransport,credentials:getCredentials(runtime),providerToken:async provider=>modelRegistry?.getApiKeyForProvider(provider),log:getServerLog(runtime),onTools:connection2=>{isCurrent()&®isterTools(connection2)},onChange:connection2=>{
|
|
75
77
|
isCurrent()?onConnectionChange(connection2):tokensAtSignIn.delete(connection2)}});return server.connection=connection,emitChange(),connection},startConnection=(server,after)=>{let{signal}=session,attempt=Symbol();server.attempt=attempt;let isCurrent=()=>!signal.aborted&&server.attempt===attempt&&isEnabled(server)&&servers.includes(server),ready=(async()=>{if(await after,!isCurrent())return;let connection=await createConnection(server,isCurrent);!connection||!isCurrent()||await connection.getClient().
|
|
76
|
-
catch(()=>{})})();return server.ready=ready.catch(()=>{}),ready},waitForServers=async(waiting,signal)=>{for(;;){let ready=waiting.flatMap(server=>isEnabled(server)&&servers.includes(server)&&server.ready?[{server,ready:server.ready}]:[]);if(ready.length===0||signal?.aborted)return;let onAbort;if(await Promise.race([Promise.all(ready.map(attempt=>attempt.ready)),new Promise(
|
|
78
|
+
catch(()=>{})})();return server.ready=ready.catch(()=>{}),ready},waitForServers=async(waiting,signal)=>{for(;;){let ready=waiting.flatMap(server=>isEnabled(server)&&servers.includes(server)&&server.ready?[{server,ready:server.ready}]:[]);if(ready.length===0||signal?.aborted)return;let onAbort;if(await Promise.race([Promise.all(ready.map(attempt=>attempt.ready)),new Promise(resolve4=>{onAbort=()=>resolve4(),signal?.addEventListener("abort",onAbort,{once:!0})})]),onAbort&&signal?.removeEventListener(
|
|
77
79
|
"abort",onAbort),signal?.aborted||ready.every(attempt=>!isEnabled(attempt.server)||!servers.includes(attempt.server)||attempt.ready===attempt.server.ready))return}},reportProblems=(ctx,only)=>{let lines=only?[]:configErrors.map(error=>`config: ${error}`);for(let server of only??servers){let state=server.connection?.state;(state==="needs-auth"||state==="failed")&&lines.push(`${server.entry.name}: ${describeState(server)}`)}lines.length!==0&&ctx.ui.notify(`MCP servers need attention:
|
|
78
80
|
${lines.map(line=>` ${line}`).join(`
|
|
79
81
|
`)}
|
|
@@ -105,9 +107,9 @@ return preferred[0];let choice=await ctx.ui.select("MCP server",candidates.map(s
|
|
|
105
107
|
in to MCP server "${name}" requires interactive mode.`,"error");return}let{signal}=session,failure;if(ctx.mode==="tui"?await showMcpManager(ctx,async ui=>{failure=await signInWithUi(ui,server)}):failure=await signIn(server,{showAuthorizationUrl:url=>{ctx.ui.notify(`Sign in to MCP server "${name}" in your browser:
|
|
106
108
|
${url.href}`,"info"),openUrl(url.href)},promptForRedirectUrl:signal2=>ctx.ui.input(`Waiting for sign-in to "${name}". If the browser cannot reach this machine, paste the URL it was redirected to.`,"http://127.0.0.1:.../callback?code=...",{signal:signal2})}),!signal.aborted){if(failure){ctx.ui.notify(failure,failure==="Sign-in cancelled."?"info":"error");return}ensureDiscoveryActive(ctx),ctx.ui.notify(`Signed in to MCP server "${name}" (${server.connection?.tools.length??0} tools).`,"info")}};pi.
|
|
107
109
|
on("session_start",(_event,ctx)=>{let loaded=(options.loadConfig??defaultLoadConfig)(ctx);configErrors=loaded.errors,projectConfig=loaded.projectConfig,autoEnableCodemode=loaded.autoEnableCodemode??!0,warnedUnreachable=!1,waitedForStartup=!1,sessionCwd=ctx.cwd,modelRegistry=ctx.modelRegistry,session=new AbortController;let{signal}=session;configuredEntries=loaded.servers;let registered=registeredServers();overridden=registered.overridden,servers=[...loaded.servers.map(entry=>({entry})),...registered.
|
|
108
|
-
servers],statusOwner&&statusProviders.delete(statusOwner),statusOwner=ctx.sessionManager,statusProviders.set(statusOwner,()=>({connected:servers.reduce((count,server)=>count+ +(server.connection?.state==="connected"),0),total:servers.length})),emitChange(),ensureDiscoveryActive(ctx);let enabled=servers.filter(isEnabled);if(enabled.length===0){reportProblems(ctx);return}let runtime=new Promise(
|
|
109
|
-
server,runtime))).then(()=>{signal.aborted||reportProblems(ctx)}).catch(error=>{try{ctx.ui.notify(`MCP failed to load: ${errorMessage2(error)}`,"error")}catch{}})});let waitForDirectServers=async ctx=>{if(waitedForStartup)return;waitedForStartup=!0;let ready=servers.flatMap(server=>isEnabled(server)&&hasDirectTools(server.entry)&&server.ready?[server.ready]:[]);if(ready.length===0)return;let timer,finished=await Promise.race([Promise.all(ready).then(()=>!0),new Promise(
|
|
110
|
-
()=>
|
|
110
|
+
servers],statusOwner&&statusProviders.delete(statusOwner),statusOwner=ctx.sessionManager,statusProviders.set(statusOwner,()=>({connected:servers.reduce((count,server)=>count+ +(server.connection?.state==="connected"),0),total:servers.length})),emitChange(),ensureDiscoveryActive(ctx);let enabled=servers.filter(isEnabled);if(enabled.length===0){reportProblems(ctx);return}let runtime=new Promise(resolve4=>setImmediate(resolve4)).then(()=>loadMcpRuntime());pending=Promise.all(enabled.map(server=>startConnection(
|
|
111
|
+
server,runtime))).then(()=>{signal.aborted||reportProblems(ctx)}).catch(error=>{try{ctx.ui.notify(`MCP failed to load: ${errorMessage2(error)}`,"error")}catch{}})});let waitForDirectServers=async ctx=>{if(waitedForStartup)return;waitedForStartup=!0;let ready=servers.flatMap(server=>isEnabled(server)&&hasDirectTools(server.entry)&&server.ready?[server.ready]:[]);if(ready.length===0)return;let timer,finished=await Promise.race([Promise.all(ready).then(()=>!0),new Promise(resolve4=>{timer=setTimeout(
|
|
112
|
+
()=>resolve4(!1),startupWaitMs)})]);clearTimeout(timer),finished||ctx.ui.notify("MCP servers are still connecting; their tools become available once connected.","info")};pi.on("before_agent_start",async(event,ctx)=>{await waitForDirectServers(ctx);let{sections}=event.systemPromptOptions,section=renderServersSection(servers);section?sections[MCP_SERVERS_SECTION]=section:delete sections[MCP_SERVERS_SECTION]}),pi.on("tool_call",async(event,ctx)=>{let tool=pi.getAllTools().find(candidate=>candidate.
|
|
111
113
|
name===event.toolName);if(!tool)return;let readyServers=servers.filter(server=>isEnabled(server)&&server.ready);if(readyServers.length===0)return;let waiting=[],reach=tool.reachesTools?.(event.input);if(reach!==void 0)waiting=readyServers.filter(server=>reachesServer(reach,server.entry.name));else if(RESOURCE_TOOL_NAMES.has(tool.name))waiting=readyServers;else{let owner=toolOwners.get(event.toolName)?.split("\0",1)[0];waiting=readyServers.filter(server=>server.entry.name===owner)}await waitForServers(
|
|
112
114
|
waiting,ctx.signal)}),pi.on("turn_start",async(_event,ctx)=>{tokensAtSignIn.size>0&&await reconnectSignedIn(ctx)}),pi.on("mcp_servers_change",async(_event,ctx)=>{let{signal}=session;if(signal.aborted)return;let registered=registeredServers();overridden=registered.overridden;let next=new Map(registered.servers.map(server=>[server.entry.name,server])),removed=servers.filter(server=>server.entry.scope==="extension"&&next.get(server.entry.name)?.registeredConfig!==server.registeredConfig);servers=servers.
|
|
113
115
|
filter(server=>!removed.includes(server));for(let server of removed)hideTools(server.entry.name);let added=registered.servers.filter(server=>!findServer(server.entry.name));servers.push(...added),emitChange(),ensureDiscoveryActive(ctx),await Promise.all(removed.map(server=>server.connection?.close()));let connecting=added.filter(isEnabled);if(!(signal.aborted||connecting.length===0)){try{if(await Promise.all(connecting.map(server=>startConnection(server))),signal.aborted){await Promise.all(connecting.
|
|
@@ -116,13 +118,119 @@ rvers: sign in, reconnect, enable or disable, and change exposure",getArgumentCo
|
|
|
116
118
|
filter(candidate=>candidate.entry.name.startsWith(server)).map(candidate=>({value:`${action} ${candidate.entry.name}`,label:candidate.entry.name,description:describeState(candidate)}));return items.length>0?items:null},handler:async(args,ctx)=>{let[action,name,...extra]=args.trim().split(/\s+/).filter(Boolean);if(action===void 0){ctx.mode==="tui"?await showMcpManager(ctx,ui=>manage(ui,ctx)):(await pending,ctx.ui.notify(formatStatus(),"info"));return}if(extra.length>0){ctx.ui.notify(MCP_USAGE,"wa\
|
|
117
119
|
rning");return}switch(await pending,action){case"login":{let server=await pickServer(name,ctx,oauthPick);server&&await loginCommand(server,ctx);return}case"logout":{let server=await pickServer(name,ctx,oauthPick);if(!server)return;let removed=await signOut(server);ctx.ui.notify(removed?`Signed out of MCP server "${server.entry.name}".`:`No stored credentials for MCP server "${server.entry.name}".`,"info");return}case"reconnect":{let server=await pickServer(name,ctx,{eligible:candidate=>candidate.
|
|
118
120
|
connection!==void 0,preferred:candidate=>candidate.connection?.state==="failed"||candidate.connection?.state==="disconnected",none:"No enabled MCP server to reconnect."});if(!server)return;let failure=await reconnect(server);failure?ctx.ui.notify(failure,"error"):(ensureDiscoveryActive(ctx),ctx.ui.notify(`Reconnected to MCP server "${server.entry.name}" (${describeState(server)}).`,"info"));return}default:ctx.ui.notify(MCP_USAGE,"warning")}}})}}function defaultLoadConfig(ctx){return loadMcpConfig(
|
|
119
|
-
{agentDir:getAgentDir(),cwd:ctx.cwd,projectTrusted:ctx.isProjectTrusted()})}var mcp_default=createMcpExtension();var current,listeners=new Set;function notify(){for(let listener of listeners)try{listener()}catch{}}function trackUserWait(reason,promise){let wait={reason};return current=wait,notify(),promise.finally(()=>{current===wait&&(current=void 0,notify())})}function currentUserWait(){return current?.reason}function onUserWaitChange(listener){return listeners.add(listener),()=>{listeners.delete(listener)}}
|
|
121
|
+
{agentDir:getAgentDir(),cwd:ctx.cwd,projectTrusted:ctx.isProjectTrusted()})}var mcp_default=createMcpExtension();var current,listeners=new Set;function notify(){for(let listener of listeners)try{listener()}catch{}}function trackUserWait(reason,promise){let wait={reason};return current=wait,notify(),promise.finally(()=>{current===wait&&(current=void 0,notify())})}function currentUserWait(){return current?.reason}function onUserWaitChange(listener){return listeners.add(listener),()=>{listeners.delete(listener)}}import{dirname as dirname2}from"node:path";import{createHash as createHash2,randomBytes}from"node:crypto";import{closeSync,constants,fchmodSync,fstatSync,fsyncSync,lstatSync,openSync,readSync,realpathSync,unlinkSync as unlinkSync2,writeSync}from"node:fs";import{basename,dirname,isAbsolute,join as join3,relative,resolve as resolve2,sep}from"node:path";var COPY_CHUNK_BYTES=64*1024,MAX_RELATIVE_PATH_CHARS=4096,READ_FLAGS=constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK,CREATE_FLAGS=constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,FETCHED_FILE_MODE=420;function errnoCode(error){return typeof error=="object"&&error!==null&&"code"in error&&typeof error.code=="string"?error.code:"error"}function isInside(root,path){return path===root||path.startsWith(root.endsWith(sep)?root:`${root}${sep}`)}function lstatOrUndefined(path){
|
|
122
|
+
try{return lstatSync(path)}catch(error){let code=errnoCode(error);if(code==="ENOENT"||code==="ENOTDIR")return;throw error}}function sameFile(a,b){return a.dev===b.dev&&a.ino===b.ino}function unlinkIfSame(path,identity){try{let current2=lstatOrUndefined(path);current2&&sameFile(current2,identity)&&unlinkSync2(path)}catch{}}function isGitName(segment){return segment.toLowerCase()===".git"}function closeQuietly(fd){try{closeSync(fd)}catch{}}function splitRelative(relativePath,label){if(typeof relativePath!=
|
|
123
|
+
"string"||relativePath.length===0)throw new Error(`${label} is required`);if(relativePath.length>MAX_RELATIVE_PATH_CHARS||relativePath.includes("\0"))throw new Error(`${label} is not a valid path`);if(isAbsolute(relativePath))throw new Error(`${label} must be relative to the working directory, not absolute`);let segments=relativePath.split("/").filter(segment=>segment!==""&&segment!==".");if(segments.includes(".."))throw new Error(`${label} must not contain ".." segments`);if(segments.some(isGitName))
|
|
124
|
+
throw new Error(`${label} must not go through a ".git" directory`);if(segments.length===0)throw new Error(`${label} does not name a file`);return segments}function isInsideDirectory(directory,path){let real;try{real=realpathSync(directory)}catch{real=resolve2(directory)}return isInside(real,path)}function assertAllowedLocation(path,worktreeRoot,agentDir,sessionDir,label){let root=realpathSync(worktreeRoot);if(!isInside(root,path))throw new Error(`${label} is outside the worktree`);if(relative(root,
|
|
125
|
+
path).split(sep).some(isGitName))throw new Error(`${label} must not go through a ".git" directory`);if(isInsideDirectory(agentDir,path))throw new Error(`${label} is inside the HUMAIN agent directory, which holds credentials and session transcripts`);if(sessionDir&&isInsideDirectory(sessionDir,path))throw new Error(`${label} is inside the HUMAIN session directory, which holds session transcripts`)}function realpathOrUndefined(path){try{return realpathSync(path)}catch{return}}function locateWorkingDirectory(cwd,worktreeRoot){
|
|
126
|
+
let root=realpathSync(worktreeRoot),below=[];for(let base=resolve2(cwd);realpathOrUndefined(base)!==root;base=dirname(base)){if(dirname(base)===base)throw new Error("the working directory is outside the worktree");below.unshift(basename(base))}let current2=root;for(let name of below){if(isGitName(name))throw new Error('the working directory is inside a ".git" directory');current2=join3(current2,name);let stats=lstatOrUndefined(current2);if(!stats)throw new Error("the working directory does not e\
|
|
127
|
+
xist");if(stats.isSymbolicLink())throw new Error("the working directory goes through a symbolic link");if(!stats.isDirectory())throw new Error("the working directory goes through something that is not a directory")}return current2}function resolveRelativeInside(cwd,worktreeRoot,relativePath,agentDir,sessionDir){let segments=splitRelative(relativePath,"path"),current2=locateWorkingDirectory(cwd,worktreeRoot),stats;for(let segment of segments){if(current2=join3(current2,segment),stats=lstatOrUndefined(
|
|
128
|
+
current2),!stats)throw new Error(`${relativePath} does not exist`);if(stats.isSymbolicLink())throw new Error(`${relativePath} goes through a symbolic link; symbolic links are not published`)}if(!stats?.isFile())throw new Error(`${relativePath} is not a regular file`);return assertAllowedLocation(current2,worktreeRoot,agentDir,sessionDir,relativePath),current2}function resolveNewFileInside(cwd,worktreeRoot,relativePath,agentDir,sessionDir){let segments=splitRelative(relativePath,"destination"),current2=locateWorkingDirectory(
|
|
129
|
+
cwd,worktreeRoot);for(let segment of segments.slice(0,-1)){current2=join3(current2,segment);let stats=lstatOrUndefined(current2);if(!stats)throw new Error(`the directory for ${relativePath} does not exist`);if(stats.isSymbolicLink())throw new Error(`${relativePath} goes through a symbolic link`);if(!stats.isDirectory())throw new Error(`${relativePath} goes through something that is not a directory`)}let target=join3(current2,segments[segments.length-1]);if(lstatOrUndefined(target))throw new Error(
|
|
130
|
+
`${relativePath} already exists; choose a new destination`);return assertAllowedLocation(target,worktreeRoot,agentDir,sessionDir,relativePath),target}function copyAndHash(from,to,maxBytes){let hash=createHash2("sha256"),buffer=Buffer.allocUnsafe(COPY_CHUNK_BYTES),size=0;for(;;){let read=readSync(from,buffer,0,buffer.length,null);if(read===0)break;if(size+=read,size>maxBytes)throw new Error(`the file is larger than its expected ${maxBytes} bytes`);hash.update(buffer.subarray(0,read));let written=0;
|
|
131
|
+
for(;written<read;)written+=writeSync(to,buffer,written,read-written)}return{sha256:hash.digest("hex"),size}}function stageArtifactFile(input){let{relativePath}=input,source=resolveRelativeInside(input.cwd,input.worktreeRoot,relativePath,input.agentDir,input.sessionDir),sourceFd;try{sourceFd=openSync(source,READ_FLAGS)}catch(error){throw new Error(`${relativePath} cannot be opened (${errnoCode(error)})`)}let stagedFd,stagedPath,stagedIdentity;try{let opened=fstatSync(sourceFd);if(!opened.isFile())
|
|
132
|
+
throw new Error(`${relativePath} is not a regular file`);let real=realpathOrUndefined(source);if(real===void 0)throw new Error(`${relativePath} changed while it was being checked`);assertAllowedLocation(real,input.worktreeRoot,input.agentDir,input.sessionDir,relativePath);let checked=lstatSync(real);if(real!==source||!sameFile(checked,opened))throw new Error(`${relativePath} changed while it was being checked`);if(opened.size>MAX_ARTIFACT_BYTES)throw new Error(`${relativePath} is ${opened.size} \
|
|
133
|
+
bytes; the limit is ${MAX_ARTIFACT_BYTES} bytes (16 MiB)`);let stagedFile=`${randomBytes(16).toString("hex")}.part`,path=join3(input.incomingDir,stagedFile);try{stagedFd=openSync(path,CREATE_FLAGS,COORDINATION_FILE_MODE)}catch(error){throw new Error(`cannot create a staging file (${errnoCode(error)})`)}stagedPath=path,stagedIdentity=fstatSync(stagedFd),fchmodSync(stagedFd,COORDINATION_FILE_MODE);let copied=copyAndHash(sourceFd,stagedFd,MAX_ARTIFACT_BYTES);if(fsyncSync(stagedFd),realpathSync(source)!==
|
|
134
|
+
source)throw new Error(`${relativePath} changed while it was being copied`);closeSync(stagedFd),stagedFd=void 0,stagedPath=void 0;let identity=stagedIdentity;return stagedIdentity=void 0,{stagedFile,stagedIdentity:identity,sha256:copied.sha256,size:copied.size}}finally{closeQuietly(sourceFd),stagedFd!==void 0&&closeQuietly(stagedFd),stagedPath!==void 0&&stagedIdentity!==void 0&&unlinkIfSame(stagedPath,stagedIdentity)}}function installFetchedArtifact(input){let{artifact}=input;if(!isSha256Hex(artifact.
|
|
135
|
+
sha256))throw new Error("the broker returned an invalid artifact digest");if(input.blobPath!==input.expectedBlobPath)throw new Error("the broker returned an unexpected blob path; refusing to read it");let target=resolveNewFileInside(input.cwd,input.worktreeRoot,input.destination,input.agentDir,input.sessionDir),sourceFd;try{sourceFd=openSync(input.blobPath,READ_FLAGS)}catch(error){throw new Error(`artifact ${artifact.name} cannot be read (${errnoCode(error)})`)}let targetFd,targetIdentity,installed=!1;
|
|
136
|
+
try{let stats=fstatSync(sourceFd);if(!stats.isFile()||stats.size!==artifact.size)throw new Error(`stored artifact ${artifact.name} is damaged`);try{targetFd=openSync(target,CREATE_FLAGS,FETCHED_FILE_MODE)}catch(error){throw new Error(`cannot create ${input.destination} (${errnoCode(error)})`)}let created=fstatSync(targetFd);targetIdentity=created;let real=realpathOrUndefined(target);if(real===void 0)throw new Error(`${input.destination} changed while it was being created`);if(assertAllowedLocation(
|
|
137
|
+
real,input.worktreeRoot,input.agentDir,input.sessionDir,input.destination),real!==target||!sameFile(lstatSync(real),created))throw new Error(`${input.destination} changed while it was being created`);let copied=copyAndHash(sourceFd,targetFd,artifact.size);if(copied.size!==artifact.size||copied.sha256!==artifact.sha256)throw new Error(`stored artifact ${artifact.name} does not match its hash; nothing was kept`);if(fsyncSync(targetFd),realpathSync(target)!==target)throw new Error(`${input.destination}\
|
|
138
|
+
changed while it was being written`);return installed=!0,target}finally{closeQuietly(sourceFd),targetFd!==void 0&&(closeQuietly(targetFd),!installed&&targetIdentity!==void 0&&unlinkIfSame(target,targetIdentity))}}function createArtifactBackend(deps){let ready=()=>{let client=deps.client(),location=deps.location();if(!client||!location)throw new Error("coordination is not connected");return{client,location}};return{async artifactPublish(input){let{client,location}=ready(),incomingDir=join3(location.
|
|
139
|
+
artifactsDir,"incoming"),staged=stageArtifactFile({cwd:location.cwd,worktreeRoot:location.worktreeRoot,relativePath:input.path,incomingDir,agentDir:deps.agentDir(),sessionDir:deps.sessionDir()});try{return await client.artifactPublish({name:input.name,stagedFile:staged.stagedFile,sha256:staged.sha256,size:staged.size,...input.recordKey!==void 0?{recordKey:input.recordKey}:{}})}finally{unlinkIfSame(join3(incomingDir,staged.stagedFile),staged.stagedIdentity)}},async artifactFetch(input){let{client,
|
|
140
|
+
location}=ready(),{artifact,blobPath}=await client.artifactFetch(input.name),destination=installFetchedArtifact({cwd:location.cwd,worktreeRoot:location.worktreeRoot,destination:input.destination,artifact,blobPath,expectedBlobPath:join3(location.artifactsDir,"blobs",artifact.sha256),agentDir:deps.agentDir(),sessionDir:deps.sessionDir()});return{artifact,destination}},async artifactList(){return ready().client.artifactList()}}}var INTEGRATION_USAGE=[" /coordinate owner show the integration owner, lease and queue"," /coordinate owner assign <session> assign the integration owner (no owner, or after a lease loss)"," /coordinate owner transfer <session> move the lease to another live session"," /coordinate owner release drop the integration owner"," /coordinate owner reconcile [<attempt> integrated|not-integrated|manual <explanation>]"," \
|
|
141
|
+
inspect, then record, an attempt that has no outcome or stopped on a conflict"," /coordinate writer assign <session> make a session the single writer of its worktree"," /coordinate writer release <session> release that assignment"],RESOLUTIONS=["integrated","not-integrated","manual"],usageError=line=>({kind:"error",message:`Usage: /coordinate ${line}`});function parseIntegrationArgs(tokens){let[area,action,value,extra,...rest]=tokens;if(area==="o\
|
|
142
|
+
wner"){if(action===void 0)return{kind:"owner-status"};if(action==="release")return value===void 0?{kind:"owner-release"}:usageError("owner release");if(action==="assign"||action==="transfer")return value===void 0||value.length>MAX_SESSION_FIELD_CHARS.id||extra!==void 0?usageError(`owner ${action} <session>`):{kind:action==="assign"?"owner-assign":"owner-transfer",session:value};if(action==="reconcile"){let usage="owner reconcile [<attempt> integrated|not-integrated|manual <explanation>]";if(value===
|
|
143
|
+
void 0&&extra===void 0)return{kind:"owner-reconcile"};if(value===void 0||extra===void 0||!RESOLUTIONS.includes(extra))return usageError(usage);let explanation=rest.join(" ");return explanation.length===0||explanation.length>MAX_EVIDENCE_CHARS?usageError(usage):{kind:"owner-reconcile",attemptId:value,resolution:extra,explanation}}return usageError("owner [assign|transfer <session> | release | reconcile ...]")}if(area==="writer")return(action==="assign"||action==="release")&&value!==void 0&&value.
|
|
144
|
+
length<=MAX_SESSION_FIELD_CHARS.id&&extra===void 0?{kind:action==="assign"?"writer-assign":"writer-release",session:value}:usageError("writer assign|release <session>")}function isIntegrationInvocation(parsed){return/^(owner|writer)-/.test(parsed.kind)}async function resolveSessionId(client,token){let sessions=await client.listSessions({scope:"repo"}),byId=sessions.find(session=>session.id===token);if(byId)return byId.id;let byName=sessions.filter(session=>session.name===token);if(byName.length===
|
|
145
|
+
1&&byName[0])return byName[0].id;let label=cleanMeta(token,MAX_NAME_CHARS);throw new Error(byName.length>1?`More than one session is named ${label}; use its id.`:`No live session has the id or name ${label}.`)}function describeIntegration(status,sessions=[]){let label=id=>peerLabel(sessions.find(peer=>peer.id===id)??{id},sessions),lines=[];status.stateInvalid&&lines.push("Integration is disabled: the stored integration state is invalid and nothing will be changed. Stop every session of this repo\
|
|
146
|
+
sitory, then repair or move the integration state file (docs/coordination.md, Invalid integration state)."),status.owner?(lines.push(`Integration owner: ${label(status.owner.sessionId)} (lease ${status.owner.lease}, generation ${status.generation}, assigned by ${label(status.owner.assignedBy)})`),status.owner.lease==="lost"&&lines.push("Coordinated Git steps are blocked until you run /coordinate owner assign <session>.")):lines.push(`Integration owner: none assigned (generation ${status.generation}\
|
|
147
|
+
)`),lines.push(`Queued handoffs: ${status.queuedHandoffs}`);for(let writer of status.writers)lines.push(`Writer: ${label(writer.sessionId)} for ${cleanMeta(writer.worktreeRoot,MAX_WORKTREE_CHARS)}`);lines.push(status.sharedWith.length>0?`This worktree is shared with: ${status.sharedWith.map(label).join(", ")}`:"This worktree is not shared."),status.openAttempt&&lines.push(`Attempt without an outcome: ${status.openAttempt.id} (handoff ${status.openAttempt.handoffId}, generation ${status.openAttempt.
|
|
148
|
+
generation}). Inspect it with /coordinate owner reconcile.`);for(let conflict of status.conflictAttempts)lines.push(`Conflict not resolved: attempt ${conflict.id} (handoff ${conflict.handoffId}, generation ${conflict.generation}). It blocks new attempts on target ${cleanMeta(conflict.target,80)}. Resolve or abort the merge yourself, then let the owner report it, or record it with /coordinate owner reconcile.`);return lines.join(`
|
|
149
|
+
`)}async function reconcile(invocation,client,deps,notify2){let status=await client.integrationStatus();if(status.stateInvalid){notify2("Integration is disabled: the stored integration state is invalid. A human has to repair or move the integration state; do not retry (docs/coordination.md, Invalid integration state).","error");return}let unresolved=[...status.openAttempt?[status.openAttempt]:[],...status.conflictAttempts];if(unresolved.length===0){notify2("No integration attempt is waiting for \
|
|
150
|
+
reconciliation.","info");return}if(!deps.inspectAttempt){notify2("This session cannot inspect the repository, so it cannot reconcile.","error");return}let attempt=invocation.attemptId===void 0?unresolved[0]:unresolved.find(candidate=>candidate.id===invocation.attemptId);if(!attempt)throw new Error(`The attempts waiting for reconciliation are ${unresolved.map(item=>item.id).join(", ")}, not ${cleanMeta(invocation.attemptId??"",32)}.`);let{handoff}=await client.handoffGet(attempt.handoffId),inspection=await deps.
|
|
151
|
+
inspectAttempt(attempt,{base:handoff.base,commits:handoff.commits}),report=[`Attempt ${attempt.id} for handoff ${handoff.id} (generation ${attempt.generation}, owner ${cleanMeta(attempt.ownerSessionId,MAX_ID_CHARS)}) ${attempt.status==="conflict"?"stopped on a conflict":"has no recorded outcome"}.`,...inspection.lines.map(line=>cleanMeta(line,300)),`Real state: ${inspection.classification}.`];if(unresolved.length>1){let others=unresolved.filter(item=>item.id!==attempt.id).map(item=>item.id);report.
|
|
152
|
+
push(`Other unresolved attempts: ${others.join(", ")}.`)}if(invocation.resolution===void 0||invocation.explanation===void 0){report.push(`Record your decision with: /coordinate owner reconcile ${attempt.id} integrated|not-integrated|manual <what you did and saw>`,"integrated and not-integrated are accepted only when Git shows exactly that (not-integrated needs this session to have observed the checkout's HEAD before the attempt; a clean checkout it did not observe shows as unexpected). manual re\
|
|
153
|
+
cords that you handled it by hand; it is the only choice when the real state is unavailable or unexpected. Your explanation is stored with the record."),notify2(report.join(`
|
|
154
|
+
`),"info");return}let expected={integrated:"integrated","not-integrated":"aborted"};if(invocation.resolution!=="manual"&&inspection.classification!==expected[invocation.resolution]){notify2(`${report.join(`
|
|
155
|
+
`)}
|
|
156
|
+
Git does not show "${invocation.resolution}" (real state: ${inspection.classification}); nothing was recorded. Use manual if you handled it by hand.`,"error");return}let result=await client.ownerReconcile({attemptId:attempt.id,resolution:invocation.resolution,inspected:inspection.classification,...invocation.resolution==="integrated"&&inspection.head?{headAfter:inspection.head}:{},evidence:invocation.explanation});notify2(`Recorded ${invocation.resolution} for attempt ${attempt.id}; handoff ${handoff.
|
|
157
|
+
id} is now ${result.handoff?.status??"unknown"}. You can assign an integration owner again with /coordinate owner assign <session>.
|
|
158
|
+
${report.join(`
|
|
159
|
+
`)}`,"info")}async function runIntegrationCommand(invocation,client,deps,notify2){let describe=async status=>describeIntegration(status,await client.listSessions().catch(()=>[]));switch(invocation.kind){case"owner-status":notify2(await describe(await client.integrationStatus()),"info");return;case"owner-assign":{let status=await client.ownerAssign(await resolveSessionId(client,invocation.session));notify2(`Integration owner assigned.
|
|
160
|
+
${await describe(status)}`,"info");return}case"owner-transfer":{let status=await client.ownerTransfer(await resolveSessionId(client,invocation.session));notify2(`Integration lease transferred.
|
|
161
|
+
${await describe(status)}`,"info");return}case"owner-release":{notify2(`Integration owner released.
|
|
162
|
+
${await describe(await client.ownerRelease())}`,"info");return}case"owner-reconcile":await reconcile(invocation,client,deps,notify2);return;case"writer-assign":{let status=await client.writerAssign(await resolveSessionId(client,invocation.session));notify2(`Writer assigned.
|
|
163
|
+
${await describe(status)}`,"info");return}case"writer-release":{let status=await client.writerRelease(await resolveSessionId(client,invocation.session));notify2(`Writer released.
|
|
164
|
+
${await describe(status)}`,"info");return}}}var MAX_MESSAGE_CHARS=256,USAGE=["Usage:"," /coordinate policy show the ownership policy"," /coordinate policy accept drop this session's conflicting ownership request"," /coordinate policy propose on|off propose a repository ownership policy"," /coordinate policy agree agree to the pending proposal"," /coordinate policy reset on|off set the policy now (human override)"," /coordinate reclaim <key> take over a record whose owner is gone",
|
|
165
|
+
...INTEGRATION_USAGE].join(`
|
|
166
|
+
`);function usageError2(line){return{kind:"error",message:`Usage: /coordinate ${line}`}}function parseCoordinateArgs(args){let tokens=args.split(/\s+/).filter(token=>token.length>0),[area,action,value,...rest]=tokens;if(area===void 0)return{kind:"usage"};let integration=parseIntegrationArgs(tokens);return integration||(area==="policy"?action===void 0?{kind:"policy-status"}:action==="accept"?value===void 0?{kind:"policy-accept"}:usageError2("policy accept"):action==="agree"?value===void 0?{kind:"\
|
|
167
|
+
policy-agree"}:usageError2("policy agree"):action==="propose"||action==="reset"?!isOwnershipMode(value)||rest.length>0?usageError2(`policy ${action} on|off`):{kind:action==="propose"?"policy-propose":"policy-reset",mode:value}:{kind:"error",message:`Unknown policy subcommand "${cleanMeta(action,32)}".
|
|
168
|
+
${USAGE}`}:area==="reclaim"?!isRecordKey(action)||value!==void 0?usageError2("reclaim <key>"):{kind:"reclaim",key:action}:{kind:"error",message:`Unknown subcommand "${cleanMeta(area,32)}".
|
|
169
|
+
${USAGE}`})}function ids(values){return values.map(id=>cleanMeta(id,MAX_ID_CHARS)).join(", ")}function describePolicy(status){let lines=[];if(status.policy?lines.push(`Ownership policy: ${status.policy.mode} (set by ${cleanMeta(status.policy.setBy,MAX_ID_CHARS)} via ${status.policy.via})`):lines.push("Ownership policy: not stored yet (the broker could not persist one)"),status.policyAccepted)lines.push("This session: accepted");else{let requested=status.requestedOwnership?` (requested ${status.requestedOwnership}\
|
|
170
|
+
)`:"";lines.push(`This session: not accepted${requested}; record and artifact writes are blocked`)}if(status.proposal){let waiting=status.awaiting.length>0?`; waiting for ${ids(status.awaiting)}`:"";lines.push(`Proposal: ${status.proposal.mode} by ${cleanMeta(status.proposal.proposedBy,MAX_ID_CHARS)}, ${status.proposal.agreedBy.length} of ${status.liveParticipantCount} live sessions agreed${waiting}`)}return!status.policyAccepted&&status.policy&&lines.push("Run /coordinate policy accept to adopt\
|
|
171
|
+
the current policy, or /coordinate policy propose on|off."),lines.join(`
|
|
172
|
+
`)}function formatPolicyNotice(notice){return[`Coordination: this session asked for ownership "${notice.requested}" but the repository policy is "${notice.current}". Record and artifact writes are blocked for this session.`,notice.proposalPending?`A proposal for "${notice.requested}" is pending: run /coordinate policy agree to agree to it,`:`Run /coordinate policy propose ${notice.requested} to ask the other sessions to switch,`,`or /coordinate policy accept to adopt "${notice.current}".`].join(
|
|
173
|
+
" ")}function describeFailure(error){if(error instanceof CoordinationRequestError){let revision=error.currentRevision===void 0?"":` (current revision ${error.currentRevision??"none"})`;return`Error [${cleanMeta(error.code,32)}]: ${cleanMeta(error.message,MAX_MESSAGE_CHARS)}${revision}`}return`Error: ${cleanMeta(error instanceof Error?error.message:String(error),MAX_MESSAGE_CHARS)}`}function createCoordinateCommand(deps){return{description:"Coordination authority (human only): policy [accept|agre\
|
|
174
|
+
e|propose on|off|reset on|off], reclaim <key>, owner [assign|transfer|release|reconcile], writer assign|release",handler:async(args,ctx)=>{let parsed=parseCoordinateArgs(args);if(parsed.kind==="error"){ctx.ui.notify(parsed.message,"error");return}if(parsed.kind==="usage"){ctx.ui.notify(USAGE,"info");return}if(ctx.mode!=="tui"&&parsed.kind!=="policy-status"&&parsed.kind!=="owner-status"){let refusal=`/coordinate ${args.trim().split(/\s+/).slice(0,2).map(t=>cleanMeta(t,32)).join(" ")} requires int\
|
|
175
|
+
eractive mode; no change made.`;process.stderr.write(`${refusal}
|
|
176
|
+
`),ctx.hasUI&&ctx.ui.notify(refusal,"error");return}let client=deps.client();if(!client){ctx.ui.notify("Coordination is not connected.","warning");return}try{if(isIntegrationInvocation(parsed)){await runIntegrationCommand(parsed,client,deps,(message,type)=>ctx.ui.notify(message,type));return}switch(parsed.kind){case"policy-status":{let status=client.getPolicyStatus();ctx.ui.notify(status?describePolicy(status):"The broker has not reported a policy yet.","info");return}case"policy-accept":{let status=await client.
|
|
177
|
+
policyAccept();deps.onPolicyAccepted(),ctx.ui.notify(`Accepted the current ownership policy.
|
|
178
|
+
${describePolicy(status)}`,"info");return}case"policy-propose":{let status=await client.policyPropose(parsed.mode),applied=status.proposal===null&&status.policy?.mode===parsed.mode;ctx.ui.notify(applied?`Ownership policy is now "${parsed.mode}".
|
|
179
|
+
${describePolicy(status)}`:`Proposed ownership "${parsed.mode}". Other live sessions must run /coordinate policy agree.
|
|
180
|
+
${describePolicy(status)}`,"info");return}case"policy-agree":{let status=await client.policyAgree();ctx.ui.notify(`Agreed to the pending proposal.
|
|
181
|
+
${describePolicy(status)}`,"info");return}case"policy-reset":{let status=await client.policyReset(parsed.mode);ctx.ui.notify(`Ownership policy set to "${parsed.mode}" (human reset).
|
|
182
|
+
${describePolicy(status)}`,"info");return}case"reclaim":{let{record}=await client.recordGet(parsed.key),reclaimed=await client.recordReclaim(parsed.key,record.revision);ctx.ui.notify(`Reclaimed ${cleanMeta(reclaimed.key,128)}: owner is now ${cleanMeta(reclaimed.owner,MAX_ID_CHARS)} (revision ${reclaimed.revision}).`,"info");return}}}catch(error){ctx.ui.notify(describeFailure(error),"error")}}}}var INITIAL_INTEGRATION_NOTICES={shared:"",owner:!1,ownerAssigned:!1,leaseLost:!1,attempt:"",conflicts:"",invalid:!1};function integrationNotices(previous,status,sessionId,suggestWorktree=!1,sessions=[]){let notices=[],label=id=>peerLabel(sessions.find(peer=>peer.id===id)??{id},sessions);status.stateInvalid&&!previous.invalid&¬ices.push({message:"Coordination: the stored integration state is invalid, so integration is disabled and nothing was changed. A human has to repair or move it; see doc\
|
|
183
|
+
s/coordination.md (Invalid integration state).",level:"warning"});let shared=[...status.sharedWith].sort().join(",");if(shared!==""&&previous.shared===""&&!status.callerIsWriter){let n=status.sharedWith.length,hint=suggestWorktree?" The writer gate does not protect edits or Git commands run through bash. Prefer a separate checkout: replace the placeholders in git worktree add ../<repo>-<name>, then restart this session in that worktree.":"";notices.push({message:`Coordination: this worktree is s\
|
|
184
|
+
hared with ${n} other session${n===1?"":"s"}. Coordinated Git actions (handoff_publish, integrate) are refused until a human assigns a single writer: /coordinate writer assign <session>. /coordinate owner lists the sessions.${hint}`,level:"warning"})}let ownerAssigned=status.owner!==null;!ownerAssigned&&previous.ownerAssigned&&status.queuedHandoffs>0&¬ices.push({message:`Coordination: there is no integration owner and ${status.queuedHandoffs} handoffs are queued. A human can assign an owner w\
|
|
185
|
+
ith /coordinate owner assign <session>.`,level:"warning"}),status.callerIsOwner&&!previous.owner&¬ices.push({message:`Coordination: this session is now the integration owner: ${label(status.owner?.sessionId??sessionId??"")} (generation ${status.generation}); ${status.queuedHandoffs} handoffs are queued. Integration still needs your approval of each Git command.`,level:"info"});let leaseLost=status.owner?.lease==="lost"&&status.owner.sessionId===sessionId;leaseLost&&!previous.leaseLost&¬ices.
|
|
186
|
+
push({message:`Coordination: this session ${label(status.owner?.sessionId??sessionId??"")} lost the integration lease. Coordinated Git steps are blocked until a human runs /coordinate owner assign <session>.`,level:"warning"});let attempt=status.openAttempt!==null&&status.owner?.lease!=="held"?status.openAttempt.id:"";attempt!==""&&attempt!==previous.attempt&¬ices.push({message:`Coordination: integration attempt ${attempt} has no recorded outcome. Inspect it with /coordinate owner reconcile b\
|
|
187
|
+
efore assigning an owner again.`,level:"warning"});let conflicts=status.conflictAttempts.map(item=>item.id).sort().join(",");return conflicts!==""&&conflicts!==previous.conflicts&¬ices.push({message:`Coordination: integration attempt ${conflicts.replaceAll(",",", ")} stopped on a conflict that is not resolved; it blocks new attempts on its target. Resolve or abort the merge yourself; /coordinate owner reconcile shows the real state.`,level:"warning"}),{notices,next:{shared:status.callerIsWriter?
|
|
188
|
+
"":shared,owner:status.callerIsOwner,ownerAssigned,leaseLost,attempt,conflicts,invalid:status.stateInvalid}}}var SESSION_ID_ENV=`${ENV_PREFIX}_SESSION_ID`;function isChildSession(env){return currentSubagentDepth(env)>0||!!env[TASK_ID_ENV]||!!env[SESSION_ID_ENV]}function decideParticipation(input){return input.noCoordinate?{participate:!1,reason:"disabled by --no-coordinate",notify:!1}:input.settingEnabled?input.agentExec?{participate:!1,reason:"agent-exec sessions are represented by their host",notify:!1}:isChildSession(input.env)?{participate:!1,reason:"child session of another HUMAIN session",notify:!1}:
|
|
189
|
+
input.platform==="win32"?{participate:!1,reason:"Session coordination is not supported on Windows yet.",notify:!0}:{participate:!0}:{participate:!1,reason:"disabled by coordination.enabled",notify:!1}}import{realpathSync as realpathSync2}from"node:fs";import{basename as basename2,isAbsolute as isAbsolute2,relative as relative2,sep as sep2}from"node:path";function repositoryLabel(remote,worktreeRoot){let path;if(remote){path=remote.replace(/^[a-z][a-z\d+.-]*:\/\//i,"").replace(/^.*@/,"").replace(/^[^/]+:/,"");try{let url=new URL(remote);(url.host!==""||url.protocol==="file:")&&(path=url.pathname)}catch{}}return truncateChars(cleanMeta(path?.replace(/^\/+|\/+$/g,"").replace(/\.git$/,"")||basename2(worktreeRoot),256),256)}async function readRepositoryLabel(worktreeRoot,env){let remote;try{remote=(await runGit(["config","--get","remote.origin.url"],
|
|
190
|
+
{cwd:worktreeRoot,env})).trim()}catch{}return repositoryLabel(remote,worktreeRoot)}function worktreeRelativePath(path,worktreeRoot){try{let local=relative2(realpathSync2(worktreeRoot),realpathSync2(path));return isAbsolute2(local)||local===".."||local.startsWith(`..${sep2}`)||local.length>4096?void 0:local.split(sep2).join("/")}catch{return}}var SessionPresence=class{prompt="";explicitFocus;touched=[];references=[];focusAt=Date.now();refreshNeeded=!1;setPrompt(prompt){let firstLine2=truncateChars(
|
|
191
|
+
cleanMeta(prompt.split(/[\r\n\u2028\u2029]/)[0]??"",256),256);this.prompt&&firstLine2!==this.prompt&&(this.refreshNeeded=!0),this.references=[...new Set([...prompt.match(/[!#]\d+\b/g)??[],...this.references])].slice(0,16),this.prompt=firstLine2}setFocus(focus){this.explicitFocus=focus===""?void 0:truncateChars(cleanMeta(focus,256),256),this.focusAt=Date.now(),this.refreshNeeded=!1}focus(name){let focus=this.explicitFocus??(name?truncateChars(cleanMeta(name,256),256):this.prompt),refs=this.references.
|
|
192
|
+
filter(ref=>!tokenMatch(focus,ref)).join(" ");return truncateChars(refs?`${focus.slice(0,Math.max(0,255-refs.length))} ${refs}`:focus,256)}noteCommand(command){/\bgit\s+(?:[^;&|]*\s)?(?:commit|push)\b/.test(command)&&(this.refreshNeeded=!0)}focusNudge(){if(!(!this.refreshNeeded&&Date.now()-this.focusAt<15*6e4))return this.refreshNeeded=!1,this.focusAt=Date.now(),"Coordination: refresh presence_set focus after a commit, push or phase change, or when focus is older than 15 minutes."}get touchedPaths(){
|
|
193
|
+
return this.touched.map(entry=>({...entry}))}track(path,cwd,worktreeRoot,timestamp=Date.now()){let normalized=worktreeRelativePath(resolveToCwd(path,cwd),worktreeRoot);normalized&&(this.touched=[{path:normalized,timestamp},...this.touched.filter(entry=>entry.path!==normalized)].slice(0,20))}};var TRACKING_FULL_DETAIL="recipient tracking full",DEFAULT_MAX_OUTSTANDING=1e3,DEFAULT_MAX_TERMINAL=1e3,DEFAULT_MAX_QUEUED=1e3;function addBounded(set,value,max){if(set.add(value),set.size>max){let oldest=set.values().next().value;oldest!==void 0&&set.delete(oldest)}}var ReceiptTracker=class{sendReceipt;maxOutstanding;maxTerminal;maxQueued;now;outstanding=new Map;terminal=new Map;emitted=new Set;terminalQueue=new Map;noteQueue=new Map;constructor(options){this.sendReceipt=options.send,this.maxOutstanding=
|
|
194
|
+
options.maxOutstanding??DEFAULT_MAX_OUTSTANDING,this.maxTerminal=options.maxTerminal??DEFAULT_MAX_TERMINAL,this.maxQueued=options.maxQueued??DEFAULT_MAX_QUEUED,this.now=options.now??Date.now}get outstandingCount(){return this.outstanding.size}get queuedCount(){return this.terminalQueue.size+this.noteQueue.size}track(messageId,run,fromId=""){if(this.terminal.has(messageId))return!1;let held=this.outstanding.get(messageId);return held?held.fromId!==fromId?!1:(held.run===Number.POSITIVE_INFINITY&&(held.
|
|
195
|
+
run=run),!0):this.outstanding.size>=this.maxOutstanding?(this.resolve(messageId,"not_injected",TRACKING_FULL_DETAIL),!1):(this.outstanding.set(messageId,{run,fromId}),!0)}reserve(messageId,fromId){return this.track(messageId,Number.POSITIVE_INFINITY,fromId)}trackBatch(members,run){let accepted=members.map(member=>!this.deferIfHeldByOther(member.messageId,member.fromId,ID_IN_USE_DETAIL)&&this.track(member.messageId,run,member.fromId));if(accepted.every(Boolean))return!0;for(let i=0;i<members.length;i++)
|
|
196
|
+
accepted[i]&&this.resolve(members[i].messageId,"not_injected",TRACKING_FULL_DETAIL);return!1}outstandingIds(){return[...this.outstanding.keys()]}outstandingFrom(messageId){return this.outstanding.get(messageId)?.fromId}deferIfHeldByOther(messageId,fromId,detail){let held=this.outstanding.get(messageId);return!held||held.fromId===fromId?!1:(this.emit({messageId,status:"deferred",timestamp:this.now(),detail},fromId),!0)}forget(messageId){if(!this.outstanding.has(messageId)){this.terminal.delete(messageId);
|
|
197
|
+
for(let status of["receiver_received","injected","not_injected","deferred"]){let key=`${messageId}\0${status}\0`;this.emitted.delete(key),this.terminalQueue.delete(key),this.noteQueue.delete(key)}}}outstandingBefore(run){let ids2=[];for(let[messageId,entry]of this.outstanding)entry.run<run&&ids2.push(messageId);return ids2}resolve(messageId,status,detail){if(this.outstanding.delete(messageId),this.terminal.has(messageId))return!1;if(this.terminal.set(messageId,{status,detail}),this.terminal.size>
|
|
198
|
+
this.maxTerminal){let oldest=this.terminal.keys().next().value;oldest!==void 0&&this.terminal.delete(oldest)}return this.emit({messageId,status,timestamp:this.now(),detail}),!0}defer(messageId,detail){let fromId=this.outstanding.get(messageId)?.fromId;this.outstanding.delete(messageId),!this.terminal.has(messageId)&&this.emit({messageId,status:"deferred",timestamp:this.now(),detail},fromId)}replayTerminal(messageId){let known=this.terminal.get(messageId);return known?(this.emitted.delete(`${messageId}\
|
|
199
|
+
\0${known.status}\0`),this.emit({messageId,status:known.status,timestamp:this.now(),detail:known.detail}),!0):!1}note(messageId,status,detail){this.emit({messageId,status,timestamp:this.now(),detail})}flush(){for(let queue of[this.noteQueue,this.terminalQueue])for(let[key,receipt]of queue){if(!this.sendReceipt(receipt))return;queue.delete(key)}}close(detail){for(let messageId of this.outstandingIds())this.defer(messageId,detail);this.flush(),this.clear()}clear(){this.outstanding.clear(),this.terminal.
|
|
200
|
+
clear(),this.emitted.clear(),this.terminalQueue.clear(),this.noteQueue.clear()}emit(receipt,fromId=""){let key=`${receipt.messageId}\0${receipt.status}\0${fromId}`;if(receipt.status!=="receiver_received"){if(this.emitted.has(key))return;addBounded(this.emitted,key,this.maxTerminal*2)}receipt.status==="injected"||receipt.status==="not_injected"||receipt.status==="deferred"?this.terminalQueue.set(key,receipt):(this.noteQueue.set(key,receipt),this.trimNotes()),this.flush()}trimNotes(){for(;this.noteQueue.
|
|
201
|
+
size>this.maxQueued;){let oldest=this.noteQueue.keys().next().value;if(oldest===void 0)return;this.noteQueue.delete(oldest)}}};var RECONNECT_BACKOFF_MS=[1e3,2e3,5e3,1e4,3e4],defaultTimers={setTimeout:(fn,ms)=>setTimeout(fn,ms),clearTimeout:handle=>clearTimeout(handle)},ConnectionSupervisor=class{options;timers;current;connecting;droppedWhileConnecting=!1;timer;attempt=0;running=!1;stopped=!1;constructor(options){this.options=options,this.timers=options.timers??defaultTimers}get client(){return this.current?.isConnected()?this.current:void 0}start(){this.connectOnce()}async stop(){this.stopped=!0,this.timer!==void 0&&this.
|
|
202
|
+
timers.clearTimeout(this.timer),this.timer=void 0;let clients=[this.current,this.connecting];this.current=void 0,await Promise.all(clients.map(client=>client?.disconnect().catch(()=>{})))}async connectOnce(){if(this.stopped||this.running)return;this.running=!0,this.timer=void 0,this.droppedWhileConnecting=!1,this.options.onStateChange?.("connecting");let client;try{if(await this.options.ensureBroker(),this.stopped)return;let created=this.options.createClient();if(client=created,this.connecting=created,
|
|
203
|
+
created.on("disconnected",()=>{this.current===created?(this.current=void 0,this.options.onStateChange?.("degraded"),this.schedule()):this.connecting===created&&(this.droppedWhileConnecting=!0)}),await created.connect(this.options.registration(),this.options.sessionId),this.stopped){await created.disconnect().catch(()=>{});return}if(this.droppedWhileConnecting)throw new Error("Disconnected during connect");this.current=created,this.attempt=0,this.options.onStateChange?.("connected");try{this.options.
|
|
204
|
+
onConnected(created)}catch(error){this.reportError(error)}}catch(error){if(await client?.disconnect().catch(()=>{}),error instanceof CoordinationSessionHeldError){this.stopped||(this.stopped=!0,this.options.onStateChange?.("degraded",error.message));return}let reason=error instanceof Error&&error.message.includes("Coordination protocol version mismatch")?"Coordination protocol version mismatch; restart the broker and update HUMAIN Code CLI.":void 0;this.stopped||this.options.onStateChange?.("deg\
|
|
205
|
+
raded",reason),this.schedule()}finally{this.connecting=void 0,this.running=!1}}reportError(error){this.options.onError?this.options.onError(error):console.error("Coordination onConnected handler failed:",error)}schedule(){if(this.stopped||this.timer!==void 0)return;let delay=RECONNECT_BACKOFF_MS[Math.min(this.attempt,RECONNECT_BACKOFF_MS.length-1)]??3e4;this.attempt++;let handle=this.timers.setTimeout(()=>{this.timer=void 0,this.connectOnce()},delay);handle.unref?.(),this.timer=handle}};function defaultConnection(identity,agentDir=getAgentDir()){let repositoryPaths=resolveCoordinationRuntimePaths(agentDir,identity.repositoryKey),paths={...resolveCoordinationRuntimePaths(agentDir,"device"),artifactsDir:repositoryPaths.artifactsDir,pendingAsksDir:repositoryPaths.pendingAsksDir};return{paths,ensureBroker:()=>ensureBroker({paths,repositoryKey:identity.repositoryKey,agentDir:dirname2(dirname2(paths.runtimeDir))}),createClient:()=>new CoordinationClient({socketPath:paths.socketPath,scopeId:identity.
|
|
206
|
+
repositoryKey})}}function isPeerDetails(value){return typeof value=="object"&&value!==null&&"messageId"in value&&typeof value.messageId=="string"&&value.messageId.length>0}var readLiveSessionCount=()=>0;function getLiveSessionCount(){return readLiveSessionCount()}function createCoordinationExtension(options){return pi=>{readLiveSessionCount=()=>0;let env=options.env??process.env,decision=decideParticipation({env,platform:options.platform??process.platform,noCoordinate:options.noCoordinate,agentExec:options.
|
|
207
|
+
agentExec,settingEnabled:options.settingsManager.getCoordinationEnabled()});if(!decision.participate){decision.notify&&pi.on("session_start",(_event,ctx)=>{ctx.hasUI&&ctx.ui.notify(decision.reason,"info")});return}let state="connecting",reason,supervisor,delivery,identity,runtimePaths,latestClient,liveSessions=[];readLiveSessionCount=()=>{if(!connectedClient())return 0;let count=0;for(let session of liveSessions)session.id!==latestClient?.sessionId&&count++;return count},pi.registerMessageRenderer(
|
|
208
|
+
COORDINATION_MESSAGE_TYPE,(message,renderOptions,theme2)=>renderPeerMessage(message,renderOptions,theme2,liveSessions));let branch="HEAD",repo="",presence=new SessionPresence,requestedOwnership=options.ownership,streaming=!1,generation=0,liveCtx,startedAt=Date.now(),runSeq=0,connectedClient=()=>latestClient?.isConnected()?latestClient:void 0,registration=()=>({cwd:liveCtx?.cwd??process.cwd(),model:liveCtx?.model?.id??"unknown",pid:process.pid,startedAt,lastActivity:Date.now(),name:liveCtx?.sessionManager.
|
|
209
|
+
getSessionName(),worktreeRoot:identity?.worktreeRoot,branch,status:streaming?"working":"idle",acknowledgesReceipts:!0,ownership:requestedOwnership,repo,focus:presence.focus(liveCtx?.sessionManager.getSessionName()),subpath:identity?worktreeRelativePath(liveCtx?.cwd??identity.worktreeRoot,identity.worktreeRoot)??"":"",touchedPaths:presence.touchedPaths}),tracker=new ReceiptTracker({send:receipt=>{let client=connectedClient();return client?(client.sendMessageReceipt(receipt),!0):!1}}),peerKey=(fromId,messageId)=>`${fromId}\
|
|
210
|
+
\0${messageId}`,branchMessageKeys=()=>{let ids2=new Set;for(let entry of liveCtx?.sessionManager.getBranch()??[])if(entry.type==="custom_message"&&entry.customType===COORDINATION_MESSAGE_TYPE&&isPeerDetails(entry.details)){ids2.add(peerKey(entry.details.fromId,entry.details.messageId));for(let member of entry.details.batchMessages??[])ids2.add(peerKey(member.fromId,member.messageId))}return ids2},reconcile2=settled=>{if(tracker.outstandingCount===0)return;let present=branchMessageKeys();for(let messageId of tracker.
|
|
211
|
+
outstandingIds())present.has(peerKey(tracker.outstandingFrom(messageId),messageId))&&tracker.resolve(messageId,"injected");if(settled)for(let messageId of tracker.outstandingBefore(runSeq))tracker.resolve(messageId,"not_injected","message was not added to the session")},shutdown=async()=>{generation++;let activeDelivery=delivery,activeSupervisor=supervisor;delivery=void 0,supervisor=void 0,activeDelivery?.shutdown(),tracker.close("session ended before delivery"),await activeSupervisor?.stop(),latestClient=
|
|
212
|
+
void 0,liveSessions=[],tracker.clear()},artifactsBackend=createArtifactBackend({client:connectedClient,location:()=>identity&&runtimePaths?{cwd:liveCtx?.cwd??process.cwd(),worktreeRoot:identity.worktreeRoot,artifactsDir:runtimePaths.artifactsDir}:void 0,agentDir:getAgentDir,sessionDir:()=>liveCtx?.sessionManager.getSessionDir()||void 0}),preflightHeads=new Map,integrationBackend=createIntegrationBackend({client:connectedClient,location:()=>identity?{cwd:liveCtx?.cwd??process.cwd(),worktreeRoot:identity.
|
|
213
|
+
worktreeRoot,commonDir:identity.commonDir}:void 0,env:()=>options.gitEnv??process.env,preflightHeads});pi.registerTool(createCoordinationToolDefinition(createClientBackend({status:()=>({state,reason}),client:connectedClient,sessions:()=>liveSessions,artifacts:artifactsBackend,integration:integrationBackend,inbox:()=>delivery?.readInbox()??[],resolve:id=>delivery?.resolveQuestion(id),openQuestion:(id,recipients,group)=>delivery?.openQuestion(id,recipients,group),presenceSet:focus=>{presence.setFocus(
|
|
214
|
+
focus),connectedClient()?.updatePresence({focus:presence.focus(liveCtx?.sessionManager.getSessionName())})}}))),pi.registerCommand("coordinate",createCoordinateCommand({client:connectedClient,onPolicyAccepted:()=>{requestedOwnership=void 0},inspectAttempt:(attempt,handoff)=>{let repository=identity;if(!repository)return Promise.resolve({classification:"unavailable",lines:["This session has no repository identity."]});let env2=options.gitEnv??process.env,preIntegrationHead=preflightHeads.get(attempt.
|
|
215
|
+
id);return inspectAttempt({trusted:{cwd:repository.worktreeRoot,env:env2},identity:repository,attempt,handoff,env:env2,...preIntegrationHead!==void 0?{preIntegrationHead}:{}})}}));let warnedConflicts=new Set,notifyPolicyConflict=status=>{let notice=status.notice;try{if(!notice||!liveCtx?.hasUI)return;let pair=`${notice.requested}>${notice.current}`;if(warnedConflicts.has(pair))return;warnedConflicts.add(pair),liveCtx.ui.notify(formatPolicyNotice(notice),"warning")}catch{}},integrationNoticeState=INITIAL_INTEGRATION_NOTICES,
|
|
216
|
+
notifyIntegration=(status,sessionId)=>{let{notices,next}=integrationNotices(integrationNoticeState,status,sessionId,env.HUMAIN_TERMINAL_COORDINATION_WORKTREE_HINT==="1",liveSessions);integrationNoticeState=next;try{if(!liveCtx?.hasUI)return;for(let notice of notices)liveCtx.ui.notify(notice.message,notice.level)}catch{}};pi.on("before_agent_start",(event,ctx)=>{liveCtx=ctx,event.messageType==="user"&&presence.setPrompt(event.prompt),connectedClient()?.updatePresence({name:ctx.sessionManager.getSessionName(),
|
|
217
|
+
focus:presence.focus(ctx.sessionManager.getSessionName())})}),pi.on("context",event=>{let digest=[delivery?.inboxDigest(),presence.focusNudge()].filter(Boolean).join(`
|
|
218
|
+
`);if(digest)return{messages:[...event.messages,{role:"custom",customType:"coordination-inbox-digest",content:digest,display:!0,timestamp:Date.now()}]}}),pi.on("tool_result",(event,ctx)=>{!event.isError&&event.toolName==="bash"&&typeof event.input.command=="string"&&presence.noteCommand(event.input.command),!(event.isError||!identity||event.toolName!=="edit"&&event.toolName!=="write")&&typeof event.input.path=="string"&&(presence.track(event.input.path,ctx.cwd,identity.worktreeRoot),connectedClient()?.
|
|
219
|
+
updatePresence({touchedPaths:presence.touchedPaths}))}),pi.on("agent_start",()=>{runSeq++,streaming=!0,connectedClient()?.updatePresence({status:"working"})}),pi.on("agent_end",async()=>{streaming=!1,identity&&(branch=await readGitBranch(identity.worktreeRoot,env)),connectedClient()?.updatePresence({status:"idle",branch,name:liveCtx?.sessionManager.getSessionName(),focus:presence.focus(liveCtx?.sessionManager.getSessionName())}),delivery?.drainHeld()}),pi.on("message_end",event=>{let message=event.
|
|
220
|
+
message;if(!(message.role!=="custom"||message.customType!==COORDINATION_MESSAGE_TYPE)&&isPeerDetails(message.details)){tracker.resolve(message.details.messageId,"injected");for(let member of message.details.batchMessages??[])tracker.resolve(member.messageId,"injected")}}),pi.on("turn_start",()=>{reconcile2(!1)}),pi.on("agent_settled",()=>{reconcile2(!0)}),pi.on("session_start",async(_event,ctx)=>{await shutdown(),integrationNoticeState=INITIAL_INTEGRATION_NOTICES;let mine=generation;liveCtx=ctx,
|
|
221
|
+
presence=new SessionPresence;let resolved=await(options.resolveIdentity??(cwd=>resolveGitRepositoryIdentity(cwd,env)))(ctx.cwd);if(mine!==generation)return;if(identity=resolved,!resolved){state="unavailable",reason="this directory is not inside a Git work tree";return}if(branch=await readGitBranch(resolved.worktreeRoot,env),repo=await readRepositoryLabel(resolved.worktreeRoot,options.gitEnv??env),mine!==generation)return;state="connecting",reason=void 0;let connection;try{connection=(options.connection??
|
|
222
|
+
(repository=>defaultConnection(repository)))(resolved)}catch(error){state="unavailable",reason=error instanceof Error?error.message:String(error);return}runtimePaths=connection.paths;let activeDelivery=new InboundDelivery({onInboxChange:ctx.hasUI?unread=>{try{liveCtx?.ui.setStatus("coordination-inbox",unread?`peers: ${unread} unread`:void 0)}catch{}}:void 0,self:()=>({...registration(),id:latestClient?.sessionId??ctx.sessionManager.getSessionId()}),sessions:()=>liveSessions,target:{mode:ctx.mode,
|
|
223
|
+
isStreaming:()=>streaming,isIdle:()=>ctx.isIdle(),send:(content,details,deliveryOptions)=>{let message={customType:COORDINATION_MESSAGE_TYPE,content,display:!0,details};tracker.trackBatch(details.batchMessages??[details],runSeq)&&(deliveryOptions.deliverAs==="steer"?pi.sendMessage(message,{deliverAs:"steer"}):(pi.sendMessage(message,{triggerTurn:deliveryOptions.triggerTurn}),deliveryOptions.triggerTurn||reconcile2(!1)))}},receipts:(messageId,status,detail)=>{status==="not_injected"||status==="in\
|
|
224
|
+
jected"?tracker.resolve(messageId,status,detail):status==="deferred"?tracker.defer(messageId,detail):tracker.note(messageId,status,detail)},reservePending:(messageId,fromId)=>tracker.reserve(messageId,fromId),onDuplicate:messageId=>{tracker.replayTerminal(messageId)},onIdReused:messageId=>{tracker.forget(messageId)},deferIfIdHeld:(messageId,fromId)=>tracker.deferIfHeldByOther(messageId,fromId,ID_IN_USE_DETAIL),alreadyInjected:(messageId,fromId)=>branchMessageKeys().has(peerKey(fromId,messageId)),
|
|
225
|
+
budget:new WakeBudget(options.settingsManager.getCoordinationPeerWakeLimit())});delivery=activeDelivery;let activeSupervisor=new ConnectionSupervisor({ensureBroker:connection.ensureBroker,createClient:()=>{let client=connection.createClient();client.on("message",(from,message)=>activeDelivery.accept(from,message));let updateSession=session=>{latestClient===client&&(liveSessions=[...liveSessions.filter(peer=>peer.id!==session.id),session])};return client.on("session_joined",updateSession),client.
|
|
226
|
+
on("presence_update",updateSession),client.on("session_left",sessionId=>{latestClient===client&&(liveSessions=liveSessions.filter(peer=>peer.id!==sessionId))}),client.on("error",()=>{}),client.on("policy_status",status=>{status.requestedOwnership===void 0&&(requestedOwnership=void 0),notifyPolicyConflict(status)}),client.on("integration_status",status=>{client.listSessions().then(sessions=>{latestClient===client&&(liveSessions=sessions,notifyIntegration(status,client.sessionId))},()=>{latestClient===
|
|
227
|
+
client&¬ifyIntegration(status,client.sessionId)})}),latestClient=client,client},registration,sessionId:ctx.sessionManager.getSessionId(),onStateChange:(next,failureReason)=>{state=next,reason=failureReason},onConnected:()=>{tracker.flush(),activeDelivery.drainHeld()}});supervisor=activeSupervisor,activeSupervisor.start()}),pi.on("session_shutdown",async()=>{await shutdown()})}}var handlers=new WeakMap;function bindClaudeUsageReconnect(registry,handler){return handlers.set(registry,handler),()=>{handlers.get(registry)===handler&&handlers.delete(registry)}}function getClaudeUsageReconnect(registry){return handlers.get(registry)}function formatSubscriptionCredits(credits){if(credits?.unlimited===!0)return"unlimited";if(credits?.hasCredits===!1)return"none";let balance=parseSubscriptionCreditAmount(credits?.balance);if(balance===void 0||credits?.unit===void 0)return"unavailable";if(Number(balance)===0)return"none";let[integer,fraction]=balance.split("."),amount=`${Number(integer).toLocaleString("en-US")}${fraction===void 0?"":`.${fraction}`}`;return credits.unit==="USD"?`$${amount}`:`${amount} credits`}function formatSubscriptionAccountSummary(result){
|
|
120
228
|
let usage=subscriptionAccountUsage(result),weekly=usage.weeklyLeft===void 0?`weekly usage: unavailable${usage.expired?" (sign-in expired)":""}`:`weekly: ${usage.weeklyLeft}% left`;return usage.availability&&(weekly+=`, provider: ${usage.availability}`),usage.reset&&(weekly+=usage.availability?`, resets ${usage.reset}`:`, Next reset ${usage.reset}`),`${weekly}, saved resets: ${usage.savedResets}, paid credits: ${usage.paidCredits}${usage.extraUsage===void 0?"":`, extra usage: ${usage.extraUsage}`}`}
|
|
121
229
|
function subscriptionAccountUsage(result){let ok=result?.status==="ok"?result:void 0,claude=ok&&"fetchedAt"in ok?ok:void 0,codex=ok&&"usage"in ok?ok.usage:void 0,weekly=claude?.windows.find(window=>window.id==="seven_day"),percent=weekly?100-weekly.usedPercent:codex?.remainingPercent,count=ok?.resets?.availableCount,enabled=ok?.credits?.enabled;return{expired:result?.status==="unavailable"&&result.reason==="expired_credential",weeklyLeft:percent===void 0?void 0:Math.round(percent),reset:claude?formatNextQuotaReset(
|
|
122
230
|
claude.windows):codex?.resetsAt===void 0?void 0:formatOAuthAccountResetTime(codex.resetsAt),availability:codex?getCodexAvailability(codex):void 0,savedResets:count===void 0?"unavailable":count===0?"none":String(count),paidCredits:formatSubscriptionCredits(ok?.credits),extraUsage:enabled===void 0?void 0:enabled?"enabled":"disabled"}}function formatNextQuotaReset(windows,now=Date.now()){let nearest=1/0;for(let{resetsAt}of windows)resetsAt!==void 0&&resetsAt>now&&resetsAt<nearest&&(nearest=resetsAt);
|
|
123
231
|
return nearest===1/0?void 0:formatOAuthAccountResetTime(nearest)}function formatOAuthAccountResetTime(epochMs){let date=new Date(epochMs),time=`${String(date.getHours()).padStart(2,"0")}:${String(date.getMinutes()).padStart(2,"0")}`;return date.toDateString()===new Date().toDateString()?time:`${time} on ${date.toLocaleDateString()}`}function formatOAuthAccountUsage(usage){switch(usage.kind){case"none":return"";case"loading":return"weekly usage: loading\u2026";case"subscription":return[usage.status,
|
|
124
232
|
formatSubscriptionAccountSummary(usage.result)].filter(Boolean).join(", ");case"unavailable":return usage.reason==="expired_credential"?"weekly usage: unavailable (sign-in expired)":"weekly usage: unavailable";case"available":{let remaining=`weekly: ${Math.round(usage.remainingPercent)}% left, provider: ${getCodexAvailability(usage)}`;return usage.resetsAt!==void 0?`${remaining}, resets ${formatOAuthAccountResetTime(usage.resetsAt)}`:remaining}}}function formatOAuthAccountOption(label,usage){let usageText=formatOAuthAccountUsage(
|
|
125
|
-
usage);return usageText?`${label} (${usageText})`:label}import{readFile}from"node:fs/promises";import{homedir}from"node:os";import{join as
|
|
233
|
+
usage);return usageText?`${label} (${usageText})`:label}import{readFile}from"node:fs/promises";import{homedir}from"node:os";import{join as join4}from"node:path";function usageDisplayText(text){return sanitizeTerminalText(text).replace(/[\t\r\n\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g," ")}function formatTokens(count){return count<1e3?count.toString():count<1e4?`${(count/1e3).toFixed(1)}k`:count<1e6?`${Math.round(count/1e3)}k`:count<1e7?`${(count/1e6).toFixed(1)}M`:`${Math.round(count/1e6)}M`}function formatDuration(ms){let totalSeconds=Math.max(0,Math.floor(ms/1e3)),hours=Math.floor(totalSeconds/3600),minutes=Math.floor(totalSeconds%3600/
|
|
126
234
|
60),seconds=totalSeconds%60;return hours>0?`${hours}h ${minutes}m ${seconds}s`:minutes>0?`${minutes}m ${seconds}s`:`${seconds}s`}function percentTone(percent){return percent>90?"error":percent>70?"warning":"accent"}function contextTone(percent){return percent===null?"accent":percentTone(percent)}function buildUsageOverview(opts){let{providerId,modelId,stats,durationMs,usageIncomplete,subscriptionBacked,accountBars}=opts,bars=[],lines=[],notes=[];accountBars&&bars.push(...accountBars);let cu=stats.
|
|
127
235
|
contextUsage;return cu&&bars.push({id:"context",label:"Context",used:cu.tokens??0,total:cu.contextWindow,display:`${cu.percent!==null?`${cu.percent.toFixed(1)}%`:"?"} / ${formatTokens(cu.contextWindow)}`,tone:contextTone(cu.percent)}),lines.push({label:"tokens",value:`\u2191${formatTokens(stats.tokens.input)} \u2193${formatTokens(stats.tokens.output)}`}),lines.push(usageIncomplete?{label:"cost",value:`\u2265$${stats.cost.toFixed(3)} (usage incomplete)`,tone:"warning"}:{label:"cost",value:`$${stats.
|
|
128
236
|
cost.toFixed(3)}`}),durationMs!==null&&lines.push({label:"time",value:formatDuration(durationMs)}),subscriptionBacked&¬es.push("Subscription limits (weekly / 5h) are not exposed by this provider's API. See its usage dashboard."),{providerId,modelId,bars,lines,notes}}function formatUsageOverview(overview){let rows=[...overview.bars.map(bar=>({label:bar.label,value:`${bar.display}${bar.note?` (${bar.note})`:""}`})),...overview.lines],labelWidth=Math.max(0,...rows.map(row=>visibleWidth(row.label)));
|
|
@@ -135,43 +243,45 @@ used_dollars:used,limit_dollars:total}=value;if(!(typeof used!="number"||typeof
|
|
|
135
243
|
Claude usage was refused (HTTP 401/403).",rate_limited:"Claude usage is rate limited (HTTP 429). Try again later.",http_error:"Claude usage is unavailable (HTTP error).",timeout:"Claude usage timed out.",network:"Claude usage is unreachable.",malformed:"Claude usage returned an unexpected response."},CODEX_UNAVAILABLE={expired_credential:"Codex sign-in expired. Run /login.",unauthorized:"Codex usage was refused (HTTP 401/403).",rate_limited:"Codex usage is rate limited (HTTP 429). Try again late\
|
|
136
244
|
r.",http_error:"Codex usage is unavailable (HTTP error).",timeout:"Codex usage timed out.",network:"Codex usage is unreachable.",malformed:"Codex usage returned an unexpected response.",no_weekly_window:"Codex reported no weekly limit."};function codexUsageBars(result,now=Date.now()){return result?result.status==="unavailable"?{error:CODEX_UNAVAILABLE[result.reason]}:result.windows.length===0&&!result.credits?{error:"Codex reported no usage limits."}:{bars:result.windows.map(window=>limitBar(`co\
|
|
137
245
|
dex-${window.id}`,window.label,window.usedPercent,window.resetsAt,window.limitReached===!0,now)),lines:[...nextQuotaResetLines(result.windows,now),...paidUsageLines(result.credits)]}:{error:"No active Codex account. Run /login."}}function usageAge(ms){return`${ms>=1728e5?`${Math.floor(ms/864e5)} days`:formatAge(ms)} ago`}function formatAge(ms){let minutes=Math.floor(Math.max(0,ms)/6e4);if(minutes<1)return"under a minute";if(minutes<60)return`${minutes} min`;let hours=Math.floor(minutes/60);return hours<
|
|
138
|
-
48?`${hours} h`:`${Math.floor(hours/24)} d`}async function readClaudeCachedUsage(readOwner,now,home=homedir()){let text;try{text=await readFile(
|
|
246
|
+
48?`${hours} h`:`${Math.floor(hours/24)} d`}async function readClaudeCachedUsage(readOwner,now,home=homedir()){let text;try{text=await readFile(join4(home,".claude.json"),"utf8")}catch(err){return err.code==="ENOENT"?{error:"~/.claude.json not found."}:{error:"Could not read ~/.claude.json."}}let data;try{data=JSON.parse(text)}catch{return{error:"~/.claude.json is not valid JSON."}}let identity=data&&typeof data=="object"?data.oauthAccount:void 0,{accountUuid,organizationUuid}=identity??{},{accountId,
|
|
139
247
|
organizationId}=await readOwner()??{},sameOrganization=typeof organizationUuid=="string"?organizationUuid.toLowerCase()===organizationId?.toLowerCase():organizationUuid===void 0&&organizationId===void 0;if(!accountId||typeof accountUuid!="string"||accountUuid.toLowerCase()!==accountId.toLowerCase()||!sameOrganization)return{error:"Claude Code's cache does not match this account."};let cached=data&&typeof data=="object"?data.cachedUsageUtilization:void 0;if(!cached||typeof cached!="object")return{
|
|
140
248
|
error:"No cached Claude Code usage in ~/.claude.json."};let fetchedAt=cached.fetchedAtMs,fetchedAtMs=typeof fetchedAt=="number"&&Number.isFinite(fetchedAt)&&fetchedAt>=0&&fetchedAt<=now?fetchedAt:void 0,payload=cached.utilization??cached,stale=fetchedAtMs===void 0||now-fetchedAtMs>36e5||parseAnthropicSubscriptionUsage(payload).some(window=>window.resetsAt!==void 0&&window.resetsAt<=now),bars=parseClaudeUtilization(cached,now);return bars.length===0?{error:"No cached Claude Code usage in ~/.claud\
|
|
141
249
|
e.json."}:{bars:stale?[]:bars,fetchedAtMs,stale}}async function readClaudeUsage(registry,accountKey,request,home){let result,failure,lastKnown;try{if(result=await registry.getAnthropicUsage({accountKey,...request}),result?.status==="ok"&&result.windows.length>0){let now2=Date.now(),windows=result.windows.filter(({resetsAt})=>resetsAt===void 0||resetsAt>now2);if(windows.length>0&&now2-result.fetchedAt<=36e5)return{result:{...result,windows}};lastKnown=result.fetchedAt,result={...result,windows:[]}}
|
|
142
250
|
failure=result?.status==="unavailable"?CLAUDE_UNAVAILABLE[result.reason]:result?"Claude reported no usage limits.":"No saved Claude account. Run /login."}catch{failure="Claude usage is unavailable."}let now=Date.now(),cache=await readClaudeCachedUsage(async()=>{try{return(await registry.getUsageAccounts(ANTHROPIC_USAGE_PROVIDER_ID,{signal:request.signal})).find(({key})=>key===accountKey)}catch{return}},now,home),required=result?.status==="unavailable"&&result.reason==="refresh_rejected";if("erro\
|
|
143
251
|
r"in cache)return{result,fallback:{status:lastKnown===void 0?"No live data":`No live data; last known ${usageAge(now-lastKnown)}`,bars:[],failure,cacheError:cache.error,reconnect:required?"required":lastKnown!==void 0?"optional":void 0}};let age=cache.fetchedAtMs===void 0?void 0:usageAge(now-cache.fetchedAtMs);return{result,fallback:{status:cache.stale?`No live data; last known ${age??"(age unknown)"}`:`Claude Code's cached numbers, from ${age}`,bars:cache.bars,failure,reconnect:required?"requir\
|
|
144
|
-
ed":cache.stale?"optional":void 0}}}function nextQuotaResetLines(windows,now){let reset=formatNextQuotaReset(windows,now);return reset?[{label:"Next reset",value:reset}]:[]}var SIGNAL_SHUTDOWN_GRACE_MS=1500;async function waitForSignalShutdown(shutdown){let timer;try{await Promise.race([shutdown,new Promise(
|
|
252
|
+
ed":cache.stale?"optional":void 0}}}function nextQuotaResetLines(windows,now){let reset=formatNextQuotaReset(windows,now);return reset?[{label:"Next reset",value:reset}]:[]}var SIGNAL_SHUTDOWN_GRACE_MS=1500;async function waitForSignalShutdown(shutdown){let timer;try{await Promise.race([shutdown,new Promise(resolve4=>{timer=setTimeout(resolve4,SIGNAL_SHUTDOWN_GRACE_MS)})])}finally{clearTimeout(timer)}}async function exitAfterSignalShutdown(shutdown,exitCode){try{await waitForSignalShutdown(shutdown)}finally{await killTrackedDetachedChildrenAsync(),process.exit(exitCode)}}function onUnhandledRejection(crash){let listener=reason=>{process.listenerCount("unhandledRejection")>1||crash(rejectionError(reason))};return process.on("unhandledRejection",listener),()=>process.off("unhandledRejection",listener)}function onUncaughtErrors(crash){let onException=error=>{process.listenerCount("uncaughtException")>1||crash(error)};process.on("uncaughtException",onException);let offRejection=onUnhandledRejection(error=>process.emit("uncaughtException",error));return()=>{process.off(
|
|
145
253
|
"uncaughtException",onException),offRejection()}}function formatUncaughtError(error){return error.stack??`${error.name}: ${error.message}`}function rejectionError(reason){if(reason instanceof Error)return reason;let error=new Error(`This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with a non-Error reason (${reason===null?"null":typeof reason}).`);return error.name="Unhan\
|
|
146
|
-
dledPromiseRejection",Object.assign(error,{code:"ERR_UNHANDLED_REJECTION"})}function composeStatusLine(state,model,context,fields,width,priority="balanced"){if(width<1)return"";let separator=" \u203A ";if(priority==="maintenance"){let line2=truncateToWidth(state,width,"");for(let field of[model,context,...fields]){if(!field)continue;let next=`${line2}${separator}${field}`;if(visibleWidth(next)>width)break;line2=next}return line2}let line=[state,model,context].join(separator);if(visibleWidth(line)>width){let budget=Math.max(0,width-visibleWidth(context)-6),
|
|
147
|
-
min(visibleWidth(state),Math.floor(budget/2));return line=[truncateToWidth(state,stateWidth,""),truncateToWidth(model,budget-stateWidth,""),context].join(separator),truncateToWidth(line,width,"")}for(let[index,field]of fields.entries()){if(!field)continue;let next=index<2?[state,model,...fields.slice(0,index+1),context].join(separator):`${line}${separator}${field}`;if(visibleWidth(next)>width)break;line=next}return line}var StatusLineContainer=class extends Container{draw;constructor(draw){
|
|
148
|
-
this.draw=draw}render(width){return this.draw(width)}};import{basename,isAbsolute,relative,resolve as
|
|
149
|
-
".."&&!relativeToHome.startsWith(`..${
|
|
254
|
+
dledPromiseRejection",Object.assign(error,{code:"ERR_UNHANDLED_REJECTION"})}function composeStatusLine(state,model,context,fields,width,priority="balanced"){if(width<1)return"";let separator=" \u203A ";if(priority==="maintenance"){let line2=truncateToWidth(state,width,"");for(let field of[model,context,...fields]){if(!field)continue;let next=`${line2}${separator}${field}`;if(visibleWidth(next)>width)break;line2=next}return line2}let line=[state,model,context].filter(Boolean).join(separator);if(visibleWidth(line)>width){let budget=Math.max(0,width-visibleWidth(context)-6),
|
|
255
|
+
stateWidth=Math.min(visibleWidth(state),Math.floor(budget/2));return line=[truncateToWidth(state,stateWidth,""),truncateToWidth(model,budget-stateWidth,""),context].join(separator),truncateToWidth(line,width,"")}for(let[index,field]of fields.entries()){if(!field)continue;let next=index<2?[state,model,...fields.slice(0,index+1),context].filter(Boolean).join(separator):`${line}${separator}${field}`;if(visibleWidth(next)>width)break;line=next}return line}var StatusLineContainer=class extends Container{draw;constructor(draw){
|
|
256
|
+
super(),this.draw=draw}render(width){return this.draw(width)}};import{basename as basename3,isAbsolute as isAbsolute3,relative as relative3,resolve as resolve3,sep as sep3}from"node:path";function sanitizeStatusText(text){return text.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()}function formatTokens2(count){return count<1e3?count.toString():count<1e4?`${(count/1e3).toFixed(1)}k`:count<1e6?`${Math.round(count/1e3)}k`:count<1e7?`${(count/1e6).toFixed(1)}M`:`${Math.round(count/1e6)}M`}function formatCwdForFooter(cwd,home){if(!home)return cwd;let resolvedCwd=resolve3(cwd),resolvedHome=resolve3(home),relativeToHome=relative3(resolvedHome,resolvedCwd);return relativeToHome===""||
|
|
257
|
+
relativeToHome!==".."&&!relativeToHome.startsWith(`..${sep3}`)&&!isAbsolute3(relativeToHome)?relativeToHome===""?"~":`~${sep3}${relativeToHome}`:cwd}var FOOTER_VALUE_INPUTS=["width","sidebarVisible","theme","identity","effort","modelName","accountLabel","routedModelId","provider","age","contextPercent","contextWindow","usingSubscription","usageIncomplete","cost","input","output","cacheRead","cacheWrite","latestCacheHitRate","tokensPerSecond","experimental"];var NO_EXTENSION_STATUSES=[];function sameFooterInputs(a,b){for(let key of FOOTER_VALUE_INPUTS)if(!Object.is(a[key],b[key]))return!1;let statuses=a.extensionStatuses;if(statuses.length!==b.extensionStatuses.length)return!1;for(let i=0;i<statuses.length;i++)if(statuses[i]!==b.extensionStatuses[i])return!1;return!0}var FooterComponent=class{extensionStatusesOnly=!1;sidebarVisible=!1;tasksProvider;lastEventAt;activitySessionId;activityTimer;session;footerData;sessionStats;rendered;constructor(session,footerData,requestRender){
|
|
150
258
|
this.session=session,this.footerData=footerData,this.activitySessionId=session.sessionManager.getSessionId(),this.refreshActivityFromSession(),requestRender&&this.startActivityTimer(requestRender)}setSession(session){let changed=this.session!==session||this.activitySessionId!==session.sessionManager.getSessionId();this.session=session,changed&&this.refreshActivityFromSession()}markActivity(){this.lastEventAt=performance.now()}refreshActivityFromSession(){this.activitySessionId=this.session.sessionManager.
|
|
151
259
|
getSessionId(),this.lastEventAt=void 0;let now=Date.now(),latest=0;for(let entry of this.session.sessionManager.getBranch()){if(entry.type!=="message"||entry.message.role!=="user"&&entry.message.role!=="assistant"&&entry.message.role!=="toolResult")continue;let timestamp=Date.parse(entry.timestamp);Number.isFinite(timestamp)&×tamp>latest&×tamp<=now&&(latest=timestamp)}latest>0&&(this.lastEventAt=performance.now()-(now-latest))}startActivityTimer(onTick){this.activityTimer||(this.activityTimer=
|
|
152
260
|
setInterval(()=>{this.lastEventAt!==void 0&&onTick()},1e3),this.activityTimer.unref())}invalidate(){}dispose(){this.activityTimer&&clearInterval(this.activityTimer),this.activityTimer=void 0}getSessionStats(){let sessionManager=this.session.sessionManager,entryCount=sessionManager.getEntryCount(),sessionId=sessionManager.getSessionId(),leafId=sessionManager.getLeafId(),limitsModel=this.session.routedModel?.model??this.session.model,cached=this.sessionStats;if(cached&&cached.session===this.session&&
|
|
153
261
|
cached.sessionId===sessionId&&cached.leafId===leafId&&cached.entryCount===entryCount&&cached.limitsModel===limitsModel)return cached;let usageTotals=createUsageTotals(),latestCacheHitRate,tokensPerSecond,entries=sessionManager.getEntries();for(let{usage}of getSessionUsage(entries))addUsageToTotals(usageTotals,usage);for(let entry of entries)if(entry.type==="message"&&entry.message.role==="assistant"){tokensPerSecond=entry.message.durationMs&&entry.message.durationMs>0?entry.message.usage.output*
|
|
154
262
|
1e3/entry.message.durationMs:void 0;let latestPromptTokens=entry.message.usage.input+entry.message.usage.cacheRead+entry.message.usage.cacheWrite;latestCacheHitRate=latestPromptTokens>0?entry.message.usage.cacheRead/latestPromptTokens*100:void 0}let contextUsage=this.session.getContextUsage();return this.sessionStats={session:this.session,sessionId,leafId,entryCount,limitsModel,usageTotals,latestCacheHitRate,tokensPerSecond,contextUsage},this.sessionStats}renderInputs(width){let state=this.session.
|
|
155
|
-
state,{usageTotals,latestCacheHitRate,tokensPerSecond,contextUsage}=this.getSessionStats(),routed=this.session.routedModel,pwd=
|
|
156
|
-
model?this.footerData.getOAuthAccountLabel(state.model.provider):void 0,statuses=this.footerData.getExtensionStatuses();return{width,theme:getThemeInstance(),identity:[pwd,branch,sessionName].filter(Boolean).map(text=>stripAnsi(sanitizeStatusText(text))).join(" \xB7 "),effort:this.session.autoEffortSelecting?"Choosing effort\u2026":effectiveModel?.reasoning&&thinkingLevel!=="off"?thinkingLevel[0].toUpperCase()+thinkingLevel.slice(1):"
|
|
157
|
-
id??"no-model")),accountLabel:accountLabel?stripAnsi(sanitizeStatusText(accountLabel)):void 0,routedModelId:routed?stripAnsi(sanitizeStatusText(routed.model.id)):void 0,provider:this.footerData.getAvailableProviderCount()>1&&state.model?stripAnsi(sanitizeStatusText(state.model.provider)):void 0,age:elapsed===void 0?"\u2014":elapsed===0?"now":elapsed<60?`${elapsed}s ago`:elapsed<3600?`${Math.floor(elapsed/60)}m ago`:elapsed<86400?`${Math.
|
|
158
|
-
|
|
159
|
-
extensionStatuses:statuses.size===0?NO_EXTENSION_STATUSES:Array.from(statuses.entries()).filter(([key])=>key!=="adhd"&&key!=="caveman"&&key!=="ponytail").sort(([a],[b])=>a.localeCompare(b)).map(([,text])=>sanitizeStatusText(text))}}renderStatus(width,state,busy,startedAt=0,_lastDuration=0,effortColor,statePriority="balanced"){busy=busy||this.session.isStreaming||this.session.isCompacting||this.session.isRetrying;let inputs=this.renderInputs(
|
|
160
|
-
text??"",mcp=getMcpStatus(this.session.sessionManager),percent=inputs.contextPercent,contextColor=(percent??0)>90?"error":(percent??0)>70?"warning":"text",contextPercent=`Context ${percent===void 0?"?":`${percent.toFixed(1)}%`}`,model=theme.fg("text",inputs.routedModelId??inputs.modelName),fullContext=`${contextPercent} of ${formatTokens2(inputs.contextWindow)}`,context=theme.fg(contextColor,
|
|
161
|
-
fg("dim",busy?`${Math.max(0,Math.floor((performance.now()-startedAt)/1e3))}s`:`last event ${inputs.age}`),timingWidth=visibleWidth([state,model,context].join(" \u203A "))+5+visibleWidth(timing)<=width?visibleWidth(timing):0,leftWidth=timingWidth?width-timingWidth-5:width,left=composeStatusLine(state,model,context,[(effortColor??theme.getThinkingBorderColor(this.session.routedModel?.thinkingLevel??
|
|
162
|
-
|
|
163
|
-
remaining>0?` ${"\u2500".repeat(remaining-1)}`:"")}return left+borderColor(` ${"\u2500".repeat(width-visibleWidth(left)-timingWidth-4)} `)+timing+borderColor(" \u2500")}renderDetails(width){let inputs=this.renderInputs(width),fields=[`${inputs.usageIncomplete?"\u2265":""}$${inputs.cost.toFixed(3)}${inputs.usingSubscription?" (sub)":""}${inputs.usageIncomplete?
|
|
164
|
-
inputs.input)}`,`Out ${formatTokens2(inputs.output)}
|
|
165
|
-
width<1?[]:[truncateToWidth(theme.fg("dim",fields.join(" \u203A ")),width,"")]}render(width){if(width<1)return[];if(this.extensionStatusesOnly){let statuses=this.renderInputs(width).extensionStatuses;return statuses.length?[truncateToWidth(statuses.join(" "),width,"")]:[]}let inputs=this.renderInputs(width),known=this.rendered;
|
|
166
|
-
let{width,contextPercent}=inputs,context=`Context ${contextPercent===void 0?"?":`${contextPercent.toFixed(1)}%`}/${formatTokens2(inputs.contextWindow)}`,lines=[truncateToWidth(theme.fg("dim",inputs.identity),width,theme.fg("dim","..."))],{effort,modelName}=inputs,model=modelName,modelFields=[theme.fg("accent",effort)],
|
|
167
|
-
2+visibleWidth(activity)<=width&&(model=withAccount)}if(modelFields.push(theme.fg("text",model)),inputs.routedModelId!==void 0&&modelFields.push(theme.fg("muted",`\u2192 ${inputs.routedModelId}`)),inputs.provider!==void 0){let provider=theme.fg("dim",`(${inputs.provider})`);visibleWidth([...modelFields,provider].join(
|
|
168
|
-
0)>70?"warning":"text",{usingSubscription}=inputs,statsParts=[theme.fg(contextColor,context)]
|
|
169
|
-
|
|
170
|
-
theme.fg("dim","/settings"),width)),inputs.extensionStatuses.length&&lines.push(truncateToWidth(inputs.extensionStatuses.join(" "),width,theme.fg("dim","..."))),lines}renderBand(fields,right,width){
|
|
171
|
-
if(line&&visibleWidth(line)
|
|
263
|
+
state,{usageTotals,latestCacheHitRate,tokensPerSecond,contextUsage}=this.getSessionStats(),routed=this.session.routedModel,pwd=basename3(this.session.sessionManager.getCwd())||sep3,branch=this.sidebarVisible?null:this.footerData.getGitBranch(),sessionName=this.session.sessionManager.getSessionName(),effectiveModel=routed?.model??state.model,thinkingLevel=routed?.thinkingLevel??state.thinkingLevel??"off",elapsed=this.lastEventAt===void 0?void 0:Math.max(0,Math.floor((performance.now()-this.lastEventAt)/
|
|
264
|
+
1e3)),accountLabel=state.model?this.footerData.getOAuthAccountLabel(state.model.provider):void 0,statuses=this.footerData.getExtensionStatuses();return{width,sidebarVisible:this.sidebarVisible,theme:getThemeInstance(),identity:[pwd,branch,sessionName].filter(Boolean).map(text=>stripAnsi(sanitizeStatusText(text))).join(" \xB7 "),effort:this.session.autoEffortSelecting?"Choosing effort\u2026":effectiveModel?.reasoning&&thinkingLevel!=="off"?thinkingLevel[0].toUpperCase()+thinkingLevel.slice(1):"Th\
|
|
265
|
+
inking off",modelName:stripAnsi(sanitizeStatusText(state.model?.id??"no-model")),accountLabel:accountLabel?stripAnsi(sanitizeStatusText(accountLabel)):void 0,routedModelId:routed?stripAnsi(sanitizeStatusText(routed.model.id)):void 0,provider:this.footerData.getAvailableProviderCount()>1&&state.model?stripAnsi(sanitizeStatusText(state.model.provider)):void 0,age:elapsed===void 0?"\u2014":elapsed===0?"now":elapsed<60?`${elapsed}s ago`:elapsed<3600?`${Math.floor(elapsed/60)}m ago`:elapsed<86400?`${Math.
|
|
266
|
+
floor(elapsed/3600)}h ago`:`${Math.floor(elapsed/86400)}d ago`,contextPercent:contextUsage?.percent??void 0,contextWindow:contextUsage?.contextWindow??routed?.model.contextWindow??state.model?.contextWindow??0,usingSubscription:state.model?this.session.modelRuntime.isUsingSubscription(state.model.provider):!1,usageIncomplete:!!usageTotals.usageIncomplete,cost:usageTotals.cost,input:usageTotals.input,output:usageTotals.output,cacheRead:usageTotals.cacheRead,cacheWrite:usageTotals.cacheWrite,latestCacheHitRate,
|
|
267
|
+
tokensPerSecond,experimental:areExperimentalFeaturesEnabled(),extensionStatuses:statuses.size===0?NO_EXTENSION_STATUSES:Array.from(statuses.entries()).filter(([key])=>key!=="adhd"&&key!=="caveman"&&key!=="ponytail").sort(([a],[b])=>a.localeCompare(b)).map(([,text])=>sanitizeStatusText(text))}}renderStatus(width,state,busy,startedAt=0,_lastDuration=0,effortColor,statePriority="balanced"){busy=busy||this.session.isStreaming||this.session.isCompacting||this.session.isRetrying;let inputs=this.renderInputs(
|
|
268
|
+
width),tasks=inputs.sidebarVisible?"":this.tasksProvider?.getChecklistStatusSegment()?.text??"",mcp=getMcpStatus(this.session.sessionManager),percent=inputs.contextPercent,contextColor=(percent??0)>90?"error":(percent??0)>70?"warning":"text",contextPercent=`Context ${percent===void 0?"?":`${percent.toFixed(1)}%`}`,model=theme.fg("text",inputs.routedModelId??inputs.modelName),fullContext=`${contextPercent} of ${formatTokens2(inputs.contextWindow)}`,context=inputs.sidebarVisible?"":theme.fg(contextColor,
|
|
269
|
+
visibleWidth([state,model,fullContext].join(" \u203A "))<=width?fullContext:contextPercent),timing=theme.fg("dim",busy?`${Math.max(0,Math.floor((performance.now()-startedAt)/1e3))}s`:`last event ${inputs.age}`),timingWidth=visibleWidth([state,model,context].join(" \u203A "))+5+visibleWidth(timing)<=width?visibleWidth(timing):0,leftWidth=timingWidth?width-timingWidth-5:width,left=composeStatusLine(state,model,context,[(effortColor??theme.getThinkingBorderColor(this.session.routedModel?.thinkingLevel??
|
|
270
|
+
this.session.thinkingLevel))(inputs.effort),theme.fg("dim",inputs.identity),tasks,inputs.sidebarVisible?"":theme.fg("dim",`TPS ${inputs.tokensPerSecond?.toFixed(1)??"\u2014"} \u203A Hit ${inputs.latestCacheHitRate===void 0?"\u2014":`${inputs.latestCacheHitRate.toFixed(1)}%`}`),mcp?theme.fg("dim",`MCP ${mcp.connected}/${mcp.total}`):"",busy?theme.fg("dim",`${keyText("app.interrupt")} to interrupt`):""],leftWidth,statePriority),borderColor=effortColor??theme.getThinkingBorderColor(this.session.routedModel?.
|
|
271
|
+
thinkingLevel??this.session.thinkingLevel);if(!timingWidth){let remaining=width-visibleWidth(left);return left+borderColor(remaining>0?` ${"\u2500".repeat(remaining-1)}`:"")}return left+borderColor(` ${"\u2500".repeat(width-visibleWidth(left)-timingWidth-4)} `)+timing+borderColor(" \u2500")}renderDetails(width){let inputs=this.renderInputs(width),fields=[...inputs.sidebarVisible?[]:[`${inputs.usageIncomplete?"\u2265":""}$${inputs.cost.toFixed(3)}${inputs.usingSubscription?" (sub)":""}${inputs.usageIncomplete?
|
|
272
|
+
" (usage incomplete)":""}`],`Account ${inputs.accountLabel??"\u2014"}`,`Provider ${this.session.state.model?.provider??"\u2014"}`,`In ${formatTokens2(inputs.input)}`,`Out ${formatTokens2(inputs.output)}`,...inputs.sidebarVisible?[]:[`Cache read ${formatTokens2(inputs.cacheRead)}`,`Cache write ${formatTokens2(inputs.cacheWrite)}`,`Context ${inputs.contextPercent===void 0?"?":`${inputs.contextPercent.toFixed(1)}%`} of ${formatTokens2(inputs.contextWindow)}`],`Model ${inputs.modelName}`];return inputs.
|
|
273
|
+
routedModelId&&inputs.routedModelId!==inputs.modelName&&fields.push(`Routed model ${inputs.routedModelId}`),inputs.experimental&&fields.push(theme.bold(theme.fg("warning","xp"))),width<1?[]:[truncateToWidth(theme.fg("dim",fields.join(" \u203A ")),width,"")]}render(width){if(width<1)return[];if(this.extensionStatusesOnly){let statuses=this.renderInputs(width).extensionStatuses;return statuses.length?[truncateToWidth(statuses.join(" "),width,"")]:[]}let inputs=this.renderInputs(width),known=this.rendered;
|
|
274
|
+
if(known&&sameFooterInputs(known.inputs,inputs))return known.lines.slice();let lines=this.renderLines(inputs);return this.rendered={inputs,lines:lines.slice()},lines}renderLines(inputs){let{width,contextPercent}=inputs,context=`Context ${contextPercent===void 0?"?":`${contextPercent.toFixed(1)}%`}/${formatTokens2(inputs.contextWindow)}`,lines=[truncateToWidth(theme.fg("dim",inputs.identity),width,theme.fg("dim","..."))],{effort,modelName}=inputs,model=modelName,modelFields=[theme.fg("accent",effort)],
|
|
275
|
+
activity=theme.fg("dim",`Last event ${inputs.age}`);if(inputs.accountLabel){let withAccount=`${modelName} [${inputs.accountLabel}]`;visibleWidth(effort)+3+visibleWidth(withAccount)+2+visibleWidth(activity)<=width&&(model=withAccount)}if(modelFields.push(theme.fg("text",model)),inputs.routedModelId!==void 0&&modelFields.push(theme.fg("muted",`\u2192 ${inputs.routedModelId}`)),inputs.provider!==void 0){let provider=theme.fg("dim",`(${inputs.provider})`);visibleWidth([...modelFields,provider].join(
|
|
276
|
+
" \xB7 "))+2+visibleWidth(activity)<=width&&modelFields.push(provider)}lines.push(...this.renderBand(modelFields,activity,width));let contextColor=(contextPercent??0)>90?"error":(contextPercent??0)>70?"warning":"text",{usingSubscription}=inputs,statsParts=inputs.sidebarVisible?[]:[theme.fg(contextColor,context)];!inputs.sidebarVisible&&inputs.usageIncomplete?statsParts.push(theme.fg("muted",`${inputs.cost>0?`\u2265$${inputs.cost.toFixed(3)}`:"Cost unknown"}${usingSubscription?" (sub)":""} (usage\
|
|
277
|
+
incomplete)`)):!inputs.sidebarVisible&&(inputs.cost||usingSubscription)&&statsParts.push(theme.fg("muted",`$${inputs.cost.toFixed(3)}${usingSubscription?" (sub)":""}`)),statsParts.push(theme.fg("dim",`In ${formatTokens2(inputs.input)}`),theme.fg("dim",`Out ${formatTokens2(inputs.output)}`)),inputs.experimental&&statsParts.push(theme.bold(theme.fg("warning","xp"))),lines.push(...this.renderBand(statsParts,void 0,width));let cacheParts=[theme.fg("dim",`Cache read ${formatTokens2(inputs.cacheRead)}`)];
|
|
278
|
+
return inputs.cacheWrite&&cacheParts.push(theme.fg("dim",`Cache write ${formatTokens2(inputs.cacheWrite)}`)),cacheParts.push(theme.fg("dim",`Hit ${inputs.latestCacheHitRate===void 0?"\u2014":`${inputs.latestCacheHitRate.toFixed(1)}%`}`)),inputs.sidebarVisible||lines.push(...this.renderBand(cacheParts,theme.fg("dim","/settings"),width)),inputs.extensionStatuses.length&&lines.push(truncateToWidth(inputs.extensionStatuses.join(" "),width,theme.fg("dim","..."))),lines}renderBand(fields,right,width){
|
|
279
|
+
let lines=[],line="";for(let field of fields)if(line&&visibleWidth(`${line} \xB7 ${field}`)>width&&(lines.push(line),line=""),visibleWidth(field)>width){let wrapped=wrapTextWithAnsi(field,width);lines.push(...wrapped.slice(0,-1)),line=wrapped.at(-1)??""}else line=line?`${line} \xB7 ${field}`:field;if(right)if(line&&visibleWidth(line)+2+visibleWidth(right)<=width)line+=" ".repeat(width-visibleWidth(line)-visibleWidth(right))+right;else{line&&lines.push(line);let wrapped=wrapTextWithAnsi(right,width);
|
|
280
|
+
lines.push(...wrapped.slice(0,-1)),line=wrapped.at(-1)??""}return line&&lines.push(line),lines.map(rendered=>truncateToWidth(rendered,width,""))}};var ModelCatalogRefreshCoordinator=class{activeByRuntime=new WeakMap;hcodeOnlyByRuntime=new WeakMap;checkWatchedHcode(runtime,signal){return this.activeByRuntime.has(runtime)||this.hcodeOnlyByRuntime.has(runtime)?Promise.resolve(void 0):this.refreshHcode(runtime,signal)}refreshHcode(runtime,signal){signal.throwIfAborted();let hcode=this.hcodeOnlyByRuntime.get(runtime);if(hcode)return raceWithAbortSignal(hcode,signal);if(this.activeByRuntime.has(runtime))return this.refresh(runtime,signal).then(({
|
|
172
281
|
aborted,errors})=>({aborted,errors:new Map([...errors].filter(([provider])=>provider===HCODE_PROVIDER))}));let operation=raceWithAbortSignal(runtime.refresh({providers:[HCODE_PROVIDER],signal}),signal).finally(()=>this.hcodeOnlyByRuntime.delete(runtime));return this.hcodeOnlyByRuntime.set(runtime,operation),operation}refresh(modelRuntime,signal){signal.throwIfAborted();let active=this.activeByRuntime.get(modelRuntime);if(!active){let controller=new AbortController,created,hcode=this.hcodeOnlyByRuntime.
|
|
173
282
|
get(modelRuntime),operation=hcode?raceWithAbortSignal(hcode,controller.signal).then(result=>(controller.signal.throwIfAborted(),result.aborted?result:modelRuntime.refresh({signal:controller.signal}))):modelRuntime.refresh({signal:controller.signal}),promise=raceWithAbortSignal(operation,controller.signal).finally(()=>{this.activeByRuntime.get(modelRuntime)===created&&this.activeByRuntime.delete(modelRuntime)});created={controller,promise,waiters:0},active=created,this.activeByRuntime.set(modelRuntime,
|
|
174
283
|
active)}return active.waiters++,raceWithAbortSignal(active.promise,signal).finally(()=>{active.waiters--,active.waiters===0&&this.activeByRuntime.get(modelRuntime)===active&&active.controller.abort()})}},modelCatalogRefreshCoordinator=new ModelCatalogRefreshCoordinator;async function checkWatchedHcodeCatalog(modelRuntime,signal){return modelCatalogRefreshCoordinator.checkWatchedHcode(modelRuntime,signal)}async function retryHcodeCatalog(modelRuntime,signal){return modelCatalogRefreshCoordinator.
|
|
175
284
|
refreshHcode(modelRuntime,signal)}function refreshModelCatalogs(modelRuntime,signal){return modelCatalogRefreshCoordinator.refresh(modelRuntime,signal)}function refreshStartupModelCatalogs(modelRuntime,signal){return signal.throwIfAborted(),raceWithAbortSignal(modelRuntime.refresh({providers:modelRuntime.getProviders().filter(provider=>provider.id!==HCODE_PROVIDER).map(provider=>provider.id),signal}),signal)}var FULLSCREEN_OVERLAY={overlay:!0,overlayOptions:{width:"100%",maxHeight:"100%",margin:0}};function fullscreenSurface(component,height){let render=component.render.bind(component);return component.render=width=>{let lines=render(width);if(lines.length===0)return[];let black="\x1B[48;2;0;0;0m";return Array.from({length:Math.max(0,height())},(_,index)=>{let line=truncateToWidth(lines[index]??"",width);return black+line.replace(/\x1b\[(?:0|49)?m/g,`$&${black}`)+" ".repeat(Math.max(0,width-visibleWidth(
|
|
176
|
-
line)))+"\x1B[0m"})},component}function usagePaneRow(theme2,list,detail,listWidth){return truncateToWidth(list,listWidth,"\u2026",!0)+theme2.fg("dim"," \u2502 ")+detail}function renderUsageBar(theme2,bar,width){let fraction=bar.total&&bar.total>0?Math.min(1,Math.max(0,bar.used/bar.total)):0,filled=Math.round(fraction*width);return theme2.fg(bar.tone,"\u2588".repeat(filled))+theme2.fg("muted","\u2591".repeat(width-filled))}export{HCODE_LOGIN_MISMATCH_DETAILS,hcodeEmptyCatalogMessage,hcodeEmptyCatalogReason,hcodeEmptyCatalogNotice,hcodeLoginAvailability,hcodeSignedInElsewhereNotice,runClipboardCommand,readClipboardText,readClipboardFilePaths,copyToClipboard,AuthUrlComponent,createMcpExtension,mcp_default,trackUserWait,currentUserWait,onUserWaitChange,bindClaudeUsageReconnect,getClaudeUsageReconnect,subscriptionAccountUsage,formatOAuthAccountResetTime,
|
|
177
|
-
buildUsageOverview,formatUsageOverview,weeklyResetLines,paidUsageLines,claudeUsageBars,codexUsageBars,usageAge,readClaudeUsage,nextQuotaResetLines,waitForSignalShutdown,exitAfterSignalShutdown,onUnhandledRejection,onUncaughtErrors,formatUncaughtError,usagePaneRow,renderUsageBar,StatusLineContainer,formatTokens2 as formatTokens,formatCwdForFooter,FooterComponent,checkWatchedHcodeCatalog,retryHcodeCatalog,refreshModelCatalogs,refreshStartupModelCatalogs,
|
|
285
|
+
line)))+"\x1B[0m"})},component}function usagePaneRow(theme2,list,detail,listWidth){return truncateToWidth(list,listWidth,"\u2026",!0)+theme2.fg("dim"," \u2502 ")+detail}function renderUsageBar(theme2,bar,width){let fraction=bar.total&&bar.total>0?Math.min(1,Math.max(0,bar.used/bar.total)):0,filled=Math.round(fraction*width);return theme2.fg(bar.tone,"\u2588".repeat(filled))+theme2.fg("muted","\u2591".repeat(width-filled))}export{HCODE_LOGIN_MISMATCH_DETAILS,hcodeEmptyCatalogMessage,hcodeEmptyCatalogReason,hcodeEmptyCatalogNotice,hcodeLoginAvailability,hcodeSignedInElsewhereNotice,runClipboardCommand,readClipboardText,readClipboardFilePaths,copyToClipboard,AuthUrlComponent,createMcpExtension,mcp_default,trackUserWait,currentUserWait,onUserWaitChange,isChildSession,ConnectionSupervisor,getLiveSessionCount,createCoordinationExtension,bindClaudeUsageReconnect,getClaudeUsageReconnect,subscriptionAccountUsage,formatOAuthAccountResetTime,
|
|
286
|
+
formatOAuthAccountUsage,formatOAuthAccountOption,usageDisplayText,buildUsageOverview,formatUsageOverview,weeklyResetLines,paidUsageLines,claudeUsageBars,codexUsageBars,usageAge,readClaudeUsage,nextQuotaResetLines,waitForSignalShutdown,exitAfterSignalShutdown,onUnhandledRejection,onUncaughtErrors,formatUncaughtError,usagePaneRow,renderUsageBar,StatusLineContainer,formatTokens2 as formatTokens,formatCwdForFooter,FooterComponent,checkWatchedHcodeCatalog,retryHcodeCatalog,refreshModelCatalogs,refreshStartupModelCatalogs,
|
|
287
|
+
FULLSCREEN_OVERLAY,fullscreenSurface};
|
|
@@ -10,7 +10,7 @@ stack,code:typeof code=="string"||typeof code=="number"?code:void 0}}function cr
|
|
|
10
10
|
|
|
11
11
|
${value}`);return parts.join(`
|
|
12
12
|
|
|
13
|
-
`)}function ownedSlice(text,start,end=text.length){return`${text.slice(start,end)} `.slice(0,-1)}var PROVIDER_CLIENT_VERSIONS={claudeCode:"2.1.
|
|
13
|
+
`)}function ownedSlice(text,start,end=text.length){return`${text.slice(start,end)} `.slice(0,-1)}var PROVIDER_CLIENT_VERSIONS={claudeCode:"2.1.333",codex:"0.172.0",copilotChat:"0.48.1",vscode:"1.148.0"},COPILOT_HEADERS={"User-Agent":`GitHubCopilotChat/${PROVIDER_CLIENT_VERSIONS.copilotChat}`,"Editor-Version":`vscode/${PROVIDER_CLIENT_VERSIONS.vscode}`,"Editor-Plugin-Version":`copilot-chat/${PROVIDER_CLIENT_VERSIONS.copilotChat}`,"Copilot-Integration-Id":"vscode-chat"};var CREDENTIAL_HEADER_NAMES=["authorization","api-key","x-api-key","cf-aig-authorization","cookie","proxy-authorization"];function getModelHeaders(model){return model.provider==="github-copilot"?mergeHeaders(model.headers,COPILOT_HEADERS):model.headers}function mergeHeaders(...headerSources){if(headerSources.every(source=>source===void 0))return;let merged={};for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let lowerName=name.toLowerCase();for(let existingName of Object.
|
|
14
14
|
keys(merged))existingName.toLowerCase()===lowerName&&delete merged[existingName];merged[name]=value}return merged}function headersToRecord(headers){let result={};for(let[key,value]of headers.entries())result[key]=value;return result}function providerHeadersToRecord(...headerSources){let merged=new Map;for(let source of headerSources)for(let[name,value]of Object.entries(source??{})){let normalizedName=name.toLowerCase();merged.delete(normalizedName),value!==null&&merged.set(normalizedName,[name,value])}
|
|
15
15
|
return merged.size>0?Object.fromEntries(merged.values()):void 0}var PI_AI_VERSION="1.7.0";var PI_ATTRIBUTION={name:"pi",url:"https://pi.dev",categories:["cli-agent"]},NVIDIA_NIM_HOST="integrate.api.nvidia.com",OPENCODE_HOST="opencode.ai",CLOUDFLARE_API_HOST="api.cloudflare.com",CLOUDFLARE_AI_GATEWAY_HOST="gateway.ai.cloudflare.com",VERCEL_GATEWAY_HOST="ai-gateway.vercel.sh";function mergeClientIdentity(...sources){let merged;for(let source of sources)source&&(merged={...merged},source.userAgent!==void 0&&(merged.userAgent=source.userAgent),source.attribution!==void 0&&(merged.attribution=
|
|
16
16
|
source.attribution),source.version!==void 0&&(merged.version=source.version),source.product!==void 0&&(merged.product=source.product));return merged}function getClientVersion(identity){return identity?.version??PI_AI_VERSION}function getClientProduct(identity){return identity?.product??"pi"}function runtimeDescription(){if(typeof process>"u")return;let versions=process.versions;if(versions?.bun)return`bun/${versions.bun}`;if(versions?.node)return`node/${process.version}`}function formatUserAgent(identity){
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{clampThinkingLevel}from"./chunk-
|
|
2
|
+
import{clampThinkingLevel}from"./chunk-BVBEJBVY.js";import{getSystemMessageText}from"./chunk-H6CKS7HC.js";var UnsupportedStrictJsonSchemaError=class extends Error{},UNSUPPORTED_STRICT_SCHEMA_KEYS=["$ref","$defs","definitions","allOf","oneOf","patternProperties","dependentSchemas","dependencies","unevaluatedProperties","propertyNames","contains","prefixItems","not","if","then","else"];function isJsonSchemaObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isStructuredSchema(schema){if(!isJsonSchemaObject(schema))return!1;let types=typeof schema.type=="string"?[schema.
|
|
3
3
|
type]:Array.isArray(schema.type)?schema.type:[];return types.includes("object")||types.includes("array")||schema.properties!==void 0||schema.items!==void 0}function schemaAllowsNull(schema){return isJsonSchemaObject(schema)?schema.type==="null"||Array.isArray(schema.type)&&schema.type.includes("null")||schema.const===null||Array.isArray(schema.enum)&&schema.enum.includes(null)?!0:Array.isArray(schema.anyOf)&&schema.anyOf.some(variant=>schemaAllowsNull(variant)):!1}function makeJsonSchemaNodeStrict(schema,isUnsupportedKeyword){
|
|
4
4
|
if(!isJsonSchemaObject(schema))throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");for(let key of UNSUPPORTED_STRICT_SCHEMA_KEYS)if(schema[key]!==void 0)throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);if(isUnsupportedKeyword){for(let[key,value]of Object.entries(schema))if(isUnsupportedKeyword(key,value))throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`)}if(schema.type===void 0&&schema.anyOf===void 0&&
|
|
5
5
|
schema.enum===void 0)throw new UnsupportedStrictJsonSchemaError("schemas without a type are unsupported");if(schema.anyOf!==void 0){if(!Array.isArray(schema.anyOf)||schema.anyOf.length===0)throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");for(let variant of schema.anyOf){if(isStructuredSchema(variant))throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");makeJsonSchemaNodeStrict(variant,isUnsupportedKeyword)}}if(schema.items!==void 0){
|