@orion-agents/orion-code 0.4.7 → 0.4.8

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 (36) hide show
  1. package/CHANGELOG.md +9 -1
  2. package/README.md +8 -9
  3. package/README.zh-CN.md +8 -8
  4. package/dist/acp/session-updates.js +1 -0
  5. package/dist/framework/query.d.ts +3 -7
  6. package/dist/framework/query.js +22 -74
  7. package/dist/framework/verification-command.d.ts +21 -0
  8. package/dist/framework/verification-command.js +53 -4
  9. package/dist/harness/context-harness.d.ts +3 -9
  10. package/dist/harness/context-harness.js +43 -163
  11. package/dist/harness/state.d.ts +3 -0
  12. package/dist/harness/state.js +37 -4
  13. package/dist/harness/task-checklist.d.ts +1 -1
  14. package/dist/harness/task-checklist.js +1 -1
  15. package/dist/harness/types.d.ts +1 -0
  16. package/dist/harness/verification.js +5 -4
  17. package/dist/runtime/agent-loop.js +6 -33
  18. package/dist/runtime/goal-lifecycle-v2.js +5 -0
  19. package/dist/runtime/goal-runtime-coordinator.js +6 -2
  20. package/dist/runtime/orion-runtime-v1.js +33 -6
  21. package/dist/runtime/product-orion-runtime.js +6 -2
  22. package/dist/runtime/step-snapshot.js +57 -10
  23. package/dist/runtime/task-context-recovery.js +7 -3
  24. package/dist/runtime/task-context-service.d.ts +2 -6
  25. package/dist/runtime/task-context-service.js +3 -12
  26. package/dist/runtime/thread-ui-adapter.js +13 -1
  27. package/dist/runtime/ui-events.d.ts +3 -0
  28. package/dist/runtime/verification-feedback.d.ts +4 -0
  29. package/dist/runtime/verification-feedback.js +61 -0
  30. package/dist/tools/bash_security.d.ts +1 -24
  31. package/dist/tools/bash_security.js +7 -124
  32. package/dist/tools/todo.js +9 -13
  33. package/dist/utils/shell-command.d.ts +29 -0
  34. package/dist/utils/shell-command.js +185 -0
  35. package/npm-shrinkwrap.json +2 -2
  36. package/package.json +1 -1
@@ -4,6 +4,7 @@ exports.OrionRuntimeV1 = exports.OrionRuntimeV1Error = void 0;
4
4
  exports.createOrionRuntimeV1 = createOrionRuntimeV1;
5
5
  const fs_1 = require("fs");
6
6
  const path_1 = require("path");
7
+ const state_1 = require("../harness/state");
7
8
  const paths_1 = require("../product/paths");
8
9
  const task_checklist_1 = require("../harness/task-checklist");
9
10
  const file_lock_1 = require("../services/file-lock");
@@ -541,12 +542,15 @@ class OrionRuntimeV1 {
541
542
  previousCommitDigest: () => latestTurnCommitProjection(eventStore)?.digest,
542
543
  enableTaskTodos: this.options.enableTaskTodos,
543
544
  resolveGoalTask: () => goal.state,
544
- loadBaseMessages: context => loadRuntimeBaseMessages(compactPersistence, this.options.loadBaseMessages?.(eventStore, context, prompts, {
545
- taskContext,
546
- goal,
547
- skills,
548
- mcp,
549
- })),
545
+ loadBaseMessages: async (context) => {
546
+ const history = await loadRuntimeBaseMessages(compactPersistence, this.options.loadBaseMessages?.(eventStore, context, prompts, {
547
+ taskContext,
548
+ goal,
549
+ skills,
550
+ mcp,
551
+ }));
552
+ return restoreLegacyHarnessHistory(history, eventStore);
553
+ },
550
554
  toolContext: () => this.options.toolContext,
551
555
  streamCallbacks: this.options.loop?.streamCallbacks,
552
556
  get loopBudget() {
@@ -1050,6 +1054,29 @@ function parseModelVisibleHistory(history) {
1050
1054
  }
1051
1055
  return history.map(message => ({ ...message }));
1052
1056
  }
1057
+ function restoreLegacyHarnessHistory(history, store) {
1058
+ if (!history.some(message => message.role === 'user' &&
1059
+ ((0, state_1.isLegacyCompletionFeedback)(message) ||
1060
+ (0, state_1.withoutLegacyGoalGate)(message.content) !== undefined)))
1061
+ return history;
1062
+ const projection = store.loadProjection();
1063
+ const recordedInputs = new Set(Object.values(projection.items)
1064
+ .filter(item => item.role === 'user')
1065
+ .map(item => item.content));
1066
+ if (!recordedInputs.size)
1067
+ return history;
1068
+ const goalInputs = new Set(Object.values(projection.turns)
1069
+ .filter(turn => turn.mode === 'goal')
1070
+ .map(turn => turn.input));
1071
+ return history.flatMap(message => {
1072
+ if ((0, state_1.isLegacyCompletionFeedback)(message) && !recordedInputs.has(message.content))
1073
+ return [];
1074
+ const repaired = message.role === 'user' && goalInputs.has(message.content)
1075
+ ? (0, state_1.withoutLegacyGoalGate)(message.content)
1076
+ : undefined;
1077
+ return [repaired ? { ...message, content: repaired } : message];
1078
+ });
1079
+ }
1053
1080
  function isMessage(value) {
1054
1081
  if (!value || typeof value !== 'object')
1055
1082
  return false;
@@ -933,8 +933,12 @@ function createPlanStopDecision(commit, promptReceiptDigest) {
933
933
  progressDelta: structuredClone(completion.progressDelta),
934
934
  }
935
935
  : {}),
936
- ...(completion?.stopDecision?.evidenceRefs
937
- ? { evidenceRefs: [...completion.stopDecision.evidenceRefs] }
936
+ ...(completion?.criterionResults
937
+ ? {
938
+ evidenceRefs: [
939
+ ...new Set(completion.criterionResults.flatMap(result => result.evidenceRefs)),
940
+ ],
941
+ }
938
942
  : {}),
939
943
  resumable: false,
940
944
  });
@@ -9,6 +9,7 @@ const verification_command_1 = require("../framework/verification-command");
9
9
  const tool_artifacts_1 = require("../core/tool-artifacts");
10
10
  const canonical_1 = require("./protocol/canonical");
11
11
  const runtime_protocol_v1_1 = require("./protocol/runtime-protocol-v1");
12
+ const verification_feedback_1 = require("./verification-feedback");
12
13
  const EXECUTION_SERVICE_TOKEN = Symbol('orion.execution-service');
13
14
  class StepSnapshotValidationError extends Error {
14
15
  constructor(message) {
@@ -149,21 +150,67 @@ class ExecutionService {
149
150
  }, execute)
150
151
  : await execute();
151
152
  const presented = persistLargeToolOutput(request.context.cwd, request.toolName, result);
153
+ const terminal = timeoutController.signal.aborted
154
+ ? 'interrupted'
155
+ : presented.success
156
+ ? 'completed'
157
+ : 'failed';
158
+ const command = descriptor?.executorId === 'builtin:exec_command:v1' &&
159
+ typeof request.args.command === 'string'
160
+ ? request.args.command
161
+ : undefined;
162
+ const directKind = command ? (0, verification_command_1.classifyDirectVerificationCommand)(command) : undefined;
163
+ const verificationKind = directKind ??
164
+ (command && request.verificationCommand === command
165
+ ? (0, verification_command_1.classifyVerificationSelector)(command)
166
+ : undefined);
152
167
  // Capture the completed check's actual workspace, after any
153
168
  // test-generated files have been written and before committing its receipt.
154
- const verificationWorkspace = descriptor?.executorId === 'builtin:exec_command:v1' &&
155
- typeof request.args.command === 'string' &&
156
- ((0, verification_command_1.classifyDirectVerificationCommand)(request.args.command) ||
157
- request.verificationCommand === request.args.command)
169
+ const verificationWorkspace = verificationKind && terminal !== 'interrupted'
158
170
  ? this.captureVerificationWorkspace?.()
159
171
  : undefined;
172
+ let verification;
173
+ if (verificationKind) {
174
+ if (terminal === 'interrupted') {
175
+ verification = { kind: verificationKind, status: 'unverified', reason: 'interrupted' };
176
+ }
177
+ else if (terminal === 'failed' && !(0, verification_command_1.hasNonzeroShellExitCode)(presented.metadata)) {
178
+ verification = {
179
+ kind: verificationKind,
180
+ status: 'unverified',
181
+ reason: 'process_did_not_exit',
182
+ };
183
+ }
184
+ else if (verificationWorkspace === null ||
185
+ (!directKind && verificationWorkspace === undefined)) {
186
+ verification = {
187
+ kind: verificationKind,
188
+ status: 'unverified',
189
+ reason: 'workspace_unavailable',
190
+ };
191
+ }
192
+ else {
193
+ verification = {
194
+ kind: verificationKind,
195
+ status: terminal === 'completed' ? 'passed' : 'failed',
196
+ };
197
+ }
198
+ }
199
+ else if (command && terminal !== 'interrupted') {
200
+ verification = (0, verification_feedback_1.describeCompoundVerification)(command, request.args);
201
+ }
160
202
  return {
161
- terminal: timeoutController.signal.aborted
162
- ? 'interrupted'
163
- : presented.success
164
- ? 'completed'
165
- : 'failed',
166
- result: presented,
203
+ terminal,
204
+ result: verification
205
+ ? {
206
+ ...presented,
207
+ metadata: {
208
+ ...(terminal === 'completed' ? { exitCode: 0 } : {}),
209
+ ...presented.metadata,
210
+ verification,
211
+ },
212
+ }
213
+ : presented,
167
214
  durationMs: Date.now() - startedAt,
168
215
  ...(verificationWorkspace !== undefined ? { verificationWorkspace } : {}),
169
216
  };
@@ -83,7 +83,11 @@ function projectTaskToolEvidence(receipt, args, cwd) {
83
83
  typeof reportedWritePath === 'string'
84
84
  ? (0, verification_1.workspaceArtifactPath)(cwd, reportedWritePath)
85
85
  : undefined;
86
- const command = receipt.toolName === 'exec_command' && typeof args.command === 'string'
86
+ const command = receipt.toolName === 'exec_command' &&
87
+ (receipt.terminal === 'completed' ||
88
+ (receipt.terminal === 'failed' && (0, verification_command_1.hasNonzeroShellExitCode)(receipt.result.metadata))) &&
89
+ receipt.verificationWorkspace !== null &&
90
+ typeof args.command === 'string'
87
91
  ? args.command
88
92
  : undefined;
89
93
  const kind = command &&
@@ -95,13 +99,13 @@ function projectTaskToolEvidence(receipt, args, cwd) {
95
99
  toolReceiptDigest: receipt.digest,
96
100
  command,
97
101
  cwd: (0, path_1.resolve)(cwd, typeof args.cwd === 'string' ? (0, common_1.normalizeToolPath)(args.cwd) : '.'),
98
- passed: receipt.success && receipt.verificationWorkspace !== null,
102
+ passed: receipt.success,
99
103
  }
100
104
  : undefined;
101
105
  return { changedFile, verification };
102
106
  }
103
107
  function recordTaskTodoToolReceipt(taskContext, todo, receipt, { changedFile, verification }) {
104
- if (verification && receipt.verificationWorkspace !== undefined) {
108
+ if (receipt.verificationWorkspace !== undefined) {
105
109
  taskContext.observeVerificationWorkspace(receipt.verificationWorkspace);
106
110
  }
107
111
  if (!todo || receipt.terminalPhase !== 'execute' || (!receipt.success && !verification))
@@ -1,4 +1,3 @@
1
- import { HarnessKernel } from '../harness/context-harness';
2
1
  import type { PromptAssemblyOptions } from '../harness/assembler';
3
2
  import type { CreateTurnSummaryInput } from '../harness/turn-summary';
4
3
  import type { CapabilityProfileInput, CompletionGateResult, ContextCapsule, DriftCheckResult, HarnessConfig, HarnessProgressState, HarnessState, IntentUpdate, TaskContract, TaskTodoObservation, TaskWorkspaceAction, ToolResultObservation, TurnSummary } from '../harness/types';
@@ -57,7 +56,7 @@ export interface TaskContextExplanation {
57
56
  readonly turnSummaryCount: number;
58
57
  }
59
58
  /**
60
- * The sole in-memory owner of task contract, evidence, progress and completion semantics.
59
+ * The in-memory owner of the task contract, progress and verification evidence.
61
60
  * Persistence and Goal lifecycle deliberately remain outside this contract.
62
61
  */
63
62
  export interface TaskContextService {
@@ -78,15 +77,12 @@ export interface TaskContextService {
78
77
  observeTurn(input: TaskContextTurnInput): DeepReadonly<TurnSummary> | undefined;
79
78
  activeTaskTodo(): string | undefined;
80
79
  hasTaskTodos(): boolean;
81
- missingExecutionChecklist(action?: TaskWorkspaceAction): string | undefined;
82
- prepareTaskPlanStopCheck(): ReturnType<HarnessKernel['prepareTaskPlanStopCheck']>;
83
- requiresVerification(): boolean;
80
+ deferredWorkspaceWriteReason(action: TaskWorkspaceAction): string | undefined;
84
81
  recordTaskTodoReceipt(step: string, observation: TaskTodoObservation): void;
85
82
  updateTaskTodos(todos: NonNullable<HarnessState['taskTodos']>, blockedReason?: string): TodoWriteAdjustment | string | undefined;
86
83
  progressState(): HarnessProgressState;
87
84
  recordProgress(baseline: HarnessProgressState, unconfirmedWorkspaceRevisions?: number): void;
88
85
  auditCompletion(enforceTaskTodos?: boolean, requireEveryCriterion?: boolean): TaskContextCompletionDecisionV1;
89
- completionBlockedMessage(result: CompletionGateResult): Message;
90
86
  toolBlockedResult(result: DriftCheckResult): string;
91
87
  linkEvidence(criterionId: string, evidenceRef: string): boolean;
92
88
  authorizeCriterionWaiver(criterionId: string, waiver: TaskContextCriterionWaiver): boolean;
@@ -30,7 +30,7 @@ class HarnessKernelTaskContextService {
30
30
  cwd: this.options.cwd,
31
31
  modelId: this.options.modelId,
32
32
  state: state ? structuredClone(state) : undefined,
33
- config: { completionGate: 'block', ...this.options.config },
33
+ config: this.options.config,
34
34
  requireLocalVerificationReceipt: this.options.requireLocalVerificationReceipt,
35
35
  });
36
36
  }
@@ -87,14 +87,8 @@ class HarnessKernelTaskContextService {
87
87
  hasTaskTodos() {
88
88
  return this.kernel.hasTaskTodos();
89
89
  }
90
- missingExecutionChecklist(action) {
91
- return this.kernel.missingExecutionChecklist(action);
92
- }
93
- prepareTaskPlanStopCheck() {
94
- return this.kernel.prepareTaskPlanStopCheck();
95
- }
96
- requiresVerification() {
97
- return this.kernel.requiresVerification();
90
+ deferredWorkspaceWriteReason(action) {
91
+ return this.kernel.deferredWorkspaceWriteReason(action);
98
92
  }
99
93
  recordTaskTodoReceipt(step, observation) {
100
94
  this.mutate(() => this.kernel.recordTaskTodoReceipt(step, observation));
@@ -120,9 +114,6 @@ class HarnessKernelTaskContextService {
120
114
  auditedAt: Date.now(),
121
115
  });
122
116
  }
123
- completionBlockedMessage(result) {
124
- return this.kernel.asCompletionBlockedMessage(result);
125
- }
126
117
  toolBlockedResult(result) {
127
118
  return this.kernel.asToolBlockedResult(result);
128
119
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ThreadUiAdmissionError = exports.ThreadUiAdapterError = exports.ThreadUiAdapterV1 = exports.THREAD_UI_ADAPTER_VERSION = void 0;
4
+ const verification_command_1 = require("../framework/verification-command");
4
5
  const agent_runtime_protocol_1 = require("./agent-runtime-protocol");
5
6
  const goal_runtime_coordinator_1 = require("./goal-runtime-coordinator");
6
7
  const runtime_protocol_v1_1 = require("./protocol/runtime-protocol-v1");
@@ -457,6 +458,12 @@ class ThreadUiAdapterV1 {
457
458
  }
458
459
  this.toolReceiptFacts.delete(presentation.itemId);
459
460
  const success = receipt?.success ?? event.payload.type === 'item.completed';
461
+ const verification = receipt?.toolName === 'exec_command'
462
+ ? (0, verification_command_1.verificationToolStatus)(receipt.result.metadata?.verification)
463
+ : undefined;
464
+ const verificationNote = verification?.status === 'unverified'
465
+ ? `Verification unavailable (${verification.reason?.replace(/_/gu, ' ') ?? 'missing evidence'}).`
466
+ : undefined;
460
467
  this.emit({
461
468
  type: 'tool_finished',
462
469
  event: {
@@ -469,6 +476,7 @@ class ThreadUiAdapterV1 {
469
476
  sequence: presentation.sequence,
470
477
  ...(terminal.summary ? { summary: terminal.summary } : {}),
471
478
  ...(terminal.error ? { error: terminal.error } : {}),
479
+ ...(verification ? { verification } : {}),
472
480
  ...(presentation.content
473
481
  ? { outputBytes: Buffer.byteLength(presentation.content, 'utf8') }
474
482
  : {}),
@@ -490,7 +498,11 @@ class ThreadUiAdapterV1 {
490
498
  name: presentation.name,
491
499
  success,
492
500
  command: presentation.command,
493
- output: presentation.content || terminal.error,
501
+ output: verificationNote
502
+ ? [presentation.content || terminal.error, verificationNote]
503
+ .filter(Boolean)
504
+ .join('\n')
505
+ : presentation.content || terminal.error,
494
506
  }),
495
507
  live: false,
496
508
  },
@@ -14,6 +14,7 @@ import type { GoalRuntimeEvent } from './goals/types';
14
14
  import type { McpServerDescriptorInputV1 } from './mcp';
15
15
  import type { SkillDescriptorV1 } from './skills';
16
16
  import type { ToolExternalAssertion } from '../framework/external-assertion';
17
+ import type { VerificationToolStatus } from '../framework/verification-command';
17
18
  import type { EffortLevel, EffortPreference, EffortScope } from '../services/effort';
18
19
  import type { AgentRuntimeRunnerV1 } from './agent-runtime-runner';
19
20
  import type { FirstPartyApprovalHandlerV1 } from './first-party-tool-services';
@@ -213,6 +214,8 @@ export interface RuntimeToolFinishedEvent {
213
214
  };
214
215
  /** Runtime-produced external assertion; never inferred from display text. */
215
216
  externalAssertion?: ToolExternalAssertion;
217
+ /** Verification status from the validated command receipt. */
218
+ verification?: VerificationToolStatus;
216
219
  /** Authorization provenance carried to every renderer and protocol consumer. */
217
220
  authorization?: ToolAuthorizationView;
218
221
  /** Exact ExecutionPolicy digest embedded in the validated durable ToolInvocationReceipt. */
@@ -0,0 +1,4 @@
1
+ import { type VerificationToolFeedback } from '../framework/verification-command';
2
+ /** Describe an identifiable check whose Shell composition hides its individual exit status. */
3
+ export declare function describeCompoundVerification(command: string, args: Readonly<Record<string, unknown>>): VerificationToolFeedback | undefined;
4
+ //# sourceMappingURL=verification-feedback.d.ts.map
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.describeCompoundVerification = describeCompoundVerification;
4
+ const verification_command_1 = require("../framework/verification-command");
5
+ const redaction_1 = require("../services/redaction");
6
+ const shell_command_1 = require("../utils/shell-command");
7
+ const displayCommand = /^(?:head|tail)(?:[ \t]+-(?:[0-9]+|n[ \t]*[0-9]+))?$/u;
8
+ const retryOutputLimit = 4096;
9
+ /** Describe an identifiable check whose Shell composition hides its individual exit status. */
10
+ function describeCompoundVerification(command, args) {
11
+ if (!verification_command_1.SHELL_CONTROL_OPERATOR.test(command))
12
+ return;
13
+ const operators = [];
14
+ const scan = (0, shell_command_1.scanShellCommand)(command, operator => operators.push(operator));
15
+ if (!operators.length)
16
+ return;
17
+ const commands = scan.segments.map(segment => segment.replace(/[ \t]+2>&1$/u, ''));
18
+ const kind = commands.map(verification_command_1.identifyVerificationRunner).find(check => check !== undefined);
19
+ if (!kind)
20
+ return;
21
+ const pipe = operators.includes('|');
22
+ const retryCommand = scan.supported &&
23
+ !scan.writesFile &&
24
+ operators.length === 1 &&
25
+ operators[0] === '|' &&
26
+ commands.length === 2 &&
27
+ (0, verification_command_1.classifyDirectVerificationCommand)(commands[0]) === kind &&
28
+ displayCommand.test(commands[1]) &&
29
+ !scan.segments[0].includes('\\') &&
30
+ !/[<>&]/u.test(commands[0])
31
+ ? commands[0]
32
+ : undefined;
33
+ const cwd = typeof args.cwd === 'string' ? args.cwd : '.';
34
+ const maxOutput = typeof args.maxOutput === 'number' && args.maxOutput >= 1024
35
+ ? Math.min(args.maxOutput, retryOutputLimit)
36
+ : retryOutputLimit;
37
+ const retryArgs = retryCommand
38
+ ? {
39
+ command: retryCommand,
40
+ cwd,
41
+ maxOutput,
42
+ ...(typeof args.timeout === 'number' ? { timeout: args.timeout } : {}),
43
+ }
44
+ : undefined;
45
+ const retry = retryArgs &&
46
+ (0, redaction_1.redactTraceText)(retryArgs.command) === retryArgs.command &&
47
+ (0, redaction_1.redactTraceText)(cwd) === cwd &&
48
+ Buffer.byteLength(JSON.stringify(retryArgs), 'utf8') <= 768
49
+ ? { tool: 'exec_command', args: retryArgs }
50
+ : undefined;
51
+ return {
52
+ kind,
53
+ status: 'unverified',
54
+ reason: pipe ? 'shell_pipeline' : 'compound_shell',
55
+ message: pipe
56
+ ? 'The shell status can come from the final pipeline command. This execution supplied no verification receipt.'
57
+ : 'The compound shell status does not establish the individual check result. No verification receipt was recorded.',
58
+ ...(retry ? { retry } : {}),
59
+ };
60
+ }
61
+ //# sourceMappingURL=verification-feedback.js.map
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * Provides safety checks and sandbox options for command execution.
5
5
  */
6
+ export { scanShellCommand, type ShellCommandScan } from '../utils/shell-command';
6
7
  /**
7
8
  * Commands that are considered read-only and safe to execute without confirmation.
8
9
  * These commands only read data and do not modify the filesystem.
@@ -42,30 +43,6 @@ export declare const DANGEROUS_PATTERNS: {
42
43
  * Potentially destructive patterns that should ask for confirmation.
43
44
  */
44
45
  export declare const POTENTIALLY_DESTRUCTIVE_PATTERNS: RegExp[];
45
- /**
46
- * Result of a quote-aware scan over a whole command line.
47
- */
48
- export interface ShellCommandScan {
49
- /** The individual commands on the line, split on unquoted separators. */
50
- segments: string[];
51
- /**
52
- * False when the line uses a construct this scanner cannot reason about --
53
- * command substitution, process substitution or an unbalanced quote. Such a
54
- * line can hide an arbitrary command and must never be auto-approved.
55
- */
56
- supported: boolean;
57
- /** True when the line redirects output somewhere other than /dev/null. */
58
- writesFile: boolean;
59
- }
60
- /**
61
- * Split a command line into the individual commands it will actually run.
62
- *
63
- * The classifier below hands out "run without confirmation" verdicts, so it has
64
- * to see every command on the line rather than just the leading token. Quote
65
- * state is tracked so `echo "a && b"` stays one segment, and substitutions are
66
- * reported as unsupported instead of being silently skipped over.
67
- */
68
- export declare function scanShellCommand(cmd: string): ShellCommandScan;
69
46
  /**
70
47
  * Check if a command is read-only and safe to execute without confirmation.
71
48
  *
@@ -5,8 +5,7 @@
5
5
  * Provides safety checks and sandbox options for command execution.
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.POTENTIALLY_DESTRUCTIVE_PATTERNS = exports.DANGEROUS_PATTERNS = exports.VALIDATION_COMMAND_PATTERNS = exports.READ_ONLY_SUBCOMMANDS = exports.READ_ONLY_COMMANDS = void 0;
9
- exports.scanShellCommand = scanShellCommand;
8
+ exports.POTENTIALLY_DESTRUCTIVE_PATTERNS = exports.DANGEROUS_PATTERNS = exports.VALIDATION_COMMAND_PATTERNS = exports.READ_ONLY_SUBCOMMANDS = exports.READ_ONLY_COMMANDS = exports.scanShellCommand = void 0;
10
9
  exports.isReadOnlyCommand = isReadOnlyCommand;
11
10
  exports.isValidationCommand = isValidationCommand;
12
11
  exports.containsRecursiveRm = containsRecursiveRm;
@@ -15,6 +14,9 @@ exports.checkDangerousCommand = checkDangerousCommand;
15
14
  exports.isPotentiallyDestructive = isPotentiallyDestructive;
16
15
  exports.assessCommandSecurity = assessCommandSecurity;
17
16
  const path_1 = require("path");
17
+ const shell_command_1 = require("../utils/shell-command");
18
+ var shell_command_2 = require("../utils/shell-command");
19
+ Object.defineProperty(exports, "scanShellCommand", { enumerable: true, get: function () { return shell_command_2.scanShellCommand; } });
18
20
  /**
19
21
  * Commands that are considered read-only and safe to execute without confirmation.
20
22
  * These commands only read data and do not modify the filesystem.
@@ -251,125 +253,6 @@ exports.POTENTIALLY_DESTRUCTIVE_PATTERNS = [
251
253
  /curl.*>\s*\//,
252
254
  /wget.*-O\s*\//,
253
255
  ];
254
- /** The one redirect target that does not count as writing to the filesystem. */
255
- const DISCARD_REDIRECT_TARGET = '/dev/null';
256
- /**
257
- * Split a command line into the individual commands it will actually run.
258
- *
259
- * The classifier below hands out "run without confirmation" verdicts, so it has
260
- * to see every command on the line rather than just the leading token. Quote
261
- * state is tracked so `echo "a && b"` stays one segment, and substitutions are
262
- * reported as unsupported instead of being silently skipped over.
263
- */
264
- function scanShellCommand(cmd) {
265
- const segments = [];
266
- let current = '';
267
- let supported = true;
268
- let writesFile = false;
269
- let inSingleQuote = false;
270
- let inDoubleQuote = false;
271
- const pushSegment = () => {
272
- const segment = current.trim();
273
- if (segment.length > 0) {
274
- segments.push(segment);
275
- }
276
- current = '';
277
- };
278
- for (let i = 0; i < cmd.length; i++) {
279
- const ch = cmd[i];
280
- const next = cmd[i + 1];
281
- if (ch === '\\' && !inSingleQuote && next !== undefined) {
282
- current += ch + next;
283
- i++;
284
- continue;
285
- }
286
- if (ch === "'" && !inDoubleQuote) {
287
- inSingleQuote = !inSingleQuote;
288
- current += ch;
289
- continue;
290
- }
291
- if (ch === '"' && !inSingleQuote) {
292
- inDoubleQuote = !inDoubleQuote;
293
- current += ch;
294
- continue;
295
- }
296
- if (inSingleQuote) {
297
- // Single quotes disable every expansion, so the contents stay inert.
298
- current += ch;
299
- continue;
300
- }
301
- if (inDoubleQuote) {
302
- // Double quotes only suppress globbing and word splitting -- bash still
303
- // expands `$(...)` and backticks inside them. Skipping the substitution
304
- // check here made `echo "$(rm -rf $HOME)"` classify as safe/read-only and
305
- // auto-approve, i.e. a straight command-execution bypass.
306
- if (ch === '`' || (ch === '$' && next === '(')) {
307
- supported = false;
308
- }
309
- current += ch;
310
- continue;
311
- }
312
- // Command and process substitution can hide an arbitrary command inside an
313
- // otherwise innocent-looking line, and neither is worth modelling here.
314
- if (ch === '`' ||
315
- (ch === '$' && next === '(') ||
316
- ((ch === '<' || ch === '>') && next === '(')) {
317
- supported = false;
318
- current += ch;
319
- continue;
320
- }
321
- if (ch === ';' || ch === '\n') {
322
- pushSegment();
323
- continue;
324
- }
325
- if ((ch === '&' && next === '&') || (ch === '|' && next === '|')) {
326
- pushSegment();
327
- i++;
328
- continue;
329
- }
330
- if (ch === '&' || ch === '|') {
331
- pushSegment();
332
- continue;
333
- }
334
- if (ch === '>') {
335
- let cursor = i + 1;
336
- if (cmd[cursor] === '>') {
337
- cursor++;
338
- }
339
- if (cmd[cursor] === '&') {
340
- // `>&1` / `2>&1` duplicate a descriptor and `>&-` closes one; nothing
341
- // reaches the filesystem. Consume the whole reference so its `&` is not
342
- // mistaken for a background-job separator.
343
- let end = cursor + 1;
344
- while (end < cmd.length && cmd[end] >= '0' && cmd[end] <= '9') {
345
- end++;
346
- }
347
- if (cmd[end] === '-') {
348
- end++;
349
- }
350
- current += cmd.slice(i, end);
351
- i = end - 1;
352
- continue;
353
- }
354
- while (cursor < cmd.length && (cmd[cursor] === ' ' || cmd[cursor] === '\t')) {
355
- cursor++;
356
- }
357
- const target = cmd.slice(cursor).split(/[\s;&|<>]/)[0];
358
- if (target !== DISCARD_REDIRECT_TARGET) {
359
- writesFile = true;
360
- }
361
- current += ch;
362
- continue;
363
- }
364
- current += ch;
365
- }
366
- pushSegment();
367
- return {
368
- segments,
369
- supported: supported && !inSingleQuote && !inDoubleQuote,
370
- writesFile,
371
- };
372
- }
373
256
  /**
374
257
  * Require every command on the line to satisfy `predicate`.
375
258
  *
@@ -377,7 +260,7 @@ function scanShellCommand(cmd) {
377
260
  * is what stops `echo hi && rm -rf ~` from inheriting `echo`'s verdict.
378
261
  */
379
262
  function everySegmentSatisfies(cmd, predicate) {
380
- const scan = scanShellCommand(cmd.trim());
263
+ const scan = (0, shell_command_1.scanShellCommand)(cmd.trim());
381
264
  if (!scan.supported || scan.writesFile || scan.segments.length === 0) {
382
265
  return false;
383
266
  }
@@ -758,7 +641,7 @@ function parseRmInvocation(segment) {
758
641
  * misclassify recursive deletion as an ordinary state write.
759
642
  */
760
643
  function containsRecursiveRm(cmd) {
761
- const scan = scanShellCommand(cmd);
644
+ const scan = (0, shell_command_1.scanShellCommand)(cmd);
762
645
  if (!scan.supported) {
763
646
  // Unsupported substitutions remain non-read-only and therefore require an
764
647
  // explicit policy decision, but uncertainty alone is not proof that the
@@ -784,7 +667,7 @@ function containsRecursiveRm(cmd) {
784
667
  * on GNU coreutils.
785
668
  */
786
669
  function findDestructiveRmTarget(cmd) {
787
- for (const segment of scanShellCommand(cmd).segments) {
670
+ for (const segment of (0, shell_command_1.scanShellCommand)(cmd).segments) {
788
671
  const invocation = parseRmInvocation(segment);
789
672
  if (!invocation)
790
673
  continue;