File size: 10,615 Bytes
f0634fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { toDisposable } from '#/_base/di/lifecycle';
import { Event } from '#/_base/event';
import type { IAgentLoopService, LoopErrorHandler, LoopErrorHandlerRegistrationOptions, LoopNotify, LoopNotifyHandle, LoopSubmitOptions, PromptHandle, Turn, TurnResult } from '#/agent/loop/loop';
import type { UserEntry } from '#human/agent/turn';

export function submitPromptTurn(
  loop: IAgentLoopService,
  input: UserEntry,
  options?: LoopSubmitOptions,
): { readonly turn: Turn } {
  const { id } = loop.submit(input, options);
  const handle = loop.promptHandle(id);
  if (handle === undefined) throw new Error(`missing prompt handle for ${id}`);
  let backing: Turn | undefined;
  let settledCancelled = false;
  void handle.launched.then((turn) => {
    backing = turn;
  });
  void handle.completion.then((completion) => {
    settledCancelled = completion.state === 'cancelled';
  });
  const controller = new AbortController();
  const result: Promise<TurnResult> = handle.launched.then(
    (turn) =>
      turn?.result ??
      handle.completion.then((completion) => {
        if (completion.result !== undefined) return completion.result;
        if (completion.state === 'cancelled') {
          return { type: 'cancelled', steps: 0, reason: undefined } as TurnResult;
        }
        return new Promise<TurnResult>(() => {});
      }),
  );
  return {
    turn: {
      get id() {
        return backing?.id;
      },
      get state() {
        return backing?.state ?? (settledCancelled ? 'cancelled' : 'queued');
      },
      signal: controller.signal,
      ready: handle.launched.then(async (turn) => {
        await turn?.ready;
      }),
      result,
      cancel: (reason) => loop.cancel({ promptId: id }, reason),
    },
  };
}
import type { MachineEngine, MachineEngineAttachBundle } from '#/agent/loop/machine/engine';
import type { AgentEventStore } from '#human/agent/slices';
import type { IAgentToolExecutorService } from '#/agent/toolExecutor/toolExecutor';
import type { BeforeToolExecuteEvent, ToolDidExecuteContext, WillExecuteToolEvent } from '#/agent/toolExecutor/toolHooks';
import { OrderedHookSlot } from '#/hooks';
import type { ContextMessage, PromptOrigin } from '#/agent/contextMemory/types';
import { createHooks } from '#/hooks';
import type { IWireService } from '#/wire/wire';

import { stubAgentWire } from '../../wire/stubs';

export interface StubLoopOptions { readonly hasActiveTurn?: boolean; readonly currentId?: string | number; readonly pendingTurnResult?: boolean; readonly manualTurnResult?: boolean }
export type StubTurn = Turn & { readonly id: number };
export type StubLoop = IAgentLoopService & {
  readonly launches: readonly number[];
  readonly cancels: readonly { readonly turnId?: number; readonly reason?: unknown }[];
  readonly queue: { hasPendingRequests(): boolean };
  startTurn(): StubTurn;
  settleActive(result?: TurnResult): void;
  drainNextBatch(context: { append(...messages: ContextMessage[]): void }): { readonly driver: { readonly kind: string } } | undefined;
};
const turnControllers = new WeakMap<Turn, AbortController>();
export function makeTurn(id: number): StubTurn {
  const controller = new AbortController();
  const turn: StubTurn = { id, signal: controller.signal, ready: Promise.resolve(), result: Promise.resolve({ type: 'completed', steps: 0, truncated: false }), cancel: (reason) => { controller.abort(reason); return true; } };
  turnControllers.set(turn, controller);
  return turn;
}
interface PendingEntry { readonly kind: string; readonly message?: ContextMessage; readonly onConsume?: () => void }
function registry(): { handlers: LoopErrorHandler[]; register: IAgentLoopService['registerLoopErrorHandler'] } {
  const handlers: LoopErrorHandler[] = [];
  const remove = (id: string) => { const i = handlers.findIndex((h) => h.id === id); if (i >= 0) handlers.splice(i, 1); };
  const register = (handler: LoopErrorHandler, options: LoopErrorHandlerRegistrationOptions = {}) => {
    remove(handler.id); const target = options.before ?? options.after;
    if (target === undefined) handlers.push(handler); else { const i = handlers.findIndex((h) => h.id === target); if (i < 0) throw new Error(`Loop error handler target "${target}" is not registered`); handlers.splice(options.before !== undefined ? i : i + 1, 0, handler); }
    return toDisposable(() => remove(handler.id));
  };
  return { handlers, register };
}
function stubAttachStore(): AgentEventStore {
  return {
    ref: { tree: 'test', branch: 'main' },
    getState: () => ({ history: [], queue: [], notifications: [], reminders: [], turnIndex: { nextTurnId: 0 } }),
    subscribe: () => () => {},
    dispatch: () => Promise.resolve({ kind: 'entry', seq: 0, ts: 0, type: 'noop', payload: null }),
    registerSlice: () => Promise.resolve(() => {}),
    reset: () => Promise.resolve(),
    flush: () => Promise.resolve(),
    close: () => Promise.resolve(),
  } as unknown as AgentEventStore;
}
function stubAttachBundle(): MachineEngineAttachBundle {
  return { store: stubAttachStore(), request: { model: { provider: 'test', model: 'test' } } } as unknown as MachineEngineAttachBundle;
}
function stubAttachEngine(): MachineEngine {
  return {
    submit: () => {},
    steer: () => {},
    notify: () => {},
    remind: () => {},
    cancelQueueItem: () => {},
    abort: () => {},
    pause: () => {},
    resume: () => {},
    resetHistory: () => Promise.resolve(),
    resetJournal: () => Promise.resolve(),
    stop: () => {},
    snapshot: () => ({ running: false, aborting: false, waitingForBackground: false, paused: false, queue: [], queueLength: 0, queueIds: [], notificationCount: 0, reminderCount: 0, backgroundCount: 0 }),
    currentStep: () => 0,
    lastFinish: () => undefined,
    toolExtras: new Map(),
    handleToolProgress: () => {},
  };
}
export function stubLoopWithHooks(options: StubLoopOptions = {}): StubLoop {
  const hooks = createHooks(['onWillBeginStep', 'onDidFinishStep', 'onBeforeSubmitPrompt']) as IAgentLoopService['hooks'];
  const errorHandlers = registry(); const launches: number[] = []; const cancels: { turnId?: number; reason?: unknown }[] = [];
  const pending: PendingEntry[] = [];
  const handles = new Map<string, PromptHandle>();
  let active: Turn | undefined; let nextId = typeof options.currentId === 'number' ? options.currentId : 0;
  let releaseActiveResult: ((result: TurnResult) => void) | undefined;
  const startTurn = () => {
    const turn = makeTurn(nextId++);
    const result = options.manualTurnResult === true
      ? new Promise<TurnResult>((resolve) => { releaseActiveResult = resolve; })
      : options.pendingTurnResult === true ? new Promise<never>(() => {}) : turn.result;
    const configured = { ...turn, result };
    launches.push(configured.id); active = configured; return configured;
  };
  const hasPending = () => pending.length > 0;
  const stub: StubLoop = {
    _serviceBrand: undefined, hooks, launches, cancels, startTurn,
    queue: { hasPendingRequests: hasPending },
    settleActive(result = { type: 'completed', steps: 0, truncated: false }) { releaseActiveResult?.(result); },
    submit(input: UserEntry, options?: LoopSubmitOptions) {
      const turn = startTurn();
      const id = input.meta?.promptId ?? 'p';
      const message: ContextMessage = {
        ...input.message,
        toolCalls: [],
        origin: input.meta?.origin as PromptOrigin | undefined,
      };
      pending.push({ kind: 'prompt', message, onConsume: options?.onMaterialize });
      handles.set(id, {
        id,
        userMessageId: id,
        createdAt: '',
        state: 'running',
        message,
        launched: Promise.resolve(turn),
        completion: new Promise(() => {}),
      });
      return { id };
    },
    steer: async () => {},
    notify(note: LoopNotify = {}): LoopNotifyHandle {
      const entry: PendingEntry = {
        kind: note.bypassMaxSteps === true ? 'handoff' : note.message !== undefined ? 'message' : 'continuation',
        message: note.message,
        onConsume: note.onConsume,
      };
      pending.push(entry);
      let dropped = false;
      return {
        get dropped() { return dropped; },
        drop: () => {
          if (dropped) return;
          dropped = true;
          const index = pending.indexOf(entry);
          if (index >= 0) pending.splice(index, 1);
          note.onDrop?.();
        },
      };
    },
    snapshot() {
      return {
        state: active !== undefined ? 'running' : 'idle',
        activeTurnId: active?.id,
        activePromptId: undefined,
        queue: [],
        notificationCount: 0,
        paused: false,
        hasPendingRequests: hasPending(),
        turn: undefined,
        activeTraceId: undefined,
      };
    },
    promptHandle: (id) => handles.get(id),
    cancel(target, reason) { cancels.push({ turnId: target?.turnId, reason }); if (target?.promptId !== undefined) return true; if (active === undefined || (target?.turnId !== undefined && active.id !== target.turnId)) return false; active.cancel(reason); return true; },
    tryAcquireQuiescence: () => toDisposable(() => {}),
    buildAttachBundle: () => stubAttachBundle(),
    attachEngine: () => stubAttachEngine(),
    resetMachineEngine: () => Promise.resolve(),
    registerLoopErrorHandler: errorHandlers.register,
    settled: () => Promise.resolve(),
    drainNextBatch(context) {
      const batch = pending.splice(0);
      if (batch.length === 0) return undefined;
      for (const entry of batch) {
        entry.onConsume?.();
        if (entry.message !== undefined && entry.message.content.length > 0) context.append(entry.message);
      }
      return { driver: { kind: batch[0]!.kind } };
    },
  };
  return stub;
}
export async function runWillBeginStepHooks(
  loop: IAgentLoopService,
  firstStepOfTurn = false,
): Promise<void> {
  await loop.hooks.onWillBeginStep.run({
    turnId: 0,
    step: 0,
    firstStepOfTurn,
    signal: new AbortController().signal,
  });
}
export function stubWire(): IWireService { return stubAgentWire(); }
export function stubToolExecutor(): IAgentToolExecutorService { return { _serviceBrand: undefined, execute: async function* () {}, onBeforeExecuteTool: Event.None as Event<BeforeToolExecuteEvent>, onWillExecuteTool: Event.None as Event<WillExecuteToolEvent>, hooks: { onDidExecuteTool: new OrderedHookSlot<ToolDidExecuteContext>() }, recordDupType: () => {}, registerToolCallGuard: () => ({ dispose() {} }), registerUnavailableToolDescriber: () => ({ dispose() {} }), registerMissingToolDescriber: () => ({ dispose() {} }) }; }