@humain/humain-code 0.4.8 → 0.4.10

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.
Files changed (143) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/bundle/agent-monitor.js +1 -1
  3. package/dist/bundle/chunks/{anthropic-messages-YMPB2HJ7.js → anthropic-messages-UNHXXOD4.js} +3 -3
  4. package/dist/bundle/chunks/{azure-openai-responses-PDHOT7UC.js → azure-openai-responses-4QRYJCC2.js} +2 -2
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +109 -92
  6. package/dist/bundle/chunks/{chunk-GNOKILVU.js → chunk-2QTTNAD4.js} +3385 -3947
  7. package/dist/bundle/chunks/{chunk-II2442A2.js → chunk-5CDES42D.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-IMR3ZJM5.js → chunk-5XD3DHYL.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-RXHSJSYY.js → chunk-6KAMTNN3.js} +1 -1
  10. package/dist/bundle/chunks/chunk-76X5KOIA.js +28 -0
  11. package/dist/bundle/chunks/{chunk-KRMTBTWU.js → chunk-77EWF2NW.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-SKIP6KJV.js → chunk-7Z5MWPYE.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-PBBQBIHY.js → chunk-AS2Y2MO6.js} +37 -37
  14. package/dist/bundle/chunks/{chunk-TIAXGIMN.js → chunk-AUFEF24K.js} +10 -10
  15. package/dist/bundle/chunks/{chunk-ILRBME2Y.js → chunk-BCF7KZ3R.js} +757 -745
  16. package/dist/bundle/chunks/{chunk-WPLW452J.js → chunk-DZ5C66IU.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-2W5PWUPO.js → chunk-EDKZRYWJ.js} +2 -2
  18. package/dist/bundle/chunks/{chunk-W2QRCQBX.js → chunk-FF26YENK.js} +3 -4
  19. package/dist/bundle/chunks/{chunk-UZ5FVVCP.js → chunk-HMWAH7ZY.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-F7UMX5BV.js → chunk-HSDTSUZE.js} +13 -2
  21. package/dist/bundle/chunks/chunk-I2ZWZAIV.js +751 -0
  22. package/dist/bundle/chunks/{chunk-GUUAEK6G.js → chunk-LCOHFEZZ.js} +1 -1
  23. package/dist/bundle/chunks/chunk-MVYV6MJY.js +23 -0
  24. package/dist/bundle/chunks/{chunk-Z5LYSSTY.js → chunk-QSPDLT2R.js} +2 -2
  25. package/dist/bundle/chunks/{chunk-UBQSONVR.js → chunk-R5VIAWGA.js} +103 -145
  26. package/dist/bundle/chunks/{chunk-YURQPD6Y.js → chunk-RYC5BYVE.js} +1 -2
  27. package/dist/bundle/chunks/{chunk-ROSZII6E.js → chunk-V5ZF7Q7L.js} +1 -1
  28. package/dist/bundle/chunks/chunk-VEYTRNQC.js +5 -0
  29. package/dist/bundle/chunks/{chunk-LQ4S7CRR.js → chunk-VYIIPF57.js} +1 -1
  30. package/dist/bundle/chunks/chunk-WBJN6PEI.js +43 -0
  31. package/dist/bundle/chunks/{chunk-SWRU4BOC.js → chunk-XGO43DKL.js} +1 -1
  32. package/dist/bundle/chunks/{chunk-PMISFIBM.js → chunk-XMHLSV3I.js} +1 -1
  33. package/dist/bundle/chunks/{chunk-3E4SMILM.js → chunk-YJBE3IGR.js} +14 -14
  34. package/dist/bundle/chunks/{chunk-OTXURGIO.js → chunk-YKZGL4MB.js} +1 -1
  35. package/dist/bundle/chunks/chunk-Z33NNMNB.js +6 -0
  36. package/dist/bundle/chunks/{cli-ZKT34WPW.js → cli-5ACW3WND.js} +2 -2
  37. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-YPOLSCPT.js → cloudflare-workers-ai-system-one-FZ3UQCZ7.js} +1 -1
  38. package/dist/bundle/chunks/{compat-J5FTRJ6S.js → compat-TQKA4I7M.js} +3 -3
  39. package/dist/bundle/chunks/{dist-N7XDUAAO.js → dist-VNSMKBZ6.js} +3 -3
  40. package/dist/bundle/chunks/{dist-6FQCCUSC.js → dist-WHC67QRM.js} +1077 -912
  41. package/dist/bundle/chunks/dist-cjs-RL2OCAP2.js +179 -0
  42. package/dist/bundle/chunks/{easter-egg-3d-5KKDWEIA.js → easter-egg-3d-3L3IKAT6.js} +1 -1
  43. package/dist/bundle/chunks/{esm-NCUV2DF7.js → esm-763X2IA7.js} +1 -1
  44. package/dist/bundle/chunks/event-streams-R5OECII4.js +2 -0
  45. package/dist/bundle/chunks/{execute-OSBDNQU5.js → execute-4X6G65NZ.js} +1 -1
  46. package/dist/bundle/chunks/{extract-56PXVZVW.js → extract-DLZ425VI.js} +4 -4
  47. package/dist/bundle/chunks/github-copilot.js +32 -31
  48. package/dist/bundle/chunks/{google-generative-ai-TS4ZE2RO.js → google-generative-ai-JD2FVOIX.js} +2 -2
  49. package/dist/bundle/chunks/{google-vertex-MJK2SMNE.js → google-vertex-PFBMDCBW.js} +3 -3
  50. package/dist/bundle/chunks/host-4J7H7KDS.js +2 -0
  51. package/dist/bundle/chunks/{llama-cpp-classify-5KAR326J.js → llama-cpp-classify-AGCW7HYN.js} +1 -1
  52. package/dist/bundle/chunks/{mistral-conversations-XA2ZGSAH.js → mistral-conversations-D74NZ65O.js} +2 -2
  53. package/dist/bundle/chunks/{node-XGNY74WT.js → node-W47VUEGE.js} +1 -1
  54. package/dist/bundle/chunks/{openai-codex-responses-Y6NRWMOI.js → openai-codex-responses-JAAA7MSS.js} +3 -3
  55. package/dist/bundle/chunks/{openai-completions-FY77MIZH.js → openai-completions-PGPMGQPU.js} +34 -33
  56. package/dist/bundle/chunks/{openai-decisions-MKH4OJHH.js → openai-decisions-QQ4MEABI.js} +1 -1
  57. package/dist/bundle/chunks/openai-responses-FG2R2M4L.js +23 -0
  58. package/dist/bundle/chunks/{openrouter-images-R3QMMLPH.js → openrouter-images-NTBP3UUE.js} +1 -1
  59. package/dist/bundle/chunks/{pi-messages-LYJZPRST.js → pi-messages-JD4O7KIP.js} +1 -1
  60. package/dist/bundle/chunks/{runtime-JFLZUNYP.js → runtime-SI76JZNE.js} +1 -1
  61. package/dist/bundle/chunks/{typesafe-system-one-PAYJECQK.js → typesafe-system-one-TTC7YCO3.js} +1 -1
  62. package/dist/bundle/chunks/virtual-modules-ID2GA4GE.js +5 -0
  63. package/dist/bundle/cli-runtime.js +3 -3
  64. package/dist/bundle/flow/assets/contract.json +1 -1
  65. package/dist/bundle/flow/package.json +1 -1
  66. package/dist/bundle/index.js +17 -17
  67. package/dist/bundle/rpc-entry.js +3 -2
  68. package/dist/core/account-reporting.d.ts +109 -0
  69. package/dist/core/account-reporting.d.ts.map +1 -0
  70. package/dist/core/account-reporting.js +328 -0
  71. package/dist/core/account-reporting.js.map +1 -0
  72. package/dist/core/agent-session.d.ts +22 -2
  73. package/dist/core/agent-session.d.ts.map +1 -1
  74. package/dist/core/agent-session.js +131 -0
  75. package/dist/core/agent-session.js.map +1 -1
  76. package/dist/core/anthropic-account-reporting.d.ts +76 -0
  77. package/dist/core/anthropic-account-reporting.d.ts.map +1 -0
  78. package/dist/core/anthropic-account-reporting.js +380 -0
  79. package/dist/core/anthropic-account-reporting.js.map +1 -0
  80. package/dist/core/bedrock-account-reporting.d.ts +82 -0
  81. package/dist/core/bedrock-account-reporting.d.ts.map +1 -0
  82. package/dist/core/bedrock-account-reporting.js +402 -0
  83. package/dist/core/bedrock-account-reporting.js.map +1 -0
  84. package/dist/core/model-runtime.d.ts +17 -0
  85. package/dist/core/model-runtime.d.ts.map +1 -1
  86. package/dist/core/model-runtime.js +64 -10
  87. package/dist/core/model-runtime.js.map +1 -1
  88. package/dist/core/oauth-account-pool.d.ts +4 -0
  89. package/dist/core/oauth-account-pool.d.ts.map +1 -1
  90. package/dist/core/oauth-account-pool.js +10 -3
  91. package/dist/core/oauth-account-pool.js.map +1 -1
  92. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +353 -29
  93. package/dist/humain/flow-accounts-host.d.ts +120 -0
  94. package/dist/humain/flow-accounts-host.d.ts.map +1 -0
  95. package/dist/humain/flow-accounts-host.js +346 -0
  96. package/dist/humain/flow-accounts-host.js.map +1 -0
  97. package/dist/humain/flow-command.d.ts +28 -0
  98. package/dist/humain/flow-command.d.ts.map +1 -0
  99. package/dist/humain/flow-command.js +226 -0
  100. package/dist/humain/flow-command.js.map +1 -0
  101. package/dist/humain/flow-loader.d.ts +4 -2
  102. package/dist/humain/flow-loader.d.ts.map +1 -1
  103. package/dist/humain/flow-loader.js +120 -91
  104. package/dist/humain/flow-loader.js.map +1 -1
  105. package/dist/humain/node-account-failure.d.ts +18 -0
  106. package/dist/humain/node-account-failure.d.ts.map +1 -0
  107. package/dist/humain/node-account-failure.js +73 -0
  108. package/dist/humain/node-account-failure.js.map +1 -0
  109. package/dist/humain/node-account-fallback.d.ts +85 -0
  110. package/dist/humain/node-account-fallback.d.ts.map +1 -0
  111. package/dist/humain/node-account-fallback.js +175 -0
  112. package/dist/humain/node-account-fallback.js.map +1 -0
  113. package/dist/humain/node-http.d.ts.map +1 -1
  114. package/dist/humain/node-http.js +11 -0
  115. package/dist/humain/node-http.js.map +1 -1
  116. package/dist/humain/node-provider.d.ts +4 -0
  117. package/dist/humain/node-provider.d.ts.map +1 -1
  118. package/dist/humain/node-provider.js +11 -0
  119. package/dist/humain/node-provider.js.map +1 -1
  120. package/dist/index.d.ts +4 -0
  121. package/dist/index.d.ts.map +1 -1
  122. package/dist/index.js.map +1 -1
  123. package/dist/modes/interactive/components/login-dialog.d.ts +2 -0
  124. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  125. package/dist/modes/interactive/components/login-dialog.js +5 -0
  126. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  127. package/dist/modes/interactive/interactive-mode.d.ts +26 -0
  128. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  129. package/dist/modes/interactive/interactive-mode.js +242 -19
  130. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  131. package/docs/flow-profiles.md +57 -5
  132. package/docs/flow.md +130 -45
  133. package/docs/providers.md +37 -0
  134. package/npm-shrinkwrap.json +48 -6
  135. package/package.json +3 -2
  136. package/dist/bundle/chunks/chunk-AKA7HNO3.js +0 -4
  137. package/dist/bundle/chunks/chunk-JYWVRJYG.js +0 -6
  138. package/dist/bundle/chunks/chunk-MEIYGK5O.js +0 -6
  139. package/dist/bundle/chunks/chunk-PYU5BR3Z.js +0 -27
  140. package/dist/bundle/chunks/event-streams-CGCQQL5M.js +0 -2
  141. package/dist/bundle/chunks/host-2ARI7PQ5.js +0 -2
  142. package/dist/bundle/chunks/openai-responses-LNSCERKH.js +0 -23
  143. package/dist/bundle/chunks/virtual-modules-TT2VTOSY.js +0 -5
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{classifySystemOne}from"./chunk-RXHSJSYY.js";import{isRecord}from"./chunk-SKIP6KJV.js";import"./chunk-JYWVRJYG.js";import"./chunk-MEIYGK5O.js";import"./chunk-II2442A2.js";import"./chunk-WPLW452J.js";import"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import"./chunk-JXWJOIH4.js";var transport={api:"typesafe-system-one",label:"System One API",url:model=>new URL("systemone",`${model.baseUrl.replace(/\/+$/u,"")}/`),payload:(model,request)=>({model:model.id,...request}),output:body=>{if(!isRecord(body))throw new Error("System One API returned an unexpected response");return body}},classify=(model,context,options)=>classifySystemOne(transport,model,context,options);export{classify};
2
+ import{classifySystemOne}from"./chunk-6KAMTNN3.js";import{isRecord}from"./chunk-7Z5MWPYE.js";import"./chunk-Z33NNMNB.js";import"./chunk-MVYV6MJY.js";import"./chunk-5CDES42D.js";import"./chunk-DZ5C66IU.js";import"./chunk-RYC5BYVE.js";import"./chunk-VEYTRNQC.js";import"./chunk-JXWJOIH4.js";var transport={api:"typesafe-system-one",label:"System One API",url:model=>new URL("systemone",`${model.baseUrl.replace(/\/+$/u,"")}/`),payload:(model,request)=>({model:model.id,...request}),output:body=>{if(!isRecord(body))throw new Error("System One API returned an unexpected response");return body}},classify=(model,context,options)=>classifySystemOne(transport,model,context,options);export{classify};
@@ -0,0 +1,5 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{dist_exports as dist_exports3}from"./chunk-76X5KOIA.js";import{dist_exports as dist_exports2}from"./chunk-2QTTNAD4.js";import"./chunk-HMWAH7ZY.js";import"./chunk-I2ZWZAIV.js";import"./chunk-LCOHFEZZ.js";import"./chunk-77EWF2NW.js";import"./chunk-V5ZF7Q7L.js";import{all_exports,compat_exports}from"./chunk-BCF7KZ3R.js";import"./chunk-QSPDLT2R.js";import"./chunk-HSDTSUZE.js";import"./chunk-XMHLSV3I.js";import{dist_exports}from"./chunk-VYIIPF57.js";
3
+ import"./chunk-SCIGZFN5.js";import"./chunk-WBJN6PEI.js";import"./chunk-R5VIAWGA.js";import"./chunk-KQM7ZGL6.js";import"./chunk-CIA6V3BP.js";import"./chunk-XQZG5HPT.js";import"./chunk-FACBDLFU.js";import"./chunk-AUFEF24K.js";import"./chunk-YJBE3IGR.js";import"./chunk-BRXQUQSC.js";import"./chunk-YKZGL4MB.js";import"./chunk-DBL35X7L.js";import"./chunk-GVVRXZHN.js";import"./chunk-DZ5C66IU.js";import"./chunk-RYC5BYVE.js";
4
+ import"./chunk-VEYTRNQC.js";import{compile_exports,value_exports2 as value_exports}from"./chunk-QMUIATLD.js";import{build_exports}from"./chunk-BHM75BJJ.js";import"./chunk-JXWJOIH4.js";var oauth_exports={};var VIRTUAL_MODULES={typebox:build_exports,"typebox/compile":compile_exports,"typebox/value":value_exports,"@sinclair/typebox":build_exports,"@sinclair/typebox/compile":compile_exports,"@sinclair/typebox/value":value_exports,"@earendil-works/pi-agent-core":dist_exports2,"@earendil-works/pi-tui":dist_exports,"@earendil-works/pi-ai":compat_exports,"@earendil-works/pi-ai/compat":compat_exports,"@earendil-works/pi-ai/oauth":oauth_exports,"@earendil-works/pi-ai/providers/all":all_exports,"@earendil-w\
5
+ orks/pi-coding-agent":dist_exports3,"@mariozechner/pi-agent-core":dist_exports2,"@mariozechner/pi-tui":dist_exports,"@mariozechner/pi-ai":compat_exports,"@mariozechner/pi-ai/compat":compat_exports,"@mariozechner/pi-ai/oauth":oauth_exports,"@mariozechner/pi-ai/providers/all":all_exports,"@mariozechner/pi-coding-agent":dist_exports3};export{VIRTUAL_MODULES};
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
3
- import{configureHttpDispatcher,main,warnIfDeprecatedCommand}from"./chunks/chunk-GNOKILVU.js";import"./chunks/chunk-UZ5FVVCP.js";import"./chunks/chunk-KRMTBTWU.js";import"./chunks/chunk-UBQSONVR.js";import"./chunks/chunk-ROSZII6E.js";import"./chunks/chunk-ILRBME2Y.js";import"./chunks/chunk-Z5LYSSTY.js";import"./chunks/chunk-F7UMX5BV.js";import"./chunks/chunk-PMISFIBM.js";import"./chunks/chunk-GUUAEK6G.js";import"./chunks/chunk-LQ4S7CRR.js";import"./chunks/chunk-SCIGZFN5.js";import"./chunks/chunk-KQM7ZGL6.js";
4
- import"./chunks/chunk-CIA6V3BP.js";import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import"./chunks/chunk-TIAXGIMN.js";import{APP_COMMAND,ENV_PREFIX}from"./chunks/chunk-3E4SMILM.js";import"./chunks/chunk-BRXQUQSC.js";import"./chunks/chunk-OTXURGIO.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-GVVRXZHN.js";import"./chunks/chunk-WPLW452J.js";import"./chunks/chunk-YURQPD6Y.js";import"./chunks/chunk-AKA7HNO3.js";import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";
5
- import"./chunks/chunk-JXWJOIH4.js";function setupCli(){process.title=APP_COMMAND,process.env.PI_CODING_AGENT="true",process.env[`${ENV_PREFIX}_CODING_AGENT`]="true",process.env.AI_AGENT="pi",process.emitWarning=(()=>{}),configureHttpDispatcher()}setupCli();warnIfDeprecatedCommand(process.argv.slice(2));main(process.argv.slice(2));
3
+ import{configureHttpDispatcher,main,warnIfDeprecatedCommand}from"./chunks/chunk-2QTTNAD4.js";import"./chunks/chunk-HMWAH7ZY.js";import"./chunks/chunk-I2ZWZAIV.js";import"./chunks/chunk-LCOHFEZZ.js";import"./chunks/chunk-77EWF2NW.js";import"./chunks/chunk-V5ZF7Q7L.js";import"./chunks/chunk-BCF7KZ3R.js";import"./chunks/chunk-QSPDLT2R.js";import"./chunks/chunk-HSDTSUZE.js";import"./chunks/chunk-XMHLSV3I.js";import"./chunks/chunk-VYIIPF57.js";import"./chunks/chunk-SCIGZFN5.js";import"./chunks/chunk-WBJN6PEI.js";
4
+ import"./chunks/chunk-R5VIAWGA.js";import"./chunks/chunk-KQM7ZGL6.js";import"./chunks/chunk-CIA6V3BP.js";import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import"./chunks/chunk-AUFEF24K.js";import{APP_COMMAND,ENV_PREFIX}from"./chunks/chunk-YJBE3IGR.js";import"./chunks/chunk-BRXQUQSC.js";import"./chunks/chunk-YKZGL4MB.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-GVVRXZHN.js";import"./chunks/chunk-DZ5C66IU.js";import"./chunks/chunk-RYC5BYVE.js";import"./chunks/chunk-VEYTRNQC.js";
5
+ import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";import"./chunks/chunk-JXWJOIH4.js";function setupCli(){process.title=APP_COMMAND,process.env.PI_CODING_AGENT="true",process.env[`${ENV_PREFIX}_CODING_AGENT`]="true",process.env.AI_AGENT="pi",process.emitWarning=(()=>{}),configureHttpDispatcher()}setupCli();warnIfDeprecatedCommand(process.argv.slice(2));main(process.argv.slice(2));
@@ -6,7 +6,7 @@
6
6
  "dispatch_finished": {
7
7
  "fields": ["outcome", "timeout_reason", "failure_class", "provider", "provider_model", "error_code"],
8
8
  "outcome_values": ["completed", "completed_after_process_error", "failed", "timed_out", "cancelled"],
9
- "failure_class_values": ["provider_stall", "wait_stall", "transient", "quota", "task", "cancelled"],
9
+ "failure_class_values": ["provider_stall", "wait_stall", "transient", "provider_unreachable", "quota", "task", "cancelled"],
10
10
  "_note": "Existing model remains the full dispatch model id; provider_model is its short normalized component. Optional failure_class only applies to non-successful dispositions."
11
11
  },
12
12
  "provider_error": {
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "dependencies": {
30
30
  "@earendil-works/pi-tui": "1.1.0",
31
- "@humain/humain-code-contracts": "0.4.8",
31
+ "@humain/humain-code-contracts": "0.4.10",
32
32
  "typebox": "1.3.35"
33
33
  },
34
34
  "devDependencies": {
@@ -1,18 +1,18 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-PYU5BR3Z.js";import{ACCOUNT_RETURN_COOLDOWN_MS,ACCOUNT_RETURN_MAX_COOLDOWN_MS,AgentExecInputError,AgentSession,AgentSessionRuntime,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,
3
- ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthAccountPool,OAuthSelectorComponent,RpcClient,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,VIRTUAL_MODEL_STATE_ENTRY,calculateContextTokens,collectEntriesForBranchSummary,
4
- compact,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPiAgentExecutionHost,
5
- createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSubagentTool,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAgents,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,findTurnStartIndex,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,
6
- getFlowChildLaunchHost,getFlowControlHost,getFlowTraceProducer,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,parseArgs,parseFrontmatter,parseSkillBlock,prepareBranchEntries,prepareChildLaunch,renderDiff,renderTaskWithContext,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,
7
- serializeConversation,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-GNOKILVU.js";import"./chunks/chunk-UZ5FVVCP.js";import{ProjectTrustStore,hasTrustRequiringProjectResources}from"./chunks/chunk-KRMTBTWU.js";import"./chunks/chunk-UBQSONVR.js";import{CURRENT_SESSION_VERSION,SessionManager,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,formatDimensionNote,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,
8
- resizeImage,sessionEntryToContextMessages}from"./chunks/chunk-ROSZII6E.js";import"./chunks/chunk-ILRBME2Y.js";import"./chunks/chunk-Z5LYSSTY.js";import{readStoredCredential}from"./chunks/chunk-F7UMX5BV.js";import{DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,formatSize,getPowerShellConfig,getShellConfig,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-PMISFIBM.js";import{ArminComponent}from"./chunks/chunk-GUUAEK6G.js";import{Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,
9
- getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-LQ4S7CRR.js";import"./chunks/chunk-SCIGZFN5.js";import"./chunks/chunk-KQM7ZGL6.js";import"./chunks/chunk-CIA6V3BP.js";import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import{HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,
10
- HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse}from"./chunks/chunk-TIAXGIMN.js";import{CONFIG_DIR_NAME,UPSTREAM_PI_VERSION,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-3E4SMILM.js";import"./chunks/chunk-BRXQUQSC.js";import"./chunks/chunk-OTXURGIO.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-GVVRXZHN.js";import"./chunks/chunk-WPLW452J.js";
11
- import"./chunks/chunk-YURQPD6Y.js";import"./chunks/chunk-AKA7HNO3.js";import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";import"./chunks/chunk-JXWJOIH4.js";export{ACCOUNT_RETURN_COOLDOWN_MS,ACCOUNT_RETURN_MAX_COOLDOWN_MS,AgentExecInputError,AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,
12
- ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FooterComponent,HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthAccountPool,
13
- OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UPSTREAM_PI_VERSION,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,buildContextEntries,buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,
14
- compact,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,
15
- createPiAgentExecutionHost,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSubagentTool,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAgents,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,findTurnStartIndex,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,
16
- generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getFlowChildLaunchHost,getFlowControlHost,getFlowTraceProducer,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,
17
- isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFrontmatter,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse,parseSessionEntries,parseSkillBlock,prepareBranchEntries,prepareChildLaunch,rawKeyHint,readStoredCredential,renderDiff,renderTaskWithContext,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,serializeConversation,
18
- sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
2
+ import{ShowImagesSelectorComponent,ThemeSelectorComponent}from"./chunks/chunk-76X5KOIA.js";import{ACCOUNT_RETURN_COOLDOWN_MS,ACCOUNT_RETURN_MAX_COOLDOWN_MS,AgentExecInputError,AgentSession,AgentSessionRuntime,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,
3
+ ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FLOW_ACCOUNT_PERSISTENCE_NOTICE,FLOW_SETUP_TERMINAL_ONLY,FLOW_SUBCOMMANDS,FooterComponent,InteractiveMode,LoginDialogComponent,ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthAccountPool,OAuthSelectorComponent,RpcClient,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,SkillInvocationMessageComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UserMessageComponent,UserMessageSelectorComponent,
4
+ VIRTUAL_MODEL_STATE_ENTRY,assessNodeFallback,calculateContextTokens,collectEntriesForBranchSummary,compact,completeFlowArguments,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,
5
+ createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPiAgentExecutionHost,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSubagentTool,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAgents,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,
6
+ findTurnStartIndex,flowBuildUnavailable,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getFlowAccountsHost,getFlowChildLaunchHost,getFlowControlHost,getFlowTraceProducer,getLastAssistantUsage,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,parseArgs,parseFlowCommand,
7
+ parseFrontmatter,parseSkillBlock,prepareBranchEntries,prepareChildLaunch,renderDiff,renderFlowHelp,renderTaskWithContext,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,serializeConversation,shouldCompact,stripFrontmatter,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools}from"./chunks/chunk-2QTTNAD4.js";import"./chunks/chunk-HMWAH7ZY.js";import"./chunks/chunk-I2ZWZAIV.js";import{ArminComponent}from"./chunks/chunk-LCOHFEZZ.js";import{ProjectTrustStore,
8
+ hasTrustRequiringProjectResources}from"./chunks/chunk-77EWF2NW.js";import{CURRENT_SESSION_VERSION,SessionManager,buildContextEntries,buildSessionContext,buildSessionProjection,convertToLlm,formatDimensionNote,getLatestCompactionEntry,migrateSessionEntries,parseSessionEntries,resizeImage,sessionEntryToContextMessages}from"./chunks/chunk-V5ZF7Q7L.js";import"./chunks/chunk-BCF7KZ3R.js";import"./chunks/chunk-QSPDLT2R.js";import{readStoredCredential}from"./chunks/chunk-HSDTSUZE.js";import{DEFAULT_MAX_BYTES,
9
+ DEFAULT_MAX_LINES,formatSize,getPowerShellConfig,getShellConfig,truncateHead,truncateLine,truncateTail,truncateToVisualLines}from"./chunks/chunk-XMHLSV3I.js";import{Theme,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getSettingsListTheme,highlightCode,initTheme,keyHint,keyText,rawKeyHint}from"./chunks/chunk-VYIIPF57.js";import"./chunks/chunk-SCIGZFN5.js";import"./chunks/chunk-WBJN6PEI.js";import"./chunks/chunk-R5VIAWGA.js";import"./chunks/chunk-KQM7ZGL6.js";import"./chunks/chunk-CIA6V3BP.js";
10
+ import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import{HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse}from"./chunks/chunk-AUFEF24K.js";import{
11
+ CONFIG_DIR_NAME,UPSTREAM_PI_VERSION,VERSION,getAgentDir,getDocsPath,getExamplesPath,getPackageDir,getReadmePath}from"./chunks/chunk-YJBE3IGR.js";import"./chunks/chunk-BRXQUQSC.js";import"./chunks/chunk-YKZGL4MB.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-GVVRXZHN.js";import"./chunks/chunk-DZ5C66IU.js";import"./chunks/chunk-RYC5BYVE.js";import"./chunks/chunk-VEYTRNQC.js";import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";import"./chunks/chunk-JXWJOIH4.js";export{ACCOUNT_RETURN_COOLDOWN_MS,ACCOUNT_RETURN_MAX_COOLDOWN_MS,AgentExecInputError,AgentSession,AgentSessionRuntime,ArminComponent,AssistantMessageComponent,BashExecutionComponent,BorderedLoader,BranchSummaryMessageComponent,CONFIG_DIR_NAME,CURRENT_SESSION_VERSION,CompactionSummaryMessageComponent,CredentialSynchronizationError,CustomEditor,CustomMessageComponent,DEFAULT_COMPACTION_SETTINGS,DEFAULT_MAX_BYTES,DEFAULT_MAX_LINES,DefaultPackageManager,DefaultResourceLoader,DynamicBorder,ExtensionEditorComponent,
12
+ ExtensionInputComponent,ExtensionRunner,ExtensionSelectorComponent,FLOW_ACCOUNT_PERSISTENCE_NOTICE,FLOW_SETUP_TERMINAL_ONLY,FLOW_SUBCOMMANDS,FooterComponent,HUMAIN_AGENT_EXECUTION_FAILURE_CODES,HUMAIN_AGENT_EXECUTION_SCHEMA_VERSION,HumainAgentArtifactSchema,HumainAgentExecutionClaimSchema,HumainAgentExecutionControlsSchema,HumainAgentExecutionOutcomeSchema,HumainAgentExecutionRequestSchema,HumainAgentExecutionResponseSchema,HumainAgentRouteRefSchema,HumainAgentUsageSchema,InteractiveMode,LoginDialogComponent,
13
+ ModelRegistry,ModelRuntime,ModelSelectorComponent,OAuthAccountPool,OAuthSelectorComponent,ProjectTrustStore,RpcClient,SessionManager,SessionSelectorComponent,SettingsManager,SettingsSelectorComponent,ShowImagesSelectorComponent,SkillInvocationMessageComponent,Theme,ThemeSelectorComponent,ThinkingSelectorComponent,ToolExecutionComponent,TreeSelectorComponent,UPSTREAM_PI_VERSION,UserMessageComponent,UserMessageSelectorComponent,VERSION,VIRTUAL_MODEL_STATE_ENTRY,assessNodeFallback,buildContextEntries,
14
+ buildSessionContext,buildSessionProjection,calculateContextTokens,collectEntriesForBranchSummary,compact,completeFlowArguments,convertToLlm,convertToPng,copyToClipboard,createAgentSession,createAgentSessionFromServices,createAgentSessionRuntime,createAgentSessionServices,createBashTool,createBashToolDefinition,createCodemodeExtension,createCodingTools,createEditTool,createEditToolDefinition,createEventBus,createExtensionRuntime,createFindTool,createFindToolDefinition,createGrepTool,createGrepToolDefinition,
15
+ createLocalBashOperations,createLocalPowerShellOperations,createLsTool,createLsToolDefinition,createMcpExtension,createPiAgentExecutionHost,createPowerShellTool,createPowerShellToolDefinition,createReadOnlyTools,createReadTool,createReadToolDefinition,createSubagentTool,createSyntheticSourceInfo,createToolSearchExtension,createWriteTool,createWriteToolDefinition,defineTool,detectSupportedImageMimeTypeFromFile,discoverAgents,discoverAndLoadExtensions,estimateTokens,executeHumainAgentRequest,findCutPoint,
16
+ findTurnStartIndex,flowBuildUnavailable,formatDimensionNote,formatSize,formatSkillsForPrompt,generateBranchSummary,generateDiffString,generateSummary,generateSummaryWithUsage,generateUnifiedPatch,getAgentDir,getDocsPath,getExamplesPath,getFlowAccountsHost,getFlowChildLaunchHost,getFlowControlHost,getFlowTraceProducer,getLanguageFromPath,getLastAssistantUsage,getLatestCompactionEntry,getMarkdownTheme,getPackageDir,getPowerShellConfig,getReadmePath,getSelectListTheme,getSettingsListTheme,getShellConfig,
17
+ hasTrustRequiringProjectResources,highlightCode,initTheme,isBashToolResult,isEditToolResult,isFindToolResult,isGrepToolResult,isLsToolResult,isPowerShellToolResult,isReadToolResult,isToolCallEventType,isWriteToolResult,keyHint,keyText,loadProjectContextFiles,loadSkills,loadSkillsFromDir,main,migrateSessionEntries,parseArgs,parseFlowCommand,parseFrontmatter,parseHumainAgentExecutionRequest,parseHumainAgentExecutionResponse,parseSessionEntries,parseSkillBlock,prepareBranchEntries,prepareChildLaunch,
18
+ rawKeyHint,readStoredCredential,renderDiff,renderFlowHelp,renderTaskWithContext,resizeImage,resolveCliModel,resolveModelScopeWithDiagnostics,runAgentExecMode,runPrintMode,runRpcMode,serializeConversation,sessionEntryToContextMessages,shouldCompact,stripFrontmatter,truncateHead,truncateLine,truncateTail,truncateToVisualLines,withFileMutationQueue,wrapRegisteredTool,wrapRegisteredTools};
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
3
- import{configureHttpDispatcher,main}from"./chunks/chunk-GNOKILVU.js";import"./chunks/chunk-UZ5FVVCP.js";import"./chunks/chunk-KRMTBTWU.js";import"./chunks/chunk-UBQSONVR.js";import"./chunks/chunk-ROSZII6E.js";import"./chunks/chunk-ILRBME2Y.js";import"./chunks/chunk-Z5LYSSTY.js";import"./chunks/chunk-F7UMX5BV.js";import"./chunks/chunk-PMISFIBM.js";import"./chunks/chunk-GUUAEK6G.js";import"./chunks/chunk-LQ4S7CRR.js";import"./chunks/chunk-SCIGZFN5.js";import"./chunks/chunk-KQM7ZGL6.js";import"./chunks/chunk-CIA6V3BP.js";
4
- import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import"./chunks/chunk-TIAXGIMN.js";import{APP_COMMAND}from"./chunks/chunk-3E4SMILM.js";import"./chunks/chunk-BRXQUQSC.js";import"./chunks/chunk-OTXURGIO.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-GVVRXZHN.js";import"./chunks/chunk-WPLW452J.js";import"./chunks/chunk-YURQPD6Y.js";import"./chunks/chunk-AKA7HNO3.js";import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";import"./chunks/chunk-JXWJOIH4.js";process.title=`${APP_COMMAND}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
3
+ import{configureHttpDispatcher,main}from"./chunks/chunk-2QTTNAD4.js";import"./chunks/chunk-HMWAH7ZY.js";import"./chunks/chunk-I2ZWZAIV.js";import"./chunks/chunk-LCOHFEZZ.js";import"./chunks/chunk-77EWF2NW.js";import"./chunks/chunk-V5ZF7Q7L.js";import"./chunks/chunk-BCF7KZ3R.js";import"./chunks/chunk-QSPDLT2R.js";import"./chunks/chunk-HSDTSUZE.js";import"./chunks/chunk-XMHLSV3I.js";import"./chunks/chunk-VYIIPF57.js";import"./chunks/chunk-SCIGZFN5.js";import"./chunks/chunk-WBJN6PEI.js";import"./chunks/chunk-R5VIAWGA.js";
4
+ import"./chunks/chunk-KQM7ZGL6.js";import"./chunks/chunk-CIA6V3BP.js";import"./chunks/chunk-XQZG5HPT.js";import"./chunks/chunk-FACBDLFU.js";import"./chunks/chunk-AUFEF24K.js";import{APP_COMMAND}from"./chunks/chunk-YJBE3IGR.js";import"./chunks/chunk-BRXQUQSC.js";import"./chunks/chunk-YKZGL4MB.js";import"./chunks/chunk-DBL35X7L.js";import"./chunks/chunk-GVVRXZHN.js";import"./chunks/chunk-DZ5C66IU.js";import"./chunks/chunk-RYC5BYVE.js";import"./chunks/chunk-VEYTRNQC.js";import"./chunks/chunk-QMUIATLD.js";import"./chunks/chunk-BHM75BJJ.js";
5
+ import"./chunks/chunk-JXWJOIH4.js";process.title=`${APP_COMMAND}-rpc`;process.env.PI_CODING_AGENT="true";process.env.AI_AGENT="pi";process.emitWarning=(()=>{});configureHttpDispatcher();main(["--mode","rpc",...process.argv.slice(2)]);
@@ -0,0 +1,109 @@
1
+ import type { OAuthAccount } from "./oauth-account-pool.ts";
2
+ /**
3
+ * Host-owned, consent-bound account reporting. Nothing here runs unless the host calls `refreshAccountUsage` after an
4
+ * explicit "Refresh usage" action. Listing accounts or opening Advanced never reaches this module.
5
+ *
6
+ * Reports never fabricate zero: unavailable, empty, partial and stale states keep their own labels, and every report
7
+ * names its scope (source), target (account/source, region, UTC period) and last update time.
8
+ */
9
+ export declare const ACCOUNT_REPORT_DEADLINE_MS = 30000;
10
+ export declare const ACCOUNT_REPORT_REQUEST_TIMEOUT_MS = 10000;
11
+ export declare const ACCOUNT_REPORT_CACHE_TTL_MS = 60000;
12
+ export interface AccountReportPeriod {
13
+ /** UTC, RFC 3339 with a `Z` suffix. */
14
+ start: string;
15
+ /** UTC, RFC 3339 with a `Z` suffix. Exclusive. */
16
+ end: string;
17
+ }
18
+ export interface AccountReportTarget {
19
+ providerId: string;
20
+ /** Opaque account identity. Never a credential. Empty only when `source` names a non-account reporting source. */
21
+ accountKey: string;
22
+ /** Explicit reporting source that is not an account (for example organization-wide reporting). */
23
+ source?: string;
24
+ /** Region for providers whose figures are regional (for example Bedrock). */
25
+ region?: string;
26
+ period: AccountReportPeriod;
27
+ }
28
+ export type AccountReportStatus = "ok" | "partial" | "empty" | "unavailable";
29
+ /** What a report measures. Distinct scopes are never merged or linked to each other. */
30
+ export type AccountReportScope = "openai-codex-oauth-usage" | "anthropic-api-rate-limits" | "anthropic-organization-usage" | "bedrock-cloudwatch" | "unsupported";
31
+ export interface AccountUsageMetric {
32
+ name: string;
33
+ value: number;
34
+ unit: string;
35
+ /** UTC RFC 3339 time when the window this metric belongs to resets, when the source reports one. */
36
+ resetsAt?: string;
37
+ }
38
+ export interface AccountUsageReport {
39
+ status: AccountReportStatus;
40
+ target: AccountReportTarget;
41
+ scope: AccountReportScope;
42
+ /** Epoch ms of the observation: when the source answered, or when the observed response arrived. */
43
+ updatedAt?: number;
44
+ /** Present metrics only. Missing data is never listed as zero. */
45
+ metrics: AccountUsageMetric[];
46
+ /** Safe, fixed text. Never raw provider or transport errors. */
47
+ reason?: string;
48
+ /** Specific next action for the user, when one exists. */
49
+ nextAction?: string;
50
+ /** True when the observation is older than the cache window or a later refresh failed. */
51
+ stale?: boolean;
52
+ }
53
+ export interface AccountReportCollector {
54
+ /** Scope this collector reports for the target, used to label unavailable states too. */
55
+ scopeFor(target: AccountReportTarget): AccountReportScope;
56
+ /** Collect one report. Must honour the signal and return only safe reasons. */
57
+ collect(target: AccountReportTarget, signal: AbortSignal): Promise<AccountUsageReport>;
58
+ /** Return false for targets whose `collect` only reads local state, so every refresh sees the newest observation. */
59
+ cachesTarget?(target: AccountReportTarget): boolean;
60
+ }
61
+ export declare function unavailableReport(target: AccountReportTarget, scope: AccountReportScope, reason: string, nextAction?: string): AccountUsageReport;
62
+ export interface AccountReporterOptions {
63
+ /** Collectors by provider ID. Providers without one report "unsupported". */
64
+ collectors: Readonly<Record<string, AccountReportCollector>>;
65
+ /** Injected clock (epoch ms). Defaults to Date.now. */
66
+ now?: () => number;
67
+ deadlineMs?: number;
68
+ cacheTtlMs?: number;
69
+ }
70
+ /**
71
+ * Session-bound reporter. Late results of a superseded or cancelled refresh are discarded and never cached; caches are
72
+ * isolated by provider, account/source, region and period.
73
+ */
74
+ export declare class AccountReporter {
75
+ private readonly collectors;
76
+ private readonly now;
77
+ private readonly deadlineMs;
78
+ private readonly ttlMs;
79
+ private readonly cache;
80
+ /** One in-flight refresh per provider and scope (and explicit source): a different target there supersedes it. */
81
+ private readonly inFlight;
82
+ constructor(options: AccountReporterOptions);
83
+ /** Cancel every in-flight refresh (session, account or dialog change). Their results are discarded. */
84
+ cancelAll(): void;
85
+ refreshAccountUsage(target: AccountReportTarget, signal: AbortSignal): Promise<AccountUsageReport>;
86
+ private start;
87
+ /**
88
+ * Each caller cancels independently: the shared collection is aborted only once every attached caller has aborted.
89
+ * An aborted caller gets its own cancelled report while others still receive the shared result.
90
+ */
91
+ private attach;
92
+ private settle;
93
+ /** Mark observations older than the cache window stale; never alters the metrics or times. */
94
+ private label;
95
+ }
96
+ /** Render a report for Advanced. Always names source/scope, account, period, region and update time. */
97
+ export declare function formatAccountUsageReport(report: AccountUsageReport, now: number): string[];
98
+ export interface CodexUsageCollectorDeps {
99
+ /** Stored Codex account for a pool key. No OAuth refresh happens here: expired sign-ins are reported as expired. */
100
+ readAccount(accountKey: string, signal: AbortSignal): Promise<OAuthAccount | undefined>;
101
+ fetch?: typeof fetch;
102
+ now?: () => number;
103
+ }
104
+ /**
105
+ * Reuses the existing Codex weekly usage fetcher for one `openai-codex` OAuth account. `openai` API-key accounts are a
106
+ * different provider and have no collector here: their usage is never inferred from Codex sign-ins.
107
+ */
108
+ export declare function createCodexUsageCollector(deps: CodexUsageCollectorDeps): AccountReportCollector;
109
+ //# sourceMappingURL=account-reporting.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"account-reporting.d.ts","sourceRoot":"","sources":["../../src/core/account-reporting.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,328 @@
1
+ import { CODEX_USAGE_PROVIDER_ID, fetchCodexWeeklyUsage } from "./codex-usage.js";
2
+ /**
3
+ * Host-owned, consent-bound account reporting. Nothing here runs unless the host calls `refreshAccountUsage` after an
4
+ * explicit "Refresh usage" action. Listing accounts or opening Advanced never reaches this module.
5
+ *
6
+ * Reports never fabricate zero: unavailable, empty, partial and stale states keep their own labels, and every report
7
+ * names its scope (source), target (account/source, region, UTC period) and last update time.
8
+ */
9
+ export const ACCOUNT_REPORT_DEADLINE_MS = 30_000;
10
+ export const ACCOUNT_REPORT_REQUEST_TIMEOUT_MS = 10_000;
11
+ export const ACCOUNT_REPORT_CACHE_TTL_MS = 60_000;
12
+ const MAX_CACHE_ENTRIES = 64;
13
+ const MAX_ACCOUNT_KEY_LENGTH = 256;
14
+ const MAX_PROVIDER_ID_LENGTH = 128;
15
+ const MAX_LABEL_LENGTH = 64;
16
+ // C0/C1 controls, DEL and Unicode line/paragraph separators: they would reach the terminal or cache keys verbatim.
17
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;
18
+ export function unavailableReport(target, scope, reason, nextAction) {
19
+ return { status: "unavailable", target, scope, metrics: [], reason, ...(nextAction ? { nextAction } : {}) };
20
+ }
21
+ const UTC_INSTANT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/;
22
+ function utcInstantMs(value) {
23
+ if (typeof value !== "string" || !UTC_INSTANT.test(value))
24
+ return undefined;
25
+ const ms = Date.parse(value);
26
+ return Number.isFinite(ms) ? ms : undefined;
27
+ }
28
+ function validText(value, minLength, maxLength) {
29
+ return (typeof value === "string" &&
30
+ value.length >= minLength &&
31
+ value.length <= maxLength &&
32
+ !CONTROL_CHARACTERS.test(value));
33
+ }
34
+ function targetProblem(target) {
35
+ if (!validText(target.providerId, 1, MAX_PROVIDER_ID_LENGTH))
36
+ return "invalid report target";
37
+ if (target.source !== undefined && !validText(target.source, 1, MAX_LABEL_LENGTH))
38
+ return "invalid report target";
39
+ if (!validText(target.accountKey, target.source === undefined ? 1 : 0, MAX_ACCOUNT_KEY_LENGTH)) {
40
+ return "invalid report target";
41
+ }
42
+ if (target.region !== undefined && !validText(target.region, 1, MAX_LABEL_LENGTH))
43
+ return "invalid report target";
44
+ const start = utcInstantMs(target.period?.start);
45
+ const end = utcInstantMs(target.period?.end);
46
+ if (start === undefined || end === undefined || start >= end)
47
+ return "invalid reporting period";
48
+ return undefined;
49
+ }
50
+ /** A target that failed validation, made safe to echo into a report: no control characters, bounded length. */
51
+ function sanitizedTarget(target) {
52
+ const clean = (value, max) => typeof value === "string" ? value.replace(new RegExp(CONTROL_CHARACTERS, "g"), "?").slice(0, max) : "";
53
+ return {
54
+ providerId: clean(target?.providerId, MAX_PROVIDER_ID_LENGTH),
55
+ accountKey: clean(target?.accountKey, MAX_ACCOUNT_KEY_LENGTH),
56
+ ...(typeof target?.source === "string" ? { source: clean(target.source, MAX_LABEL_LENGTH) } : {}),
57
+ ...(typeof target?.region === "string" ? { region: clean(target.region, MAX_LABEL_LENGTH) } : {}),
58
+ period: { start: clean(target?.period?.start, 40), end: clean(target?.period?.end, 40) },
59
+ };
60
+ }
61
+ function cacheKey(target) {
62
+ return JSON.stringify([
63
+ target.providerId,
64
+ target.accountKey,
65
+ target.source ?? null,
66
+ target.region ?? null,
67
+ target.period.start,
68
+ target.period.end,
69
+ ]);
70
+ }
71
+ /**
72
+ * Session-bound reporter. Late results of a superseded or cancelled refresh are discarded and never cached; caches are
73
+ * isolated by provider, account/source, region and period.
74
+ */
75
+ export class AccountReporter {
76
+ collectors;
77
+ now;
78
+ deadlineMs;
79
+ ttlMs;
80
+ cache = new Map();
81
+ /** One in-flight refresh per provider and scope (and explicit source): a different target there supersedes it. */
82
+ inFlight = new Map();
83
+ constructor(options) {
84
+ this.collectors = options.collectors;
85
+ this.now = options.now ?? Date.now;
86
+ this.deadlineMs = options.deadlineMs ?? ACCOUNT_REPORT_DEADLINE_MS;
87
+ this.ttlMs = options.cacheTtlMs ?? ACCOUNT_REPORT_CACHE_TTL_MS;
88
+ }
89
+ /** Cancel every in-flight refresh (session, account or dialog change). Their results are discarded. */
90
+ cancelAll() {
91
+ for (const entry of this.inFlight.values())
92
+ entry.controller.abort();
93
+ this.inFlight.clear();
94
+ }
95
+ refreshAccountUsage(target, signal) {
96
+ const problem = targetProblem(target);
97
+ if (problem)
98
+ return Promise.resolve(unavailableReport(sanitizedTarget(target), "unsupported", problem));
99
+ const collector = Object.hasOwn(this.collectors, target.providerId)
100
+ ? this.collectors[target.providerId]
101
+ : undefined;
102
+ if (!collector) {
103
+ return Promise.resolve(unavailableReport(target, "unsupported", `usage reporting is not supported for ${target.providerId}`));
104
+ }
105
+ const key = cacheKey(target);
106
+ const useCache = collector.cachesTarget?.(target) !== false;
107
+ const cached = useCache ? this.cache.get(key) : undefined;
108
+ if (cached && this.now() - cached.fetchedAt < this.ttlMs)
109
+ return Promise.resolve(this.label(cached.report));
110
+ const scope = collector.scopeFor(target);
111
+ // Different scopes of one provider (for example organization reporting and selected-key limits) run independently.
112
+ const slot = JSON.stringify([target.providerId, scope, target.source ?? null]);
113
+ let running = this.inFlight.get(slot);
114
+ if (running && (running.key !== key || running.controller.signal.aborted)) {
115
+ running.controller.abort();
116
+ running = undefined;
117
+ }
118
+ if (!running) {
119
+ running = this.start(slot, key, useCache, target, scope, collector);
120
+ this.inFlight.set(slot, running);
121
+ }
122
+ return this.attach(running, signal, target, scope);
123
+ }
124
+ start(slot, key, useCache, target, scope, collector) {
125
+ const controller = new AbortController();
126
+ const combined = AbortSignal.any([controller.signal, AbortSignal.timeout(this.deadlineMs)]);
127
+ const promise = (async () => {
128
+ let report;
129
+ try {
130
+ report = await collector.collect(target, combined);
131
+ }
132
+ catch {
133
+ // Collector failures can carry URLs or credentials: report only a fixed category.
134
+ report = unavailableReport(target, scope, "the usage lookup failed");
135
+ }
136
+ if (controller.signal.aborted)
137
+ return unavailableReport(target, scope, "the usage refresh was cancelled");
138
+ if (combined.aborted) {
139
+ // Deadline: keep pages already gathered, labelled partial and never cached so the next refresh retries.
140
+ if ((report.status === "ok" || report.status === "partial") && report.metrics.length > 0) {
141
+ return this.label({
142
+ ...report,
143
+ target,
144
+ status: "partial",
145
+ reason: "the usage refresh timed out before all data was retrieved",
146
+ });
147
+ }
148
+ return unavailableReport(target, scope, "the usage refresh timed out");
149
+ }
150
+ return this.settle(key, useCache, target, report);
151
+ })().finally(() => {
152
+ if (this.inFlight.get(slot)?.controller === controller)
153
+ this.inFlight.delete(slot);
154
+ });
155
+ return { controller, key, promise, callers: 0 };
156
+ }
157
+ /**
158
+ * Each caller cancels independently: the shared collection is aborted only once every attached caller has aborted.
159
+ * An aborted caller gets its own cancelled report while others still receive the shared result.
160
+ */
161
+ attach(entry, signal, target, scope) {
162
+ entry.callers++;
163
+ return new Promise((resolve) => {
164
+ let attached = true;
165
+ const detach = () => {
166
+ if (!attached)
167
+ return;
168
+ attached = false;
169
+ signal.removeEventListener("abort", onAbort);
170
+ };
171
+ const onAbort = () => {
172
+ if (!attached)
173
+ return;
174
+ detach();
175
+ if (--entry.callers === 0)
176
+ entry.controller.abort();
177
+ resolve(unavailableReport(target, scope, "the usage refresh was cancelled"));
178
+ };
179
+ if (signal.aborted)
180
+ return onAbort();
181
+ signal.addEventListener("abort", onAbort, { once: true });
182
+ void entry.promise.then((report) => {
183
+ if (!attached)
184
+ return;
185
+ detach();
186
+ resolve(report);
187
+ });
188
+ });
189
+ }
190
+ settle(key, useCache, target, report) {
191
+ const bound = { ...report, target };
192
+ if (bound.status === "unavailable") {
193
+ const previous = useCache ? this.cache.get(key)?.report : undefined;
194
+ if (previous && previous.status !== "unavailable") {
195
+ // Keep the last real observation with its own time and label it stale instead of dropping it.
196
+ return {
197
+ ...previous,
198
+ stale: true,
199
+ reason: `the latest refresh failed: ${bound.reason ?? "unavailable"}`,
200
+ };
201
+ }
202
+ return bound;
203
+ }
204
+ if (useCache) {
205
+ this.cache.delete(key);
206
+ this.cache.set(key, { report: bound, fetchedAt: this.now() });
207
+ while (this.cache.size > MAX_CACHE_ENTRIES)
208
+ this.cache.delete(this.cache.keys().next().value);
209
+ }
210
+ return this.label(bound);
211
+ }
212
+ /** Mark observations older than the cache window stale; never alters the metrics or times. */
213
+ label(report) {
214
+ if (report.stale || report.status === "unavailable" || report.updatedAt === undefined)
215
+ return report;
216
+ return this.now() - report.updatedAt > this.ttlMs ? { ...report, stale: true } : report;
217
+ }
218
+ }
219
+ const SCOPE_LABELS = {
220
+ "openai-codex-oauth-usage": "OpenAI Codex sign-in usage (weekly window reported by the Codex usage service)",
221
+ "anthropic-api-rate-limits": "Anthropic API rate-limit windows from the last API response (not a Claude subscription allowance)",
222
+ "anthropic-organization-usage": "Anthropic organization usage report (Admin API reporting credentials; not linked to any ordinary API key)",
223
+ "bedrock-cloudwatch": "Amazon Bedrock CloudWatch metrics (AWS/Bedrock; not a billing invoice or remaining quota)",
224
+ unsupported: "Usage reporting",
225
+ };
226
+ function formatNumber(value) {
227
+ return Number.isInteger(value) ? String(value) : String(Number(value.toFixed(4)));
228
+ }
229
+ /** Render a report for Advanced. Always names source/scope, account, period, region and update time. */
230
+ export function formatAccountUsageReport(report, now) {
231
+ const { target } = report;
232
+ const lines = [`${SCOPE_LABELS[report.scope]} — account/source [${target.accountKey || target.source}]`];
233
+ const place = [
234
+ `Period ${target.period.start} to ${target.period.end} (UTC).`,
235
+ target.region ? `Region ${target.region}.` : undefined,
236
+ report.updatedAt === undefined ? "Not updated." : `Updated ${new Date(report.updatedAt).toISOString()}.`,
237
+ ].filter(Boolean);
238
+ lines.push(place.join(" "));
239
+ if (report.status === "unavailable") {
240
+ const detail = report.reason ?? "no reason was reported";
241
+ lines.push(`Account usage is unavailable: ${detail}.${report.nextAction ? ` ${report.nextAction}` : ""}`);
242
+ return lines;
243
+ }
244
+ if (report.stale) {
245
+ const age = report.updatedAt === undefined
246
+ ? ""
247
+ : ` ${Math.max(0, Math.round((now - report.updatedAt) / 1000))} seconds ago`;
248
+ lines.push(`Stale: last observed${age || " at an unknown time"}; refresh to update.`);
249
+ }
250
+ if (report.status === "empty") {
251
+ lines.push("No usage was reported for this period. This is not a zero count.");
252
+ }
253
+ else {
254
+ if (report.status === "partial") {
255
+ lines.push(`Partial results: ${report.reason ?? "some data was missing"}. Totals may be incomplete.`);
256
+ }
257
+ else if (report.reason) {
258
+ lines.push(`Note: ${report.reason}.`);
259
+ }
260
+ for (const metric of report.metrics) {
261
+ lines.push(`${metric.name}: ${formatNumber(metric.value)} ${metric.unit}${metric.resetsAt ? ` (resets ${metric.resetsAt})` : ""}`);
262
+ }
263
+ }
264
+ return lines;
265
+ }
266
+ const CODEX_REASONS = {
267
+ expired_credential: "the Codex sign-in has expired",
268
+ unauthorized: "the Codex usage service rejected the sign-in",
269
+ rate_limited: "the Codex usage service is rate limiting requests",
270
+ http_error: "the Codex usage service returned an error",
271
+ timeout: "the Codex usage request timed out",
272
+ network: "the Codex usage service is unreachable",
273
+ malformed: "the Codex usage response was not recognised",
274
+ no_weekly_window: "the Codex usage service reported no weekly window",
275
+ };
276
+ const CODEX_NEXT_ACTIONS = {
277
+ expired_credential: "Sign in to OpenAI Codex again, then refresh usage.",
278
+ unauthorized: "Sign in to OpenAI Codex again, then refresh usage.",
279
+ rate_limited: "Wait a minute, then refresh usage.",
280
+ timeout: "Check the connection, then refresh usage.",
281
+ network: "Check the connection, then refresh usage.",
282
+ };
283
+ /**
284
+ * Reuses the existing Codex weekly usage fetcher for one `openai-codex` OAuth account. `openai` API-key accounts are a
285
+ * different provider and have no collector here: their usage is never inferred from Codex sign-ins.
286
+ */
287
+ export function createCodexUsageCollector(deps) {
288
+ const scope = "openai-codex-oauth-usage";
289
+ return {
290
+ scopeFor: () => scope,
291
+ async collect(target, signal) {
292
+ if (target.providerId !== CODEX_USAGE_PROVIDER_ID) {
293
+ return unavailableReport(target, scope, "not an OpenAI Codex sign-in");
294
+ }
295
+ const account = await deps.readAccount(target.accountKey, signal);
296
+ if (!account) {
297
+ return unavailableReport(target, scope, "the Codex sign-in is no longer stored", "Reconnect OpenAI Codex.");
298
+ }
299
+ const now = deps.now?.() ?? Date.now();
300
+ const result = await fetchCodexWeeklyUsage(account, {
301
+ signal: AbortSignal.any([signal, AbortSignal.timeout(ACCOUNT_REPORT_REQUEST_TIMEOUT_MS)]),
302
+ fetch: deps.fetch,
303
+ now,
304
+ });
305
+ if (result.status === "unavailable") {
306
+ if (result.reason === "no_weekly_window") {
307
+ return {
308
+ status: "empty",
309
+ target,
310
+ scope,
311
+ updatedAt: now,
312
+ metrics: [],
313
+ reason: CODEX_REASONS[result.reason],
314
+ };
315
+ }
316
+ return unavailableReport(target, scope, CODEX_REASONS[result.reason], CODEX_NEXT_ACTIONS[result.reason]);
317
+ }
318
+ const metric = {
319
+ name: "Weekly allowance remaining",
320
+ value: result.usage.remainingPercent,
321
+ unit: "%",
322
+ ...(result.usage.resetsAt === undefined ? {} : { resetsAt: new Date(result.usage.resetsAt).toISOString() }),
323
+ };
324
+ return { status: "ok", target, scope, updatedAt: now, metrics: [metric] };
325
+ },
326
+ };
327
+ }
328
+ //# sourceMappingURL=account-reporting.js.map