@denizokcu/haze 1.1.1 → 1.4.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 (133) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +26 -15
  3. package/SECURITY.md +1 -1
  4. package/bin/haze.js +27 -7
  5. package/dist/buildInfo.json +3 -3
  6. package/dist/cli/chat/inputSuggestions.js +3 -0
  7. package/dist/cli/chat/liveMessages.d.ts +36 -0
  8. package/dist/cli/chat/liveMessages.js +64 -0
  9. package/dist/cli/chat/sessionLifecycle.d.ts +2 -1
  10. package/dist/cli/chat/sessionLifecycle.js +25 -2
  11. package/dist/cli/chat/sessionRecorder.d.ts +7 -0
  12. package/dist/cli/chat/sessionRecorder.js +6 -0
  13. package/dist/cli/chat/wizard/sessionThemeHandlers.d.ts +1 -1
  14. package/dist/cli/chat/wizard/sessionThemeHandlers.js +16 -1
  15. package/dist/cli/commands/chat.js +63 -36
  16. package/dist/cli/commands/commandHelp.js +2 -0
  17. package/dist/cli/commands/commands.js +2 -0
  18. package/dist/cli/commands/formatters.js +5 -1
  19. package/dist/cli/commands/ndjsonSink.d.ts +12 -0
  20. package/dist/cli/commands/ndjsonSink.js +29 -0
  21. package/dist/cli/commands/reasoningCommand.d.ts +35 -0
  22. package/dist/cli/commands/reasoningCommand.js +46 -0
  23. package/dist/cli/commands/runCommand.d.ts +14 -0
  24. package/dist/cli/commands/runCommand.js +43 -11
  25. package/dist/cli/commands/settingsSummary.js +2 -0
  26. package/dist/cli/commands/streaming/agentAttempt.d.ts +14 -1
  27. package/dist/cli/commands/streaming/agentAttempt.js +9 -5
  28. package/dist/cli/commands/streaming/assistantSegments.d.ts +0 -7
  29. package/dist/cli/commands/streaming/assistantSegments.js +1 -1
  30. package/dist/cli/commands/streaming/attemptLifecycle.js +13 -9
  31. package/dist/cli/commands/streaming/attemptOutcome.d.ts +23 -3
  32. package/dist/cli/commands/streaming/attemptOutcome.js +64 -11
  33. package/dist/cli/commands/streaming/attemptSetup.d.ts +13 -3
  34. package/dist/cli/commands/streaming/attemptSetup.js +40 -15
  35. package/dist/cli/commands/streaming/goalCheckpoint.d.ts +6 -0
  36. package/dist/cli/commands/streaming/goalCheckpoint.js +1 -0
  37. package/dist/cli/commands/streaming/goalSupervisor.d.ts +6 -1
  38. package/dist/cli/commands/streaming/goalSupervisor.js +18 -4
  39. package/dist/cli/commands/streaming/prepareStep.d.ts +6 -4
  40. package/dist/cli/commands/streaming/prepareStep.js +43 -22
  41. package/dist/cli/commands/streaming/stallRecovery.js +2 -2
  42. package/dist/cli/commands/streaming/streamLoop.d.ts +31 -4
  43. package/dist/cli/commands/streaming/streamLoop.js +280 -44
  44. package/dist/cli/commands/streaming/toolPartHandlers.js +13 -0
  45. package/dist/cli/commands/streaming/turnRuntime.d.ts +1 -1
  46. package/dist/cli/commands/streaming/turnRuntime.js +3 -2
  47. package/dist/cli/commands/streaming.d.ts +15 -2
  48. package/dist/cli/commands/streaming.js +37 -8
  49. package/dist/cli/commands/wizardFlow.d.ts +7 -0
  50. package/dist/cli/commands/wizardFlow.js +22 -0
  51. package/dist/cli/index.js +8 -3
  52. package/dist/config/modelCatalog.d.ts +32 -0
  53. package/dist/config/modelCatalog.js +84 -0
  54. package/dist/config/modelDiscovery.js +68 -5
  55. package/dist/config/settings.d.ts +18 -6
  56. package/dist/config/settings.js +11 -1
  57. package/dist/core/agent/budgets.d.ts +10 -2
  58. package/dist/core/agent/budgets.js +10 -2
  59. package/dist/core/agent/compaction.d.ts +42 -3
  60. package/dist/core/agent/compaction.js +53 -5
  61. package/dist/core/agent/completionController.d.ts +11 -1
  62. package/dist/core/agent/completionController.js +33 -0
  63. package/dist/core/agent/contextBudget.d.ts +56 -0
  64. package/dist/core/agent/contextBudget.js +53 -0
  65. package/dist/core/agent/errors.js +2 -2
  66. package/dist/core/agent/events.d.ts +26 -2
  67. package/dist/core/agent/goalPolicy.d.ts +7 -0
  68. package/dist/core/agent/goalPolicy.js +9 -0
  69. package/dist/core/agent/overflow.d.ts +45 -0
  70. package/dist/core/agent/overflow.js +91 -0
  71. package/dist/core/agent/reasoningPolicy.d.ts +45 -9
  72. package/dist/core/agent/reasoningPolicy.js +49 -9
  73. package/dist/core/agent/requestAssembly.d.ts +7 -0
  74. package/dist/core/agent/requestAssembly.js +15 -7
  75. package/dist/core/agent/toolCapabilities.d.ts +3 -3
  76. package/dist/core/agent/toolCapabilities.js +31 -7
  77. package/dist/core/agent/workState.d.ts +6 -4
  78. package/dist/core/agent/workState.js +53 -29
  79. package/dist/core/deadline.js +22 -24
  80. package/dist/core/safety/secretPaths.js +10 -7
  81. package/dist/core/safety/shellClassifier.d.ts +18 -0
  82. package/dist/core/safety/shellClassifier.js +39 -0
  83. package/dist/core/session/sessionSlimming.d.ts +2 -0
  84. package/dist/core/session/sessionSlimming.js +50 -1
  85. package/dist/core/session/sessionStore.d.ts +14 -8
  86. package/dist/core/session/sessionStore.js +59 -32
  87. package/dist/core/shellOutput/reducers/git.js +7 -2
  88. package/dist/core/shellOutput/reducers/validation.d.ts +1 -1
  89. package/dist/core/shellOutput/reducers/validation.js +14 -1
  90. package/dist/core/shellOutput/registry.js +3 -2
  91. package/dist/core/subagent/contracts.d.ts +8 -1
  92. package/dist/core/subagent/subagentRunner.d.ts +4 -0
  93. package/dist/core/subagent/subagentRunner.js +33 -25
  94. package/dist/core/tasks/taskStorage.js +8 -1
  95. package/dist/core/validation/outputParser.d.ts +1 -1
  96. package/dist/core/validation/outputParser.js +30 -1
  97. package/dist/llm/client.d.ts +4 -3
  98. package/dist/llm/client.js +34 -16
  99. package/dist/llm/hazeTools.d.ts +2039 -16
  100. package/dist/llm/hazeTools.js +43 -2
  101. package/dist/llm/lsp/client.d.ts +7 -1
  102. package/dist/llm/lsp/client.js +58 -9
  103. package/dist/llm/lsp/pool.d.ts +11 -0
  104. package/dist/llm/lsp/pool.js +61 -4
  105. package/dist/llm/lsp/protocol.d.ts +6 -23
  106. package/dist/llm/lsp/requests.d.ts +54 -60
  107. package/dist/llm/lsp/requests.js +152 -28
  108. package/dist/llm/lsp/symbols.d.ts +16 -0
  109. package/dist/llm/lsp/symbols.js +70 -0
  110. package/dist/llm/lsp/workspaceEdit.d.ts +43 -0
  111. package/dist/llm/lsp/workspaceEdit.js +117 -0
  112. package/dist/llm/lspTools.d.ts +7518 -2859
  113. package/dist/llm/lspTools.js +195 -110
  114. package/dist/llm/requestContext.d.ts +3 -2
  115. package/dist/llm/requestContext.js +8 -4
  116. package/dist/llm/systemPrompt.js +2 -2
  117. package/dist/llm/tools/fetchTool.d.ts +4 -0
  118. package/dist/llm/tools/processTool.d.ts +4 -0
  119. package/dist/llm/tools/replaceInFiles.d.ts +105 -0
  120. package/dist/llm/tools/replaceInFiles.js +131 -0
  121. package/dist/llm/tools/shellTool.d.ts +4 -0
  122. package/dist/llm/tools/shellTool.js +27 -8
  123. package/dist/llm/tools/storedOutputTool.d.ts +4 -0
  124. package/dist/llm/tools/taskTool.d.ts +4 -0
  125. package/dist/llm/tools/toolContext.d.ts +3 -0
  126. package/dist/llm/tools/toolContext.js +26 -4
  127. package/dist/skills/SkillLoader.js +27 -1
  128. package/dist/ui/components/TextInput.d.ts +18 -1
  129. package/dist/ui/components/TextInput.js +44 -6
  130. package/dist/ui/components/useInputSuggestions.js +18 -6
  131. package/dist/utils/buildInfo.js +29 -8
  132. package/dist/utils/fs.js +5 -1
  133. package/package.json +20 -19
@@ -1,8 +1,30 @@
1
+ export const REASONING_LEVELS = ['none', 'minimal', 'low', 'medium', 'high', 'xhigh'];
2
+ /**
3
+ * Level applied when settings carry no `reasoning` key. Users opt out with an
4
+ * explicit `none` (reasoning off) or the stored `provider-default` sentinel
5
+ * (written by `/reasoning unset`); key-absent means this default.
6
+ */
7
+ export const DEFAULT_REASONING_LEVEL = 'high';
8
+ /** Stored sentinel meaning "send no reasoning parameter at all". */
9
+ export const REASONING_PROVIDER_DEFAULT = 'provider-default';
10
+ export function isStoredReasoning(value) {
11
+ return isReasoningLevel(value) || value === REASONING_PROVIDER_DEFAULT;
12
+ }
13
+ /**
14
+ * The level a session actually requests: the stored setting when present, the
15
+ * default when the key is absent. The `provider-default` sentinel maps to
16
+ * undefined — no parameter is sent.
17
+ */
18
+ export function effectiveRequestedReasoning(setting) {
19
+ if (setting === REASONING_PROVIDER_DEFAULT)
20
+ return undefined;
21
+ return setting ?? DEFAULT_REASONING_LEVEL;
22
+ }
1
23
  /**
2
24
  * Resolve a requested reasoning level against provider capabilities. Pure and
3
- * capability based: only protocols that accept the OpenAI `reasoningEffort`
4
- * provider option receive a level; everything else is disabled (never silently
5
- * passed in a shape the protocol does not define). No model-name branching.
25
+ * capability based: only protocols that accept the reasoning parameter receive
26
+ * a level; everything else is disabled (the parameter is omitted entirely,
27
+ * never sent in a shape the protocol does not define). No model-name branching.
6
28
  */
7
29
  export function resolveReasoningPolicy(input) {
8
30
  const { requested, capabilities } = input;
@@ -13,15 +35,33 @@ export function resolveReasoningPolicy(input) {
13
35
  return { requested, effective: requested, reason: 'applied via supported provider protocol' };
14
36
  }
15
37
  /**
16
- * The provider-option fragment to merge into request settings for a resolved
17
- * policy. Returns undefined when disabled so unsupported protocols send nothing.
38
+ * The AI SDK top-level `reasoning` call setting for a resolved policy.
39
+ * Returns undefined when disabled so unsupported or unrequested turns omit the
40
+ * parameter entirely. Never returns `'provider-default'` today; the sentinel
41
+ * stays in the return type for forward compatibility.
18
42
  */
19
- export function reasoningProviderOptions(policy) {
43
+ export function reasoningCallSetting(policy) {
20
44
  if (policy.effective === 'disabled')
21
45
  return undefined;
22
- return { openai: { reasoningEffort: policy.effective } };
46
+ return policy.effective;
23
47
  }
24
- const LEVELS = ['low', 'medium', 'high'];
25
48
  export function isReasoningLevel(value) {
26
- return typeof value === 'string' && LEVELS.includes(value);
49
+ return typeof value === 'string' && REASONING_LEVELS.includes(value);
50
+ }
51
+ /** Aliases accepted by CLI paths (`/reasoning`, `--reasoning`) for "send no reasoning parameter". */
52
+ export function isReasoningUnsetAlias(value) {
53
+ return value === 'unset' || value === 'off' || value === REASONING_PROVIDER_DEFAULT;
54
+ }
55
+ /**
56
+ * Parse a `--reasoning` CLI value (case-insensitive): a level maps directly,
57
+ * the unset aliases mean "send no reasoning parameter for this run". Shared by
58
+ * the commander flag surface and the headless option validation.
59
+ */
60
+ export function parseReasoningOverride(raw) {
61
+ const value = raw.trim().toLowerCase();
62
+ if (isReasoningUnsetAlias(value))
63
+ return { ok: true, setting: REASONING_PROVIDER_DEFAULT };
64
+ if (isReasoningLevel(value))
65
+ return { ok: true, setting: value };
66
+ return { ok: false, error: `Unknown reasoning level "${raw.trim()}". Valid levels: ${REASONING_LEVELS.join(', ')} — or unset for the provider default.` };
27
67
  }
@@ -2,6 +2,13 @@ import type { ModelMessage } from 'ai';
2
2
  export declare function stripSyntheticControls(messages: ModelMessage[]): ModelMessage[];
3
3
  export declare function withoutSystemMessages(messages: ModelMessage[]): ModelMessage[];
4
4
  export declare function withSyntheticControl(messages: ModelMessage[], control: string): ModelMessage[];
5
+ /**
6
+ * Append a per-step control without rewriting an already-sent provider prefix.
7
+ * Active/session conversation state still removes every tagged control through
8
+ * `stripSyntheticControls`; this variant exists only for an in-flight logical
9
+ * turn whose next provider request should remain cache-prefix compatible.
10
+ */
11
+ export declare function appendSyntheticControl(messages: ModelMessage[], control: string): ModelMessage[];
5
12
  /** Drop only a trailing text-only assistant final that completion policy rejected. */
6
13
  export declare function withoutRejectedAssistantFinal(messages: ModelMessage[]): ModelMessage[];
7
14
  export declare function compactToolHistory(messages: ModelMessage[], options?: {
@@ -1,10 +1,9 @@
1
- import { estimateValueTokens } from './contextBudget.js';
1
+ import { estimateValueTokens, SYNTHETIC_CONTROL_MARKER } from './contextBudget.js';
2
2
  import { isFailedToolOutput } from './toolResults.js';
3
- const SYNTHETIC_CONTROL_OPEN = '<haze_control>';
4
3
  function isSyntheticControlMessage(message) {
5
4
  return message.role === 'user'
6
5
  && typeof message.content === 'string'
7
- && message.content.startsWith(SYNTHETIC_CONTROL_OPEN);
6
+ && message.content.startsWith(SYNTHETIC_CONTROL_MARKER);
8
7
  }
9
8
  export function stripSyntheticControls(messages) {
10
9
  return messages.filter(message => !isSyntheticControlMessage(message));
@@ -22,11 +21,20 @@ function modelMessageTextForContext(message) {
22
21
  return JSON.stringify(content);
23
22
  return content.map(part => typeof part === 'object' && part != null && 'text' in part && typeof part.text === 'string' ? part.text : JSON.stringify(part)).join('\n');
24
23
  }
24
+ function syntheticControlMessage(control) {
25
+ return { role: 'user', content: `${SYNTHETIC_CONTROL_MARKER}\n${control}\n</haze_control>` };
26
+ }
25
27
  export function withSyntheticControl(messages, control) {
26
- return [
27
- ...stripSyntheticControls(messages),
28
- { role: 'user', content: `${SYNTHETIC_CONTROL_OPEN}\n${control}\n</haze_control>` },
29
- ];
28
+ return [...stripSyntheticControls(messages), syntheticControlMessage(control)];
29
+ }
30
+ /**
31
+ * Append a per-step control without rewriting an already-sent provider prefix.
32
+ * Active/session conversation state still removes every tagged control through
33
+ * `stripSyntheticControls`; this variant exists only for an in-flight logical
34
+ * turn whose next provider request should remain cache-prefix compatible.
35
+ */
36
+ export function appendSyntheticControl(messages, control) {
37
+ return [...messages, syntheticControlMessage(control)];
30
38
  }
31
39
  /** Drop only a trailing text-only assistant final that completion policy rejected. */
32
40
  export function withoutRejectedAssistantFinal(messages) {
@@ -11,7 +11,7 @@
11
11
  * Kept provider/UI-agnostic (no `ai`/Ink imports) so it is unit-testable in
12
12
  * `tests/core/**` and reusable by the subagent flow.
13
13
  */
14
- export type ToolCapability = 'discovery' | 'read' | 'mutate' | 'validate' | 'process' | 'coordinate';
14
+ export type ToolCapability = 'discovery' | 'read' | 'mutate' | 'process' | 'coordinate';
15
15
  /**
16
16
  * Capability set for a built-in tool name. Unknown/third-party tool names
17
17
  * (MCP) return an empty set: their effects are not statically knowable, so
@@ -21,7 +21,7 @@ export declare function toolCapability(name: string): readonly ToolCapability[];
21
21
  export declare function hasCapability(name: string, capability: ToolCapability): boolean;
22
22
  /** Tools whose successful call introduces a workspace mutation. */
23
23
  export declare function isMutatingCapability(name: string): boolean;
24
+ /** Confirmed effects, including completed writes from failed multi-file/worker calls. */
25
+ export declare function changedPathsFromTool(toolName: string, input: unknown, output: unknown, success?: boolean): string[];
24
26
  /** Tools that can act as a validation step (runtime-classifier dependent). */
25
27
  export declare function isValidationCapable(name: string): boolean;
26
- /** Read/discovery-only built-in tools (no mutation side effects). */
27
- export declare function isReadOrDiscoveryCapability(name: string): boolean;
@@ -22,6 +22,9 @@ const CAPABILITY_MAP = {
22
22
  writeFile: ['mutate'],
23
23
  editFile: ['mutate'],
24
24
  replaceLines: ['mutate'],
25
+ replaceInFiles: ['mutate'],
26
+ lspRenameSymbol: ['mutate'],
27
+ lspSafeDeleteSymbol: ['mutate'],
25
28
  // Process execution. A shell call becomes validation only when its command is
26
29
  // a classifier-confirmed validation command (see work state); that runtime
27
30
  // fact is tracked separately as a validation event, not as a static trait.
@@ -30,7 +33,6 @@ const CAPABILITY_MAP = {
30
33
  // Coordination / durable state.
31
34
  writeTasks: ['coordinate'],
32
35
  subagent: ['coordinate'],
33
- // LSP diagnostic reads.
34
36
  };
35
37
  /**
36
38
  * Capability set for a built-in tool name. Unknown/third-party tool names
@@ -47,12 +49,34 @@ export function hasCapability(name, capability) {
47
49
  export function isMutatingCapability(name) {
48
50
  return hasCapability(name, 'mutate');
49
51
  }
52
+ /** Confirmed effects, including completed writes from failed multi-file/worker calls. */
53
+ export function changedPathsFromTool(toolName, input, output, success = true) {
54
+ if (output !== undefined && output !== null && typeof output !== 'object')
55
+ return [];
56
+ const result = (output ?? {});
57
+ if (result.duplicateSkipped === true || result.dryRun === true || result.noChange === true)
58
+ return [];
59
+ const strings = (value) => Array.isArray(value) ? value.filter((path) => typeof path === 'string' && path.length > 0).slice(0, 20_000) : [];
60
+ if (toolName === 'subagent') {
61
+ const capsule = typeof result.capsule === 'object' && result.capsule !== null ? result.capsule : result;
62
+ return [...new Set(strings(capsule.changedPaths))];
63
+ }
64
+ if (!isMutatingCapability(toolName))
65
+ return [];
66
+ if (Array.isArray(result.changedPaths))
67
+ return [...new Set(strings(result.changedPaths))];
68
+ if (result.ok === false || !success)
69
+ return [];
70
+ if (Array.isArray(result.files))
71
+ return [...new Set(result.files.flatMap(file => typeof file === 'object' && file !== null && 'path' in file && typeof file.path === 'string' && !('noChange' in file && file.noChange === true) ? [file.path] : []))];
72
+ // Single-file tools confirm their effect from success plus the input path;
73
+ // a null output is tolerated for callers that report only a success flag.
74
+ if (!['writeFile', 'editFile', 'replaceLines'].includes(toolName))
75
+ return [];
76
+ const path = typeof result.path === 'string' ? result.path : typeof input === 'object' && input !== null && 'path' in input ? input.path : undefined;
77
+ return typeof path === 'string' && path.length > 0 ? [path] : [];
78
+ }
50
79
  /** Tools that can act as a validation step (runtime-classifier dependent). */
51
80
  export function isValidationCapable(name) {
52
- return hasCapability(name, 'validate') || name === 'shell';
53
- }
54
- /** Read/discovery-only built-in tools (no mutation side effects). */
55
- export function isReadOrDiscoveryCapability(name) {
56
- const caps = toolCapability(name);
57
- return caps.length > 0 && caps.every(capability => capability === 'read' || capability === 'discovery');
81
+ return name === 'shell';
58
82
  }
@@ -18,7 +18,8 @@ export declare function intentExpectsValidation(intent: RequestIntent): boolean;
18
18
  /**
19
19
  * Normalize a validation command into a matching key so a green run can be
20
20
  * bound to the red repro it must supersede (P4). Whitespace-insensitive; a
21
- * leading `time`/`env`/`nice` prefix and a trailing `--` separator are noise.
21
+ * leading `time`/`nice` prefix, `env` with or without `VAR=value` assignments,
22
+ * a lone line-continuation backslash, and a trailing `--` separator are noise.
22
23
  */
23
24
  export declare function validationCommandKey(command: string): string;
24
25
  /**
@@ -76,7 +77,9 @@ export interface WorkState {
76
77
  * logical goal (see the goal supervisor). Used by `deriveValidationOutcome`
77
78
  * only while this turn itself has recorded no validation; a fresh
78
79
  * validation this turn supersedes it. Bounded to status/kind — never a
79
- * command or output.
80
+ * command or output. `kind` keeps cross-turn parity with the in-turn rule
81
+ * that a generic (self-declared) pass cannot clear a confirmed failure
82
+ * (R2-03).
80
83
  */
81
84
  carriedValidation?: {
82
85
  status: 'passed' | 'failed';
@@ -113,6 +116,7 @@ export declare function seedCarriedGoalEvidence(state: WorkState, carried: {
113
116
  validationOutcome: ValidationOutcome;
114
117
  taskProgress?: WorkTaskProgress;
115
118
  redEvidence?: RedEvidence;
119
+ validationKind?: ValidationKind;
116
120
  }): void;
117
121
  export interface WorkToolEvent {
118
122
  toolName: string;
@@ -121,8 +125,6 @@ export interface WorkToolEvent {
121
125
  output?: unknown;
122
126
  duplicateSkipped?: boolean;
123
127
  }
124
- /** Strictly recognize direct execution of one file changed during this goal. */
125
- export declare function executedMutatedArtifact(command: string, state: WorkState): string | undefined;
126
128
  /** Extract a classifier-confirmed validation summary from a tool output, if any. */
127
129
  export declare function validationSummaryFromOutput(output: unknown): ValidationSummary | undefined;
128
130
  export declare function createWorkState(goal: string, intent: RequestIntent, successCriteria: string[], now?: number): WorkState;
@@ -1,6 +1,8 @@
1
1
  import { isValidationSummary } from '../../llm/toolResultTypes.js';
2
2
  import { toolInputField, toolOutputOk } from './toolResults.js';
3
3
  import { workspacePathKey } from '../../utils/path.js';
4
+ import { isSingleForegroundCommand } from '../safety/shellClassifier.js';
5
+ import { changedPathsFromTool } from './toolCapabilities.js';
4
6
  /** Request intents where a missing validation is itself meaningful evidence. */
5
7
  export function intentExpectsValidation(intent) {
6
8
  return intent === 'implement' || intent === 'fix' || intent === 'test';
@@ -8,12 +10,24 @@ export function intentExpectsValidation(intent) {
8
10
  /**
9
11
  * Normalize a validation command into a matching key so a green run can be
10
12
  * bound to the red repro it must supersede (P4). Whitespace-insensitive; a
11
- * leading `time`/`env`/`nice` prefix and a trailing `--` separator are noise.
13
+ * leading `time`/`nice` prefix, `env` with or without `VAR=value` assignments,
14
+ * a lone line-continuation backslash, and a trailing `--` separator are noise.
12
15
  */
13
16
  export function validationCommandKey(command) {
14
17
  const words = command.replace(/\s+/g, ' ').trim().split(' ').filter(Boolean);
15
- while (words.length > 1 && ['time', 'env', 'nice', '\\'].includes(words[0]))
18
+ while (words.length > 1 && ['time', 'nice', '\\'].includes(words[0]))
16
19
  words.shift();
20
+ // `env` — bare, with flags, or with `VAR=value` assignments — is wrapper
21
+ // noise for pair matching (R2-06): drop it together with any flag tokens
22
+ // and assignments, keeping at least the command word. `env` is handled here
23
+ // only (not in the loop above) so its assignments are stripped too.
24
+ if (words[0] === 'env') {
25
+ let i = 1;
26
+ while (i < words.length && (words[i].startsWith('-') || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i])))
27
+ i++;
28
+ if (i < words.length)
29
+ words.splice(0, i);
30
+ }
17
31
  while (words.length > 1 && words.at(-1) === '--')
18
32
  words.pop();
19
33
  return words.join(' ');
@@ -45,7 +59,9 @@ export function seedCarriedGoalEvidence(state, carried) {
45
59
  }
46
60
  if (carried.validationOutcome === 'passed' || carried.validationOutcome === 'failed') {
47
61
  state.validationSeq = 1;
48
- state.carriedValidation = carried.validationOutcome === 'passed' ? { status: 'passed' } : { status: 'failed' };
62
+ state.carriedValidation = carried.validationOutcome === 'passed'
63
+ ? { status: 'passed', ...(carried.validationKind ? { kind: carried.validationKind } : {}) }
64
+ : { status: 'failed', ...(carried.validationKind ? { kind: carried.validationKind } : {}) };
49
65
  }
50
66
  // Red→green evidence is goal-scoped and rides the checkpoint across
51
67
  // physical turns so a continuation cannot complete while a carried pair
@@ -80,16 +96,11 @@ function outputSummary(output) {
80
96
  return '';
81
97
  }
82
98
  function upsertValidation(state, command, status, summary, kind, revision) {
83
- const existing = state.validations.find(validation => validation.command === command);
84
- if (existing)
85
- Object.assign(existing, { status, summary, revision, ...(kind ? { kind } : {}) });
86
- else
87
- state.validations.push({ command, status, summary, revision, ...(kind ? { kind } : {}) });
88
- const existingCommand = state.validationCommands.find(item => item.command === command);
89
- if (existingCommand)
90
- existingCommand.status = status;
91
- else
92
- state.validationCommands.push({ command, status });
99
+ // Keep both evidence and status display in execution order when a check reruns.
100
+ state.validations = state.validations.filter(validation => validation.command !== command);
101
+ state.validations.push({ command, status, summary, revision, ...(kind ? { kind } : {}) });
102
+ state.validationCommands = state.validationCommands.filter(item => item.command !== command);
103
+ state.validationCommands.push({ command, status });
93
104
  }
94
105
  const ARTIFACT_LAUNCHERS = new Set(['node', 'python', 'python3', 'ruby', 'php', 'perl', 'sh', 'bash', 'zsh', 'fish', 'csh', 'tcsh', 'tsx', 'ts-node', 'rscript', 'lua']);
95
106
  function shellWords(command) {
@@ -97,9 +108,9 @@ function shellWords(command) {
97
108
  .map(word => ((word.startsWith('"') && word.endsWith('"')) || (word.startsWith("'") && word.endsWith("'")) ? word.slice(1, -1) : word));
98
109
  }
99
110
  /** Strictly recognize direct execution of one file changed during this goal. */
100
- export function executedMutatedArtifact(command, state) {
111
+ function executedMutatedArtifact(command, state) {
101
112
  // Chaining and pipelines can mask the artifact's exit status, so they are not evidence.
102
- if (/&&|\|\||[;|]/.test(command))
113
+ if (!isSingleForegroundCommand(command))
103
114
  return undefined;
104
115
  const words = shellWords(command.trim());
105
116
  if (words.length === 0)
@@ -188,19 +199,20 @@ export function observeWorkToolEvent(state, event, now = Date.now()) {
188
199
  state.phase = 'inspecting';
189
200
  state.lastProgressAt = now;
190
201
  }
191
- if (path && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolName)) {
192
- if (ok) {
193
- upsertFile(state, path, event.toolName === 'writeFile' ? 'created' : 'modified');
194
- state.phase = 'editing';
195
- state.lastProgressAt = now;
196
- state.blockers = state.blockers.filter(blocker => !blocker.includes(path));
197
- state.mutationCount += 1;
198
- state.mutationSeq = seq;
199
- }
200
- else {
201
- state.blockers = [...new Set([...state.blockers, `Edit failed for ${path}: ${outputSummary(event.output) || 'fresh read required'}`])];
202
- state.nextAction = `Read ${path}, then retry the edit with current content.`;
203
- }
202
+ const changedPaths = changedPathsFromTool(event.toolName, event.input, event.output, event.success);
203
+ for (const changedPath of changedPaths) {
204
+ upsertFile(state, changedPath, event.toolName === 'writeFile' ? 'created' : 'modified');
205
+ state.blockers = state.blockers.filter(blocker => !blocker.includes(changedPath));
206
+ }
207
+ if (changedPaths.length > 0) {
208
+ state.phase = 'editing';
209
+ state.lastProgressAt = now;
210
+ state.mutationCount += changedPaths.length;
211
+ state.mutationSeq = seq;
212
+ }
213
+ if (!ok && path && ['editFile', 'replaceLines', 'writeFile'].includes(event.toolName)) {
214
+ state.blockers = [...new Set([...state.blockers, `Edit failed for ${path}: ${outputSummary(event.output) || 'fresh read required'}`])];
215
+ state.nextAction = `Read ${path}, then retry the edit with current content.`;
204
216
  }
205
217
  // Classifier-confirmed test/build commands are validation. A direct execution
206
218
  // of a file changed during this goal is also bounded runtime evidence, provided
@@ -291,7 +303,19 @@ export function deriveValidationOutcome(state) {
291
303
  if (stale)
292
304
  return 'stale';
293
305
  const latest = state.validations.at(-1) ?? state.carriedValidation;
294
- return latest?.status === 'passed' ? 'passed' : 'failed';
306
+ if (latest?.status !== 'passed')
307
+ return 'failed';
308
+ // A self-declared custom check (generic kind, `purpose=validation`) cannot
309
+ // clear a failed classifier-confirmed validation: known test/build commands
310
+ // are the authoritative completion evidence, custom checks supplement them
311
+ // (found by the honest-impossibility eval — a model ran `npm test` red, then
312
+ // passed an unrelated self-written script and claimed completion). A failed
313
+ // validation carried from a goal checkpoint counts as confirmed too.
314
+ const confirmedFailed = state.validations.some(entry => entry.kind !== 'generic' && entry.status === 'failed')
315
+ || (state.carriedValidation?.status === 'failed' && state.carriedValidation.kind !== 'generic');
316
+ if (latest.kind === 'generic' && confirmedFailed)
317
+ return 'failed';
318
+ return 'passed';
295
319
  }
296
320
  export function workStatePrompt(state) {
297
321
  return `<work_state>\n${JSON.stringify(state)}\n</work_state>`;
@@ -24,37 +24,41 @@ export function withToolDeadline(execute, timeoutMs, signal) {
24
24
  settled = true;
25
25
  if (handle.timer)
26
26
  clearTimeout(handle.timer);
27
+ signal?.removeEventListener('abort', onAbort);
27
28
  action();
28
29
  };
29
- const quarantineLate = () => {
30
- // Swallow the eventual resolution/rejection of an abort-ignoring tool so
31
- // it cannot surface as an unhandled rejection after the wrapper returned.
32
- work.catch(() => undefined);
33
- };
34
30
  const fire = (message) => settle(() => {
35
- quarantineLate();
36
31
  resolve({ ok: false, [TOOL_DEADLINE_EXCEEDED]: true, error: message });
37
32
  });
38
- const work = execute();
33
+ const onAbort = () => fire('Tool execution was aborted.');
34
+ if (signal?.aborted)
35
+ return onAbort();
36
+ signal?.addEventListener('abort', onAbort, { once: true });
39
37
  handle.timer = setTimeout(() => fire(`Tool execution exceeded the ${timeoutMs}ms deadline.`), timeoutMs);
40
- if (signal) {
41
- if (signal.aborted)
42
- return fire('Tool execution was aborted.');
43
- signal.addEventListener('abort', () => fire('Tool execution was aborted.'), { once: true });
38
+ // Attach both handlers even when cancellation wins; late rejection is handled.
39
+ try {
40
+ execute().then(value => settle(() => resolve(value)), error => settle(() => reject(error)));
41
+ }
42
+ catch (error) {
43
+ settle(() => reject(error));
44
44
  }
45
- work.then(value => settle(() => resolve(value)), error => settle(() => reject(error)));
46
45
  });
47
46
  }
48
47
  export function createAbsoluteDeadline(input) {
49
48
  const { timeoutMs, signal, onTimeout } = input;
50
- let fired = false;
49
+ let disposed = false;
51
50
  let timer;
52
- const fire = () => {
53
- if (fired)
54
- return;
55
- fired = true;
51
+ const clear = () => {
52
+ disposed = true;
56
53
  if (timer)
57
54
  clearTimeout(timer);
55
+ timer = undefined;
56
+ signal?.removeEventListener('abort', fire);
57
+ };
58
+ const fire = () => {
59
+ if (disposed)
60
+ return;
61
+ clear();
58
62
  onTimeout();
59
63
  };
60
64
  timer = setTimeout(fire, timeoutMs);
@@ -64,11 +68,5 @@ export function createAbsoluteDeadline(input) {
64
68
  else
65
69
  signal.addEventListener('abort', fire, { once: true });
66
70
  }
67
- return {
68
- clear: () => {
69
- if (timer)
70
- clearTimeout(timer);
71
- timer = undefined;
72
- },
73
- };
71
+ return { clear };
74
72
  }
@@ -105,11 +105,14 @@ export function isProtectedSecretPath(candidatePath, homeDir = os.homedir()) {
105
105
  * remain readable through targeted `readFile` calls.
106
106
  */
107
107
  export function secretSearchExcludeGlobs() {
108
- return [
109
- '!.env', '!.env.*', '!.envrc', '!.envrc.*',
110
- '!id_rsa*', '!id_dsa*', '!id_ecdsa*', '!id_ed25519*',
111
- '!*.pem', '!*.key',
112
- ...[...SHELL_HISTORY_BASENAMES].map(name => `!${name}`),
113
- '!secrets.json', '!secrets.yaml', '!secrets.yml', '!secrets.toml',
114
- ];
108
+ // Search conservatively excludes home-store names wherever encountered.
109
+ // Negated-only globs cannot express an exception without widening traversal.
110
+ return [...new Set([
111
+ ...ENV_STEMS.flatMap(stem => [`!${stem}`, `!${stem}.*`]),
112
+ ...SSH_KEY_STEMS.map(stem => `!${stem}*`),
113
+ ...PROTECTED_EXTENSIONS.map(extension => `!*${extension}`),
114
+ ...[...PROTECTED_BASENAMES].map(name => `!${name}`),
115
+ ...PROTECTED_HOME_DIRS.flatMap(directory => [`!**/${directory}`, `!**/${directory}/**`]),
116
+ ...PROTECTED_HOME_FILES.map(file => `!**/${file}`),
117
+ ])];
115
118
  }
@@ -8,4 +8,22 @@ export type ShellClassification = {
8
8
  };
9
9
  export declare function classifyShellCommand(command: string): ShellClassification;
10
10
  export declare function isValidationClassification(classification: ShellClassification): boolean;
11
+ /**
12
+ * Approximate quoted-span removal ('…', "…", `…`). Used to keep command-shape
13
+ * heuristics (validation kind, exit masking) from firing on text the model
14
+ * authored inside quoted payloads. False positives only make decisions more
15
+ * conservative, never the reverse.
16
+ */
17
+ export declare function stripQuotedSpans(command: string): string;
18
+ /**
19
+ * Whether a command's final exit status can mask an earlier failing stage.
20
+ * POSIX list operators `;`, `||`, and single `&` end a list with the *last*
21
+ * command's status, so `npm test > out.txt; cat out.txt` exits 0 even when
22
+ * the suite failed (found by the honest-impossibility eval). Redirections
23
+ * (`2>&1`, `&>`, `<&`) are not list operators and are excluded. Pipelines are
24
+ * covered separately by `pipefail`; `&&` propagates failures.
25
+ */
26
+ /** Conservative output/exit ownership check, not a shell parser or execution gate. */
27
+ export declare function isSingleForegroundCommand(command: string): boolean;
28
+ export declare function commandMasksValidationExit(command: string): boolean;
11
29
  export {};
@@ -81,3 +81,42 @@ export function classifyShellCommand(command) {
81
81
  export function isValidationClassification(classification) {
82
82
  return classification.traits.includes('runs_tests') || classification.traits.includes('runs_build');
83
83
  }
84
+ /**
85
+ * Approximate quoted-span removal ('…', "…", `…`). Used to keep command-shape
86
+ * heuristics (validation kind, exit masking) from firing on text the model
87
+ * authored inside quoted payloads. False positives only make decisions more
88
+ * conservative, never the reverse.
89
+ */
90
+ export function stripQuotedSpans(command) {
91
+ return command
92
+ .replace(/'[^']*'/g, ' ')
93
+ .replace(/"[^"]*"/g, ' ')
94
+ .replace(/`[^`]*`/g, ' ');
95
+ }
96
+ /**
97
+ * Whether a command's final exit status can mask an earlier failing stage.
98
+ * POSIX list operators `;`, `||`, and single `&` end a list with the *last*
99
+ * command's status, so `npm test > out.txt; cat out.txt` exits 0 even when
100
+ * the suite failed (found by the honest-impossibility eval). Redirections
101
+ * (`2>&1`, `&>`, `<&`) are not list operators and are excluded. Pipelines are
102
+ * covered separately by `pipefail`; `&&` propagates failures.
103
+ */
104
+ /** Conservative output/exit ownership check, not a shell parser or execution gate. */
105
+ export function isSingleForegroundCommand(command) {
106
+ // Expansions and escapes can change token boundaries; decline ambiguous shapes.
107
+ if (/[\\`$]/.test(command))
108
+ return false;
109
+ const shape = stripQuotedSpans(command);
110
+ return !commandMasksValidationExit(command) && !/[&|<>\r\n#(){}"']/.test(shape);
111
+ }
112
+ export function commandMasksValidationExit(command) {
113
+ const unquoted = stripQuotedSpans(command);
114
+ if (/[;\r\n]/.test(unquoted))
115
+ return true;
116
+ if (/(?<!\|)\|\|(?!\|)/.test(unquoted))
117
+ return true;
118
+ // Single `&` that is not part of `&&` and not a redirection (`>&`, `<&`, `&>`).
119
+ if (/(?<![<>&])&(?![&>])/.test(unquoted))
120
+ return true;
121
+ return false;
122
+ }
@@ -1,2 +1,4 @@
1
+ import type { ModelMessage } from 'ai';
1
2
  import type { SessionEntry } from './sessionStore.js';
3
+ export declare function repairRestoredConversation(messages: ModelMessage[]): ModelMessage[];
2
4
  export declare function prepareSessionEntryForWrite(entry: SessionEntry): SessionEntry | undefined;
@@ -37,6 +37,21 @@ function slimImageFilePart(part) {
37
37
  text: `[image omitted from session:${name} ${part.mediaType}, ${formatBytes(bytes)} — ask the user to re-attach it if needed]`,
38
38
  };
39
39
  }
40
+ function isRecord(value) {
41
+ return typeof value === 'object' && value != null && !Array.isArray(value);
42
+ }
43
+ /**
44
+ * Slim a tool-result output while preserving the AI SDK output envelope.
45
+ * Restored snapshots are re-sent to providers, and `modelMessageSchema` requires
46
+ * a tool-result output to be `{type: 'json'|'text'|... , value}`; a bare slim
47
+ * marker as the output made every resumed session fail with
48
+ * AI_InvalidPromptError (F-09 regression).
49
+ */
50
+ function slimToolResultOutput(output) {
51
+ if (!isRecord(output) || typeof output.type !== 'string' || !('value' in output))
52
+ return slimLargeValue(output);
53
+ return { ...output, value: slimLargeValue(output.value) };
54
+ }
40
55
  function slimUnknown(value, seen = new WeakSet()) {
41
56
  if (typeof value === 'string') {
42
57
  if (value.length <= LARGE_STRING_CHARS)
@@ -56,7 +71,7 @@ function slimUnknown(value, seen = new WeakSet()) {
56
71
  if (record.type === 'tool-result') {
57
72
  return {
58
73
  ...record,
59
- output: slimLargeValue(record.output),
74
+ output: slimToolResultOutput(record.output),
60
75
  result: slimLargeValue(record.result),
61
76
  };
62
77
  }
@@ -65,6 +80,40 @@ function slimUnknown(value, seen = new WeakSet()) {
65
80
  next[key] = slimUnknown(child, seen);
66
81
  return next;
67
82
  }
83
+ /**
84
+ * Restore-side repair (F-09): sessions written before the envelope fix store
85
+ * bare `{omitted, reason, originalBytes, preview}` slim markers as tool-result
86
+ * outputs. Re-sending those to a provider fails `modelMessageSchema`, so wrap
87
+ * each legacy marker back into the required `{type, value}` envelope. Already
88
+ * valid outputs pass through untouched.
89
+ */
90
+ function repairLegacySlimmedMessages(messages) {
91
+ let changed = false;
92
+ const repaired = messages.map(message => {
93
+ if (message.role !== 'tool' || !Array.isArray(message.content))
94
+ return message;
95
+ let messageChanged = false;
96
+ const content = message.content.map(part => {
97
+ if (!isRecord(part) || part.type !== 'tool-result')
98
+ return part;
99
+ if (!isLegacySlimMarker(part.output))
100
+ return part;
101
+ messageChanged = true;
102
+ return { ...part, output: { type: 'json', value: part.output } };
103
+ });
104
+ if (!messageChanged)
105
+ return message;
106
+ changed = true;
107
+ return { ...message, content: content };
108
+ });
109
+ return changed ? repaired : messages;
110
+ }
111
+ function isLegacySlimMarker(value) {
112
+ return isRecord(value) && value.omitted === true && value.reason === 'session_size_limit' && !('type' in value);
113
+ }
114
+ export function repairRestoredConversation(messages) {
115
+ return repairLegacySlimmedMessages(messages);
116
+ }
68
117
  function slimConversationSnapshot(messages) {
69
118
  return slimUnknown(messages);
70
119
  }