File size: 9,715 Bytes
68d7816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/* oxlint-disable typescript-eslint/no-unsafe-declaration-merging, eslint-plugin-import/namespace -- Event2 class+payload-interface declaration merging is the sanctioned event-declaration idiom. */
import { LifecycleScope } from '#/app/scopes';

import { ScopeActivation, registerScopedService } from '#/_base/di/scope';
import { defineState } from '#/state/state';
import { userCancellationReason } from '#/_base/utils/abort';
import { escapeXml } from '#/_base/utils/xml-escape';
import { IAgentContextMemoryService } from '#/agent/contextMemory/contextMemory';
import type { PromptOrigin } from '#/agent/contextMemory/types';
import { IAgentLoopService } from '#/agent/loop/loop';
import { IAgentScopeContext } from '#/agent/scopeContext/scopeContext';
import { IAgentStateService } from '#/agent/state/agentState';
import type { ToolUpdate } from '#/tool/toolContract';
import { IAgentToolRegistryService } from '#/agent/toolRegistry/toolRegistry';
import { AgentEvent2 } from '#/app/event/event2';
import { ITelemetryService } from '#/app/telemetry/telemetry';
import { Error2, ErrorCodes } from '#/errors';
import { IEventDispatcher } from '#/state/eventDispatcher';

import {
  IAgentShellCommandService,
  type RunShellCommandInput,
  type RunShellCommandResult,
} from './shellCommand';

export interface ShellOutputPayload {
  readonly agentId: string;
  readonly commandId: string;
  readonly update: ToolUpdate;
  readonly taskId?: string;
}

export class ShellOutput extends AgentEvent2<ShellOutputPayload> {
  static override readonly type = 'shell.output';
  static override readonly observable = true;
}
export interface ShellOutput extends ShellOutputPayload {}

export interface ShellStartedPayload {
  readonly agentId: string;
  readonly commandId: string;
  readonly taskId: string;
}

export class ShellStarted extends AgentEvent2<ShellStartedPayload> {
  static override readonly type = 'shell.started';
  static override readonly observable = true;
}
export interface ShellStarted extends ShellStartedPayload {}

export interface ShellCompletedPayload {
  readonly agentId: string;
  readonly commandId: string;
  readonly isError: boolean;
  readonly taskId?: string;
}

export class ShellCompleted extends AgentEvent2<ShellCompletedPayload> {
  static override readonly type = 'shell.completed';
  static override readonly observable = true;
}
export interface ShellCompleted extends ShellCompletedPayload {}

const SHELL_FOREGROUND_TIMEOUT_S = 2 * 60;

export const shellCommandTasksKey = defineState<Map<string, string>>(
  'shellCommand.tasks',
  () => new Map(),
);

export class AgentShellCommandService implements IAgentShellCommandService {
  declare readonly _serviceBrand: undefined;
  private readonly shellCommandControllers = new Map<string, AbortController>();

  constructor(
    @IAgentToolRegistryService private readonly toolRegistry: IAgentToolRegistryService,
    @IAgentContextMemoryService private readonly context: IAgentContextMemoryService,
    @IAgentLoopService private readonly loop: IAgentLoopService,
    @IEventDispatcher private readonly dispatcher: IEventDispatcher,
    @IAgentScopeContext private readonly scopeContext: IAgentScopeContext,
    @IAgentStateService private readonly states: IAgentStateService,
    @ITelemetryService private readonly telemetry: ITelemetryService,
  ) {
    this.states.contributeState(shellCommandTasksKey);
  }

  private get shellCommandTasks(): Map<string, string> {
    return this.states.get(shellCommandTasksKey);
  }

  async run(input: RunShellCommandInput): Promise<RunShellCommandResult> {
    this.appendShellInput(input.command);

    const controller = new AbortController();
    if (input.commandId !== undefined) {
      this.shellCommandControllers.set(input.commandId, controller);
    }

    let stdout = '';
    let stderr = '';
    const startedAt = Date.now();
    let isError = false;
    let backgrounded = false;
    try {
      const bash = this.ensureBashTool();
      const execution = await bash.resolveExecution({
        command: input.command,
        timeout: SHELL_FOREGROUND_TIMEOUT_S,
      });
      if (execution.isError === true) {
        const output = typeof execution.output === 'string' ? execution.output : 'Command failed.';
        this.appendShellOutput('', output);
        isError = true;
        return { stdout: '', stderr: output, isError: true };
      }

      const result = await execution.execute({
        turnId: -1,
        toolCallId: 'shell-command',
        signal: controller.signal,
        onUpdate: (update: ToolUpdate) => {
          if (update.kind === 'stdout') stdout += update.text ?? '';
          else if (update.kind === 'stderr') stderr += update.text ?? '';
          else return;
          if (input.commandId !== undefined) {
            void this.dispatcher.dispatch(
              new ShellOutput({
                agentId: this.scopeContext.agentId,
                commandId: input.commandId,
                update,
                taskId: this.shellCommandTasks.get(input.commandId),
              }),
            );
          }
        },
        onForegroundTaskStart: (taskId: string) => {
          if (input.commandId !== undefined) {
            this.shellCommandTasks.set(input.commandId, taskId);
            void this.dispatcher.dispatch(
              new ShellStarted({
                agentId: this.scopeContext.agentId,
                commandId: input.commandId,
                taskId,
              }),
            );
          }
        },
      });

      isError = result.isError === true;
      if (typeof result.output === 'string' && result.output.startsWith('task_id: ')) {
        this.notifyBackgrounded(result.output);
        backgrounded = true;
        return { stdout: result.output, stderr: '', isError: false, backgrounded: true };
      }
      if (isError && stdout.length === 0 && stderr.length === 0) {
        stderr = typeof result.output === 'string' ? result.output : 'Command failed.';
        if (input.commandId !== undefined && stderr.length > 0) {
          void this.dispatcher.dispatch(
            new ShellOutput({
              agentId: this.scopeContext.agentId,
              commandId: input.commandId,
              update: { kind: 'stderr', text: stderr },
              taskId: this.shellCommandTasks.get(input.commandId),
            }),
          );
        }
      }
      if (input.commandId !== undefined) {
        void this.dispatcher.dispatch(
          new ShellCompleted({
            agentId: this.scopeContext.agentId,
            commandId: input.commandId,
            isError,
            taskId: this.shellCommandTasks.get(input.commandId),
          }),
        );
      }
      this.appendShellOutput(stdout, stderr, isError);
      return { stdout, stderr, isError };
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      stderr += message;
      isError = true;
      if (input.commandId !== undefined) {
        if (message.length > 0) {
          void this.dispatcher.dispatch(
            new ShellOutput({
              agentId: this.scopeContext.agentId,
              commandId: input.commandId,
              update: { kind: 'stderr', text: message },
              taskId: this.shellCommandTasks.get(input.commandId),
            }),
          );
        }
        void this.dispatcher.dispatch(
          new ShellCompleted({
            agentId: this.scopeContext.agentId,
            commandId: input.commandId,
            isError: true,
            taskId: this.shellCommandTasks.get(input.commandId),
          }),
        );
      }
      this.appendShellOutput(stdout, stderr, true);
      return { stdout, stderr, isError: true };
    } finally {
      if (input.commandId !== undefined) {
        this.shellCommandControllers.delete(input.commandId);
        this.shellCommandTasks.delete(input.commandId);
      }
      this.telemetry.track2('shell_command_finished', {
        duration_ms: Date.now() - startedAt,
        is_error: isError,
        backgrounded,
      });
    }
  }

  cancel(commandId: string): void {
    this.shellCommandControllers.get(commandId)?.abort(userCancellationReason());
  }

  private ensureBashTool() {
    const bash = this.toolRegistry.resolve('Bash');
    if (bash === undefined) {
      throw new Error2(ErrorCodes.INTERNAL, 'Bash tool is not registered.');
    }
    return bash;
  }

  private appendShellInput(command: string): void {
    const text = `<bash-input>\n${escapeXml(command)}\n</bash-input>`;
    this.context.append({
      role: 'user',
      content: [{ type: 'text', text }],
      toolCalls: [],
      origin: { kind: 'shell_command', phase: 'input' },
    });
  }

  private appendShellOutput(stdout: string, stderr: string, isError?: boolean): void {
    const text = `<bash-stdout>${escapeXml(stdout)}</bash-stdout><bash-stderr>${escapeXml(stderr)}</bash-stderr>`;
    this.context.append({
      role: 'user',
      content: [{ type: 'text', text }],
      toolCalls: [],
      origin:
        isError === true
          ? { kind: 'shell_command', phase: 'output', isError: true }
          : { kind: 'shell_command', phase: 'output' },
    });
  }

  private notifyBackgrounded(output: string): void {
    this.loop.submit(
      {
        message: { role: 'user', content: [{ type: 'text', text: output }] },
        meta: { origin: { kind: 'injection', variant: 'shell_command_backgrounded' } as PromptOrigin },
      },
      { steerIfActive: true },
    );
  }
}

registerScopedService(
  LifecycleScope.Agent,
  IAgentShellCommandService,
  AgentShellCommandService,
  ScopeActivation.OnScopeCreated,
  'shellCommand',
);