The best way to control Claude Code, Codex and more from any computer or phone

main
ts 217 lines 7.72 KB
Raw
1 // Alchemy modifications are licensed under Apache-2.0.
2 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
3 import { RpcTarget } from "cloudflare:workers";
4 import type { Event } from "./context.ts";
5 import type { Engine } from "./engine.ts";
6 import { computeHash } from "./lib/cache.ts";
7 import { isReadableStreamLike, writeStreamOutput } from "./lib/streams.ts";
8
9 export type StepSelector = {
10 name: string;
11 index?: number;
12 };
13
14 type UserEvent = {
15 type: string;
16 payload: unknown;
17 };
18
19 // KV key prefixes/values used by the modifier/mock system
20 export const MODIFIER_KEYS = {
21 REPLACE_RESULT: "replace-result-",
22 MOCK_STEP_ERROR: "mock-step-error-",
23 MOCK_EVENT: "mock-event-",
24 FORCE_STEP_TIMEOUT: "force-step-timeout-",
25 FORCE_EVENT_TIMEOUT: "force-event-timeout-",
26 FAILURE_INDEX: "failure-index-",
27 DISABLE_SLEEP: "disable-sleep-",
28 DISABLE_ALL_SLEEPS: "disableAllSleeps",
29 DISABLE_RETRY_DELAY: "disable-retry-delay-",
30 DISABLE_ALL_RETRY_DELAYS: "disableAllRetryDelays",
31 } as const;
32
33 export function isModifierKey(key: string): boolean {
34 return Object.values(MODIFIER_KEYS).some((v) => key.startsWith(v));
35 }
36
37 export class WorkflowInstanceModifier extends RpcTarget {
38 #engine: Engine;
39 #state: DurableObjectState;
40
41 constructor(engine: Engine, state: DurableObjectState) {
42 super();
43 this.#engine = engine;
44 this.#state = state;
45 }
46
47 async #getWaitForEventCacheKey(step: StepSelector): Promise<string> {
48 let count = 1;
49 if (step.index) {
50 count = step.index;
51 }
52 const name = `${step.name}-${count}`;
53 const hash = await computeHash(name);
54 const cacheKey = `${hash}-${count}`;
55 const waitForEventKey = `${cacheKey}-value`;
56
57 return waitForEventKey;
58 }
59
60 async #getBaseCacheKey(step: StepSelector): Promise<string> {
61 const hash = await computeHash(step.name);
62 let count = 1;
63 if (step.index) {
64 count = step.index;
65 }
66 return `${hash}-${count}`;
67 }
68
69 async #getStepCacheKey(step: StepSelector): Promise<string> {
70 const baseCacheKey = await this.#getBaseCacheKey(step);
71 return `${baseCacheKey}-value`;
72 }
73
74 #getAndIncrementCounter = async (valueKey: string, by: number) => {
75 const counterKey = `${MODIFIER_KEYS.FAILURE_INDEX}${valueKey}`;
76 const next = (await this.#state.storage.get<number>(counterKey)) ?? 1;
77 await this.#state.storage.put(counterKey, next + by);
78 return next;
79 };
80
81 async #getSleepStepDisableKey(step: StepSelector): Promise<string> {
82 let count = 1;
83 if (step.index) {
84 count = step.index;
85 }
86 const sleepNameCountHash = await computeHash(step.name + count);
87
88 return `${MODIFIER_KEYS.DISABLE_SLEEP}${sleepNameCountHash}`;
89 }
90
91 async disableSleeps(steps?: Array<StepSelector>): Promise<void> {
92 if (!steps) {
93 await this.#state.storage.put(MODIFIER_KEYS.DISABLE_ALL_SLEEPS, true);
94 } else {
95 for (const step of steps) {
96 const sleepDisableKey = await this.#getSleepStepDisableKey(step);
97 await this.#state.storage.put(sleepDisableKey, true);
98 }
99 }
100 }
101
102 async disableRetryDelays(steps?: Array<StepSelector>): Promise<void> {
103 if (!steps) {
104 await this.#state.storage.put(MODIFIER_KEYS.DISABLE_ALL_RETRY_DELAYS, true);
105 } else {
106 for (const step of steps) {
107 const valueKey = await this.#getStepCacheKey(step);
108 await this.#state.storage.put(`${MODIFIER_KEYS.DISABLE_RETRY_DELAY}${valueKey}`, true);
109 }
110 }
111 }
112
113 // step.do() flow: It first checks if a result or error is already in the cache and, if so, returns it immediately.
114 // If nothing is in the cache, it checks for remaining attempts and runs the user's code against the defined timeout.
115 // Since `step.do()` performs this initial cache check, directly changing the `valueKey` would cause it to
116 // assume the value was pre-cached, preventing it from writing any logs about the step's execution state.
117 // Storing the value under a separate key is crucial because it ensures all execution logs for the step are
118 // generated, rather than the step being skipped due to a premature cache hit.
119 async mockStepResult(step: StepSelector, stepResult: unknown): Promise<void> {
120 const valueKey = await this.#getStepCacheKey(step);
121
122 if (await this.#state.storage.get(`${MODIFIER_KEYS.REPLACE_RESULT}${valueKey}`)) {
123 throw new Error(`[WorkflowIntrospector] Trying to mock step '${step.name}' multiple times!`);
124 }
125
126 if (isReadableStreamLike(stepResult)) {
127 // ReadableStream is not structured-cloneable, so we consume it eagerly
128 // and store the chunks via the streaming infrastructure. We use attempt 0
129 // to distinguish mock chunks from real execution attempts (which start at 1).
130 const baseCacheKey = await this.#getBaseCacheKey(step);
131 const streamMeta = await writeStreamOutput({
132 storage: this.#state.storage,
133 cacheKey: baseCacheKey,
134 attempt: 0,
135 stream: stepResult,
136 skipMetaWrite: true,
137 });
138
139 await this.#state.storage.put(`${MODIFIER_KEYS.REPLACE_RESULT}${valueKey}`, {
140 __mockStreamOutput: true,
141 cacheKey: baseCacheKey,
142 meta: streamMeta,
143 });
144 } else {
145 await this.#state.storage.put(`${MODIFIER_KEYS.REPLACE_RESULT}${valueKey}`, stepResult);
146 }
147 }
148
149 // Same logic of `mockStepResult` but stores an error instead of a value.
150 async mockStepError(step: StepSelector, error: Error, times?: number): Promise<void> {
151 const valueKey = await this.#getStepCacheKey(step);
152 const serializableError = {
153 name: error.name,
154 message: error.message,
155 };
156
157 if (await this.#state.storage.get(`${MODIFIER_KEYS.REPLACE_RESULT}${valueKey}`)) {
158 throw new Error(
159 `[WorkflowIntrospector] Trying to mock error on step '${step.name}' after mocking its result!`,
160 );
161 }
162
163 if (times) {
164 const start = await this.#getAndIncrementCounter(valueKey, times);
165 const mockErrorsPuts = Array.from({ length: times }, (_, i) => {
166 const attempt = start + i;
167 const mockErrorKey = `${MODIFIER_KEYS.MOCK_STEP_ERROR}${valueKey}-${attempt}`;
168 return this.#state.storage.put(mockErrorKey, serializableError);
169 });
170
171 await Promise.all(mockErrorsPuts);
172 } else {
173 const mockErrorKey = `${MODIFIER_KEYS.MOCK_STEP_ERROR}${valueKey}`;
174 await this.#state.storage.put(mockErrorKey, serializableError);
175 }
176 }
177
178 async forceStepTimeout(step: StepSelector, times?: number) {
179 const valueKey = await this.#getStepCacheKey(step);
180
181 if (await this.#state.storage.get(`${MODIFIER_KEYS.REPLACE_RESULT}${valueKey}`)) {
182 throw new Error(
183 `[WorkflowIntrospector] Trying to force timeout on step '${step.name}' after mocking its result!`,
184 );
185 }
186
187 if (times) {
188 const start = await this.#getAndIncrementCounter(valueKey, times);
189 const forceTimeouts = Array.from({ length: times }, (_, i) => {
190 const attempt = start + i;
191 const forceStepTimeoutKey = `${MODIFIER_KEYS.FORCE_STEP_TIMEOUT}${valueKey}-${attempt}`;
192 return this.#state.storage.put(forceStepTimeoutKey, true);
193 });
194
195 await Promise.all(forceTimeouts);
196 } else {
197 const forceStepTimeoutKey = `${MODIFIER_KEYS.FORCE_STEP_TIMEOUT}${valueKey}`;
198 await this.#state.storage.put(forceStepTimeoutKey, true);
199 }
200 }
201
202 async mockEvent(event: UserEvent): Promise<void> {
203 const myEvent: Event = {
204 timestamp: new Date(),
205 payload: event.payload,
206 type: event.type,
207 };
208
209 await this.#state.storage.put(`${MODIFIER_KEYS.MOCK_EVENT}${event.type}`, true);
210 await this.#engine.receiveEvent(myEvent);
211 }
212
213 async forceEventTimeout(step: StepSelector): Promise<void> {
214 const waitForEventKey = await this.#getWaitForEventCacheKey(step);
215 await this.#state.storage.put(`${MODIFIER_KEYS.FORCE_EVENT_TIMEOUT}${waitForEventKey}`, true);
216 }
217 }