@denizokcu/haze 0.5.0 → 0.7.0

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 (162) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/README.md +101 -24
  3. package/dist/cli/chat/TaskBar.d.ts +9 -0
  4. package/dist/cli/chat/TaskBar.js +40 -0
  5. package/dist/cli/chat/chatMetrics.d.ts +11 -0
  6. package/dist/cli/chat/chatMetrics.js +50 -0
  7. package/dist/cli/chat/inputSuggestions.d.ts +16 -0
  8. package/dist/cli/chat/inputSuggestions.js +55 -0
  9. package/dist/cli/chat/messages.d.ts +9 -0
  10. package/dist/cli/chat/messages.js +76 -0
  11. package/dist/cli/chat/sessionRecorder.d.ts +12 -0
  12. package/dist/cli/chat/sessionRecorder.js +21 -0
  13. package/dist/cli/chat/startupInfo.d.ts +4 -0
  14. package/dist/cli/chat/startupInfo.js +53 -0
  15. package/dist/cli/chat/turnState.d.ts +5 -0
  16. package/dist/cli/chat/turnState.js +20 -0
  17. package/dist/cli/commands/chat.d.ts +0 -1
  18. package/dist/cli/commands/chat.js +519 -495
  19. package/dist/cli/commands/chatModes.d.ts +8 -0
  20. package/dist/cli/commands/chatModes.js +44 -0
  21. package/dist/cli/commands/commandHelp.d.ts +6 -0
  22. package/dist/cli/commands/commandHelp.js +25 -0
  23. package/dist/cli/commands/commands.d.ts +3 -2
  24. package/dist/cli/commands/commands.js +55 -320
  25. package/dist/cli/commands/formatters.d.ts +27 -0
  26. package/dist/cli/commands/formatters.js +149 -4
  27. package/dist/cli/commands/initCommand.d.ts +2 -0
  28. package/dist/cli/commands/initCommand.js +19 -0
  29. package/dist/cli/commands/logsCommand.d.ts +2 -0
  30. package/dist/cli/commands/logsCommand.js +63 -0
  31. package/dist/cli/commands/lspWizard.d.ts +14 -0
  32. package/dist/cli/commands/lspWizard.js +44 -0
  33. package/dist/cli/commands/mcpWizard.d.ts +15 -0
  34. package/dist/cli/commands/mcpWizard.js +69 -0
  35. package/dist/cli/commands/modelCommand.d.ts +2 -0
  36. package/dist/cli/commands/modelCommand.js +36 -0
  37. package/dist/cli/commands/providerWizard.d.ts +30 -0
  38. package/dist/cli/commands/providerWizard.js +114 -0
  39. package/dist/cli/commands/runCommand.d.ts +16 -0
  40. package/dist/cli/commands/runCommand.js +170 -0
  41. package/dist/cli/commands/settingsSummary.d.ts +3 -0
  42. package/dist/cli/commands/settingsSummary.js +40 -0
  43. package/dist/cli/commands/skillConfirmRemove.d.ts +11 -0
  44. package/dist/cli/commands/skillConfirmRemove.js +19 -0
  45. package/dist/cli/commands/skillCreation.d.ts +12 -0
  46. package/dist/cli/commands/skillCreation.js +14 -0
  47. package/dist/cli/commands/skillWizard.d.ts +15 -0
  48. package/dist/cli/commands/skillWizard.js +38 -0
  49. package/dist/cli/commands/streaming/assistantText.d.ts +17 -0
  50. package/dist/cli/commands/streaming/assistantText.js +115 -0
  51. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +55 -0
  52. package/dist/cli/commands/streaming/toolGroupRenderer.js +102 -0
  53. package/dist/cli/commands/streaming/toolResultState.d.ts +13 -0
  54. package/dist/cli/commands/streaming/toolResultState.js +25 -0
  55. package/dist/cli/commands/streaming/turnRuntime.d.ts +78 -0
  56. package/dist/cli/commands/streaming/turnRuntime.js +86 -0
  57. package/dist/cli/commands/streaming.d.ts +10 -29
  58. package/dist/cli/commands/streaming.js +249 -911
  59. package/dist/cli/commands/wizardActions.d.ts +40 -0
  60. package/dist/cli/commands/wizardActions.js +40 -0
  61. package/dist/cli/commands/wizardInput.d.ts +4 -0
  62. package/dist/cli/commands/wizardInput.js +19 -0
  63. package/dist/cli/commands/wizardPrompts.d.ts +22 -0
  64. package/dist/cli/commands/wizardPrompts.js +52 -0
  65. package/dist/cli/commands/wizardSuggestions.d.ts +23 -0
  66. package/dist/cli/commands/wizardSuggestions.js +139 -0
  67. package/dist/cli/index.js +62 -4
  68. package/dist/config/contextFiles.d.ts +8 -1
  69. package/dist/config/contextFiles.js +25 -12
  70. package/dist/config/lspSettings.d.ts +16 -0
  71. package/dist/config/lspSettings.js +95 -0
  72. package/dist/config/mcpSettings.d.ts +24 -0
  73. package/dist/config/mcpSettings.js +100 -0
  74. package/dist/config/providers.js +4 -4
  75. package/dist/config/settings.d.ts +34 -0
  76. package/dist/config/skillSettings.d.ts +15 -0
  77. package/dist/config/skillSettings.js +32 -0
  78. package/dist/config/updateCheck.d.ts +44 -0
  79. package/dist/config/updateCheck.js +83 -0
  80. package/dist/core/agent/budgets.d.ts +6 -0
  81. package/dist/core/agent/budgets.js +6 -0
  82. package/dist/core/agent/compaction.js +1 -1
  83. package/dist/core/agent/requestAssembly.d.ts +0 -7
  84. package/dist/core/agent/requestAssembly.js +27 -5
  85. package/dist/core/agent/toolOutputStore.js +5 -4
  86. package/dist/core/agent/toolResults.d.ts +31 -0
  87. package/dist/core/agent/toolResults.js +42 -0
  88. package/dist/core/agent/turnPolicy.d.ts +8 -0
  89. package/dist/core/agent/turnPolicy.js +23 -0
  90. package/dist/core/agent/workState.d.ts +18 -5
  91. package/dist/core/agent/workState.js +39 -20
  92. package/dist/core/bashOutput/reducers/content.d.ts +1 -0
  93. package/dist/core/bashOutput/reducers/content.js +1 -1
  94. package/dist/core/bashOutput/reducers/gh.d.ts +1 -0
  95. package/dist/core/bashOutput/reducers/gh.js +77 -0
  96. package/dist/core/bashOutput/registry.js +8 -0
  97. package/dist/core/goal/sessionGoal.d.ts +6 -30
  98. package/dist/core/goal/sessionGoal.js +3 -68
  99. package/dist/core/safety/bashClassifier.js +30 -0
  100. package/dist/core/safety/urlGuard.d.ts +1 -0
  101. package/dist/core/safety/urlGuard.js +6 -1
  102. package/dist/core/session/sessionSlimming.d.ts +5 -0
  103. package/dist/core/session/sessionSlimming.js +78 -0
  104. package/dist/core/session/sessionStore.d.ts +23 -3
  105. package/dist/core/session/sessionStore.js +30 -10
  106. package/dist/core/subagent/subagentRunner.d.ts +11 -1
  107. package/dist/core/subagent/subagentRunner.js +1 -0
  108. package/dist/llm/capabilities.d.ts +12 -0
  109. package/dist/llm/capabilities.js +10 -0
  110. package/dist/llm/client.d.ts +1 -0
  111. package/dist/llm/client.js +11 -2
  112. package/dist/llm/hazeTools.d.ts +31 -32
  113. package/dist/llm/hazeTools.js +40 -567
  114. package/dist/llm/lsp.d.ts +109 -0
  115. package/dist/llm/lsp.js +241 -0
  116. package/dist/llm/lspTools.d.ts +104 -0
  117. package/dist/llm/lspTools.js +115 -0
  118. package/dist/llm/mcp.d.ts +19 -0
  119. package/dist/llm/mcp.js +73 -0
  120. package/dist/llm/requestContext.d.ts +28 -0
  121. package/dist/llm/requestContext.js +41 -0
  122. package/dist/llm/systemPrompt.d.ts +5 -1
  123. package/dist/llm/systemPrompt.js +9 -3
  124. package/dist/llm/tools/bashTool.d.ts +5 -0
  125. package/dist/llm/tools/bashTool.js +81 -0
  126. package/dist/llm/tools/editMatch.d.ts +55 -0
  127. package/dist/llm/tools/editMatch.js +99 -0
  128. package/dist/llm/tools/failures.d.ts +36 -0
  129. package/dist/llm/tools/failures.js +38 -0
  130. package/dist/llm/tools/fetchTool.d.ts +65 -0
  131. package/dist/llm/tools/fetchTool.js +45 -0
  132. package/dist/llm/tools/fileToolShared.d.ts +10 -0
  133. package/dist/llm/tools/fileToolShared.js +43 -0
  134. package/dist/llm/tools/grepParse.d.ts +13 -0
  135. package/dist/llm/tools/grepParse.js +67 -0
  136. package/dist/llm/tools/outputCap.d.ts +53 -0
  137. package/dist/llm/tools/outputCap.js +67 -0
  138. package/dist/llm/tools/storedOutputTool.d.ts +10 -0
  139. package/dist/llm/tools/storedOutputTool.js +17 -0
  140. package/dist/llm/tools/taskTool.d.ts +28 -0
  141. package/dist/llm/tools/taskTool.js +41 -0
  142. package/dist/llm/tools/toolContext.d.ts +69 -0
  143. package/dist/llm/tools/toolContext.js +187 -0
  144. package/dist/llm/tools/workspaceFile.d.ts +33 -0
  145. package/dist/llm/tools/workspaceFile.js +27 -0
  146. package/dist/llm/webFetch.d.ts +13 -1
  147. package/dist/llm/webFetch.js +91 -7
  148. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  149. package/dist/skills/builder/SkillBuilder.js +24 -45
  150. package/dist/ui/components/TextInput.d.ts +1 -1
  151. package/dist/ui/components/TextInput.js +1 -99
  152. package/dist/ui/inputBuffer.d.ts +28 -0
  153. package/dist/ui/inputBuffer.js +99 -0
  154. package/dist/utils/collections.d.ts +6 -0
  155. package/dist/utils/collections.js +9 -0
  156. package/dist/utils/path.d.ts +2 -0
  157. package/dist/utils/path.js +40 -0
  158. package/dist/utils/version.d.ts +20 -0
  159. package/dist/utils/version.js +72 -0
  160. package/package.json +2 -2
  161. package/dist/cli/commands/skills.d.ts +0 -4
  162. package/dist/cli/commands/skills.js +0 -38
@@ -1,8 +1,4 @@
1
- function inputString(input, key) {
2
- return typeof input === 'object' && input != null && key in input && typeof input[key] === 'string'
3
- ? input[key]
4
- : undefined;
5
- }
1
+ import { toolInputField, toolOutputOk } from './toolResults.js';
6
2
  function upsertFile(state, path, action, note) {
7
3
  const existing = state.files.find(file => file.path === path);
8
4
  if (existing) {
@@ -14,9 +10,8 @@ function upsertFile(state, path, action, note) {
14
10
  else {
15
11
  state.files.push({ path, action, ...(note ? { note } : {}) });
16
12
  }
17
- }
18
- function outputOk(output, success) {
19
- return success && !(typeof output === 'object' && output != null && 'ok' in output && output.ok === false);
13
+ if (action !== 'read' && !state.touchedFiles.includes(path))
14
+ state.touchedFiles.push(path);
20
15
  }
21
16
  function outputSummary(output) {
22
17
  if (typeof output !== 'object' || output == null)
@@ -30,55 +25,79 @@ function outputSummary(output) {
30
25
  return `exit ${String(output.code)}`;
31
26
  return '';
32
27
  }
33
- export function createWorkState(goal, intent, successCriteria) {
28
+ function upsertValidation(state, command, status, summary) {
29
+ const existing = state.validations.find(validation => validation.command === command);
30
+ if (existing)
31
+ Object.assign(existing, { status, summary });
32
+ else
33
+ state.validations.push({ command, status, summary });
34
+ const existingCommand = state.validationCommands.find(item => item.command === command);
35
+ if (existingCommand)
36
+ existingCommand.status = status;
37
+ else
38
+ state.validationCommands.push({ command, status });
39
+ }
40
+ export function createWorkState(goal, intent, successCriteria, now = Date.now()) {
34
41
  return {
42
+ id: `goal-${now}-${Math.random().toString(36).slice(2)}`,
35
43
  goal,
44
+ originalUserRequest: goal,
36
45
  intent,
46
+ normalizedIntent: intent,
37
47
  successCriteria: [...successCriteria],
38
48
  constraints: [],
39
49
  decisions: [],
40
50
  files: [],
51
+ touchedFiles: [],
41
52
  validations: [],
53
+ validationCommands: [],
42
54
  blockers: [],
43
55
  pending: [],
56
+ status: 'active',
44
57
  phase: 'starting',
58
+ lastProgressAt: now,
45
59
  revision: 0,
46
60
  };
47
61
  }
48
- export function observeWorkToolEvent(state, event) {
62
+ export function observeWorkToolEvent(state, event, now = Date.now()) {
49
63
  if (event.duplicateSkipped)
50
64
  return state;
51
- const ok = outputOk(event.output, event.success);
52
- const path = inputString(event.input, 'path');
65
+ const ok = toolOutputOk(event.output, event.success);
66
+ const path = toolInputField(event.input, 'path');
53
67
  if (ok && path && ['listFiles', 'readFile', 'grep'].includes(event.toolName)) {
54
68
  if (event.toolName === 'readFile')
55
69
  upsertFile(state, path, 'read');
56
- state.phase = 'inspecting';
70
+ if (state.phase !== 'editing' && state.phase !== 'validating')
71
+ state.phase = 'inspecting';
72
+ state.lastProgressAt = now;
57
73
  }
58
74
  if (path && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolName)) {
59
75
  if (ok) {
60
76
  upsertFile(state, path, event.toolName === 'writeFile' ? 'created' : 'modified');
61
77
  state.phase = 'editing';
78
+ state.lastProgressAt = now;
62
79
  state.blockers = state.blockers.filter(blocker => !blocker.includes(path));
80
+ if (state.blocker?.includes(path))
81
+ state.blocker = undefined;
63
82
  }
64
83
  else {
84
+ state.blocker = `File edit failed for ${path}; recovery read is required before retry.`;
65
85
  state.blockers = [...new Set([...state.blockers, `Edit failed for ${path}: ${outputSummary(event.output) || 'fresh read required'}`])];
66
86
  state.nextAction = `Read ${path}, then retry the edit with current content.`;
67
87
  }
68
88
  }
69
89
  if (event.toolName === 'bash') {
70
- const command = inputString(event.input, 'command');
90
+ const command = toolInputField(event.input, 'command');
71
91
  if (command) {
72
92
  const status = ok ? 'passed' : 'failed';
73
- const existing = state.validations.find(validation => validation.command === command);
74
93
  const summary = outputSummary(event.output);
75
- if (existing)
76
- Object.assign(existing, { status, summary });
77
- else
78
- state.validations.push({ command, status, summary });
94
+ upsertValidation(state, command, status, summary);
79
95
  state.phase = 'validating';
80
- if (!ok)
96
+ state.lastProgressAt = now;
97
+ if (!ok) {
98
+ state.blocker = `Validation command failed: ${command}`;
81
99
  state.blockers = [...new Set([...state.blockers, `Validation failed: ${command}`])];
100
+ }
82
101
  }
83
102
  }
84
103
  state.revision += 1;
@@ -1,3 +1,4 @@
1
+ export declare function clip(line: string, max?: number): string;
1
2
  export declare function reduceJsonOutput(stdout: string, stderr: string): string | undefined;
2
3
  export declare function reduceUnifiedDiffOutput(stdout: string, stderr: string): string | undefined;
3
4
  export declare function reduceGenericLogOutput(stdout: string, stderr: string): string | undefined;
@@ -1,4 +1,4 @@
1
- function clip(line, max = 220) {
1
+ export function clip(line, max = 220) {
2
2
  return line.length <= max ? line : `${line.slice(0, max - 1)}…`;
3
3
  }
4
4
  function tryParseJson(text) {
@@ -0,0 +1 @@
1
+ export declare function reduceGhOutput(command: string, stdout: string, stderr: string): string | undefined;
@@ -0,0 +1,77 @@
1
+ import { commandCandidates } from '../command.js';
2
+ import { clip, reduceJsonOutput } from './content.js';
3
+ const GH_GROUPS = new Set(['pr', 'issue', 'run', 'release', 'repo', 'workflow']);
4
+ const READ_ONLY = new Set([
5
+ 'pr list', 'pr view', 'pr checks',
6
+ 'issue list', 'issue view',
7
+ 'run list', 'run view',
8
+ 'release list', 'release view',
9
+ 'repo view',
10
+ ]);
11
+ // Extract "<group> <action>" (e.g. "pr list") from a gh command, skipping flags.
12
+ function ghSubcommand(command) {
13
+ for (const candidate of commandCandidates(command)) {
14
+ const words = candidate.toLowerCase().split(/\s+/).filter(Boolean);
15
+ const ghIndex = words.indexOf('gh');
16
+ if (ghIndex === -1)
17
+ continue;
18
+ for (let index = ghIndex + 1; index < words.length; index++) {
19
+ const group = words[index] ?? '';
20
+ if (!GH_GROUPS.has(group))
21
+ continue;
22
+ for (let next = index + 1; next < words.length; next++) {
23
+ const action = words[next] ?? '';
24
+ if (action.startsWith('-'))
25
+ continue;
26
+ return `${group} ${action}`;
27
+ }
28
+ return group;
29
+ }
30
+ }
31
+ return undefined;
32
+ }
33
+ // gh *list / pr checks → tab/space separated rows; summarize count + capped sample.
34
+ function reduceGhTable(subcommand, text) {
35
+ const rows = text.split(/\r?\n/).filter(line => line.trim());
36
+ if (rows.length <= 10 && text.length < 2000)
37
+ return undefined;
38
+ const shown = rows.slice(0, 30);
39
+ const output = [`gh ${subcommand}: ${rows.length} row${rows.length === 1 ? '' : 's'}`, ...shown.map(line => ` ${clip(line)}`)];
40
+ if (rows.length > shown.length)
41
+ output.push(` ... ${rows.length - shown.length} more`);
42
+ return output.join('\n');
43
+ }
44
+ // gh * view (non-JSON) → key:value header lines, then `--`, then markdown body.
45
+ function reduceGhView(subcommand, text) {
46
+ if (text.length < 2000)
47
+ return undefined;
48
+ const lines = text.split(/\r?\n/);
49
+ const sepIndex = lines.findIndex(line => line.trim() === '--');
50
+ const header = (sepIndex === -1 ? lines : lines.slice(0, sepIndex)).filter(Boolean);
51
+ const body = (sepIndex === -1 ? [] : lines.slice(sepIndex + 1)).filter(Boolean);
52
+ const bodyShown = body.slice(0, 12);
53
+ const output = [`gh ${subcommand}:`, ...header.slice(0, 30).map(line => ` ${clip(line)}`)];
54
+ if (bodyShown.length) {
55
+ output.push(' --', ...bodyShown.map(line => ` ${clip(line)}`));
56
+ if (body.length > bodyShown.length)
57
+ output.push(` ... ${body.length - bodyShown.length} more body lines`);
58
+ }
59
+ return output.join('\n');
60
+ }
61
+ export function reduceGhOutput(command, stdout, stderr) {
62
+ // `gh run view --log[-failed]` emits raw CI logs (no key/value + `--` body); let
63
+ // the generic log reducer extract end-of-log error signal instead of dropping it.
64
+ if (/\s--log(?:-failed)?\b/.test(command))
65
+ return undefined;
66
+ const subcommand = ghSubcommand(command);
67
+ if (!subcommand || !READ_ONLY.has(subcommand))
68
+ return undefined;
69
+ const text = stdout || stderr;
70
+ if (!text.trim())
71
+ return undefined;
72
+ if (/^\s*[[{]/.test(text))
73
+ return reduceJsonOutput(stdout, stderr); // --json → reuse JSON reducer (undefined for small JSON)
74
+ if (subcommand.endsWith(' view'))
75
+ return reduceGhView(subcommand, text);
76
+ return reduceGhTable(subcommand, text);
77
+ }
@@ -1,6 +1,7 @@
1
1
  import { applyLineFilter, findLineFilter } from './lineFilter.js';
2
2
  import { renderValidationReduction } from './reducers/validation.js';
3
3
  import { reduceGitOutput } from './reducers/git.js';
4
+ import { reduceGhOutput } from './reducers/gh.js';
4
5
  import { reduceSearchOutput } from './reducers/search.js';
5
6
  import { reduceGenericLogOutput, reduceJsonOutput, reduceUnifiedDiffOutput } from './reducers/content.js';
6
7
  import { isInflating, reductionMetrics, retrievalHint } from '../toolOutput/reduction.js';
@@ -74,12 +75,19 @@ export function filterBashOutput(input) {
74
75
  }
75
76
  else {
76
77
  const git = reduceGitOutput(input.command, input.stdout, input.stderr);
78
+ const gh = git == null ? reduceGhOutput(input.command, input.stdout, input.stderr) : undefined;
77
79
  if (git != null) {
78
80
  filterName = 'git';
79
81
  const kind = /^git (?:diff|show):/.test(git) ? 'diff' : 'generic';
80
82
  stdout = makeReduction(input.stdout, input.stdout ? git : '', true, filterName, input, undefined, kind);
81
83
  stderr = makeReduction(input.stderr, input.stdout ? '' : git, true, filterName, input, undefined, kind);
82
84
  }
85
+ else if (gh != null) {
86
+ filterName = 'gh';
87
+ const kind = gh.trimStart().startsWith('{') ? 'json' : 'generic';
88
+ stdout = makeReduction(input.stdout, input.stdout ? gh : '', true, filterName, input, undefined, kind);
89
+ stderr = makeReduction(input.stderr, input.stdout ? '' : gh, true, filterName, input, undefined, kind);
90
+ }
83
91
  else {
84
92
  const search = reduceSearchOutput(input.command, input.stdout, input.stderr);
85
93
  if (search != null) {
@@ -1,32 +1,8 @@
1
- import { type RequestIntent } from './requestClassifier.js';
2
- import { type WorkState } from '../agent/workState.js';
3
- export type SessionGoalStatus = 'active' | 'needs-user' | 'blocked' | 'complete' | 'aborted';
4
- export type ValidationStatus = 'pending' | 'passed' | 'failed';
5
- export interface SessionGoal {
6
- id: string;
7
- originalUserRequest: string;
8
- normalizedIntent: RequestIntent;
9
- successCriteria: string[];
10
- constraints: string[];
11
- touchedFiles: string[];
12
- validationCommands: Array<{
13
- command: string;
14
- status: ValidationStatus;
15
- }>;
16
- status: SessionGoalStatus;
17
- phase: 'starting' | 'inspecting' | 'editing' | 'validating' | 'summarizing' | 'done';
18
- blocker?: string;
19
- lastProgressAt: number;
20
- workState: WorkState;
21
- }
22
- export interface GoalToolEvent {
23
- toolName: string;
24
- input?: unknown;
25
- success: boolean;
26
- output?: unknown;
27
- error?: unknown;
28
- duplicateSkipped?: boolean;
29
- }
1
+ import { observeWorkToolEvent, type WorkState, type WorkStatus, type WorkValidationStatus } from '../agent/workState.js';
2
+ export type SessionGoalStatus = WorkStatus;
3
+ export type ValidationStatus = WorkValidationStatus;
4
+ export type SessionGoal = WorkState;
5
+ export type GoalToolEvent = Parameters<typeof observeWorkToolEvent>[1];
30
6
  export declare function createSessionGoal(request: string, now?: number): SessionGoal;
31
- export declare function observeGoalToolEvent(goal: SessionGoal, event: GoalToolEvent, now?: number): SessionGoal;
7
+ export declare function observeGoalToolEvent(goal: SessionGoal, event: GoalToolEvent, now?: number): WorkState;
32
8
  export declare function formatGoalStatus(goal: SessionGoal): string;
@@ -3,23 +3,9 @@ import { createWorkState, observeWorkToolEvent } from '../agent/workState.js';
3
3
  function shortRequest(value) {
4
4
  return value.replace(/\s+/g, ' ').trim().slice(0, 160) || 'current request';
5
5
  }
6
- function inputPath(input) {
7
- return typeof input === 'object' && input != null && 'path' in input && typeof input.path === 'string'
8
- ? input.path
9
- : undefined;
10
- }
11
- function bashCommand(input) {
12
- return typeof input === 'object' && input != null && 'command' in input && typeof input.command === 'string'
13
- ? input.command
14
- : undefined;
15
- }
16
- function uniquePush(values, value) {
17
- if (!values.includes(value))
18
- values.push(value);
19
- }
20
6
  export function createSessionGoal(request, now = Date.now()) {
21
7
  const intent = classifyRequestIntent(request);
22
- const criteria = intent === 'plan'
8
+ const successCriteria = intent === 'plan'
23
9
  ? ['Create or update the requested plan artifact/answer', 'Do not implement source changes unless asked']
24
10
  : intent === 'test'
25
11
  ? ['Run the requested validation or closest relevant check', 'Report pass/fail accurately']
@@ -28,61 +14,10 @@ export function createSessionGoal(request, now = Date.now()) {
28
14
  : intent === 'answer'
29
15
  ? ['Answer the user using current project context when needed']
30
16
  : ['Inspect the relevant files', 'Make the requested change when needed', 'Validate the change when practical', 'Summarize only current-task changes and validation'];
31
- const successCriteria = criteria;
32
- return {
33
- id: `goal-${now}-${Math.random().toString(36).slice(2)}`,
34
- originalUserRequest: request,
35
- normalizedIntent: intent,
36
- successCriteria,
37
- constraints: [],
38
- touchedFiles: [],
39
- validationCommands: [],
40
- status: 'active',
41
- phase: 'starting',
42
- lastProgressAt: now,
43
- workState: createWorkState(request, intent, successCriteria),
44
- };
17
+ return createWorkState(request, intent, successCriteria, now);
45
18
  }
46
19
  export function observeGoalToolEvent(goal, event, now = Date.now()) {
47
- if (event.duplicateSkipped)
48
- return goal;
49
- observeWorkToolEvent(goal.workState, event);
50
- if (event.success && ['listFiles', 'readFile'].includes(event.toolName)) {
51
- goal.phase = goal.phase === 'editing' || goal.phase === 'validating' ? goal.phase : 'inspecting';
52
- goal.lastProgressAt = now;
53
- }
54
- goal.workState.phase = goal.phase;
55
- if (['editFile', 'replaceLines', 'writeFile'].includes(event.toolName)) {
56
- const path = inputPath(event.input);
57
- if (path)
58
- uniquePush(goal.touchedFiles, path);
59
- if (event.success) {
60
- goal.phase = 'editing';
61
- goal.lastProgressAt = now;
62
- }
63
- else {
64
- goal.blocker = `File edit failed${path ? ` for ${path}` : ''}; recovery read is required before retry.`;
65
- }
66
- }
67
- goal.workState.phase = goal.phase;
68
- if (event.toolName === 'bash') {
69
- const command = bashCommand(event.input);
70
- if (command) {
71
- const ok = typeof event.output === 'object' && event.output != null && 'ok' in event.output ? Boolean(event.output.ok) : event.success;
72
- const existing = goal.validationCommands.find(item => item.command === command);
73
- const status = ok ? 'passed' : 'failed';
74
- if (existing)
75
- existing.status = status;
76
- else
77
- goal.validationCommands.push({ command, status });
78
- goal.phase = 'validating';
79
- goal.lastProgressAt = now;
80
- if (!ok)
81
- goal.blocker = `Validation command failed: ${command}`;
82
- }
83
- }
84
- goal.workState.phase = goal.phase;
85
- return goal;
20
+ return observeWorkToolEvent(goal, event, now);
86
21
  }
87
22
  export function formatGoalStatus(goal) {
88
23
  const action = goal.phase === 'starting' ? 'starting'
@@ -33,6 +33,36 @@ export function classifyBashCommand(command) {
33
33
  traits.push('changes_git_state');
34
34
  return { riskLevel: 'mutating', traits: uniq(traits), confidence: complex ? 'medium' : 'high', reason: 'command can modify files or repository state' };
35
35
  }
36
+ // `find -delete` removes matched files outright. `-delete` is a find-specific
37
+ // primary, so gate on `find` to avoid flagging unrelated single-dash flags.
38
+ if (has(lower, /\bfind\b/) && has(lower, /(\s|^)-delete\b/)) {
39
+ traits.push('deletes_files');
40
+ return { riskLevel: 'destructive', traits: uniq(traits), confidence: complex ? 'medium' : 'high', reason: 'find -delete removes matched files' };
41
+ }
42
+ // `find -exec`/`-execdir` and `xargs` run an embedded command. Classify by
43
+ // the payload so destructive/mutating verbs are not masked by the read-only
44
+ // `find`/`xargs` wrapper, and never promise read-only for an arbitrary exec.
45
+ const execMatch = /(?:\s|^)(?:-exec(?:dir)?|xargs)\s+(.*)$/.exec(lower);
46
+ if (execMatch) {
47
+ const payload = execMatch[1];
48
+ if (has(payload, /\brm\b|git\s+clean|git\s+restore|drop\s+database|truncate\s+table/)) {
49
+ if (has(payload, /\brm\b/))
50
+ traits.push('deletes_files');
51
+ if (has(payload, /\bgit\b/))
52
+ traits.push('changes_git_state');
53
+ return { riskLevel: 'destructive', traits: uniq(traits), confidence: 'medium', reason: 'embedded command can delete files' };
54
+ }
55
+ if (has(payload, /\b(chmod|mv|cp|mkdir|touch|tee|sed\s+-i|perl\s+-pi)\b/) || has(payload, /\bgit\s+(add|commit|merge|rebase|checkout|restore)\b/)) {
56
+ traits.push('writes_files');
57
+ if (has(payload, /\bchmod\b/))
58
+ traits.push('changes_permissions');
59
+ if (has(payload, /\bgit\b/))
60
+ traits.push('changes_git_state');
61
+ return { riskLevel: 'mutating', traits: uniq(traits), confidence: 'medium', reason: 'embedded command can modify files' };
62
+ }
63
+ traits.push('reads_files');
64
+ return { riskLevel: 'unknown', traits: uniq(traits), confidence: 'low', reason: 'find -exec / xargs runs an embedded command' };
65
+ }
36
66
  if (has(lower, /(^|[;&|]\s*)(npm\s+test|npm\s+run\s+(test|typecheck|lint|build)|pnpm\s+(test|run\s+(test|typecheck|lint|build))|yarn\s+(test|run\s+(test|typecheck|lint|build))|vitest\b|jest\b|tsc\b|eslint\b)/)) {
37
67
  if (has(lower, /test|vitest|jest/))
38
68
  traits.push('runs_tests');
@@ -12,6 +12,7 @@
12
12
  export type UrlValidation = {
13
13
  ok: true;
14
14
  url: URL;
15
+ resolvedAddresses?: string[];
15
16
  } | {
16
17
  ok: false;
17
18
  reasonCode: 'invalid_url' | 'blocked_scheme' | 'blocked_host' | 'blocked_address';
@@ -178,6 +178,8 @@ export async function validateUrl(input, options) {
178
178
  return { ok: false, reasonCode: 'blocked_host', reason: 'URL has no hostname.' };
179
179
  }
180
180
  // If the host is a literal IP, check ranges directly (no DNS needed).
181
+ // No resolvedAddresses: literal IPs carry no DNS-rebinding surface, so the
182
+ // caller can connect to the URL as-is without pinning.
181
183
  if (hostLooksLikeIp(host)) {
182
184
  if (isBlockedIp(host)) {
183
185
  return { ok: false, reasonCode: 'blocked_address', reason: `Address '${host}' is private, loopback, link-local, or otherwise blocked.` };
@@ -202,5 +204,8 @@ export async function validateUrl(input, options) {
202
204
  return { ok: false, reasonCode: 'blocked_address', reason: `Hostname '${host}' resolves to blocked address '${address}'.` };
203
205
  }
204
206
  }
205
- return { ok: true, url };
207
+ // Surface the validated addresses so the caller can pin the connection to
208
+ // one of them, closing the DNS-rebinding TOCTOU between this check and the
209
+ // actual connect (a public hostname that later re-resolves to an internal IP).
210
+ return { ok: true, url, resolvedAddresses: addresses };
206
211
  }
@@ -0,0 +1,5 @@
1
+ import type { ModelMessage } from 'ai';
2
+ import type { SessionEntry } from './sessionStore.js';
3
+ export declare function slimConversationSnapshot(messages: ModelMessage[]): ModelMessage[];
4
+ export declare function prepareSessionEntryForWrite(entry: SessionEntry): SessionEntry | undefined;
5
+ export declare const SESSION_INLINE_VALUE_BYTES: number;
@@ -0,0 +1,78 @@
1
+ const INLINE_VALUE_BYTES = 32 * 1024;
2
+ const PREVIEW_CHARS = 4 * 1024;
3
+ const LARGE_STRING_CHARS = 8 * 1024;
4
+ function jsonByteLength(value) {
5
+ try {
6
+ return Buffer.byteLength(JSON.stringify(value), 'utf8');
7
+ }
8
+ catch {
9
+ return Buffer.byteLength(String(value), 'utf8');
10
+ }
11
+ }
12
+ function previewText(value) {
13
+ const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2) ?? String(value);
14
+ return text.length > PREVIEW_CHARS ? text.slice(0, PREVIEW_CHARS) : text;
15
+ }
16
+ function slimLargeValue(value) {
17
+ const bytes = jsonByteLength(value);
18
+ if (bytes <= INLINE_VALUE_BYTES)
19
+ return value;
20
+ return {
21
+ omitted: true,
22
+ reason: 'session_size_limit',
23
+ originalBytes: bytes,
24
+ preview: previewText(value),
25
+ };
26
+ }
27
+ function slimUnknown(value, seen = new WeakSet()) {
28
+ if (typeof value === 'string') {
29
+ if (value.length <= LARGE_STRING_CHARS)
30
+ return value;
31
+ return `${value.slice(0, PREVIEW_CHARS)}\n\n[Session value truncated: ${value.length - PREVIEW_CHARS} characters omitted]`;
32
+ }
33
+ if (value == null || typeof value !== 'object')
34
+ return value;
35
+ if (seen.has(value))
36
+ return '[Circular]';
37
+ seen.add(value);
38
+ if (Array.isArray(value))
39
+ return value.map(item => slimUnknown(item, seen));
40
+ const record = value;
41
+ if (record.type === 'tool-result') {
42
+ return {
43
+ ...record,
44
+ output: slimLargeValue(record.output),
45
+ result: slimLargeValue(record.result),
46
+ };
47
+ }
48
+ const next = {};
49
+ for (const [key, child] of Object.entries(record))
50
+ next[key] = slimUnknown(child, seen);
51
+ return next;
52
+ }
53
+ export function slimConversationSnapshot(messages) {
54
+ return slimUnknown(messages);
55
+ }
56
+ export function prepareSessionEntryForWrite(entry) {
57
+ if (entry.type === 'event') {
58
+ if (entry.name === 'message_update')
59
+ return undefined;
60
+ if (entry.name === 'tool_end' && entry.text) {
61
+ try {
62
+ const event = JSON.parse(entry.text);
63
+ event.output = slimLargeValue(event.output);
64
+ event.error = slimLargeValue(event.error);
65
+ return { ...entry, text: JSON.stringify(event) };
66
+ }
67
+ catch {
68
+ return entry;
69
+ }
70
+ }
71
+ return entry;
72
+ }
73
+ if (entry.type === 'conversation_snapshot') {
74
+ return { ...entry, messages: slimConversationSnapshot(entry.messages) };
75
+ }
76
+ return entry;
77
+ }
78
+ export const SESSION_INLINE_VALUE_BYTES = INLINE_VALUE_BYTES;
@@ -37,7 +37,27 @@ export declare function createSession(options?: {
37
37
  }): Promise<HazeSession>;
38
38
  export declare function latestSession(cwd?: string, sessionsDir?: string): Promise<HazeSession | undefined>;
39
39
  export declare function appendSessionEntry(session: HazeSession, entry: SessionEntry): Promise<void>;
40
- export declare function readSessionEntries(session: HazeSession): Promise<SessionEntry[]>;
41
- export declare function restoreConversation(session: HazeSession): Promise<ModelMessage[]>;
42
- export declare function restoreWorkState(session: HazeSession): Promise<WorkState | undefined>;
40
+ export interface ReadSessionEntriesResult {
41
+ entries: SessionEntry[];
42
+ /** Per-line parse failures, e.g. `Line 3: Unexpected token...`. Empty when every line parsed. */
43
+ parseErrors: string[];
44
+ }
45
+ /**
46
+ * Read a session file and parse each non-empty line as a JSONL entry.
47
+ *
48
+ * Malformed lines are not silently discarded: they are reported in
49
+ * `parseErrors` (with their 1-based line number) so callers can surface the
50
+ * loss in debug mode instead of silently dropping messages.
51
+ */
52
+ export declare function readSessionEntries(session: HazeSession): Promise<ReadSessionEntriesResult>;
53
+ export interface RestoreConversationResult {
54
+ messages: ModelMessage[];
55
+ parseErrors: string[];
56
+ }
57
+ export declare function restoreConversation(session: HazeSession): Promise<RestoreConversationResult>;
58
+ export interface RestoreWorkStateResult {
59
+ state: WorkState | undefined;
60
+ parseErrors: string[];
61
+ }
62
+ export declare function restoreWorkState(session: HazeSession): Promise<RestoreWorkStateResult>;
43
63
  export declare function formatSession(session: HazeSession): string;
@@ -2,6 +2,7 @@ import crypto from 'node:crypto';
2
2
  import path from 'node:path';
3
3
  import fs from 'fs-extra';
4
4
  import { HAZE_DIR } from '../../config/paths.js';
5
+ import { prepareSessionEntryForWrite } from './sessionSlimming.js';
5
6
  const DEFAULT_SESSIONS_DIR = path.join(HAZE_DIR, 'sessions');
6
7
  function cwdHash(cwd = process.cwd()) {
7
8
  return crypto.createHash('sha256').update(path.resolve(cwd)).digest('hex').slice(0, 16);
@@ -35,29 +36,48 @@ export async function latestSession(cwd = process.cwd(), sessionsDir = DEFAULT_S
35
36
  return { id, file: path.join(dir, latest), cwd: path.resolve(cwd) };
36
37
  }
37
38
  export async function appendSessionEntry(session, entry) {
39
+ const prepared = prepareSessionEntryForWrite(entry);
40
+ if (!prepared)
41
+ return;
38
42
  await fs.ensureDir(path.dirname(session.file));
39
- await fs.appendFile(session.file, `${JSON.stringify(entry)}\n`, 'utf8');
43
+ await fs.appendFile(session.file, `${JSON.stringify(prepared)}\n`, 'utf8');
40
44
  }
45
+ /**
46
+ * Read a session file and parse each non-empty line as a JSONL entry.
47
+ *
48
+ * Malformed lines are not silently discarded: they are reported in
49
+ * `parseErrors` (with their 1-based line number) so callers can surface the
50
+ * loss in debug mode instead of silently dropping messages.
51
+ */
41
52
  export async function readSessionEntries(session) {
42
53
  const raw = await fs.readFile(session.file, 'utf8');
43
- return raw.split('\n').filter(Boolean).flatMap(line => {
54
+ const entries = [];
55
+ const parseErrors = [];
56
+ // Number by true file position: a stray blank line (e.g. from corruption) must not shift
57
+ // the reported line number away from where the malformed line actually sits.
58
+ const lines = raw.split('\n');
59
+ for (let i = 0; i < lines.length; i++) {
60
+ const line = lines[i];
61
+ if (!line)
62
+ continue; // skip blank lines (e.g. the trailing newline)
44
63
  try {
45
- return [JSON.parse(line)];
64
+ entries.push(JSON.parse(line));
46
65
  }
47
- catch {
48
- return [];
66
+ catch (error) {
67
+ parseErrors.push(`Line ${i + 1}: ${error instanceof Error ? error.message : String(error)}`);
49
68
  }
50
- });
69
+ }
70
+ return { entries, parseErrors };
51
71
  }
52
72
  export async function restoreConversation(session) {
53
- const entries = await readSessionEntries(session);
73
+ const { entries, parseErrors } = await readSessionEntries(session);
54
74
  const snapshots = entries.filter((entry) => entry.type === 'conversation_snapshot');
55
- return snapshots.at(-1)?.messages ?? [];
75
+ return { messages: snapshots.at(-1)?.messages ?? [], parseErrors };
56
76
  }
57
77
  export async function restoreWorkState(session) {
58
- const entries = await readSessionEntries(session);
78
+ const { entries, parseErrors } = await readSessionEntries(session);
59
79
  const snapshots = entries.filter((entry) => entry.type === 'work_state_snapshot');
60
- return snapshots.at(-1)?.state;
80
+ return { state: snapshots.at(-1)?.state, parseErrors };
61
81
  }
62
82
  export function formatSession(session) {
63
83
  return `${session.id} · ${session.file}`;
@@ -17,6 +17,15 @@ export interface SubagentResult {
17
17
  durationMs: number;
18
18
  error?: string;
19
19
  }
20
+ declare function toolSummary(output: unknown): string;
21
+ declare function toolOnlyStepCount(steps: Array<{
22
+ toolCalls: unknown[];
23
+ text: string;
24
+ }>): number;
25
+ export declare const internals: {
26
+ toolSummary: typeof toolSummary;
27
+ toolOnlyStepCount: typeof toolOnlyStepCount;
28
+ };
20
29
  export declare function runSubagent(task: string, options: {
21
30
  model: Parameters<typeof streamText>[0]['model'];
22
31
  contextFiles: ContextFile[];
@@ -31,6 +40,7 @@ export declare function createSubagentTool(options: {
31
40
  session?: PromptSession;
32
41
  }): import("ai").Tool<{
33
42
  task: string;
34
- tools?: ("listFiles" | "editFile" | "replaceLines" | "writeFile" | "readFile" | "grep" | "bash" | "fetch" | "readToolOutput")[] | undefined;
43
+ tools?: ("editFile" | "replaceLines" | "writeFile" | "listFiles" | "readFile" | "grep" | "bash" | "fetch" | "readToolOutput")[] | undefined;
35
44
  maxSteps?: number | undefined;
36
45
  }, SubagentResult>;
46
+ export {};
@@ -29,6 +29,7 @@ function toolOnlyStepCount(steps) {
29
29
  }
30
30
  return count;
31
31
  }
32
+ export const internals = { toolSummary, toolOnlyStepCount };
32
33
  export async function runSubagent(task, options) {
33
34
  const start = performance.now();
34
35
  const toolNames = (options.allowedTools ?? ALL_TOOLS).filter(t => ALL_TOOLS.includes(t));