@humain/humain-code 0.4.9 → 0.4.11

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 (112) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/bundle/agent-monitor.js +1 -1
  3. package/dist/bundle/chunks/bedrock-converse-stream.js +39 -45
  4. package/dist/bundle/chunks/{chunk-KRMTBTWU.js → chunk-77EWF2NW.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-RBKDBF5G.js → chunk-AS2Y2MO6.js} +36 -36
  6. package/dist/bundle/chunks/{chunk-P4YMUUSK.js → chunk-DX3OMELJ.js} +741 -733
  7. package/dist/bundle/chunks/{chunk-W2QRCQBX.js → chunk-FF26YENK.js} +3 -4
  8. package/dist/bundle/chunks/{chunk-UZ5FVVCP.js → chunk-HMWAH7ZY.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-F7UMX5BV.js → chunk-HSDTSUZE.js} +13 -2
  10. package/dist/bundle/chunks/chunk-I2ZWZAIV.js +751 -0
  11. package/dist/bundle/chunks/{chunk-GUUAEK6G.js → chunk-LCOHFEZZ.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-6FVNSW6B.js → chunk-PIX6AAU6.js} +3354 -3939
  13. package/dist/bundle/chunks/{chunk-Z5LYSSTY.js → chunk-QSPDLT2R.js} +2 -2
  14. package/dist/bundle/chunks/{chunk-UBQSONVR.js → chunk-R5VIAWGA.js} +103 -145
  15. package/dist/bundle/chunks/{chunk-4LAKI5IL.js → chunk-SZRZXVVZ.js} +9 -9
  16. package/dist/bundle/chunks/{chunk-EMYNPLY5.js → chunk-V5ZF7Q7L.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-LQ4S7CRR.js → chunk-VYIIPF57.js} +1 -1
  18. package/dist/bundle/chunks/chunk-WBJN6PEI.js +43 -0
  19. package/dist/bundle/chunks/{chunk-SWRU4BOC.js → chunk-XGO43DKL.js} +1 -1
  20. package/dist/bundle/chunks/chunk-XKSDVBMN.js +28 -0
  21. package/dist/bundle/chunks/{chunk-PMISFIBM.js → chunk-XMHLSV3I.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-3E4SMILM.js → chunk-YJBE3IGR.js} +14 -14
  23. package/dist/bundle/chunks/{cli-ZKT34WPW.js → cli-5ACW3WND.js} +2 -2
  24. package/dist/bundle/chunks/{compat-HEUVP6UJ.js → compat-KXKKCXPQ.js} +1 -1
  25. package/dist/bundle/chunks/{dist-NU2EIVT6.js → dist-7DVXM77G.js} +742 -615
  26. package/dist/bundle/chunks/dist-cjs-RL2OCAP2.js +179 -0
  27. package/dist/bundle/chunks/{easter-egg-3d-5KKDWEIA.js → easter-egg-3d-3L3IKAT6.js} +1 -1
  28. package/dist/bundle/chunks/{esm-NCUV2DF7.js → esm-763X2IA7.js} +1 -1
  29. package/dist/bundle/chunks/event-streams-R5OECII4.js +2 -0
  30. package/dist/bundle/chunks/{execute-OSBDNQU5.js → execute-4X6G65NZ.js} +1 -1
  31. package/dist/bundle/chunks/{extract-PYRMDATF.js → extract-DLZ425VI.js} +4 -4
  32. package/dist/bundle/chunks/github-copilot.js +32 -31
  33. package/dist/bundle/chunks/{google-generative-ai-H2F5Y5H2.js → google-generative-ai-JD2FVOIX.js} +1 -1
  34. package/dist/bundle/chunks/{google-vertex-LFWD2AOO.js → google-vertex-PFBMDCBW.js} +1 -1
  35. package/dist/bundle/chunks/{host-6ZA6LK4C.js → host-4J7H7KDS.js} +1 -1
  36. package/dist/bundle/chunks/{node-XGNY74WT.js → node-W47VUEGE.js} +1 -1
  37. package/dist/bundle/chunks/{runtime-JFLZUNYP.js → runtime-SI76JZNE.js} +1 -1
  38. package/dist/bundle/chunks/virtual-modules-E3FQAR5T.js +5 -0
  39. package/dist/bundle/cli-runtime.js +3 -3
  40. package/dist/bundle/flow/package.json +1 -1
  41. package/dist/bundle/index.js +17 -17
  42. package/dist/bundle/rpc-entry.js +3 -2
  43. package/dist/core/account-reporting.d.ts +109 -0
  44. package/dist/core/account-reporting.d.ts.map +1 -0
  45. package/dist/core/account-reporting.js +328 -0
  46. package/dist/core/account-reporting.js.map +1 -0
  47. package/dist/core/agent-session.d.ts +22 -2
  48. package/dist/core/agent-session.d.ts.map +1 -1
  49. package/dist/core/agent-session.js +131 -0
  50. package/dist/core/agent-session.js.map +1 -1
  51. package/dist/core/anthropic-account-reporting.d.ts +76 -0
  52. package/dist/core/anthropic-account-reporting.d.ts.map +1 -0
  53. package/dist/core/anthropic-account-reporting.js +380 -0
  54. package/dist/core/anthropic-account-reporting.js.map +1 -0
  55. package/dist/core/bedrock-account-reporting.d.ts +82 -0
  56. package/dist/core/bedrock-account-reporting.d.ts.map +1 -0
  57. package/dist/core/bedrock-account-reporting.js +402 -0
  58. package/dist/core/bedrock-account-reporting.js.map +1 -0
  59. package/dist/core/model-runtime.d.ts +17 -0
  60. package/dist/core/model-runtime.d.ts.map +1 -1
  61. package/dist/core/model-runtime.js +64 -10
  62. package/dist/core/model-runtime.js.map +1 -1
  63. package/dist/core/oauth-account-pool.d.ts +4 -0
  64. package/dist/core/oauth-account-pool.d.ts.map +1 -1
  65. package/dist/core/oauth-account-pool.js +10 -3
  66. package/dist/core/oauth-account-pool.js.map +1 -1
  67. package/dist/humain/flow-accounts-host.d.ts +120 -0
  68. package/dist/humain/flow-accounts-host.d.ts.map +1 -0
  69. package/dist/humain/flow-accounts-host.js +346 -0
  70. package/dist/humain/flow-accounts-host.js.map +1 -0
  71. package/dist/humain/flow-command.d.ts +28 -0
  72. package/dist/humain/flow-command.d.ts.map +1 -0
  73. package/dist/humain/flow-command.js +226 -0
  74. package/dist/humain/flow-command.js.map +1 -0
  75. package/dist/humain/flow-loader.d.ts +4 -2
  76. package/dist/humain/flow-loader.d.ts.map +1 -1
  77. package/dist/humain/flow-loader.js +120 -91
  78. package/dist/humain/flow-loader.js.map +1 -1
  79. package/dist/humain/node-account-failure.d.ts +18 -0
  80. package/dist/humain/node-account-failure.d.ts.map +1 -0
  81. package/dist/humain/node-account-failure.js +73 -0
  82. package/dist/humain/node-account-failure.js.map +1 -0
  83. package/dist/humain/node-account-fallback.d.ts +85 -0
  84. package/dist/humain/node-account-fallback.d.ts.map +1 -0
  85. package/dist/humain/node-account-fallback.js +175 -0
  86. package/dist/humain/node-account-fallback.js.map +1 -0
  87. package/dist/humain/node-http.d.ts.map +1 -1
  88. package/dist/humain/node-http.js +11 -0
  89. package/dist/humain/node-http.js.map +1 -1
  90. package/dist/humain/node-provider.d.ts +4 -0
  91. package/dist/humain/node-provider.d.ts.map +1 -1
  92. package/dist/humain/node-provider.js +11 -0
  93. package/dist/humain/node-provider.js.map +1 -1
  94. package/dist/index.d.ts +4 -0
  95. package/dist/index.d.ts.map +1 -1
  96. package/dist/index.js.map +1 -1
  97. package/dist/modes/interactive/components/login-dialog.d.ts +2 -0
  98. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  99. package/dist/modes/interactive/components/login-dialog.js +5 -0
  100. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  101. package/dist/modes/interactive/interactive-mode.d.ts +26 -0
  102. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  103. package/dist/modes/interactive/interactive-mode.js +242 -19
  104. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  105. package/docs/flow-profiles.md +57 -5
  106. package/docs/flow.md +119 -37
  107. package/docs/providers.md +37 -0
  108. package/npm-shrinkwrap.json +48 -6
  109. package/package.json +3 -2
  110. package/dist/bundle/chunks/chunk-JOKJ3CEL.js +0 -27
  111. package/dist/bundle/chunks/event-streams-CGCQQL5M.js +0 -2
  112. package/dist/bundle/chunks/virtual-modules-NPWQ6NBS.js +0 -5
@@ -0,0 +1,120 @@
1
+ import type { Api, Model } from "@earendil-works/pi-ai";
2
+ import { AccountReporter, type AccountReportTarget, type AccountUsageReport } from "../core/account-reporting.ts";
3
+ import { type AnthropicReportingCredentialProvider } from "../core/anthropic-account-reporting.ts";
4
+ import { type BedrockReportCollectorDeps } from "../core/bedrock-account-reporting.ts";
5
+ import type { ExtensionContext } from "../core/extensions/types.ts";
6
+ import type { ModelRegistry } from "../core/model-registry.ts";
7
+ import type { AccountInfo, AccountSource, ModelRuntime } from "../core/model-runtime.ts";
8
+ import { type NodeAccountFallbackPolicy, type NodeAccountView, type NodeFallbackAssessment } from "./node-account-fallback.ts";
9
+ /**
10
+ * Session-bound bridge that lets Flow drive host-owned account dialogs and catalog readiness.
11
+ * Credentials never cross it: every value is non-secret metadata or a model catalog.
12
+ */
13
+ export type FlowCatalogState = {
14
+ state: "ready";
15
+ models: readonly Model<Api>[];
16
+ } | {
17
+ state: "unavailable";
18
+ reason: string;
19
+ };
20
+ export interface FlowAccountsHost {
21
+ /**
22
+ * Resolves after the user finishes or cancels the account interaction. Cancelling through the signal ends the
23
+ * dialog; sign-ins, account switches and removals already completed stay in effect.
24
+ */
25
+ openAccounts(signal: AbortSignal): Promise<void>;
26
+ /** Explicit action: refresh the provider's catalog for the selected account, allowing network access. */
27
+ refreshCatalog(providerId: string, signal: AbortSignal): Promise<FlowCatalogState>;
28
+ /**
29
+ * Explicit "Refresh usage" action. The only path that reaches a reporting transport; listing accounts and opening
30
+ * Advanced never call it. Resolves to a labelled report and never throws for unavailable data.
31
+ */
32
+ refreshAccountUsage(target: AccountReportTarget, signal: AbortSignal): Promise<AccountUsageReport>;
33
+ /** Opt-in HUMAIN Node key fallback: current policy, aliases, labels and setup warnings. No network. */
34
+ getNodeFallback(signal: AbortSignal): Promise<FlowNodeFallbackState>;
35
+ /** Validate and persist policy and labels outside the credential store, then return the new state. */
36
+ updateNodeFallback(update: FlowNodeFallbackUpdate, signal: AbortSignal): Promise<FlowNodeFallbackState>;
37
+ /** Whether `text` contains a stored HUMAIN Node key. Only the answer crosses the bridge, never a key. */
38
+ labelContainsStoredKey(text: string, signal: AbortSignal): Promise<boolean>;
39
+ }
40
+ export declare const FLOW_ACCOUNTS_UNAVAILABLE = "Account interaction unavailable";
41
+ /** Bind a host to the registry of the current session. Rebinding supersedes the previous generation. */
42
+ export declare function bindFlowAccountsHost(registry: ModelRegistry, host: FlowAccountsHost): () => void;
43
+ /** Look up the host by actual registry identity. Only the terminal UI owns secure dialogs. */
44
+ export declare function getFlowAccountsHost(ctx: Pick<ExtensionContext, "modelRegistry" | "mode">): FlowAccountsHost | undefined;
45
+ /** Secret-free account metadata. `endpoint` is the HUMAIN Node base URL; `region` the stored Bedrock region. */
46
+ export interface FlowAccountMetadata extends AccountInfo {
47
+ endpoint?: string;
48
+ region?: string;
49
+ }
50
+ export interface FlowAccountSourceMetadata extends AccountSource {
51
+ endpoint?: string;
52
+ /** Stored Bedrock region of the auth.json provider configuration. */
53
+ region?: string;
54
+ }
55
+ export interface FlowProviderAccountMetadata {
56
+ providerId: string;
57
+ accounts: FlowAccountMetadata[];
58
+ sources: FlowAccountSourceMetadata[];
59
+ }
60
+ /**
61
+ * Enumerate accounts and sources from stored metadata only. This never resolves credentials, refreshes OAuth,
62
+ * runs credential commands, or touches the network; `accounts.list/sources` are side-effect-free by contract.
63
+ */
64
+ export declare function listFlowAccountMetadata(runtime: ModelRuntime, providerId: string, signal: AbortSignal, ambientEnv?: NodeJS.ProcessEnv): Promise<FlowProviderAccountMetadata>;
65
+ export declare const NODE_USAGE_UNSUPPORTED = "Usage reporting is not yet supported for HUMAIN Node.";
66
+ export declare const BEDROCK_USAGE_NOTE = "Usage reporting reads Amazon CloudWatch metrics and needs AWS credentials saved through Connect, with a region. A Bedrock API key cannot report usage.";
67
+ export declare const FLOW_ACCOUNT_PERSISTENCE_NOTICE = "Sign-in and account changes take effect immediately and are not undone by cancelling setup.";
68
+ /** Advanced details for the selected provider. Configured and effective never mean verified. */
69
+ export declare function formatFlowAccountAdvanced(providerId: string, providerName: string, metadata: FlowProviderAccountMetadata): string[];
70
+ /**
71
+ * Wait for the selected key's catalog. HUMAIN Node discovery uses the network, so call this only after an explicit
72
+ * account or catalog action. Anything short of a fresh, non-empty catalog for the same selected key is unavailable;
73
+ * models are never invented or carried over from another key.
74
+ */
75
+ export declare function refreshFlowCatalog(runtime: ModelRuntime, providerId: string, signal: AbortSignal): Promise<FlowCatalogState>;
76
+ /** Secret-free state for the Node fallback setup step. `accounts` lists stored Node API-key accounts in pool order. */
77
+ export interface FlowNodeFallbackState extends NodeFallbackAssessment {
78
+ policy: Required<NodeAccountFallbackPolicy>;
79
+ accounts: NodeAccountView[];
80
+ }
81
+ export interface FlowNodeFallbackUpdate {
82
+ policy?: Partial<NodeAccountFallbackPolicy>;
83
+ /** Per account key. `null` clears a label. */
84
+ labels?: Record<string, {
85
+ nodeUser?: string | null;
86
+ environment?: string | null;
87
+ }>;
88
+ }
89
+ /** Read the policy and labels. Uses stored metadata only: no credential resolution, refresh or network access. */
90
+ export declare function readFlowNodeFallbackState(runtime: ModelRuntime, signal: AbortSignal, ambientEnv?: NodeJS.ProcessEnv): Promise<FlowNodeFallbackState>;
91
+ /** True when `text` would embed a stored Node API key. Stored metadata only: no refresh, no network. */
92
+ export declare function nodeLabelContainsStoredKey(runtime: ModelRuntime, text: string, signal: AbortSignal): Promise<boolean>;
93
+ /**
94
+ * Persist the opt-in fallback policy and user labels. Keys are only referenced by their stored account key; unknown
95
+ * or duplicate keys, oversized or key-bearing labels are rejected before anything is written.
96
+ */
97
+ export declare function updateFlowNodeFallback(runtime: ModelRuntime, update: FlowNodeFallbackUpdate, signal: AbortSignal, ambientEnv?: NodeJS.ProcessEnv): Promise<FlowNodeFallbackState>;
98
+ /** Providers whose Advanced view offers "Refresh usage". Node reports its own exact unsupported text instead. */
99
+ export declare const FLOW_USAGE_REPORTING_PROVIDERS: ReadonlySet<string>;
100
+ export interface FlowAccountReporterOptions {
101
+ /**
102
+ * Explicitly provisioned Anthropic Admin API reporting credentials. The host has no supported secure provisioning
103
+ * for them today, so this is normally absent and organization reporting reads "reporting credentials not configured".
104
+ */
105
+ organizationCredentials?: AnthropicReportingCredentialProvider;
106
+ fetch?: typeof fetch;
107
+ now?: () => number;
108
+ /** SDK client factory for Bedrock CloudWatch reporting. Defaults to the official AWS SDK client. */
109
+ openBedrockClient?: BedrockReportCollectorDeps["openClient"];
110
+ }
111
+ /** Build the session reporter. Nothing is fetched or resolved until `refreshAccountUsage` is called. */
112
+ export declare function createFlowAccountReporter(runtime: ModelRuntime, options?: FlowAccountReporterOptions): AccountReporter;
113
+ /** UTC calendar day containing `now`: the reporting period for window-based sources. */
114
+ export declare function utcDayPeriod(now: number): AccountReportTarget["period"];
115
+ /**
116
+ * Targets for "Refresh usage" from stored metadata: the selected account (Bedrock: with its stored region), plus
117
+ * Anthropic organization reporting as its own source. `openai` API accounts and every other provider have none: their usage is never inferred.
118
+ */
119
+ export declare function flowUsageTargets(providerId: string, metadata: FlowProviderAccountMetadata, now: number): AccountReportTarget[];
120
+ //# sourceMappingURL=flow-accounts-host.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flow-accounts-host.d.ts","sourceRoot":"","sources":["../../src/humain/flow-accounts-host.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,EACN,eAAe,EACf,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,EAEvB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAEN,KAAK,oCAAoC,EAGzC,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAGN,KAAK,0BAA0B,EAI/B,MAAM,sCAAsC,CAAC;AAE9C,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC/D,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACzF,OAAO,EAKN,KAAK,yBAAyB,EAE9B,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC3B,MAAM,4BAA4B,CAAC;AAGpC;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GACzB;IAAE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G,EAAE,MAAM,GACT,mBAAmB,EAAE,CAuBvB"}
@@ -0,0 +1,346 @@
1
+ import { AccountReporter, createCodexUsageCollector, } from "../core/account-reporting.js";
2
+ import { ANTHROPIC_PROVIDER_ID, anthropicOrganizationTarget, createAnthropicReportCollector, } from "../core/anthropic-account-reporting.js";
3
+ import { BEDROCK_AWS_CREDENTIALS_SOURCE, BEDROCK_PROVIDER_ID, bedrockReportingCredentials, createBedrockReportCollector, openCloudWatchMetricsSession, } from "../core/bedrock-account-reporting.js";
4
+ import { CODEX_USAGE_PROVIDER_ID } from "../core/codex-usage.js";
5
+ import { assessNodeFallback, isSafeNodeText, MAX_NODE_FALLBACK_KEYS, MAX_NODE_LABEL_LENGTH, } from "./node-account-fallback.js";
6
+ import { describeHumainNodeEndpoint, HUMAIN_NODE_BASE_URL_ENV, HUMAIN_NODE_PROVIDER } from "./node-provider.js";
7
+ export const FLOW_ACCOUNTS_UNAVAILABLE = "Account interaction unavailable";
8
+ const bindings = new WeakMap();
9
+ /** Bind a host to the registry of the current session. Rebinding supersedes the previous generation. */
10
+ export function bindFlowAccountsHost(registry, host) {
11
+ bindings.get(registry)?.release();
12
+ const generation = new AbortController();
13
+ const run = async (signal, operation) => {
14
+ if (generation.signal.aborted)
15
+ throw new Error(FLOW_ACCOUNTS_UNAVAILABLE);
16
+ try {
17
+ const result = await operation(AbortSignal.any([signal, generation.signal]));
18
+ if (generation.signal.aborted)
19
+ throw new Error(FLOW_ACCOUNTS_UNAVAILABLE);
20
+ return result;
21
+ }
22
+ catch (error) {
23
+ if (generation.signal.aborted)
24
+ throw new Error(FLOW_ACCOUNTS_UNAVAILABLE);
25
+ throw error;
26
+ }
27
+ };
28
+ const binding = {
29
+ handle: {
30
+ openAccounts: (signal) => run(signal, (combined) => host.openAccounts(combined)),
31
+ refreshCatalog: (providerId, signal) => run(signal, (combined) => host.refreshCatalog(providerId, combined)),
32
+ refreshAccountUsage: (target, signal) => run(signal, (combined) => host.refreshAccountUsage(target, combined)),
33
+ getNodeFallback: (signal) => run(signal, (combined) => host.getNodeFallback(combined)),
34
+ updateNodeFallback: (update, signal) => run(signal, (combined) => host.updateNodeFallback(update, combined)),
35
+ labelContainsStoredKey: (text, signal) => run(signal, (combined) => host.labelContainsStoredKey(text, combined)),
36
+ },
37
+ release: () => {
38
+ generation.abort();
39
+ if (bindings.get(registry) === binding)
40
+ bindings.delete(registry);
41
+ },
42
+ };
43
+ bindings.set(registry, binding);
44
+ return binding.release;
45
+ }
46
+ /** Look up the host by actual registry identity. Only the terminal UI owns secure dialogs. */
47
+ export function getFlowAccountsHost(ctx) {
48
+ return ctx.mode === "tui" ? bindings.get(ctx.modelRegistry)?.handle : undefined;
49
+ }
50
+ function envString(env, name) {
51
+ const value = env?.[name];
52
+ return typeof value === "string" ? value : undefined;
53
+ }
54
+ /**
55
+ * Enumerate accounts and sources from stored metadata only. This never resolves credentials, refreshes OAuth,
56
+ * runs credential commands, or touches the network; `accounts.list/sources` are side-effect-free by contract.
57
+ */
58
+ export async function listFlowAccountMetadata(runtime, providerId, signal, ambientEnv = process.env) {
59
+ const options = { signal };
60
+ const accounts = await runtime.accounts.list(providerId, options);
61
+ const sources = await runtime.accounts.sources(providerId, options);
62
+ const stored = await runtime.oauthAccounts.listAccounts(providerId, options);
63
+ const ambientEndpoint = envString(ambientEnv, HUMAIN_NODE_BASE_URL_ENV);
64
+ const isNode = providerId === HUMAIN_NODE_PROVIDER;
65
+ // Bedrock AWS-credentials logins have no key, so they are an auth.json source: read its region without resolving it.
66
+ const storedConfiguration = providerId === BEDROCK_PROVIDER_ID ? await runtime.readStoredCredential(providerId, options) : undefined;
67
+ const sourceRegion = storedConfiguration?.type === "api_key" ? envString(storedConfiguration.env, "AWS_REGION") : undefined;
68
+ return {
69
+ providerId,
70
+ accounts: accounts.map((account) => {
71
+ const credential = stored.find((entry) => entry.key === account.key)?.credential;
72
+ const env = credential?.type === "api_key" ? credential.env : undefined;
73
+ const endpoint = isNode
74
+ ? describeHumainNodeEndpoint(envString(env, HUMAIN_NODE_BASE_URL_ENV), ambientEndpoint)
75
+ : undefined;
76
+ const region = providerId === "amazon-bedrock" ? envString(env, "AWS_REGION") : undefined;
77
+ return { ...account, ...(endpoint ? { endpoint } : {}), ...(region ? { region } : {}) };
78
+ }),
79
+ sources: sources.map((source) => {
80
+ // Only the environment source is defined by the ambient base URL; other sources carry no non-secret endpoint.
81
+ const endpoint = isNode && source.source === "environment"
82
+ ? describeHumainNodeEndpoint(undefined, ambientEndpoint)
83
+ : undefined;
84
+ if (sourceRegion && source.source === "auth_json")
85
+ return { ...source, region: sourceRegion };
86
+ return endpoint ? { ...source, endpoint } : source;
87
+ }),
88
+ };
89
+ }
90
+ export const NODE_USAGE_UNSUPPORTED = "Usage reporting is not yet supported for HUMAIN Node.";
91
+ export const BEDROCK_USAGE_NOTE = "Usage reporting reads Amazon CloudWatch metrics and needs AWS credentials saved through Connect, with a region. A Bedrock API key cannot report usage.";
92
+ export const FLOW_ACCOUNT_PERSISTENCE_NOTICE = "Sign-in and account changes take effect immediately and are not undone by cancelling setup.";
93
+ /** Advanced details for the selected provider. Configured and effective never mean verified. */
94
+ export function formatFlowAccountAdvanced(providerId, providerName, metadata) {
95
+ const lines = [];
96
+ if (metadata.accounts.length === 0 && metadata.sources.length === 0) {
97
+ lines.push(`No ${providerName} account is configured.`);
98
+ }
99
+ for (const account of metadata.accounts) {
100
+ const parts = [account.type === "oauth" ? "OAuth" : "API key"];
101
+ if (account.active)
102
+ parts.push("selected");
103
+ const state = account.effective
104
+ ? "Effective for future requests."
105
+ : account.active
106
+ ? "An external source still controls requests."
107
+ : "Not selected.";
108
+ const place = [
109
+ account.endpoint ? `Endpoint ${account.endpoint}.` : undefined,
110
+ account.region ? `Region ${account.region}.` : undefined,
111
+ ].filter(Boolean);
112
+ lines.push(`${account.label} [${account.key}]: ${parts.join(", ")}. ${state} Configured — not verified. ${place.join(" ")}`.trim());
113
+ }
114
+ for (const source of metadata.sources) {
115
+ const state = source.effective ? "Effective for future requests." : "Shadowed by a higher-precedence source.";
116
+ lines.push(`${source.label} [read-only]: ${state} Configured — not verified.${source.endpoint ? ` Endpoint ${source.endpoint}.` : ""}${source.region ? ` Region ${source.region}.` : ""}`);
117
+ }
118
+ if (providerId === HUMAIN_NODE_PROVIDER)
119
+ lines.push(NODE_USAGE_UNSUPPORTED);
120
+ if (providerId === BEDROCK_PROVIDER_ID)
121
+ lines.push(BEDROCK_USAGE_NOTE);
122
+ return lines;
123
+ }
124
+ const RETRY_OTHERS = "Retry, or continue with other providers.";
125
+ const unavailable = (reason) => ({ state: "unavailable", reason });
126
+ function nodeFailureReason(error) {
127
+ const text = `${error.name} ${error.message}`;
128
+ if (/\b(401|403)\b|invalid_api_key|unauthori|revoked|inactive/iu.test(text)) {
129
+ return "HUMAIN Node rejected the selected key. Check the key, then retry.";
130
+ }
131
+ if (/TypeError|TimeoutError|fetch failed|network|ECONN|ENOTFOUND|EAI_AGAIN|timed out/iu.test(text)) {
132
+ return "HUMAIN Node is unreachable. Check the connection, then retry.";
133
+ }
134
+ // Raw provider text can carry request details; show only the category.
135
+ return `HUMAIN Node model discovery failed. ${RETRY_OTHERS}`;
136
+ }
137
+ async function selectedKeyFingerprint(runtime, providerId, signal) {
138
+ const metadata = await listFlowAccountMetadata(runtime, providerId, signal);
139
+ const selected = metadata.accounts.find((account) => account.active);
140
+ return JSON.stringify([
141
+ selected?.key,
142
+ selected?.endpoint,
143
+ metadata.sources.filter((source) => source.effective).map((source) => source.label),
144
+ ]);
145
+ }
146
+ /**
147
+ * Wait for the selected key's catalog. HUMAIN Node discovery uses the network, so call this only after an explicit
148
+ * account or catalog action. Anything short of a fresh, non-empty catalog for the same selected key is unavailable;
149
+ * models are never invented or carried over from another key.
150
+ */
151
+ export async function refreshFlowCatalog(runtime, providerId, signal) {
152
+ const cancelled = unavailable("Model discovery was cancelled. Retry when ready.");
153
+ if (signal.aborted)
154
+ return cancelled;
155
+ const models = () => runtime.getAvailableSnapshot().filter((model) => model.provider === providerId);
156
+ if (providerId !== HUMAIN_NODE_PROVIDER) {
157
+ const local = models();
158
+ return local.length > 0
159
+ ? { state: "ready", models: local }
160
+ : unavailable(`No models are available for ${providerId}. Connect the provider, then retry.`);
161
+ }
162
+ try {
163
+ const before = await selectedKeyFingerprint(runtime, providerId, signal);
164
+ const result = await runtime.refresh({ providers: [providerId], allowNetwork: true, force: true, signal });
165
+ if (signal.aborted || result.aborted)
166
+ return cancelled;
167
+ // Check the key first: a late failure from the old key must not be blamed on the newly selected one.
168
+ if ((await selectedKeyFingerprint(runtime, providerId, signal)) !== before) {
169
+ return unavailable("The selected HUMAIN Node key changed during discovery. Retry with the key you want to use.");
170
+ }
171
+ const error = result.errors.get(providerId);
172
+ if (error)
173
+ return unavailable(nodeFailureReason(error));
174
+ if (!runtime.hasConfiguredAuth(providerId)) {
175
+ return unavailable("No HUMAIN Node key is configured. Connect one, then retry.");
176
+ }
177
+ const discovered = models();
178
+ return discovered.length > 0
179
+ ? { state: "ready", models: discovered }
180
+ : unavailable(`HUMAIN Node returned no models for the selected key. ${RETRY_OTHERS}`);
181
+ }
182
+ catch {
183
+ return signal.aborted ? cancelled : unavailable(`HUMAIN Node model discovery failed. ${RETRY_OTHERS}`);
184
+ }
185
+ }
186
+ /** Read the policy and labels. Uses stored metadata only: no credential resolution, refresh or network access. */
187
+ export async function readFlowNodeFallbackState(runtime, signal, ambientEnv = process.env) {
188
+ const metadata = await listFlowAccountMetadata(runtime, HUMAIN_NODE_PROVIDER, signal, ambientEnv);
189
+ const stored = runtime.nodeAccountMetadata.read();
190
+ const accounts = metadata.accounts
191
+ .filter((account) => account.type === "api_key")
192
+ .map((account) => {
193
+ const labels = Object.hasOwn(stored.accounts, account.key) ? stored.accounts[account.key] : undefined;
194
+ return {
195
+ key: account.key,
196
+ alias: account.label,
197
+ ...(account.endpoint ? { endpoint: account.endpoint } : {}),
198
+ ...(labels?.nodeUser ? { nodeUser: labels.nodeUser } : {}),
199
+ ...(labels?.environment ? { environment: labels.environment } : {}),
200
+ active: account.active,
201
+ inFallback: stored.policy.accountKeys.includes(account.key),
202
+ };
203
+ });
204
+ return { policy: stored.policy, accounts, ...assessNodeFallback(accounts, stored.policy) };
205
+ }
206
+ const containsKey = (apiKeys, text) => apiKeys.some((secret) => secret !== undefined && secret.length > 0 && text.includes(secret));
207
+ /** True when `text` would embed a stored Node API key. Stored metadata only: no refresh, no network. */
208
+ export async function nodeLabelContainsStoredKey(runtime, text, signal) {
209
+ const stored = await runtime.oauthAccounts.listAccounts(HUMAIN_NODE_PROVIDER, { signal });
210
+ return containsKey(stored.flatMap((account) => (account.credential.type === "api_key" ? [account.credential.key] : [])), text.trim());
211
+ }
212
+ const INVALID_NODE_LABEL = "HUMAIN Node labels must be 1 to 80 printable characters and must not contain a key.";
213
+ const INVALID_NODE_POLICY_FLAG = "HUMAIN Node fallback policy flags must be true or false.";
214
+ /**
215
+ * Persist the opt-in fallback policy and user labels. Keys are only referenced by their stored account key; unknown
216
+ * or duplicate keys, oversized or key-bearing labels are rejected before anything is written.
217
+ */
218
+ export async function updateFlowNodeFallback(runtime, update, signal, ambientEnv = process.env) {
219
+ signal.throwIfAborted();
220
+ const stored = await runtime.oauthAccounts.listAccounts(HUMAIN_NODE_PROVIDER, { signal });
221
+ const apiKeys = stored.flatMap((account) => (account.credential.type === "api_key" ? [account.credential.key] : []));
222
+ const known = new Set(stored.filter((account) => account.credential.type === "api_key").map((account) => account.key));
223
+ const accountKeys = update.policy?.accountKeys;
224
+ if (accountKeys !== undefined) {
225
+ if (!Array.isArray(accountKeys) ||
226
+ accountKeys.length > MAX_NODE_FALLBACK_KEYS ||
227
+ new Set(accountKeys).size !== accountKeys.length ||
228
+ !accountKeys.every((key) => known.has(key))) {
229
+ throw new Error("The HUMAIN Node fallback list must name distinct stored Node keys.");
230
+ }
231
+ }
232
+ for (const flag of [update.policy?.enabled, update.policy?.allowCrossEndpoint]) {
233
+ if (flag !== undefined && typeof flag !== "boolean")
234
+ throw new Error(INVALID_NODE_POLICY_FLAG);
235
+ }
236
+ const labelChanges = Object.entries(update.labels ?? {});
237
+ for (const [key, labels] of labelChanges) {
238
+ if (!known.has(key))
239
+ throw new Error("HUMAIN Node labels must name a stored Node key.");
240
+ for (const value of [labels.nodeUser, labels.environment]) {
241
+ if (value === undefined || value === null)
242
+ continue;
243
+ const text = value.trim();
244
+ if (!isSafeNodeText(text, MAX_NODE_LABEL_LENGTH) || containsKey(apiKeys, text)) {
245
+ throw new Error(INVALID_NODE_LABEL);
246
+ }
247
+ }
248
+ }
249
+ signal.throwIfAborted();
250
+ runtime.nodeAccountMetadata.update((current) => {
251
+ const accounts = { ...current.accounts };
252
+ for (const [key, labels] of labelChanges) {
253
+ const next = { ...(Object.hasOwn(accounts, key) ? accounts[key] : {}) };
254
+ for (const field of ["nodeUser", "environment"]) {
255
+ const value = labels[field];
256
+ if (value === null)
257
+ delete next[field];
258
+ else if (value !== undefined)
259
+ next[field] = value.trim();
260
+ }
261
+ accounts[key] = next;
262
+ }
263
+ return {
264
+ policy: {
265
+ enabled: update.policy?.enabled ?? current.policy.enabled,
266
+ accountKeys: update.policy?.accountKeys ?? current.policy.accountKeys,
267
+ allowCrossEndpoint: update.policy?.allowCrossEndpoint ?? current.policy.allowCrossEndpoint,
268
+ },
269
+ accounts,
270
+ };
271
+ });
272
+ return readFlowNodeFallbackState(runtime, signal, ambientEnv);
273
+ }
274
+ /** Providers whose Advanced view offers "Refresh usage". Node reports its own exact unsupported text instead. */
275
+ export const FLOW_USAGE_REPORTING_PROVIDERS = new Set([
276
+ ANTHROPIC_PROVIDER_ID,
277
+ BEDROCK_PROVIDER_ID,
278
+ CODEX_USAGE_PROVIDER_ID,
279
+ ]);
280
+ /** Build the session reporter. Nothing is fetched or resolved until `refreshAccountUsage` is called. */
281
+ export function createFlowAccountReporter(runtime, options = {}) {
282
+ return new AccountReporter({
283
+ now: options.now,
284
+ collectors: {
285
+ [CODEX_USAGE_PROVIDER_ID]: createCodexUsageCollector({
286
+ readAccount: async (accountKey, signal) => (await runtime.oauthAccounts.list(CODEX_USAGE_PROVIDER_ID, { signal })).find((account) => account.key === accountKey),
287
+ fetch: options.fetch,
288
+ now: options.now,
289
+ }),
290
+ [ANTHROPIC_PROVIDER_ID]: createAnthropicReportCollector({
291
+ store: runtime.anthropicRateLimits,
292
+ accountType: async (accountKey, signal) => (await runtime.oauthAccounts.listAccounts(ANTHROPIC_PROVIDER_ID, { signal })).find((account) => account.key === accountKey)?.credential.type,
293
+ organizationCredentials: options.organizationCredentials,
294
+ fetch: options.fetch,
295
+ now: options.now,
296
+ }),
297
+ [BEDROCK_PROVIDER_ID]: createBedrockReportCollector({
298
+ resolveCredentials: async (target, signal) => {
299
+ const credential = target.source === undefined
300
+ ? (await runtime.oauthAccounts.listAccounts(BEDROCK_PROVIDER_ID, { signal })).find((entry) => entry.key === target.accountKey)?.credential
301
+ : await runtime.readStoredCredential(BEDROCK_PROVIDER_ID, { signal });
302
+ return credential ? bedrockReportingCredentials(credential) : undefined;
303
+ },
304
+ openClient: options.openBedrockClient ?? openCloudWatchMetricsSession,
305
+ now: options.now,
306
+ }),
307
+ },
308
+ });
309
+ }
310
+ /** UTC calendar day containing `now`: the reporting period for window-based sources. */
311
+ export function utcDayPeriod(now) {
312
+ const start = new Date(now);
313
+ start.setUTCHours(0, 0, 0, 0);
314
+ return { start: start.toISOString(), end: new Date(start.getTime() + 24 * 60 * 60 * 1000).toISOString() };
315
+ }
316
+ /**
317
+ * Targets for "Refresh usage" from stored metadata: the selected account (Bedrock: with its stored region), plus
318
+ * Anthropic organization reporting as its own source. `openai` API accounts and every other provider have none: their usage is never inferred.
319
+ */
320
+ export function flowUsageTargets(providerId, metadata, now) {
321
+ if (!FLOW_USAGE_REPORTING_PROVIDERS.has(providerId))
322
+ return [];
323
+ const period = utcDayPeriod(now);
324
+ const selected = metadata.accounts.find((account) => account.active);
325
+ // Bedrock figures are regional: the target carries the stored region and nothing else is assumed.
326
+ const targets = selected
327
+ ? [{ providerId, accountKey: selected.key, ...(selected.region ? { region: selected.region } : {}), period }]
328
+ : [];
329
+ if (providerId === BEDROCK_PROVIDER_ID) {
330
+ // Any stored entry without keys, profile or bearer token resolves through the ambient AWS chain, the same as inference.
331
+ const stored = metadata.sources.find((source) => source.source === "auth_json");
332
+ if (stored) {
333
+ targets.push({
334
+ providerId,
335
+ accountKey: "",
336
+ source: BEDROCK_AWS_CREDENTIALS_SOURCE,
337
+ ...(stored.region ? { region: stored.region } : {}),
338
+ period,
339
+ });
340
+ }
341
+ }
342
+ if (providerId === ANTHROPIC_PROVIDER_ID)
343
+ targets.push(anthropicOrganizationTarget(period));
344
+ return targets;
345
+ }
346
+ //# sourceMappingURL=flow-accounts-host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flow-accounts-host.js","sourceRoot":"","sources":["../../src/humain/flow-accounts-host.ts"],"names":[],"mappings":"AACA,OAAO,EACN,eAAe,EAGf,yBAAyB,GACzB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EACN,qBAAqB,EAErB,2BAA2B,EAC3B,8BAA8B,GAC9B,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACN,8BAA8B,EAC9B,mBAAmB,EAEnB,2BAA2B,EAC3B,4BAA4B,EAC5B,4BAA4B,GAC5B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAIjE,OAAO,EACN,kBAAkB,EAClB,cAAc,EACd,sBAAsB,EACtB,qBAAqB,GAKrB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,0BAA0B,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AA+BhH,MAAM,CAAC,MAAM,yBAAyB,GAAG,iCAAiC,CAAC;AAO3E,MAAM,QAAQ,GAAG,IAAI,OAAO,EAAsC,CAAC;AAEnE,wGAAwG;AACxG,MAAM,UAAU,oBAAoB,CAAC,QAAuB,EAAE,IAAsB;IACnF,QAAQ,CA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,KAAK,WAAW,CAAC,CAAC;QAChF,IAAI,MAAM,EAAE,CAAC;YACZ,OAAO,CAAC,IAAI,CAAC;gBACZ,UAAU;gBACV,UAAU,EAAE,EAAE;gBACd,MAAM,EAAE,8BAA8B;gBACtC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;gBACnD,MAAM;aACN,CAAC,CAAC;QACJ,CAAC;IACF,CAAC;IACD,IAAI,UAAU,KAAK,qBAAqB;QAAE,OAAO,CAAC,IAAI,CAAC,2BAA2B,CAAC,MAAM,CAAC,CAAC,CAAC;IAC5F,OAAO,OAAO,CAAC;AAChB,CAAC","sourcesContent":["import type { Api, Model } from \"@earendil-works/pi-ai\";\nimport {\n\tAccountReporter,\n\ttype AccountReportTarget,\n\ttype AccountUsageReport,\n\tcreateCodexUsageCollector,\n} from \"../core/account-reporting.ts\";\nimport {\n\tANTHROPIC_PROVIDER_ID,\n\ttype AnthropicReportingCredentialProvider,\n\tanthropicOrganizationTarget,\n\tcreateAnthropicReportCollector,\n} from \"../core/anthropic-account-reporting.ts\";\nimport {\n\tBEDROCK_AWS_CREDENTIALS_SOURCE,\n\tBEDROCK_PROVIDER_ID,\n\ttype BedrockReportCollectorDeps,\n\tbedrockReportingCredentials,\n\tcreateBedrockReportCollector,\n\topenCloudWatchMetricsSession,\n} from \"../core/bedrock-account-reporting.ts\";\nimport { CODEX_USAGE_PROVIDER_ID } from \"../core/codex-usage.ts\";\nimport type { ExtensionContext } from \"../core/extensions/types.ts\";\nimport type { ModelRegistry } from \"../core/model-registry.ts\";\nimport type { AccountInfo, AccountSource, ModelRuntime } from \"../core/model-runtime.ts\";\nimport {\n\tassessNodeFallback,\n\tisSafeNodeText,\n\tMAX_NODE_FALLBACK_KEYS,\n\tMAX_NODE_LABEL_LENGTH,\n\ttype NodeAccountFallbackPolicy,\n\ttype NodeAccountLabels,\n\ttype NodeAccountView,\n\ttype NodeFallbackAssessment,\n} from \"./node-account-fallback.ts\";\nimport { describeHumainNodeEndpoint, HUMAIN_NODE_BASE_URL_ENV, HUMAIN_NODE_PROVIDER } from \"./node-provider.ts\";\n\n/**\n * Session-bound bridge that lets Flow drive host-owned account dialogs and catalog readiness.\n * Credentials never cross it: every value is non-secret metadata or a model catalog.\n */\nexport type FlowCatalogState =\n\t| { state: \"ready\"; models: readonly Model<Api>[] }\n\t| { state: \"unavailable\"; reason: string };\n\nexport interface FlowAccountsHost {\n\t/**\n\t * Resolves after the user finishes or cancels the account interaction. Cancelling through the signal ends the\n\t * dialog; sign-ins, account switches and removals already completed stay in effect.\n\t */\n\topenAccounts(signal: AbortSignal): Promise<void>;\n\t/** Explicit action: refresh the provider's catalog for the selected account, allowing network access. */\n\trefreshCatalog(providerId: string, signal: AbortSignal): Promise<FlowCatalogState>;\n\t/**\n\t * Explicit \"Refresh usage\" action. The only path that reaches a reporting transport; listing accounts and opening\n\t * Advanced never call it. Resolves to a labelled report and never throws for unavailable data.\n\t */\n\trefreshAccountUsage(target: AccountReportTarget, signal: AbortSignal): Promise<AccountUsageReport>;\n\t/** Opt-in HUMAIN Node key fallback: current policy, aliases, labels and setup warnings. No network. */\n\tgetNodeFallback(signal: AbortSignal): Promise<FlowNodeFallbackState>;\n\t/** Validate and persist policy and labels outside the credential store, then return the new state. */\n\tupdateNodeFallback(update: FlowNodeFallbackUpdate, signal: AbortSignal): Promise<FlowNodeFallbackState>;\n\t/** Whether `text` contains a stored HUMAIN Node key. Only the answer crosses the bridge, never a key. */\n\tlabelContainsStoredKey(text: string, signal: AbortSignal): Promise<boolean>;\n}\n\nexport const FLOW_ACCOUNTS_UNAVAILABLE = \"Account interaction unavailable\";\n\ninterface FlowAccountsBinding {\n\thandle: FlowAccountsHost;\n\trelease: () => void;\n}\n\nconst bindings = new WeakMap<ModelRegistry, FlowAccountsBinding>();\n\n/** Bind a host to the registry of the current session. Rebinding supersedes the previous generation. */\nexport function bindFlowAccountsHost(registry: ModelRegistry, host: FlowAccountsHost): () => void {\n\tbindings.get(registry)?.release();\n\tconst generation = new AbortController();\n\tconst run = async <T>(signal: AbortSignal, operation: (signal: AbortSignal) => Promise<T>): Promise<T> => {\n\t\tif (generation.signal.aborted) throw new Error(FLOW_ACCOUNTS_UNAVAILABLE);\n\t\ttry {\n\t\t\tconst result = await operation(AbortSignal.any([signal, generation.signal]));\n\t\t\tif (generation.signal.aborted) throw new Error(FLOW_ACCOUNTS_UNAVAILABLE);\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\tif (generation.signal.aborted) throw new Error(FLOW_ACCOUNTS_UNAVAILABLE);\n\t\t\tthrow error;\n\t\t}\n\t};\n\tconst binding: FlowAccountsBinding = {\n\t\thandle: {\n\t\t\topenAccounts: (signal) => run(signal, (combined) => host.openAccounts(combined)),\n\t\t\trefreshCatalog: (providerId, signal) => run(signal, (combined) => host.refreshCatalog(providerId, combined)),\n\t\t\trefreshAccountUsage: (target, signal) => run(signal, (combined) => host.refreshAccountUsage(target, combined)),\n\t\t\tgetNodeFallback: (signal) => run(signal, (combined) => host.getNodeFallback(combined)),\n\t\t\tupdateNodeFallback: (update, signal) => run(signal, (combined) => host.updateNodeFallback(update, combined)),\n\t\t\tlabelContainsStoredKey: (text, signal) =>\n\t\t\t\trun(signal, (combined) => host.labelContainsStoredKey(text, combined)),\n\t\t},\n\t\trelease: () => {\n\t\t\tgeneration.abort();\n\t\t\tif (bindings.get(registry) === binding) bindings.delete(registry);\n\t\t},\n\t};\n\tbindings.set(registry, binding);\n\treturn binding.release;\n}\n\n/** Look up the host by actual registry identity. Only the terminal UI owns secure dialogs. */\nexport function getFlowAccountsHost(\n\tctx: Pick<ExtensionContext, \"modelRegistry\" | \"mode\">,\n): FlowAccountsHost | undefined {\n\treturn ctx.mode === \"tui\" ? bindings.get(ctx.modelRegistry)?.handle : undefined;\n}\n\n/** Secret-free account metadata. `endpoint` is the HUMAIN Node base URL; `region` the stored Bedrock region. */\nexport interface FlowAccountMetadata extends AccountInfo {\n\tendpoint?: string;\n\tregion?: string;\n}\n\nexport interface FlowAccountSourceMetadata extends AccountSource {\n\tendpoint?: string;\n\t/** Stored Bedrock region of the auth.json provider configuration. */\n\tregion?: string;\n}\n\nexport interface FlowProviderAccountMetadata {\n\tproviderId: string;\n\taccounts: FlowAccountMetadata[];\n\tsources: FlowAccountSourceMetadata[];\n}\n\nfunction envString(env: Record<string, unknown> | undefined, name: string): string | undefined {\n\tconst value = env?.[name];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Enumerate accounts and sources from stored metadata only. This never resolves credentials, refreshes OAuth,\n * runs credential commands, or touches the network; `accounts.list/sources` are side-effect-free by contract.\n */\nexport async function listFlowAccountMetadata(\n\truntime: ModelRuntime,\n\tproviderId: string,\n\tsignal: AbortSignal,\n\tambientEnv: NodeJS.ProcessEnv = process.env,\n): Promise<FlowProviderAccountMetadata> {\n\tconst options = { signal };\n\tconst accounts = await runtime.accounts.list(providerId, options);\n\tconst sources = await runtime.accounts.sources(providerId, options);\n\tconst stored = await runtime.oauthAccounts.listAccounts(providerId, options);\n\tconst ambientEndpoint = envString(ambientEnv, HUMAIN_NODE_BASE_URL_ENV);\n\tconst isNode = providerId === HUMAIN_NODE_PROVIDER;\n\t// Bedrock AWS-credentials logins have no key, so they are an auth.json source: read its region without resolving it.\n\tconst storedConfiguration =\n\t\tproviderId === BEDROCK_PROVIDER_ID ? await runtime.readStoredCredential(providerId, options) : undefined;\n\tconst sourceRegion =\n\t\tstoredConfiguration?.type === \"api_key\" ? envString(storedConfiguration.env, \"AWS_REGION\") : undefined;\n\treturn {\n\t\tproviderId,\n\t\taccounts: accounts.map((account) => {\n\t\t\tconst credential = stored.find((entry) => entry.key === account.key)?.credential;\n\t\t\tconst env = credential?.type === \"api_key\" ? credential.env : undefined;\n\t\t\tconst endpoint = isNode\n\t\t\t\t? describeHumainNodeEndpoint(envString(env, HUMAIN_NODE_BASE_URL_ENV), ambientEndpoint)\n\t\t\t\t: undefined;\n\t\t\tconst region = providerId === \"amazon-bedrock\" ? envString(env, \"AWS_REGION\") : undefined;\n\t\t\treturn { ...account, ...(endpoint ? { endpoint } : {}), ...(region ? { region } : {}) };\n\t\t}),\n\t\tsources: sources.map((source) => {\n\t\t\t// Only the environment source is defined by the ambient base URL; other sources carry no non-secret endpoint.\n\t\t\tconst endpoint =\n\t\t\t\tisNode && source.source === \"environment\"\n\t\t\t\t\t? describeHumainNodeEndpoint(undefined, ambientEndpoint)\n\t\t\t\t\t: undefined;\n\t\t\tif (sourceRegion && source.source === \"auth_json\") return { ...source, region: sourceRegion };\n\t\t\treturn endpoint ? { ...source, endpoint } : source;\n\t\t}),\n\t};\n}\n\nexport const NODE_USAGE_UNSUPPORTED = \"Usage reporting is not yet supported for HUMAIN Node.\";\nexport const BEDROCK_USAGE_NOTE =\n\t\"Usage reporting reads Amazon CloudWatch metrics and needs AWS credentials saved through Connect, with a region. A Bedrock API key cannot report usage.\";\nexport const FLOW_ACCOUNT_PERSISTENCE_NOTICE =\n\t\"Sign-in and account changes take effect immediately and are not undone by cancelling setup.\";\n\n/** Advanced details for the selected provider. Configured and effective never mean verified. */\nexport function formatFlowAccountAdvanced(\n\tproviderId: string,\n\tproviderName: string,\n\tmetadata: FlowProviderAccountMetadata,\n): string[] {\n\tconst lines: string[] = [];\n\tif (metadata.accounts.length === 0 && metadata.sources.length === 0) {\n\t\tlines.push(`No ${providerName} account is configured.`);\n\t}\n\tfor (const account of metadata.accounts) {\n\t\tconst parts = [account.type === \"oauth\" ? \"OAuth\" : \"API key\"];\n\t\tif (account.active) parts.push(\"selected\");\n\t\tconst state = account.effective\n\t\t\t? \"Effective for future requests.\"\n\t\t\t: account.active\n\t\t\t\t? \"An external source still controls requests.\"\n\t\t\t\t: \"Not selected.\";\n\t\tconst place = [\n\t\t\taccount.endpoint ? `Endpoint ${account.endpoint}.` : undefined,\n\t\t\taccount.region ? `Region ${account.region}.` : undefined,\n\t\t].filter(Boolean);\n\t\tlines.push(\n\t\t\t`${account.label} [${account.key}]: ${parts.join(\", \")}. ${state} Configured — not verified. ${place.join(\" \")}`.trim(),\n\t\t);\n\t}\n\tfor (const source of metadata.sources) {\n\t\tconst state = source.effective ? \"Effective for future requests.\" : \"Shadowed by a higher-precedence source.\";\n\t\tlines.push(\n\t\t\t`${source.label} [read-only]: ${state} Configured — not verified.${source.endpoint ? ` Endpoint ${source.endpoint}.` : \"\"}${source.region ? ` Region ${source.region}.` : \"\"}`,\n\t\t);\n\t}\n\tif (providerId === HUMAIN_NODE_PROVIDER) lines.push(NODE_USAGE_UNSUPPORTED);\n\tif (providerId === BEDROCK_PROVIDER_ID) lines.push(BEDROCK_USAGE_NOTE);\n\treturn lines;\n}\n\nconst RETRY_OTHERS = \"Retry, or continue with other providers.\";\n\nconst unavailable = (reason: string): FlowCatalogState => ({ state: \"unavailable\", reason });\n\nfunction nodeFailureReason(error: Error): string {\n\tconst text = `${error.name} ${error.message}`;\n\tif (/\\b(401|403)\\b|invalid_api_key|unauthori|revoked|inactive/iu.test(text)) {\n\t\treturn \"HUMAIN Node rejected the selected key. Check the key, then retry.\";\n\t}\n\tif (/TypeError|TimeoutError|fetch failed|network|ECONN|ENOTFOUND|EAI_AGAIN|timed out/iu.test(text)) {\n\t\treturn \"HUMAIN Node is unreachable. Check the connection, then retry.\";\n\t}\n\t// Raw provider text can carry request details; show only the category.\n\treturn `HUMAIN Node model discovery failed. ${RETRY_OTHERS}`;\n}\n\nasync function selectedKeyFingerprint(runtime: ModelRuntime, providerId: string, signal: AbortSignal): Promise<string> {\n\tconst metadata = await listFlowAccountMetadata(runtime, providerId, signal);\n\tconst selected = metadata.accounts.find((account) => account.active);\n\treturn JSON.stringify([\n\t\tselected?.key,\n\t\tselected?.endpoint,\n\t\tmetadata.sources.filter((source) => source.effective).map((source) => source.label),\n\t]);\n}\n\n/**\n * Wait for the selected key's catalog. HUMAIN Node discovery uses the network, so call this only after an explicit\n * account or catalog action. Anything short of a fresh, non-empty catalog for the same selected key is unavailable;\n * models are never invented or carried over from another key.\n */\nexport async function refreshFlowCatalog(\n\truntime: ModelRuntime,\n\tproviderId: string,\n\tsignal: AbortSignal,\n): Promise<FlowCatalogState> {\n\tconst cancelled = unavailable(\"Model discovery was cancelled. Retry when ready.\");\n\tif (signal.aborted) return cancelled;\n\tconst models = () => runtime.getAvailableSnapshot().filter((model) => model.provider === providerId);\n\tif (providerId !== HUMAIN_NODE_PROVIDER) {\n\t\tconst local = models();\n\t\treturn local.length > 0\n\t\t\t? { state: \"ready\", models: local }\n\t\t\t: unavailable(`No models are available for ${providerId}. Connect the provider, then retry.`);\n\t}\n\ttry {\n\t\tconst before = await selectedKeyFingerprint(runtime, providerId, signal);\n\t\tconst result = await runtime.refresh({ providers: [providerId], allowNetwork: true, force: true, signal });\n\t\tif (signal.aborted || result.aborted) return cancelled;\n\t\t// Check the key first: a late failure from the old key must not be blamed on the newly selected one.\n\t\tif ((await selectedKeyFingerprint(runtime, providerId, signal)) !== before) {\n\t\t\treturn unavailable(\n\t\t\t\t\"The selected HUMAIN Node key changed during discovery. Retry with the key you want to use.\",\n\t\t\t);\n\t\t}\n\t\tconst error = result.errors.get(providerId);\n\t\tif (error) return unavailable(nodeFailureReason(error));\n\t\tif (!runtime.hasConfiguredAuth(providerId)) {\n\t\t\treturn unavailable(\"No HUMAIN Node key is configured. Connect one, then retry.\");\n\t\t}\n\t\tconst discovered = models();\n\t\treturn discovered.length > 0\n\t\t\t? { state: \"ready\", models: discovered }\n\t\t\t: unavailable(`HUMAIN Node returned no models for the selected key. ${RETRY_OTHERS}`);\n\t} catch {\n\t\treturn signal.aborted ? cancelled : unavailable(`HUMAIN Node model discovery failed. ${RETRY_OTHERS}`);\n\t}\n}\n\n/** Secret-free state for the Node fallback setup step. `accounts` lists stored Node API-key accounts in pool order. */\nexport interface FlowNodeFallbackState extends NodeFallbackAssessment {\n\tpolicy: Required<NodeAccountFallbackPolicy>;\n\taccounts: NodeAccountView[];\n}\n\nexport interface FlowNodeFallbackUpdate {\n\tpolicy?: Partial<NodeAccountFallbackPolicy>;\n\t/** Per account key. `null` clears a label. */\n\tlabels?: Record<string, { nodeUser?: string | null; environment?: string | null }>;\n}\n\n/** Read the policy and labels. Uses stored metadata only: no credential resolution, refresh or network access. */\nexport async function readFlowNodeFallbackState(\n\truntime: ModelRuntime,\n\tsignal: AbortSignal,\n\tambientEnv: NodeJS.ProcessEnv = process.env,\n): Promise<FlowNodeFallbackState> {\n\tconst metadata = await listFlowAccountMetadata(runtime, HUMAIN_NODE_PROVIDER, signal, ambientEnv);\n\tconst stored = runtime.nodeAccountMetadata.read();\n\tconst accounts = metadata.accounts\n\t\t.filter((account) => account.type === \"api_key\")\n\t\t.map((account): NodeAccountView => {\n\t\t\tconst labels = Object.hasOwn(stored.accounts, account.key) ? stored.accounts[account.key] : undefined;\n\t\t\treturn {\n\t\t\t\tkey: account.key,\n\t\t\t\talias: account.label,\n\t\t\t\t...(account.endpoint ? { endpoint: account.endpoint } : {}),\n\t\t\t\t...(labels?.nodeUser ? { nodeUser: labels.nodeUser } : {}),\n\t\t\t\t...(labels?.environment ? { environment: labels.environment } : {}),\n\t\t\t\tactive: account.active,\n\t\t\t\tinFallback: stored.policy.accountKeys.includes(account.key),\n\t\t\t};\n\t\t});\n\treturn { policy: stored.policy, accounts, ...assessNodeFallback(accounts, stored.policy) };\n}\n\nconst containsKey = (apiKeys: readonly (string | undefined)[], text: string): boolean =>\n\tapiKeys.some((secret) => secret !== undefined && secret.length > 0 && text.includes(secret));\n\n/** True when `text` would embed a stored Node API key. Stored metadata only: no refresh, no network. */\nexport async function nodeLabelContainsStoredKey(\n\truntime: ModelRuntime,\n\ttext: string,\n\tsignal: AbortSignal,\n): Promise<boolean> {\n\tconst stored = await runtime.oauthAccounts.listAccounts(HUMAIN_NODE_PROVIDER, { signal });\n\treturn containsKey(\n\t\tstored.flatMap((account) => (account.credential.type === \"api_key\" ? [account.credential.key] : [])),\n\t\ttext.trim(),\n\t);\n}\n\nconst INVALID_NODE_LABEL = \"HUMAIN Node labels must be 1 to 80 printable characters and must not contain a key.\";\nconst INVALID_NODE_POLICY_FLAG = \"HUMAIN Node fallback policy flags must be true or false.\";\n\n/**\n * Persist the opt-in fallback policy and user labels. Keys are only referenced by their stored account key; unknown\n * or duplicate keys, oversized or key-bearing labels are rejected before anything is written.\n */\nexport async function updateFlowNodeFallback(\n\truntime: ModelRuntime,\n\tupdate: FlowNodeFallbackUpdate,\n\tsignal: AbortSignal,\n\tambientEnv: NodeJS.ProcessEnv = process.env,\n): Promise<FlowNodeFallbackState> {\n\tsignal.throwIfAborted();\n\tconst stored = await runtime.oauthAccounts.listAccounts(HUMAIN_NODE_PROVIDER, { signal });\n\tconst apiKeys = stored.flatMap((account) => (account.credential.type === \"api_key\" ? [account.credential.key] : []));\n\tconst known = new Set(\n\t\tstored.filter((account) => account.credential.type === \"api_key\").map((account) => account.key),\n\t);\n\tconst accountKeys = update.policy?.accountKeys;\n\tif (accountKeys !== undefined) {\n\t\tif (\n\t\t\t!Array.isArray(accountKeys) ||\n\t\t\taccountKeys.length > MAX_NODE_FALLBACK_KEYS ||\n\t\t\tnew Set(accountKeys).size !== accountKeys.length ||\n\t\t\t!accountKeys.every((key) => known.has(key))\n\t\t) {\n\t\t\tthrow new Error(\"The HUMAIN Node fallback list must name distinct stored Node keys.\");\n\t\t}\n\t}\n\tfor (const flag of [update.policy?.enabled, update.policy?.allowCrossEndpoint]) {\n\t\tif (flag !== undefined && typeof flag !== \"boolean\") throw new Error(INVALID_NODE_POLICY_FLAG);\n\t}\n\tconst labelChanges = Object.entries(update.labels ?? {});\n\tfor (const [key, labels] of labelChanges) {\n\t\tif (!known.has(key)) throw new Error(\"HUMAIN Node labels must name a stored Node key.\");\n\t\tfor (const value of [labels.nodeUser, labels.environment]) {\n\t\t\tif (value === undefined || value === null) continue;\n\t\t\tconst text = value.trim();\n\t\t\tif (!isSafeNodeText(text, MAX_NODE_LABEL_LENGTH) || containsKey(apiKeys, text)) {\n\t\t\t\tthrow new Error(INVALID_NODE_LABEL);\n\t\t\t}\n\t\t}\n\t}\n\tsignal.throwIfAborted();\n\truntime.nodeAccountMetadata.update((current) => {\n\t\tconst accounts = { ...current.accounts };\n\t\tfor (const [key, labels] of labelChanges) {\n\t\t\tconst next: NodeAccountLabels = { ...(Object.hasOwn(accounts, key) ? accounts[key] : {}) };\n\t\t\tfor (const field of [\"nodeUser\", \"environment\"] as const) {\n\t\t\t\tconst value = labels[field];\n\t\t\t\tif (value === null) delete next[field];\n\t\t\t\telse if (value !== undefined) next[field] = value.trim();\n\t\t\t}\n\t\t\taccounts[key] = next;\n\t\t}\n\t\treturn {\n\t\t\tpolicy: {\n\t\t\t\tenabled: update.policy?.enabled ?? current.policy.enabled,\n\t\t\t\taccountKeys: update.policy?.accountKeys ?? current.policy.accountKeys,\n\t\t\t\tallowCrossEndpoint: update.policy?.allowCrossEndpoint ?? current.policy.allowCrossEndpoint,\n\t\t\t},\n\t\t\taccounts,\n\t\t};\n\t});\n\treturn readFlowNodeFallbackState(runtime, signal, ambientEnv);\n}\n\n/** Providers whose Advanced view offers \"Refresh usage\". Node reports its own exact unsupported text instead. */\nexport const FLOW_USAGE_REPORTING_PROVIDERS: ReadonlySet<string> = new Set([\n\tANTHROPIC_PROVIDER_ID,\n\tBEDROCK_PROVIDER_ID,\n\tCODEX_USAGE_PROVIDER_ID,\n]);\n\nexport interface FlowAccountReporterOptions {\n\t/**\n\t * Explicitly provisioned Anthropic Admin API reporting credentials. The host has no supported secure provisioning\n\t * for them today, so this is normally absent and organization reporting reads \"reporting credentials not configured\".\n\t */\n\torganizationCredentials?: AnthropicReportingCredentialProvider;\n\tfetch?: typeof fetch;\n\tnow?: () => number;\n\t/** SDK client factory for Bedrock CloudWatch reporting. Defaults to the official AWS SDK client. */\n\topenBedrockClient?: BedrockReportCollectorDeps[\"openClient\"];\n}\n\n/** Build the session reporter. Nothing is fetched or resolved until `refreshAccountUsage` is called. */\nexport function createFlowAccountReporter(\n\truntime: ModelRuntime,\n\toptions: FlowAccountReporterOptions = {},\n): AccountReporter {\n\treturn new AccountReporter({\n\t\tnow: options.now,\n\t\tcollectors: {\n\t\t\t[CODEX_USAGE_PROVIDER_ID]: createCodexUsageCollector({\n\t\t\t\treadAccount: async (accountKey, signal) =>\n\t\t\t\t\t(await runtime.oauthAccounts.list(CODEX_USAGE_PROVIDER_ID, { signal })).find(\n\t\t\t\t\t\t(account) => account.key === accountKey,\n\t\t\t\t\t),\n\t\t\t\tfetch: options.fetch,\n\t\t\t\tnow: options.now,\n\t\t\t}),\n\t\t\t[ANTHROPIC_PROVIDER_ID]: createAnthropicReportCollector({\n\t\t\t\tstore: runtime.anthropicRateLimits,\n\t\t\t\taccountType: async (accountKey, signal) =>\n\t\t\t\t\t(await runtime.oauthAccounts.listAccounts(ANTHROPIC_PROVIDER_ID, { signal })).find(\n\t\t\t\t\t\t(account) => account.key === accountKey,\n\t\t\t\t\t)?.credential.type,\n\t\t\t\torganizationCredentials: options.organizationCredentials,\n\t\t\t\tfetch: options.fetch,\n\t\t\t\tnow: options.now,\n\t\t\t}),\n\t\t\t[BEDROCK_PROVIDER_ID]: createBedrockReportCollector({\n\t\t\t\tresolveCredentials: async (target, signal) => {\n\t\t\t\t\tconst credential =\n\t\t\t\t\t\ttarget.source === undefined\n\t\t\t\t\t\t\t? (await runtime.oauthAccounts.listAccounts(BEDROCK_PROVIDER_ID, { signal })).find(\n\t\t\t\t\t\t\t\t\t(entry) => entry.key === target.accountKey,\n\t\t\t\t\t\t\t\t)?.credential\n\t\t\t\t\t\t\t: await runtime.readStoredCredential(BEDROCK_PROVIDER_ID, { signal });\n\t\t\t\t\treturn credential ? bedrockReportingCredentials(credential) : undefined;\n\t\t\t\t},\n\t\t\t\topenClient: options.openBedrockClient ?? openCloudWatchMetricsSession,\n\t\t\t\tnow: options.now,\n\t\t\t}),\n\t\t},\n\t});\n}\n\n/** UTC calendar day containing `now`: the reporting period for window-based sources. */\nexport function utcDayPeriod(now: number): AccountReportTarget[\"period\"] {\n\tconst start = new Date(now);\n\tstart.setUTCHours(0, 0, 0, 0);\n\treturn { start: start.toISOString(), end: new Date(start.getTime() + 24 * 60 * 60 * 1000).toISOString() };\n}\n\n/**\n * Targets for \"Refresh usage\" from stored metadata: the selected account (Bedrock: with its stored region), plus\n * Anthropic organization reporting as its own source. `openai` API accounts and every other provider have none: their usage is never inferred.\n */\nexport function flowUsageTargets(\n\tproviderId: string,\n\tmetadata: FlowProviderAccountMetadata,\n\tnow: number,\n): AccountReportTarget[] {\n\tif (!FLOW_USAGE_REPORTING_PROVIDERS.has(providerId)) return [];\n\tconst period = utcDayPeriod(now);\n\tconst selected = metadata.accounts.find((account) => account.active);\n\t// Bedrock figures are regional: the target carries the stored region and nothing else is assumed.\n\tconst targets: AccountReportTarget[] = selected\n\t\t? [{ providerId, accountKey: selected.key, ...(selected.region ? { region: selected.region } : {}), period }]\n\t\t: [];\n\tif (providerId === BEDROCK_PROVIDER_ID) {\n\t\t// Any stored entry without keys, profile or bearer token resolves through the ambient AWS chain, the same as inference.\n\t\tconst stored = metadata.sources.find((source) => source.source === \"auth_json\");\n\t\tif (stored) {\n\t\t\ttargets.push({\n\t\t\t\tproviderId,\n\t\t\t\taccountKey: \"\",\n\t\t\t\tsource: BEDROCK_AWS_CREDENTIALS_SOURCE,\n\t\t\t\t...(stored.region ? { region: stored.region } : {}),\n\t\t\t\tperiod,\n\t\t\t});\n\t\t}\n\t}\n\tif (providerId === ANTHROPIC_PROVIDER_ID) targets.push(anthropicOrganizationTarget(period));\n\treturn targets;\n}\n"]}
@@ -0,0 +1,28 @@
1
+ import type { AutocompleteItem } from "@earendil-works/pi-tui";
2
+ /**
3
+ * Static vocabulary, parsing, help and completion for the single `/flow` command. Pure and dependency-light on
4
+ * purpose: the lazy loader uses it before (and without) importing Flow, so help works when Flow is disabled.
5
+ */
6
+ export declare const FLOW_SUBCOMMANDS: readonly ["help", "run", "continue", "list", "status", "cancel", "pause", "resume", "title", "message", "hide", "show", "models", "profile", "setup"];
7
+ export type FlowSubcommand = (typeof FLOW_SUBCOMMANDS)[number];
8
+ /** Refusal for `/flow setup` outside the terminal UI: secure account dialogs exist only there. */
9
+ export declare const FLOW_SETUP_TERMINAL_ONLY = "/flow setup needs the interactive terminal. Use /flow models and /flow profile for changes from other modes.";
10
+ /** Copy for a recognized subcommand this build does not implement yet. */
11
+ export declare function flowBuildUnavailable(command: string): string;
12
+ /**
13
+ * Splits `/flow` arguments into subcommand and payload. Consumes the subcommand and exactly one separating
14
+ * whitespace character; the rest of the payload is returned byte-for-byte so goal, message and title text is
15
+ * never split or rejoined. Bare or whitespace-only input means help.
16
+ */
17
+ export declare function parseFlowCommand(args: string): {
18
+ command: FlowSubcommand;
19
+ payload: string;
20
+ } | {
21
+ error: string;
22
+ command?: FlowSubcommand;
23
+ };
24
+ /** Static help text. An unrecognized topic yields the unknown-topic copy; the parser rejects those before this. */
25
+ export declare function renderFlowHelp(topic?: string): string;
26
+ /** Static completion for the argument text after `/flow `: subcommands, then help topics and nested names. */
27
+ export declare function completeFlowArguments(prefix: string): AutocompleteItem[] | null;
28
+ //# sourceMappingURL=flow-command.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flow-command.d.ts","sourceRoot":"","sources":["../../src/humain/flow-command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAG/D;;;GAGG;AAEH,eAAO,MAAM,gBAAgB,YAC5B,MAAM,EACN,KAAK,EACL,UAAU,EACV,MAAM,EACN,QAAQ,EACR,QAAQ,EACR,OAAO,EACP,QAAQ,EACR,OAAO,EACP,SAAS,EACT,MAAM,EACN,MAAM,EACN,QAAQ,EACR,SAAS,EACT,OAAO,CACE,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC;AAE/D,kGAAkG;AAClG,eAAO,MAAM,wBAAwB,iHAC0E,CAAC;AAkDhH,0EAA0E;AAC1E,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC/B,IAAI,EAAE,MAAM,GACV;IAAE,OAAO,EAAE,cAAc,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,cAAc,CAAA;CAAE,CA2B5F;AAuFD,mHAAmH;AACnH,wBAAgB,cAAc,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAOrD;AAED,8GAA8G;AAC9G,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,gBAAgB,EAAE,GAAG,IAAI,CAyB/E"}