@denizokcu/haze 1.7.10 → 1.7.12

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 (142) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +125 -99
  3. package/assets/graph-grammars/NOTICE.md +21 -0
  4. package/assets/graph-grammars/tree-sitter-javascript.wasm +0 -0
  5. package/assets/graph-grammars/tree-sitter-tsx.wasm +0 -0
  6. package/assets/graph-grammars/tree-sitter-typescript.wasm +0 -0
  7. package/assets/graph-grammars/web-tree-sitter.cjs +4116 -0
  8. package/assets/graph-grammars/web-tree-sitter.cjs.map +7 -0
  9. package/assets/graph-grammars/web-tree-sitter.js +4056 -0
  10. package/assets/graph-grammars/web-tree-sitter.js.map +7 -0
  11. package/assets/graph-grammars/web-tree-sitter.wasm +0 -0
  12. package/assets/graph-grammars/web-tree-sitter.wasm.map +55 -0
  13. package/dist/buildInfo.json +3 -3
  14. package/dist/cli/chat/BusyBar.d.ts +2 -1
  15. package/dist/cli/chat/BusyBar.js +2 -2
  16. package/dist/cli/chat/chatMetrics.d.ts +25 -0
  17. package/dist/cli/chat/chatMetrics.js +36 -0
  18. package/dist/cli/chat/inputSuggestions.js +1 -0
  19. package/dist/cli/chat/sessionLifecycle.d.ts +2 -0
  20. package/dist/cli/chat/sessionLifecycle.js +29 -19
  21. package/dist/cli/chat/sessionRecorder.d.ts +2 -1
  22. package/dist/cli/chat/sessionRecorder.js +29 -9
  23. package/dist/cli/chat/startupSequence.d.ts +2 -0
  24. package/dist/cli/chat/startupSequence.js +6 -0
  25. package/dist/cli/chat/transcriptPartition.js +10 -4
  26. package/dist/cli/chat/wizard/providerHandlers.js +57 -9
  27. package/dist/cli/chat/wizard/sessionThemeHandlers.js +5 -1
  28. package/dist/cli/commands/chat.js +44 -9
  29. package/dist/cli/commands/commandHelp.js +6 -3
  30. package/dist/cli/commands/commands.js +2 -0
  31. package/dist/cli/commands/formatters.js +28 -0
  32. package/dist/cli/commands/graphCommand.d.ts +2 -0
  33. package/dist/cli/commands/graphCommand.js +60 -0
  34. package/dist/cli/commands/initCommand.js +14 -0
  35. package/dist/cli/commands/providerWizard.js +9 -17
  36. package/dist/cli/commands/reasoningCommand.d.ts +1 -0
  37. package/dist/cli/commands/reasoningCommand.js +32 -4
  38. package/dist/cli/commands/runCommand.js +7 -1
  39. package/dist/cli/commands/streaming/agentAttempt.js +11 -1
  40. package/dist/cli/commands/streaming/attemptLifecycle.js +1 -0
  41. package/dist/cli/commands/streaming/attemptOutcome.js +6 -2
  42. package/dist/cli/commands/streaming/attemptSetup.d.ts +3 -0
  43. package/dist/cli/commands/streaming/attemptSetup.js +13 -6
  44. package/dist/cli/commands/streaming/goalSupervisor.d.ts +1 -1
  45. package/dist/cli/commands/streaming/goalSupervisor.js +22 -1
  46. package/dist/cli/commands/streaming/prepareStep.js +1 -0
  47. package/dist/cli/commands/streaming/streamLoop.d.ts +2 -0
  48. package/dist/cli/commands/streaming/streamLoop.js +14 -10
  49. package/dist/cli/commands/streaming/toolPartHandlers.js +7 -1
  50. package/dist/cli/commands/streaming.d.ts +2 -0
  51. package/dist/cli/commands/streaming.js +5 -0
  52. package/dist/cli/commands/wizardFlow.d.ts +1 -0
  53. package/dist/cli/commands/wizardFlow.js +10 -4
  54. package/dist/cli/index.js +5 -3
  55. package/dist/config/hazeBuild.d.ts +2 -2
  56. package/dist/config/hazeBuild.js +2 -2
  57. package/dist/config/modelDiscovery.d.ts +1 -1
  58. package/dist/config/modelDiscovery.js +8 -8
  59. package/dist/config/{modelCatalog.d.ts → providerModelFacts.d.ts} +13 -2
  60. package/dist/config/{modelCatalog.js → providerModelFacts.js} +145 -21
  61. package/dist/config/providerPresets.d.ts +8 -19
  62. package/dist/config/providerPresets.js +86 -555
  63. package/dist/config/providerReasoning.d.ts +16 -0
  64. package/dist/config/providerReasoning.js +56 -0
  65. package/dist/config/providers.d.ts +4 -0
  66. package/dist/config/providers.js +19 -2
  67. package/dist/config/settings.d.ts +14 -0
  68. package/dist/config/settings.js +5 -0
  69. package/dist/core/agent/compaction.d.ts +1 -0
  70. package/dist/core/agent/compaction.js +3 -0
  71. package/dist/core/agent/events.d.ts +1 -1
  72. package/dist/core/agent/providerTransition.d.ts +8 -0
  73. package/dist/core/agent/providerTransition.js +47 -0
  74. package/dist/core/agent/reasoningPolicy.d.ts +1 -1
  75. package/dist/core/agent/reasoningPolicy.js +4 -2
  76. package/dist/core/graph/analyze.d.ts +61 -0
  77. package/dist/core/graph/analyze.js +274 -0
  78. package/dist/core/graph/buildGraph.d.ts +44 -0
  79. package/dist/core/graph/buildGraph.js +290 -0
  80. package/dist/core/graph/digest.d.ts +2 -0
  81. package/dist/core/graph/digest.js +40 -0
  82. package/dist/core/graph/extract.d.ts +58 -0
  83. package/dist/core/graph/extract.js +394 -0
  84. package/dist/core/graph/model.d.ts +63 -0
  85. package/dist/core/graph/model.js +96 -0
  86. package/dist/core/graph/query.d.ts +69 -0
  87. package/dist/core/graph/query.js +391 -0
  88. package/dist/core/graph/store.d.ts +64 -0
  89. package/dist/core/graph/store.js +171 -0
  90. package/dist/core/limits.d.ts +0 -2
  91. package/dist/core/limits.js +0 -2
  92. package/dist/core/process/runBoundedProcess.js +12 -6
  93. package/dist/core/providerContracts.d.ts +9 -8
  94. package/dist/core/providerContracts.js +21 -1
  95. package/dist/core/safety/redaction.js +12 -2
  96. package/dist/core/safety/untrustedEnvelopes.d.ts +6 -0
  97. package/dist/core/safety/untrustedEnvelopes.js +17 -2
  98. package/dist/core/session/sessionSlimming.js +5 -59
  99. package/dist/core/session/sessionStore.d.ts +4 -0
  100. package/dist/core/session/sessionStore.js +149 -9
  101. package/dist/core/session/snapshotCodec.d.ts +5 -0
  102. package/dist/core/session/snapshotCodec.js +47 -0
  103. package/dist/core/shellOutput/registry.js +2 -46
  104. package/dist/core/subagent/executionProfiles.js +8 -5
  105. package/dist/core/tasks/taskStorage.js +11 -1
  106. package/dist/core/toolOutput/reduction.d.ts +55 -2
  107. package/dist/core/toolOutput/reduction.js +77 -2
  108. package/dist/core/validation/outputParser.js +16 -8
  109. package/dist/llm/client.d.ts +4 -2
  110. package/dist/llm/client.js +104 -55
  111. package/dist/llm/hazeTools.d.ts +2 -12426
  112. package/dist/llm/hazeTools.js +2 -0
  113. package/dist/llm/lspTools.d.ts +3 -12622
  114. package/dist/llm/mistralReasoning.d.ts +2 -0
  115. package/dist/llm/mistralReasoning.js +17 -0
  116. package/dist/llm/mistralVibeAuth.d.ts +5 -0
  117. package/dist/llm/mistralVibeAuth.js +63 -0
  118. package/dist/llm/requestContext.d.ts +3 -0
  119. package/dist/llm/requestContext.js +21 -11
  120. package/dist/llm/subagentRunner.d.ts +2 -308
  121. package/dist/llm/subagentRunner.js +15 -7
  122. package/dist/llm/systemPrompt.js +7 -4
  123. package/dist/llm/toolResultTypes.d.ts +1 -1
  124. package/dist/llm/toolResultTypes.js +7 -1
  125. package/dist/llm/tools/fetchTool.d.ts +2 -1221
  126. package/dist/llm/tools/fileTools.d.ts +2 -7768
  127. package/dist/llm/tools/graphAdvisory.d.ts +22 -0
  128. package/dist/llm/tools/graphAdvisory.js +68 -0
  129. package/dist/llm/tools/graphTools.d.ts +13 -0
  130. package/dist/llm/tools/graphTools.js +195 -0
  131. package/dist/llm/tools/outputCap.d.ts +2 -7
  132. package/dist/llm/tools/outputCap.js +3 -11
  133. package/dist/llm/tools/processTool.d.ts +2 -1081
  134. package/dist/llm/tools/replaceInFiles.js +5 -0
  135. package/dist/llm/tools/shellTool.d.ts +2 -1513
  136. package/dist/llm/tools/storedOutputTool.d.ts +2 -355
  137. package/dist/llm/tools/taskTool.d.ts +2 -489
  138. package/dist/llm/tools/toolContext.js +24 -9
  139. package/dist/llm/tools/toolContextState.d.ts +3 -0
  140. package/dist/llm/tools/toolContextState.js +2 -1
  141. package/dist/skills/skillTools.js +4 -1
  142. package/package.json +24 -15
@@ -0,0 +1,16 @@
1
+ import type { ReasoningLevel } from '../core/agent/reasoningPolicy.js';
2
+ import { type ResolvedReasoningPolicy } from '../core/agent/reasoningPolicy.js';
3
+ import type { HazeProviderSettings } from './settings.js';
4
+ /** Apply Mistral-specific transport only to its direct API. */
5
+ export declare function isMistralApi(url: string): boolean;
6
+ /** Known effort levels for direct endpoints; gateways retain their own policy. */
7
+ export declare function providerReasoningLevels(url: string, model: string): readonly ReasoningLevel[] | undefined;
8
+ export interface ReasoningCapabilities {
9
+ support: 'supported' | 'unsupported' | 'unknown';
10
+ levels: readonly ReasoningLevel[];
11
+ }
12
+ /** One shared profile for the UI, main request, and auxiliary calls. */
13
+ export declare function reasoningCapabilitiesForProvider(provider: HazeProviderSettings, model: string): ReasoningCapabilities;
14
+ export declare function reasoningLevelsForProvider(provider: HazeProviderSettings, model: string): readonly ReasoningLevel[];
15
+ /** Shared requested-versus-sent decision for UI and all request paths. */
16
+ export declare function resolveProviderReasoning(provider: HazeProviderSettings, model: string, requested: ReasoningLevel | undefined): ResolvedReasoningPolicy;
@@ -0,0 +1,56 @@
1
+ import { REASONING_LEVELS } from '../core/agent/reasoningPolicy.js';
2
+ import { endpointModelFacts } from './providerModelFacts.js';
3
+ /** Apply Mistral-specific transport only to its direct API. */
4
+ export function isMistralApi(url) {
5
+ try {
6
+ return new URL(url).hostname.toLowerCase() === 'api.mistral.ai';
7
+ }
8
+ catch {
9
+ return false;
10
+ }
11
+ }
12
+ /** Known effort levels for direct endpoints; gateways retain their own policy. */
13
+ export function providerReasoningLevels(url, model) {
14
+ return endpointModelFacts(url, model).reasoningLevels;
15
+ }
16
+ /** One shared profile for the UI, main request, and auxiliary calls. */
17
+ export function reasoningCapabilitiesForProvider(provider, model) {
18
+ const known = (levels) => ({ support: levels.length ? 'supported' : 'unsupported', levels });
19
+ if (provider.capabilities?.reasoningEffort === false)
20
+ return known([]);
21
+ const override = provider.modelReasoningLevels?.[model] ?? provider.reasoningLevels;
22
+ if (override)
23
+ return known(provider.reasoningFormat === 'thinking' || provider.reasoningFormat === 'enable-thinking' ? override.filter(level => level === 'none' || level === 'high') : override);
24
+ if (provider.reasoningFormat === 'thinking' || provider.reasoningFormat === 'enable-thinking')
25
+ return known(['none', 'high']);
26
+ if (provider.capabilities?.reasoningEffort === true)
27
+ return known(REASONING_LEVELS);
28
+ const documented = providerReasoningLevels(provider.kind === 'chatgpt-codex' ? 'https://api.openai.com' : provider.url, model);
29
+ if (documented)
30
+ return known(documented);
31
+ if (provider.kind === 'haze-build')
32
+ return known(['none', 'high']);
33
+ // Official OpenAI and OpenRouter protocols support portable effort settings.
34
+ // A model-specific profile above narrows the choices when documented.
35
+ try {
36
+ const host = new URL(provider.url).hostname.toLowerCase();
37
+ if (host === 'openrouter.ai')
38
+ return known(['none', 'minimal', 'low', 'medium', 'high', 'xhigh']);
39
+ }
40
+ catch { /* Invalid URLs are rejected when creating the runtime. */ }
41
+ return { support: 'unknown', levels: [] };
42
+ }
43
+ export function reasoningLevelsForProvider(provider, model) {
44
+ return reasoningCapabilitiesForProvider(provider, model).levels;
45
+ }
46
+ /** Shared requested-versus-sent decision for UI and all request paths. */
47
+ export function resolveProviderReasoning(provider, model, requested) {
48
+ if (!requested)
49
+ return { requested, effective: 'disabled', reason: 'no reasoning depth requested' };
50
+ const { support, levels } = reasoningCapabilitiesForProvider(provider, model);
51
+ if (!levels.length)
52
+ return { requested, effective: 'disabled', reason: support === 'unknown' ? 'reasoning support is unknown; parameter omitted (provider default)' : 'reasoning effort is unsupported; parameter omitted (provider default)' };
53
+ if (!levels.includes(requested))
54
+ return { requested, effective: 'disabled', reason: `${model} does not support reasoning effort ${requested}; parameter omitted (provider default). Choose ${levels.join(', ')}, or unset.` };
55
+ return { requested, effective: requested, reason: 'applied via supported provider protocol' };
56
+ }
@@ -19,7 +19,11 @@ export declare function activeModel(settings: HazeSettings): {
19
19
  } | undefined;
20
20
  export declare function resolveModelSelector(settings: HazeSettings, selector: string): ModelResolution;
21
21
  export declare function modelSelector(provider: HazeProviderSettings, model: string): string;
22
+ /** Stable non-secret endpoint identity for detecting changes across resume. */
23
+ export declare function providerEndpointFingerprint(provider: Pick<HazeProviderSettings, 'url' | 'kind'>): string;
22
24
  export declare function upsertProvider(settings: HazeSettings, provider: HazeProviderSettings): HazeProviderSettings[];
23
25
  export declare function providerHasKey(settings: HazeSettings, provider: HazeProviderSettings): boolean;
26
+ /** Legacy API keys are scoped to the legacy OpenRouter provider. */
27
+ export declare function providerApiKey(settings: HazeSettings, provider: HazeProviderSettings): string | undefined;
24
28
  /** Image input is explicit-only (F03): never inferred from URL or model name. */
25
29
  export declare function providerImageCapable(provider: HazeProviderSettings): boolean;
@@ -1,4 +1,5 @@
1
1
  import { findByName, upsertByName } from '../utils/collections.js';
2
+ import { createHash } from 'node:crypto';
2
3
  // Used only to migrate legacy single-provider OpenRouter settings (apiKey/baseURL)
3
4
  // into the providers array. There is no default provider or model anymore: users
4
5
  // must configure a provider themselves via /provider.
@@ -21,16 +22,23 @@ function normalizeProvider(provider, fallbackModel) {
21
22
  const key = provider.key?.trim();
22
23
  // Capabilities are explicit only: an absent/false flag means "not capable".
23
24
  const capabilities = provider.capabilities ?? undefined;
24
- return {
25
+ const normalized = {
26
+ ...provider,
25
27
  name,
26
28
  url,
27
29
  ...(key ? { key } : {}),
28
30
  ...(provider.kind ? { kind: provider.kind } : {}),
29
31
  ...(capabilities ? { capabilities } : {}),
32
+ ...(provider.reasoningLevels ? { reasoningLevels: provider.reasoningLevels } : {}),
33
+ ...(provider.modelReasoningLevels ? { modelReasoningLevels: provider.modelReasoningLevels } : {}),
34
+ ...(provider.reasoningFormat ? { reasoningFormat: provider.reasoningFormat } : {}),
30
35
  ...(provider.modelLimits ? { modelLimits: provider.modelLimits } : {}),
31
36
  ...(provider.trustedDeployments ? { trustedDeployments: provider.trustedDeployments } : {}),
32
37
  models: normalizeModels(provider.models, fallbackModel),
33
38
  };
39
+ if (!key)
40
+ delete normalized.key;
41
+ return normalized;
34
42
  }
35
43
  export function configuredProviders(settings) {
36
44
  const providers = (settings.providers ?? [])
@@ -86,11 +94,20 @@ export function resolveModelSelector(settings, selector) {
86
94
  export function modelSelector(provider, model) {
87
95
  return `${provider.name}:${model}`;
88
96
  }
97
+ /** Stable non-secret endpoint identity for detecting changes across resume. */
98
+ export function providerEndpointFingerprint(provider) {
99
+ return createHash('sha256').update(`${provider.kind ?? 'openai-compatible'}\0${provider.url}`).digest('hex');
100
+ }
89
101
  export function upsertProvider(settings, provider) {
90
102
  return upsertByName(configuredProviders(settings), provider);
91
103
  }
92
104
  export function providerHasKey(settings, provider) {
93
- return Boolean(provider.key ?? (provider.name === 'openrouter' ? settings.apiKey : undefined));
105
+ return Boolean(providerApiKey(settings, provider));
106
+ }
107
+ /** Legacy API keys are scoped to the legacy OpenRouter provider. */
108
+ export function providerApiKey(settings, provider) {
109
+ const legacyUrl = settings.baseURL ?? LEGACY_OPENROUTER_URL;
110
+ return provider.key ?? (provider.name === 'openrouter' && provider.url.replace(/\/+$/, '') === legacyUrl.replace(/\/+$/, '') ? settings.apiKey : undefined);
94
111
  }
95
112
  /** Image input is explicit-only (F03): never inferred from URL or model name. */
96
113
  export function providerImageCapable(provider) {
@@ -8,6 +8,7 @@ export declare const reasoningLevelSchema: z.ZodEnum<{
8
8
  medium: "medium";
9
9
  high: "high";
10
10
  xhigh: "xhigh";
11
+ max: "max";
11
12
  "provider-default": "provider-default";
12
13
  }>;
13
14
  export interface HazeProviderSettings {
@@ -17,6 +18,8 @@ export interface HazeProviderSettings {
17
18
  models: string[];
18
19
  /** Explicit runtime/auth protocol. Omitted means a normal OpenAI-compatible endpoint. */
19
20
  kind?: 'openai-compatible' | 'chatgpt-codex' | 'haze-build';
21
+ /** Override automatic local/hosted inference for custom endpoints. */
22
+ location?: 'local' | 'hosted';
20
23
  /**
21
24
  * Explicit endpoint capabilities. Never inferred: images are only sent to
22
25
  * providers the user marked image-capable (F03); `reasoningEffort: false`
@@ -27,6 +30,12 @@ export interface HazeProviderSettings {
27
30
  images?: boolean;
28
31
  reasoningEffort?: boolean;
29
32
  };
33
+ /** Explicit supported effort levels for compatible custom endpoints. */
34
+ reasoningLevels?: ReasoningLevel[];
35
+ /** Per-model overrides, keyed by the exact model ID. An empty list disables the parameter. */
36
+ modelReasoningLevels?: Record<string, ReasoningLevel[]>;
37
+ /** Wire format for custom OpenAI-compatible servers with a binary switch. */
38
+ reasoningFormat?: 'effort' | 'thinking' | 'enable-thinking';
30
39
  /** Additional exact deployment identities explicitly approved for this native provider. */
31
40
  trustedDeployments?: Array<{
32
41
  modelRepository: string;
@@ -43,6 +52,11 @@ export interface HazeProviderSettings {
43
52
  contextWindowTokens?: number;
44
53
  maxOutputTokens?: number;
45
54
  }>;
55
+ /** Last discovered endpoint limits, separate from explicit user overrides. */
56
+ discoveredModelLimits?: Record<string, {
57
+ contextWindowTokens?: number;
58
+ maxOutputTokens?: number;
59
+ }>;
46
60
  }
47
61
  export interface HazeLspServerSettings {
48
62
  name: string;
@@ -23,9 +23,14 @@ const providerSchema = z.object({
23
23
  key: z.string().optional(),
24
24
  models: z.array(z.string()),
25
25
  kind: z.enum(['openai-compatible', 'chatgpt-codex', 'haze-build']).optional(),
26
+ location: z.enum(['local', 'hosted']).optional(),
26
27
  capabilities: providerCapabilitiesSchema.optional(),
28
+ reasoningLevels: z.array(z.enum(REASONING_LEVELS)).optional(),
29
+ modelReasoningLevels: z.record(z.string(), z.array(z.enum(REASONING_LEVELS))).optional(),
30
+ reasoningFormat: z.enum(['effort', 'thinking', 'enable-thinking']).optional(),
27
31
  trustedDeployments: z.array(z.object({ modelRepository: z.string().min(1).max(256), modelRevision: z.string().regex(/^[a-f0-9]{40}$/), templateSha256: z.string().regex(/^[a-f0-9]{64}$/), runtimeVersion: z.string().regex(/^\d+\.\d+\.\d+$/) })).max(8).optional(),
28
32
  modelLimits: z.record(z.string(), z.object({ contextWindowTokens: z.number().int().positive(), maxOutputTokens: z.number().int().positive() }).partial()).optional(),
33
+ discoveredModelLimits: z.record(z.string(), z.object({ contextWindowTokens: z.number().int().positive(), maxOutputTokens: z.number().int().positive() }).partial()).optional(),
29
34
  }).passthrough();
30
35
  const lspServerSchema = z.object({
31
36
  name: z.string(),
@@ -80,6 +80,7 @@ export declare function buildLlmCompactionPrompt(input: {
80
80
  maxChars?: number;
81
81
  previousSummary?: string;
82
82
  splitTurn?: boolean;
83
+ codeGraphDigest?: string;
83
84
  }): string;
84
85
  /**
85
86
  * Assemble the compacted history around a model-written summary (F-09). Same
@@ -212,6 +212,9 @@ export function buildLlmCompactionPrompt(input) {
212
212
  ? `A previous compaction summary exists. Update it with the new messages: PRESERVE everything still relevant, ADD new progress/decisions/context, DROP only what the recent tail supersedes.\n\n<previous-summary>\n${input.previousSummary}\n</previous-summary>`
213
213
  : undefined,
214
214
  input.instructions ? `User compaction instructions: ${input.instructions}` : undefined,
215
+ input.codeGraphDigest
216
+ ? `A deterministic code-graph digest of the workspace follows. When the summary mentions structure (modules, hubs, relationships), prefer referencing these named symbols/files instead of re-describing them in prose:\n${input.codeGraphDigest}`
217
+ : undefined,
215
218
  `Write a dense summary in at most 60 lines. ${omitted > 0 ? `(${omitted} oldest message(s) already omitted from this transcript.)` : ''}`.trim(),
216
219
  '',
217
220
  '<older_conversation>',
@@ -119,7 +119,7 @@ export type AgentEvent = {
119
119
  } | {
120
120
  type: 'context_budget';
121
121
  contextWindowTokens: number;
122
- source: 'settings' | 'catalog' | 'user-fallback' | 'default-fallback' | 'deployment';
122
+ source: 'settings' | 'discovery' | 'preset' | 'catalog' | 'user-fallback' | 'default-fallback' | 'deployment';
123
123
  at: string;
124
124
  } | {
125
125
  type: 'context_overflow';
@@ -0,0 +1,8 @@
1
+ import type { ModelMessage } from 'ai';
2
+ /**
3
+ * Start a portable conversation boundary when the model changes. Provider
4
+ * reasoning and signatures cannot be reused across protocols; tool calls and
5
+ * results become labeled text so the new provider never receives an orphaned
6
+ * native call or assumes it can replay the old provider's hidden state.
7
+ */
8
+ export declare function transitionProviderConversation(messages: ModelMessage[]): ModelMessage[];
@@ -0,0 +1,47 @@
1
+ import { escapeEnvelopeClosers } from '../safety/untrustedEnvelopes.js';
2
+ /**
3
+ * Start a portable conversation boundary when the model changes. Provider
4
+ * reasoning and signatures cannot be reused across protocols; tool calls and
5
+ * results become labeled text so the new provider never receives an orphaned
6
+ * native call or assumes it can replay the old provider's hidden state.
7
+ */
8
+ export function transitionProviderConversation(messages) {
9
+ const out = [];
10
+ for (const message of messages) {
11
+ if (message.role === 'tool') {
12
+ const data = JSON.stringify(message.content.map(part => {
13
+ if (part.type !== 'tool-result')
14
+ return part;
15
+ const clean = { ...part };
16
+ delete clean.providerOptions;
17
+ return clean;
18
+ }));
19
+ out.push({ role: 'user', content: `Previous tool results (data):\n<haze_compaction source="data">${escapeEnvelopeClosers(data)}</haze_compaction>` });
20
+ continue;
21
+ }
22
+ const plain = { ...message };
23
+ delete plain.providerOptions;
24
+ if (!Array.isArray(message.content)) {
25
+ out.push(plain);
26
+ continue;
27
+ }
28
+ if (message.role === 'assistant') {
29
+ const parts = [];
30
+ for (const part of message.content) {
31
+ if (part.type === 'text')
32
+ parts.push(part.text);
33
+ else if (part.type === 'tool-call')
34
+ parts.push(`Previous tool call ${part.toolName} (${part.toolCallId}): ${JSON.stringify(part.input)}`);
35
+ }
36
+ if (parts.length)
37
+ out.push({ role: 'assistant', content: parts.join('\n') });
38
+ continue;
39
+ }
40
+ out.push({ ...plain, content: message.content.map(part => {
41
+ const rest = { ...part };
42
+ delete rest.providerOptions;
43
+ return rest;
44
+ }) });
45
+ }
46
+ return out;
47
+ }
@@ -5,7 +5,7 @@ export type { ProviderCapabilities } from '../providerContracts.js';
5
5
  * `provider-default`). `'none'` is an explicit request to disable reasoning;
6
6
  * the stored `provider-default` sentinel means "send no parameter at all".
7
7
  */
8
- export type ReasoningLevel = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh';
8
+ export type ReasoningLevel = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
9
9
  export declare const REASONING_LEVELS: readonly ReasoningLevel[];
10
10
  /**
11
11
  * Level applied when nothing more specific exists: no session per-model
@@ -1,4 +1,4 @@
1
- export const REASONING_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh'];
1
+ export const REASONING_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'];
2
2
  /**
3
3
  * Level applied when nothing more specific exists: no session per-model
4
4
  * override and no `reasoning` settings key. Users opt out with an explicit
@@ -73,7 +73,7 @@ export function isReasoningLevel(value) {
73
73
  }
74
74
  /** Aliases accepted by CLI paths (`/reasoning`, `--reasoning`) for "send no reasoning parameter". */
75
75
  export function isReasoningUnsetAlias(value) {
76
- return value === 'unset' || value === 'off' || value === REASONING_PROVIDER_DEFAULT;
76
+ return value === 'unset' || value === REASONING_PROVIDER_DEFAULT;
77
77
  }
78
78
  /**
79
79
  * Parse a `--reasoning` CLI value (case-insensitive): a level maps directly,
@@ -82,6 +82,8 @@ export function isReasoningUnsetAlias(value) {
82
82
  */
83
83
  export function parseReasoningOverride(raw) {
84
84
  const value = raw.trim().toLowerCase();
85
+ if (value === 'off')
86
+ return { ok: true, setting: 'none' };
85
87
  if (isReasoningUnsetAlias(value))
86
88
  return { ok: true, setting: REASONING_PROVIDER_DEFAULT };
87
89
  if (isReasoningLevel(value))
@@ -0,0 +1,61 @@
1
+ import { type CodeGraph, type GraphIndex } from './model.js';
2
+ /**
3
+ * Deterministic label propagation. Iteration order is node-id sorted and the
4
+ * min-label rule breaks ties, so the same graph always yields the same
5
+ * partition. Mutates `graph.nodes[].community` in place.
6
+ */
7
+ export declare function detectCommunities(graph: CodeGraph): void;
8
+ export interface CommunitySummary {
9
+ community: number;
10
+ size: number;
11
+ /** Highest-degree members, files first: a one-line identity for the cluster. */
12
+ members: Array<{
13
+ id: string;
14
+ label: string;
15
+ kind: string;
16
+ degree: number;
17
+ }>;
18
+ /** Most common top-level directories among member files. */
19
+ directories: string[];
20
+ }
21
+ export declare function communitySummaries(index: GraphIndex, limit?: number): CommunitySummary[];
22
+ /** Test-path heuristic shared by god-node ranking and query demotion. */
23
+ export declare function isTestPath(file: string): boolean;
24
+ export interface GodNode {
25
+ id: string;
26
+ label: string;
27
+ kind: string;
28
+ file: string;
29
+ degree: number;
30
+ }
31
+ /** Top-degree symbol nodes (files excluded; test helpers demoted — they mirror, not shape, the architecture). */
32
+ export declare function godNodes(index: GraphIndex, limit?: number): GodNode[];
33
+ /** Tarjan strongly-connected components over file-level `imports` edges. */
34
+ export declare function importCycles(index: GraphIndex, limit?: number): string[][];
35
+ export interface AffectedEntry {
36
+ id: string;
37
+ label: string;
38
+ kind: string;
39
+ file: string;
40
+ depth: number;
41
+ viaRelation: string;
42
+ confidence: string;
43
+ viaFile: string;
44
+ viaLine?: number;
45
+ }
46
+ /**
47
+ * Reverse blast radius from a symbol: who calls/inherits/imports it, transitively.
48
+ * File-level `imports` edges are followed one hop (the file importing the
49
+ * changed symbol's file) so consumers surface even when call sites are dynamic.
50
+ */
51
+ export declare function affectedBySymbol(index: GraphIndex, symbolId: string, maxDepth?: number, limit?: number): AffectedEntry[];
52
+ export interface GraphReportInput {
53
+ graph: CodeGraph;
54
+ files: number;
55
+ parsedFiles: number;
56
+ cachedFiles: number;
57
+ durationMs: number;
58
+ stale: boolean;
59
+ }
60
+ /** Human-readable orientation report for /graph: structure, hubs, risk areas. */
61
+ export declare function renderGraphReport(index: GraphIndex, input: GraphReportInput): string;
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Graph analysis: god nodes (degree hubs), import cycles (Tarjan SCC over
3
+ * file-level import edges), communities (deterministic label propagation),
4
+ * reverse blast radius, and the /graph report renderer.
5
+ *
6
+ * Everything here is plain TS over the in-memory index — no dependencies, no
7
+ * LLM, deterministic output (sorted iteration everywhere).
8
+ */
9
+ import path from 'node:path';
10
+ import { buildGraphIndex, nodeDegree } from './model.js';
11
+ // ---------------------------------------------------------------------------
12
+ // Communities: label propagation over the undirected projection
13
+ // ---------------------------------------------------------------------------
14
+ const COMMUNITY_ITERATIONS = 8;
15
+ /**
16
+ * Deterministic label propagation. Iteration order is node-id sorted and the
17
+ * min-label rule breaks ties, so the same graph always yields the same
18
+ * partition. Mutates `graph.nodes[].community` in place.
19
+ */
20
+ export function detectCommunities(graph) {
21
+ const index = buildGraphIndex(graph);
22
+ const labels = new Map();
23
+ const ids = [...index.nodes.keys()].sort();
24
+ for (const id of ids)
25
+ labels.set(id, id);
26
+ for (let iteration = 0; iteration < COMMUNITY_ITERATIONS; iteration++) {
27
+ let changed = false;
28
+ for (const id of ids) {
29
+ const counts = new Map();
30
+ const bump = (label) => counts.set(label, (counts.get(label) ?? 0) + 1);
31
+ bump(labels.get(id));
32
+ for (const edge of index.out.get(id) ?? [])
33
+ bump(labels.get(edge.target) ?? edge.target);
34
+ for (const edge of index.in.get(id) ?? [])
35
+ bump(labels.get(edge.source) ?? edge.source);
36
+ let bestLabel = labels.get(id);
37
+ let bestCount = -1;
38
+ for (const [label, count] of [...counts].sort(([a], [b]) => a.localeCompare(b))) {
39
+ if (count > bestCount) {
40
+ bestLabel = label;
41
+ bestCount = count;
42
+ }
43
+ }
44
+ if (bestLabel !== labels.get(id)) {
45
+ labels.set(id, bestLabel);
46
+ changed = true;
47
+ }
48
+ }
49
+ if (!changed)
50
+ break;
51
+ }
52
+ // Renumber communities by sorted representative for stable, readable ids.
53
+ const communityIds = new Map();
54
+ for (const id of ids) {
55
+ const label = labels.get(id);
56
+ if (!communityIds.has(label))
57
+ communityIds.set(label, communityIds.size);
58
+ }
59
+ for (const node of graph.nodes) {
60
+ const label = labels.get(node.id);
61
+ if (label == null)
62
+ continue;
63
+ const community = communityIds.get(label);
64
+ if (community != null)
65
+ node.community = community;
66
+ }
67
+ }
68
+ export function communitySummaries(index, limit = 12) {
69
+ const byCommunity = new Map();
70
+ for (const node of index.nodes.values()) {
71
+ if (node.community == null)
72
+ continue;
73
+ const bucket = byCommunity.get(node.community) ?? [];
74
+ bucket.push(node.id);
75
+ byCommunity.set(node.community, bucket);
76
+ }
77
+ const summaries = [];
78
+ for (const [community, ids] of byCommunity) {
79
+ const ranked = ids
80
+ .map(id => ({ id, node: index.nodes.get(id), degree: nodeDegree(index, id) }))
81
+ .filter(entry => entry.node != null)
82
+ .sort((a, b) => b.degree - a.degree || a.id.localeCompare(b.id));
83
+ const members = [
84
+ ...ranked.filter(entry => entry.node.kind === 'file').slice(0, 3),
85
+ ...ranked.filter(entry => entry.node.kind !== 'file').slice(0, 4),
86
+ ].map(entry => ({ id: entry.id, label: entry.node.label, kind: entry.node.kind, degree: entry.degree }));
87
+ const dirCounts = new Map();
88
+ for (const entry of ranked) {
89
+ const segments = path.posix.dirname(entry.node.file).split('/');
90
+ // 'src' alone says nothing in a monoglot repo; keep two segments there.
91
+ const dir = segments[0] === 'src' || segments[0] === 'tests' ? segments.slice(0, 2).join('/') : segments[0] ?? '';
92
+ if (dir && dir !== '.')
93
+ dirCounts.set(dir, (dirCounts.get(dir) ?? 0) + 1);
94
+ }
95
+ const directories = [...dirCounts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 2).map(([dir]) => dir);
96
+ summaries.push({ community, size: ids.length, members, directories });
97
+ }
98
+ return summaries.sort((a, b) => b.size - a.size || a.community - b.community).slice(0, limit);
99
+ }
100
+ // ---------------------------------------------------------------------------
101
+ // God nodes and import cycles
102
+ // ---------------------------------------------------------------------------
103
+ /** Test-path heuristic shared by god-node ranking and query demotion. */
104
+ export function isTestPath(file) {
105
+ const lowered = file.toLowerCase();
106
+ return lowered.includes('.test.') || lowered.includes('.spec.') || lowered.includes('__tests__/') || /(^|\/)(tests?|fixtures?)\//.test(lowered);
107
+ }
108
+ /** Top-degree symbol nodes (files excluded; test helpers demoted — they mirror, not shape, the architecture). */
109
+ export function godNodes(index, limit = 10) {
110
+ const ranked = [];
111
+ for (const node of index.nodes.values()) {
112
+ if (node.kind === 'file')
113
+ continue;
114
+ if (isTestPath(node.file))
115
+ continue;
116
+ ranked.push({ id: node.id, label: node.label, kind: node.kind, file: node.file, degree: nodeDegree(index, node.id) });
117
+ }
118
+ return ranked.sort((a, b) => b.degree - a.degree || a.id.localeCompare(b.id)).slice(0, limit);
119
+ }
120
+ /** Tarjan strongly-connected components over file-level `imports` edges. */
121
+ export function importCycles(index, limit = 5) {
122
+ const fileIds = [...index.nodes.values()].filter(node => node.kind === 'file').map(node => node.id).sort();
123
+ const adjacency = new Map();
124
+ for (const id of fileIds) {
125
+ const targets = (index.out.get(id) ?? [])
126
+ .filter(edge => edge.relation === 'imports')
127
+ .map(edge => edge.target);
128
+ adjacency.set(id, targets);
129
+ }
130
+ let counter = 0;
131
+ const stack = [];
132
+ const onStack = new Set();
133
+ const indices = new Map();
134
+ const lowlinks = new Map();
135
+ const cycles = [];
136
+ const strongConnect = (start) => {
137
+ const work = [{ node: start, next: 0 }];
138
+ while (work.length > 0) {
139
+ const frame = work[work.length - 1];
140
+ if (frame.next === 0) {
141
+ indices.set(frame.node, counter);
142
+ lowlinks.set(frame.node, counter);
143
+ counter += 1;
144
+ stack.push(frame.node);
145
+ onStack.add(frame.node);
146
+ }
147
+ const neighbors = adjacency.get(frame.node) ?? [];
148
+ let advanced = false;
149
+ while (frame.next < neighbors.length) {
150
+ const neighbor = neighbors[frame.next];
151
+ frame.next += 1;
152
+ if (!indices.has(neighbor)) {
153
+ work.push({ node: neighbor, next: 0 });
154
+ advanced = true;
155
+ break;
156
+ }
157
+ if (onStack.has(neighbor)) {
158
+ lowlinks.set(frame.node, Math.min(lowlinks.get(frame.node), indices.get(neighbor)));
159
+ }
160
+ }
161
+ if (advanced)
162
+ continue;
163
+ if (lowlinks.get(frame.node) === indices.get(frame.node)) {
164
+ const component = [];
165
+ while (true) {
166
+ const member = stack.pop();
167
+ onStack.delete(member);
168
+ component.push(member);
169
+ if (member === frame.node)
170
+ break;
171
+ }
172
+ if (component.length > 1)
173
+ cycles.push(component.sort());
174
+ }
175
+ work.pop();
176
+ const parent = work[work.length - 1];
177
+ if (parent)
178
+ lowlinks.set(parent.node, Math.min(lowlinks.get(parent.node), lowlinks.get(frame.node)));
179
+ }
180
+ };
181
+ for (const id of fileIds) {
182
+ if (!indices.has(id))
183
+ strongConnect(id);
184
+ }
185
+ return cycles.sort((a, b) => b.length - a.length || a[0].localeCompare(b[0])).slice(0, limit);
186
+ }
187
+ // ---------------------------------------------------------------------------
188
+ // Blast radius
189
+ // ---------------------------------------------------------------------------
190
+ const AFFECTED_RELATIONS = new Set(['calls', 'inherits', 'references']);
191
+ /**
192
+ * Reverse blast radius from a symbol: who calls/inherits/imports it, transitively.
193
+ * File-level `imports` edges are followed one hop (the file importing the
194
+ * changed symbol's file) so consumers surface even when call sites are dynamic.
195
+ */
196
+ export function affectedBySymbol(index, symbolId, maxDepth = 3, limit = 40) {
197
+ const results = new Map();
198
+ const visited = new Set([symbolId]);
199
+ // `imports` edges are file→file, so the one-hop importer surfacing is
200
+ // reachable only through the file that defines the queried symbol: seed
201
+ // that file alongside the symbol (never as a result itself).
202
+ const definingFiles = (index.in.get(symbolId) ?? [])
203
+ .filter(edge => edge.relation === 'defines')
204
+ .map(edge => edge.source);
205
+ for (const id of definingFiles)
206
+ visited.add(id);
207
+ let frontier = [{ id: symbolId, depth: 0 }, ...definingFiles.map(id => ({ id, depth: 0 }))];
208
+ while (frontier.length > 0 && results.size < limit) {
209
+ const next = [];
210
+ for (const current of frontier) {
211
+ for (const edge of index.in.get(current.id) ?? []) {
212
+ if (visited.has(edge.source))
213
+ continue;
214
+ if (!AFFECTED_RELATIONS.has(edge.relation) && !(edge.relation === 'imports' && current.depth === 0))
215
+ continue;
216
+ visited.add(edge.source);
217
+ const node = index.nodes.get(edge.source);
218
+ if (!node)
219
+ continue;
220
+ // Symbols are entries; files surface only as the documented one-hop
221
+ // importers of the defining file (the defining file itself is a
222
+ // pre-visited seed, never a result).
223
+ if (node.kind !== 'file' || edge.relation === 'imports') {
224
+ results.set(edge.source, {
225
+ id: edge.source, label: node.label, kind: node.kind, file: node.file,
226
+ depth: current.depth + 1, viaRelation: edge.relation, confidence: edge.confidence,
227
+ viaFile: edge.file ?? node.file, ...(edge.line ? { viaLine: edge.line } : {}),
228
+ });
229
+ }
230
+ next.push({ id: edge.source, depth: current.depth + 1 });
231
+ }
232
+ }
233
+ frontier = next;
234
+ if (frontier.some(entry => entry.depth >= maxDepth))
235
+ break;
236
+ }
237
+ return [...results.values()].sort((a, b) => a.depth - b.depth || b.viaRelation.localeCompare(a.viaRelation) || a.id.localeCompare(b.id)).slice(0, limit);
238
+ }
239
+ /** Human-readable orientation report for /graph: structure, hubs, risk areas. */
240
+ export function renderGraphReport(index, input) {
241
+ const lines = [];
242
+ const cacheHint = input.cachedFiles > 0 ? `, ${input.cachedFiles} cached / ${input.parsedFiles} parsed` : '';
243
+ lines.push(`Code graph: ${input.graph.nodes.length} nodes · ${input.graph.edges.length} edges · ${input.files} source files (${(input.durationMs / 1000).toFixed(1)}s${cacheHint})`);
244
+ if (input.stale)
245
+ lines.push('Note: some files changed since this graph was built; run /graph to refresh.');
246
+ const communities = communitySummaries(index, 8);
247
+ if (communities.length > 0) {
248
+ lines.push('');
249
+ lines.push('Subsystems (graph communities):');
250
+ for (const community of communities) {
251
+ const dirs = community.directories.length > 0 ? ` [${community.directories.join(', ')}]` : '';
252
+ lines.push(` ${community.community}: ${community.size} nodes${dirs}`);
253
+ const memberLabels = community.members.slice(0, 4).map(member => member.kind === 'file' ? member.label : `${member.label} (${member.kind})`);
254
+ lines.push(` ${memberLabels.join(' · ')}`);
255
+ }
256
+ }
257
+ const gods = godNodes(index, 8);
258
+ if (gods.length > 0) {
259
+ lines.push('');
260
+ lines.push('Hub symbols (god nodes — change these carefully):');
261
+ for (const god of gods) {
262
+ lines.push(` ${god.label} (${god.kind}, degree ${god.degree}) — ${god.file}`);
263
+ }
264
+ }
265
+ const cycles = importCycles(index, 3);
266
+ if (cycles.length > 0) {
267
+ lines.push('');
268
+ lines.push(`Import cycles: ${cycles.length} shown`);
269
+ for (const cycle of cycles) {
270
+ lines.push(` ${cycle.join(' -> ')}`);
271
+ }
272
+ }
273
+ return lines.join('\n');
274
+ }