@denizokcu/haze 0.6.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 (147) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +59 -12
  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 +293 -894
  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 +1 -1
  24. package/dist/cli/commands/commands.js +41 -267
  25. package/dist/cli/commands/formatters.js +12 -4
  26. package/dist/cli/commands/initCommand.d.ts +2 -0
  27. package/dist/cli/commands/initCommand.js +19 -0
  28. package/dist/cli/commands/logsCommand.d.ts +2 -0
  29. package/dist/cli/commands/logsCommand.js +63 -0
  30. package/dist/cli/commands/lspWizard.d.ts +14 -0
  31. package/dist/cli/commands/lspWizard.js +44 -0
  32. package/dist/cli/commands/mcpWizard.d.ts +15 -0
  33. package/dist/cli/commands/mcpWizard.js +69 -0
  34. package/dist/cli/commands/modelCommand.d.ts +2 -0
  35. package/dist/cli/commands/modelCommand.js +36 -0
  36. package/dist/cli/commands/providerWizard.d.ts +30 -0
  37. package/dist/cli/commands/providerWizard.js +114 -0
  38. package/dist/cli/commands/runCommand.d.ts +16 -0
  39. package/dist/cli/commands/runCommand.js +170 -0
  40. package/dist/cli/commands/settingsSummary.d.ts +3 -0
  41. package/dist/cli/commands/settingsSummary.js +40 -0
  42. package/dist/cli/commands/skillConfirmRemove.d.ts +11 -0
  43. package/dist/cli/commands/skillConfirmRemove.js +19 -0
  44. package/dist/cli/commands/skillCreation.d.ts +12 -0
  45. package/dist/cli/commands/skillCreation.js +14 -0
  46. package/dist/cli/commands/skillWizard.d.ts +15 -0
  47. package/dist/cli/commands/skillWizard.js +38 -0
  48. package/dist/cli/commands/streaming/assistantText.d.ts +17 -0
  49. package/dist/cli/commands/streaming/assistantText.js +115 -0
  50. package/dist/cli/commands/streaming/toolGroupRenderer.d.ts +55 -0
  51. package/dist/cli/commands/streaming/toolGroupRenderer.js +102 -0
  52. package/dist/cli/commands/streaming/toolResultState.d.ts +13 -0
  53. package/dist/cli/commands/streaming/toolResultState.js +25 -0
  54. package/dist/cli/commands/streaming/turnRuntime.d.ts +78 -0
  55. package/dist/cli/commands/streaming/turnRuntime.js +86 -0
  56. package/dist/cli/commands/streaming.d.ts +9 -25
  57. package/dist/cli/commands/streaming.js +82 -347
  58. package/dist/cli/commands/wizardActions.d.ts +40 -0
  59. package/dist/cli/commands/wizardActions.js +40 -0
  60. package/dist/cli/commands/wizardInput.d.ts +4 -0
  61. package/dist/cli/commands/wizardInput.js +19 -0
  62. package/dist/cli/commands/wizardPrompts.d.ts +22 -0
  63. package/dist/cli/commands/wizardPrompts.js +52 -0
  64. package/dist/cli/commands/wizardSuggestions.d.ts +23 -0
  65. package/dist/cli/commands/wizardSuggestions.js +139 -0
  66. package/dist/cli/index.js +62 -4
  67. package/dist/config/contextFiles.d.ts +8 -1
  68. package/dist/config/contextFiles.js +25 -12
  69. package/dist/config/lspSettings.js +3 -6
  70. package/dist/config/mcpSettings.js +5 -5
  71. package/dist/config/providers.js +4 -4
  72. package/dist/config/skillSettings.js +4 -3
  73. package/dist/core/agent/budgets.d.ts +6 -0
  74. package/dist/core/agent/budgets.js +6 -0
  75. package/dist/core/agent/compaction.js +1 -1
  76. package/dist/core/agent/requestAssembly.d.ts +0 -7
  77. package/dist/core/agent/requestAssembly.js +27 -5
  78. package/dist/core/agent/toolOutputStore.js +5 -4
  79. package/dist/core/agent/toolResults.d.ts +31 -0
  80. package/dist/core/agent/toolResults.js +42 -0
  81. package/dist/core/agent/turnPolicy.d.ts +8 -0
  82. package/dist/core/agent/turnPolicy.js +23 -0
  83. package/dist/core/agent/workState.d.ts +18 -5
  84. package/dist/core/agent/workState.js +39 -20
  85. package/dist/core/bashOutput/reducers/content.d.ts +1 -0
  86. package/dist/core/bashOutput/reducers/content.js +1 -1
  87. package/dist/core/bashOutput/reducers/gh.d.ts +1 -0
  88. package/dist/core/bashOutput/reducers/gh.js +77 -0
  89. package/dist/core/bashOutput/registry.js +8 -0
  90. package/dist/core/goal/sessionGoal.d.ts +6 -30
  91. package/dist/core/goal/sessionGoal.js +3 -68
  92. package/dist/core/safety/bashClassifier.js +30 -0
  93. package/dist/core/safety/urlGuard.d.ts +1 -0
  94. package/dist/core/safety/urlGuard.js +6 -1
  95. package/dist/core/session/sessionSlimming.d.ts +5 -0
  96. package/dist/core/session/sessionSlimming.js +78 -0
  97. package/dist/core/session/sessionStore.d.ts +23 -3
  98. package/dist/core/session/sessionStore.js +30 -10
  99. package/dist/core/subagent/subagentRunner.d.ts +11 -1
  100. package/dist/core/subagent/subagentRunner.js +1 -0
  101. package/dist/llm/capabilities.d.ts +12 -0
  102. package/dist/llm/capabilities.js +10 -0
  103. package/dist/llm/client.d.ts +1 -0
  104. package/dist/llm/client.js +11 -2
  105. package/dist/llm/hazeTools.d.ts +31 -32
  106. package/dist/llm/hazeTools.js +40 -567
  107. package/dist/llm/lsp.d.ts +46 -1
  108. package/dist/llm/lsp.js +9 -9
  109. package/dist/llm/lspTools.d.ts +2 -20
  110. package/dist/llm/mcp.js +9 -0
  111. package/dist/llm/requestContext.js +7 -22
  112. package/dist/llm/systemPrompt.d.ts +1 -0
  113. package/dist/llm/systemPrompt.js +1 -1
  114. package/dist/llm/tools/bashTool.d.ts +5 -0
  115. package/dist/llm/tools/bashTool.js +81 -0
  116. package/dist/llm/tools/editMatch.d.ts +55 -0
  117. package/dist/llm/tools/editMatch.js +99 -0
  118. package/dist/llm/tools/failures.d.ts +36 -0
  119. package/dist/llm/tools/failures.js +38 -0
  120. package/dist/llm/tools/fetchTool.d.ts +65 -0
  121. package/dist/llm/tools/fetchTool.js +45 -0
  122. package/dist/llm/tools/fileToolShared.d.ts +10 -0
  123. package/dist/llm/tools/fileToolShared.js +43 -0
  124. package/dist/llm/tools/grepParse.d.ts +13 -0
  125. package/dist/llm/tools/grepParse.js +67 -0
  126. package/dist/llm/tools/outputCap.d.ts +53 -0
  127. package/dist/llm/tools/outputCap.js +67 -0
  128. package/dist/llm/tools/storedOutputTool.d.ts +10 -0
  129. package/dist/llm/tools/storedOutputTool.js +17 -0
  130. package/dist/llm/tools/taskTool.d.ts +28 -0
  131. package/dist/llm/tools/taskTool.js +41 -0
  132. package/dist/llm/tools/toolContext.d.ts +69 -0
  133. package/dist/llm/tools/toolContext.js +187 -0
  134. package/dist/llm/tools/workspaceFile.d.ts +33 -0
  135. package/dist/llm/tools/workspaceFile.js +27 -0
  136. package/dist/llm/webFetch.d.ts +13 -1
  137. package/dist/llm/webFetch.js +91 -7
  138. package/dist/skills/builder/SkillBuilder.d.ts +3 -0
  139. package/dist/skills/builder/SkillBuilder.js +1 -1
  140. package/dist/ui/components/TextInput.js +1 -99
  141. package/dist/ui/inputBuffer.d.ts +28 -0
  142. package/dist/ui/inputBuffer.js +99 -0
  143. package/dist/utils/collections.d.ts +6 -0
  144. package/dist/utils/collections.js +9 -0
  145. package/dist/utils/path.d.ts +2 -0
  146. package/dist/utils/path.js +40 -0
  147. package/package.json +1 -2
@@ -1,12 +1,5 @@
1
1
  import type { ModelMessage } from 'ai';
2
2
  export declare const SYNTHETIC_CONTROL_OPEN = "<haze_control>";
3
- export declare function toolRequestSettings<T extends Record<string, unknown>>(tools: T, allowTools: boolean): {
4
- tools: T;
5
- toolChoice: "auto";
6
- } | {
7
- tools?: undefined;
8
- toolChoice?: undefined;
9
- };
10
3
  export declare function isSyntheticControlMessage(message: ModelMessage): boolean;
11
4
  export declare function stripSyntheticControls(messages: ModelMessage[]): ModelMessage[];
12
5
  export declare function withSyntheticControl(messages: ModelMessage[], control: string): ModelMessage[];
@@ -1,8 +1,6 @@
1
1
  import { estimateValueTokens } from './contextBudget.js';
2
+ import { isFailedToolOutput } from './toolResults.js';
2
3
  export const SYNTHETIC_CONTROL_OPEN = '<haze_control>';
3
- export function toolRequestSettings(tools, allowTools) {
4
- return allowTools ? { tools, toolChoice: 'auto' } : {};
5
- }
6
4
  export function isSyntheticControlMessage(message) {
7
5
  return message.role === 'user'
8
6
  && typeof message.content === 'string'
@@ -29,7 +27,7 @@ function isFailedResult(output) {
29
27
  if (type === 'error-text' || type === 'error-json' || type === 'execution-denied')
30
28
  return true;
31
29
  const value = resultValue(output);
32
- return typeof value === 'object' && value != null && 'ok' in value && value.ok === false;
30
+ return isFailedToolOutput(value);
33
31
  }
34
32
  function compactJsonValue(value, toolName) {
35
33
  if (typeof value !== 'object' || value == null || Array.isArray(value)) {
@@ -80,7 +78,7 @@ function compactResultOutput(output, toolName) {
80
78
  return { ...typed, value: `[Older successful ${toolName} result omitted from active context.]` };
81
79
  return output;
82
80
  }
83
- const COMPACTABLE_INPUT_TOOLS = new Set(['writeFile', 'bash']);
81
+ const COMPACTABLE_INPUT_TOOLS = new Set(['writeFile', 'editFile', 'replaceLines', 'bash']);
84
82
  const BASH_COMMAND_TRUNCATE_THRESHOLD = 200;
85
83
  const BASH_COMMAND_KEEP_CHARS = 150;
86
84
  function compactToolCallInput(input, toolName) {
@@ -95,6 +93,30 @@ function compactToolCallInput(input, toolName) {
95
93
  content: `[Compacted: original ${bytes} bytes. Use readFile on "${path}" to inspect.]`,
96
94
  };
97
95
  }
96
+ if (toolName === 'editFile' && Array.isArray(source.edits)) {
97
+ const path = typeof source.path === 'string' ? source.path : '<unknown>';
98
+ const edits = source.edits.map(edit => {
99
+ if (typeof edit !== 'object' || edit == null)
100
+ return edit;
101
+ const entry = edit;
102
+ const oldBytes = typeof entry.oldText === 'string' ? entry.oldText.length : 0;
103
+ const newBytes = typeof entry.newText === 'string' ? entry.newText.length : 0;
104
+ return {
105
+ ...entry,
106
+ oldText: `[Compacted: original ${oldBytes} bytes.]`,
107
+ newText: `[Compacted: original ${newBytes} bytes. Use readFile on "${path}" to inspect.]`,
108
+ };
109
+ });
110
+ return { ...source, edits };
111
+ }
112
+ if (toolName === 'replaceLines' && typeof source.content === 'string') {
113
+ const bytes = source.content.length;
114
+ const path = typeof source.path === 'string' ? source.path : '<unknown>';
115
+ return {
116
+ ...source,
117
+ content: `[Compacted: original ${bytes} bytes. Use readFile on "${path}" to inspect.]`,
118
+ };
119
+ }
98
120
  if (toolName === 'bash' && typeof source.command === 'string' && source.command.length > BASH_COMMAND_TRUNCATE_THRESHOLD) {
99
121
  const total = source.command.length;
100
122
  const truncated = source.command.slice(0, BASH_COMMAND_KEEP_CHARS).replace(/\s+/g, ' ').trim();
@@ -4,11 +4,12 @@ const MAX_STORED_OUTPUTS = 100;
4
4
  export function storeToolOutput(content) {
5
5
  const handle = `output-${crypto.randomBytes(8).toString('hex')}`;
6
6
  outputs.set(handle, content);
7
- while (outputs.size > MAX_STORED_OUTPUTS) {
7
+ // Synchronous, so the check+delete is atomic across async callers — no race.
8
+ // Each call inserts exactly one entry, so a single eviction restores the cap.
9
+ if (outputs.size > MAX_STORED_OUTPUTS) {
8
10
  const oldest = outputs.keys().next().value;
9
- if (!oldest)
10
- break;
11
- outputs.delete(oldest);
11
+ if (oldest)
12
+ outputs.delete(oldest);
12
13
  }
13
14
  return handle;
14
15
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Shared, protocol-level predicates and accessors for tool outputs and inputs.
3
+ *
4
+ * Tool results across the codebase carry a loose `{ok?: boolean}` convention
5
+ * (built-in hazeTools, subagent summaries, MCP passthrough). Centralizing these
6
+ * checks keeps the semantics identical everywhere they are used: the dedup gate
7
+ * (`hazeTools`), the work-state observer, the agent turn, and request
8
+ * compaction. Keeping them in `core/agent/` (no `ai`/UI imports) preserves
9
+ * auditability.
10
+ */
11
+ /**
12
+ * A structured tool result explicitly reports failure via `{ok: false}`.
13
+ * Returns false for results with no `ok` field (success is implied by the
14
+ * caller's `success` flag) and for non-object outputs.
15
+ */
16
+ export declare function isFailedToolOutput(output: unknown): boolean;
17
+ /**
18
+ * Combine the provider success flag with the structured `ok` field. A result
19
+ * counts as OK only when the call succeeded AND did not report `{ok: false}`.
20
+ */
21
+ export declare function toolOutputOk(output: unknown, success: boolean): boolean;
22
+ /**
23
+ * Read a string field from an `unknown` tool input object. Returns undefined
24
+ * for non-objects, missing keys, or non-string values.
25
+ */
26
+ export declare function toolInputField(input: unknown, key: string): string | undefined;
27
+ /**
28
+ * Deduplicated read-only tool calls return a `{duplicateSkipped: true}` marker
29
+ * instead of re-running. Lets observers treat them as no-ops.
30
+ */
31
+ export declare function isDuplicateSkippedOutput(output: unknown): boolean;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Shared, protocol-level predicates and accessors for tool outputs and inputs.
3
+ *
4
+ * Tool results across the codebase carry a loose `{ok?: boolean}` convention
5
+ * (built-in hazeTools, subagent summaries, MCP passthrough). Centralizing these
6
+ * checks keeps the semantics identical everywhere they are used: the dedup gate
7
+ * (`hazeTools`), the work-state observer, the agent turn, and request
8
+ * compaction. Keeping them in `core/agent/` (no `ai`/UI imports) preserves
9
+ * auditability.
10
+ */
11
+ /**
12
+ * A structured tool result explicitly reports failure via `{ok: false}`.
13
+ * Returns false for results with no `ok` field (success is implied by the
14
+ * caller's `success` flag) and for non-object outputs.
15
+ */
16
+ export function isFailedToolOutput(output) {
17
+ return typeof output === 'object' && output != null && 'ok' in output && output.ok === false;
18
+ }
19
+ /**
20
+ * Combine the provider success flag with the structured `ok` field. A result
21
+ * counts as OK only when the call succeeded AND did not report `{ok: false}`.
22
+ */
23
+ export function toolOutputOk(output, success) {
24
+ return success && !isFailedToolOutput(output);
25
+ }
26
+ /**
27
+ * Read a string field from an `unknown` tool input object. Returns undefined
28
+ * for non-objects, missing keys, or non-string values.
29
+ */
30
+ export function toolInputField(input, key) {
31
+ if (typeof input !== 'object' || input == null || !(key in input))
32
+ return undefined;
33
+ const value = input[key];
34
+ return typeof value === 'string' ? value : undefined;
35
+ }
36
+ /**
37
+ * Deduplicated read-only tool calls return a `{duplicateSkipped: true}` marker
38
+ * instead of re-running. Lets observers treat them as no-ops.
39
+ */
40
+ export function isDuplicateSkippedOutput(output) {
41
+ return typeof output === 'object' && output != null && 'duplicateSkipped' in output && output.duplicateSkipped === true;
42
+ }
@@ -0,0 +1,8 @@
1
+ export declare function uniqueRepeatedToolNames(toolCalls: Array<{
2
+ toolName: string;
3
+ input: unknown;
4
+ }>): string[];
5
+ export declare function toolOnlyStepCount(steps: Array<{
6
+ toolCalls: unknown[];
7
+ text: string;
8
+ }>): number;
@@ -0,0 +1,23 @@
1
+ function stableToolKey(toolCall) {
2
+ return `${toolCall.toolName}:${JSON.stringify(toolCall.input)}`;
3
+ }
4
+ export function uniqueRepeatedToolNames(toolCalls) {
5
+ const seen = new Set();
6
+ const repeated = new Set();
7
+ for (const toolCall of toolCalls) {
8
+ const key = stableToolKey(toolCall);
9
+ if (seen.has(key))
10
+ repeated.add(toolCall.toolName);
11
+ seen.add(key);
12
+ }
13
+ return [...repeated];
14
+ }
15
+ export function toolOnlyStepCount(steps) {
16
+ let count = 0;
17
+ for (const step of [...steps].reverse()) {
18
+ if (step.toolCalls.length === 0 || step.text.trim().length > 0)
19
+ break;
20
+ count += 1;
21
+ }
22
+ return count;
23
+ }
@@ -1,9 +1,14 @@
1
1
  import type { RequestIntent } from '../goal/requestClassifier.js';
2
2
  export type WorkFileAction = 'read' | 'created' | 'modified';
3
- export type WorkValidationStatus = 'passed' | 'failed';
3
+ export type WorkValidationStatus = 'pending' | 'passed' | 'failed';
4
+ export type WorkStatus = 'active' | 'needs-user' | 'blocked' | 'complete' | 'aborted';
5
+ export type WorkPhase = 'starting' | 'inspecting' | 'editing' | 'validating' | 'summarizing' | 'done';
4
6
  export interface WorkState {
7
+ id: string;
5
8
  goal: string;
9
+ originalUserRequest: string;
6
10
  intent: RequestIntent;
11
+ normalizedIntent: RequestIntent;
7
12
  successCriteria: string[];
8
13
  constraints: string[];
9
14
  decisions: Array<{
@@ -15,15 +20,23 @@ export interface WorkState {
15
20
  action: WorkFileAction;
16
21
  note?: string;
17
22
  }>;
23
+ touchedFiles: string[];
18
24
  validations: Array<{
19
25
  command: string;
20
- status: WorkValidationStatus;
26
+ status: Exclude<WorkValidationStatus, 'pending'>;
21
27
  summary: string;
22
28
  }>;
29
+ validationCommands: Array<{
30
+ command: string;
31
+ status: WorkValidationStatus;
32
+ }>;
23
33
  blockers: string[];
24
34
  pending: string[];
25
35
  nextAction?: string;
26
- phase: string;
36
+ status: WorkStatus;
37
+ phase: WorkPhase;
38
+ blocker?: string;
39
+ lastProgressAt: number;
27
40
  revision: number;
28
41
  }
29
42
  export interface WorkToolEvent {
@@ -33,6 +46,6 @@ export interface WorkToolEvent {
33
46
  output?: unknown;
34
47
  duplicateSkipped?: boolean;
35
48
  }
36
- export declare function createWorkState(goal: string, intent: RequestIntent, successCriteria: string[]): WorkState;
37
- export declare function observeWorkToolEvent(state: WorkState, event: WorkToolEvent): WorkState;
49
+ export declare function createWorkState(goal: string, intent: RequestIntent, successCriteria: string[], now?: number): WorkState;
50
+ export declare function observeWorkToolEvent(state: WorkState, event: WorkToolEvent, now?: number): WorkState;
38
51
  export declare function workStatePrompt(state: WorkState): string;
@@ -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');