@microfox/ai-worker 1.0.3 → 1.0.5

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 (69) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +22 -0
  3. package/dist/chainMapDefaults.d.mts +21 -0
  4. package/dist/chainMapDefaults.d.ts +21 -0
  5. package/dist/chainMapDefaults.js +59 -0
  6. package/dist/chainMapDefaults.js.map +1 -0
  7. package/dist/chainMapDefaults.mjs +10 -0
  8. package/dist/chainMapDefaults.mjs.map +1 -0
  9. package/dist/chunk-BCRJIFKB.mjs +9 -0
  10. package/dist/chunk-BCRJIFKB.mjs.map +1 -0
  11. package/dist/{chunk-72XGFZCE.mjs → chunk-CILTGUUQ.mjs} +14 -3
  12. package/dist/chunk-CILTGUUQ.mjs.map +1 -0
  13. package/dist/{chunk-7LQNS2SG.mjs → chunk-QHX55IML.mjs} +442 -56
  14. package/dist/chunk-QHX55IML.mjs.map +1 -0
  15. package/dist/chunk-SQB5FQCZ.mjs +21 -0
  16. package/dist/chunk-SQB5FQCZ.mjs.map +1 -0
  17. package/dist/{chunk-AOXGONGI.mjs → chunk-T7DRPKR6.mjs} +7 -5
  18. package/dist/chunk-T7DRPKR6.mjs.map +1 -0
  19. package/dist/chunk-XCKWV2WZ.mjs +34 -0
  20. package/dist/chunk-XCKWV2WZ.mjs.map +1 -0
  21. package/dist/chunk-ZW4PNCDH.mjs +17 -0
  22. package/dist/chunk-ZW4PNCDH.mjs.map +1 -0
  23. package/dist/client.d.mts +148 -2
  24. package/dist/client.d.ts +148 -2
  25. package/dist/client.js +13 -2
  26. package/dist/client.js.map +1 -1
  27. package/dist/client.mjs +1 -1
  28. package/dist/handler.d.mts +121 -23
  29. package/dist/handler.d.ts +121 -23
  30. package/dist/handler.js +450 -58
  31. package/dist/handler.js.map +1 -1
  32. package/dist/handler.mjs +5 -2
  33. package/dist/hitlConfig.d.mts +46 -0
  34. package/dist/hitlConfig.d.ts +46 -0
  35. package/dist/hitlConfig.js +33 -0
  36. package/dist/hitlConfig.js.map +1 -0
  37. package/dist/hitlConfig.mjs +8 -0
  38. package/dist/hitlConfig.mjs.map +1 -0
  39. package/dist/index.d.mts +28 -4
  40. package/dist/index.d.ts +28 -4
  41. package/dist/index.js +575 -74
  42. package/dist/index.js.map +1 -1
  43. package/dist/index.mjs +78 -20
  44. package/dist/index.mjs.map +1 -1
  45. package/dist/queue-B5n6YVQV.d.ts +306 -0
  46. package/dist/queue-DaR2UuZi.d.mts +306 -0
  47. package/dist/queue.d.mts +3 -0
  48. package/dist/queue.d.ts +3 -0
  49. package/dist/queue.js +47 -0
  50. package/dist/queue.js.map +1 -0
  51. package/dist/queue.mjs +12 -0
  52. package/dist/queue.mjs.map +1 -0
  53. package/dist/queueInputEnvelope.d.mts +31 -0
  54. package/dist/queueInputEnvelope.d.ts +31 -0
  55. package/dist/queueInputEnvelope.js +42 -0
  56. package/dist/queueInputEnvelope.js.map +1 -0
  57. package/dist/queueInputEnvelope.mjs +10 -0
  58. package/dist/queueInputEnvelope.mjs.map +1 -0
  59. package/dist/queueJobStore.d.mts +3 -2
  60. package/dist/queueJobStore.d.ts +3 -2
  61. package/dist/queueJobStore.js +6 -4
  62. package/dist/queueJobStore.js.map +1 -1
  63. package/dist/queueJobStore.mjs +1 -1
  64. package/package.json +7 -2
  65. package/dist/chunk-72XGFZCE.mjs.map +0 -1
  66. package/dist/chunk-7LQNS2SG.mjs.map +0 -1
  67. package/dist/chunk-AOXGONGI.mjs.map +0 -1
  68. package/dist/client-BqSJQ9mZ.d.mts +0 -183
  69. package/dist/client-BqSJQ9mZ.d.ts +0 -183
package/dist/handler.d.ts CHANGED
@@ -1,5 +1,29 @@
1
1
  import { SQSEvent, Context } from 'aws-lambda';
2
2
  import { ZodType } from 'zod';
3
+ import { R as RetryContext, S as SmartRetryConfig, Q as QueueStepOutput, b as ChainContext, H as HitlResumeContext, L as LoopContext } from './queue-B5n6YVQV.js';
4
+ export { B as BuiltInRetryPattern, C as CustomRetryPattern, a as RetryPattern } from './queue-B5n6YVQV.js';
5
+ import './hitlConfig.js';
6
+
7
+ /**
8
+ * Token budget tracking for workers.
9
+ * Workers report usage via ctx.reportTokenUsage(); the runtime accumulates
10
+ * and throws TokenBudgetExceededError when the limit is reached.
11
+ */
12
+ interface TokenUsage {
13
+ inputTokens: number;
14
+ outputTokens: number;
15
+ }
16
+ interface TokenBudgetState {
17
+ inputTokens: number;
18
+ outputTokens: number;
19
+ /** null = no budget configured */
20
+ budget: number | null;
21
+ }
22
+ declare class TokenBudgetExceededError extends Error {
23
+ readonly used: number;
24
+ readonly budget: number;
25
+ constructor(used: number, budget: number);
26
+ }
3
27
 
4
28
  /**
5
29
  * Generic Lambda handler wrapper for worker agents.
@@ -34,6 +58,7 @@ interface JobRecord {
34
58
  jobId: string;
35
59
  workerId: string;
36
60
  }>;
61
+ userId?: string;
37
62
  createdAt: string;
38
63
  updatedAt: string;
39
64
  completedAt?: string;
@@ -98,6 +123,8 @@ interface WorkerHandlerParams<INPUT, OUTPUT> {
98
123
  jobId: string;
99
124
  workerId: string;
100
125
  requestId?: string;
126
+ /** ID of the user who triggered this job. Pass via DispatchOptions.userId from your API route. */
127
+ userId?: string;
101
128
  /**
102
129
  * Job store interface for updating and retrieving job state.
103
130
  * Uses MongoDB directly when configured; never HTTP/origin URL.
@@ -116,49 +143,114 @@ interface WorkerHandlerParams<INPUT, OUTPUT> {
116
143
  messageId?: string;
117
144
  output?: unknown;
118
145
  }>;
146
+ /**
147
+ * Report token usage after an LLM call. Accumulates across all calls in this job.
148
+ * Throws TokenBudgetExceededError if the configured maxTokens budget is exceeded.
149
+ * Also persists usage to the job store for observability.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * const result = await anthropic.messages.create({ ... });
154
+ * await ctx.reportTokenUsage({
155
+ * inputTokens: result.usage.input_tokens,
156
+ * outputTokens: result.usage.output_tokens,
157
+ * });
158
+ * ```
159
+ */
160
+ reportTokenUsage: (usage: TokenUsage) => Promise<void>;
161
+ /**
162
+ * Get the current token usage and remaining budget for this job.
163
+ * Returns `{ used, budget: null, remaining: null }` when no maxTokens was set.
164
+ */
165
+ getTokenBudget: () => {
166
+ used: number;
167
+ budget: number | null;
168
+ remaining: number | null;
169
+ };
170
+ /**
171
+ * Populated on retry attempts (attempt >= 2). Contains info about the previous failure
172
+ * so the handler can self-correct (e.g. inject the error message into the next prompt).
173
+ * `undefined` on the first attempt — use `if (ctx.retryContext)` to detect retries.
174
+ */
175
+ retryContext?: RetryContext;
119
176
  [key: string]: any;
120
177
  };
121
178
  }
179
+
122
180
  type WorkerHandler<INPUT, OUTPUT> = (params: WorkerHandlerParams<INPUT, OUTPUT>) => Promise<OUTPUT>;
123
181
  /** Result of getNextStep for queue chaining. */
124
182
  interface QueueNextStep {
125
183
  workerId: string;
126
184
  delaySeconds?: number;
127
- mapInputFromPrev?: string;
185
+ requiresApproval?: boolean;
186
+ /** Whether this step has a `chain` function (or built-in string) defined. */
187
+ hasChain?: boolean;
188
+ /** Whether this step has a `resume` function defined. */
189
+ hasResume?: boolean;
190
+ /** Optional HITL metadata from queue step config (UI/tooling only). */
191
+ hitl?: {
192
+ ui?: unknown;
193
+ } | unknown;
194
+ /** Smart retry config for this step. Overrides worker-level retry for this step only. */
195
+ retry?: SmartRetryConfig;
128
196
  }
129
- /** One previous step's output (for mapInputFromPrev context). */
130
- interface QueueStepOutput {
131
- stepIndex: number;
132
- workerId: string;
133
- output: unknown;
197
+ /**
198
+ * @deprecated Use {@link ChainContext} for the normal chain path and
199
+ * {@link HitlResumeContext} for the HITL resume path instead.
200
+ * Kept for backwards compatibility with queue files written against the old API.
201
+ */
202
+ interface MapStepInputContext {
203
+ initialInput: unknown;
204
+ previousOutputs: QueueStepOutput[];
205
+ /** @deprecated Use HitlResumeContext.reviewerInput instead. */
206
+ hitlInput?: unknown;
207
+ /** @deprecated Use HitlResumeContext.pendingInput instead. */
208
+ pendingStepInput?: Record<string, unknown>;
134
209
  }
210
+
135
211
  /** Runtime helpers for queue-aware wrappers (provided by generated registry). */
136
212
  interface QueueRuntime {
137
213
  getNextStep(queueId: string, stepIndex: number): QueueNextStep | undefined;
138
- /** Optional: when provided, mapping can use outputs from any previous step. */
214
+ /** Step config at `stepIndex`. */
215
+ getStepAt?(queueId: string, stepIndex: number): QueueNextStep | undefined;
216
+ /** Optional: when provided, mappers can use outputs from any previous step. */
139
217
  getQueueJob?(queueJobId: string): Promise<{
140
218
  steps: Array<{
141
219
  workerId: string;
142
220
  output?: unknown;
143
221
  }>;
144
222
  } | null>;
145
- /** (initialInput, previousOutputs) – previousOutputs includes outputs for steps 0..stepIndex-1 and current step. */
146
- invokeMapInput?(queueId: string, stepIndex: number, initialInput: unknown, previousOutputs: QueueStepOutput[]): Promise<unknown> | unknown;
223
+ /**
224
+ * Build the input for a step when the queue advances normally (no HITL resume).
225
+ * Calls the step's `chain` function, or the built-in passthrough/continueFromPrevious.
226
+ */
227
+ invokeChain?(queueId: string, stepIndex: number, ctx: ChainContext): Promise<unknown> | unknown;
228
+ /**
229
+ * Build the domain input for a step when it resumes after HITL approval.
230
+ * Calls the step's `resume` function, or merges pendingInput + reviewerInput by default.
231
+ */
232
+ invokeResume?(queueId: string, stepIndex: number, ctx: HitlResumeContext): Promise<unknown> | unknown;
233
+ /**
234
+ * Evaluate whether a looping step should run again.
235
+ * Calls the step's `loop.shouldContinue` function. Returns false if none defined.
236
+ */
237
+ invokeLoop?(queueId: string, stepIndex: number, ctx: LoopContext): Promise<boolean> | boolean;
147
238
  }
148
239
  /**
149
- * Wraps a user handler so that when the job has __workerQueue context (from
150
- * dispatchQueue or queue cron), it dispatches the next worker in the sequence
151
- * after the handler completes. Uses literal worker IDs so the CLI env injection
152
- * picks up WORKER_QUEUE_URL_* for next-step workers.
240
+ * Wraps a user handler so that when the job has `__workerQueue` context (from
241
+ * `dispatchQueue` or queue cron), it dispatches the next worker in the sequence
242
+ * **after** the handler completes.
243
+ *
244
+ * All queue/HITL envelope keys (`__workerQueue`, `__hitlInput`, `__hitlDecision`,
245
+ * `__hitlPending`, `hitl`) are **stripped from `params.input` before the user handler
246
+ * runs** — workers receive clean domain input and do not need to accept these keys
247
+ * in their Zod schemas.
248
+ *
249
+ * **HITL resume:** When `__hitlInput` is present, `invokeResume` is called first to
250
+ * produce the merged domain input. **Chain advancement:** After a step completes,
251
+ * `invokeChain` is called to compute the next step's input.
153
252
  */
154
- declare function wrapHandlerForQueue<INPUT, OUTPUT>(handler: WorkerHandler<INPUT, OUTPUT>, queueRuntime: QueueRuntime): WorkerHandler<INPUT & {
155
- __workerQueue?: {
156
- id: string;
157
- stepIndex: number;
158
- initialInput: unknown;
159
- queueJobId?: string;
160
- };
161
- }, OUTPUT>;
253
+ declare function wrapHandlerForQueue<INPUT, OUTPUT>(handler: WorkerHandler<INPUT, OUTPUT>, queueRuntime: QueueRuntime): WorkerHandler<INPUT, OUTPUT>;
162
254
  interface SQSMessageBody {
163
255
  workerId: string;
164
256
  jobId: string;
@@ -169,6 +261,10 @@ interface SQSMessageBody {
169
261
  jobStoreUrl?: string;
170
262
  metadata?: Record<string, any>;
171
263
  timestamp: string;
264
+ /** ID of the user who triggered this job. Forwarded from dispatch options. */
265
+ userId?: string;
266
+ /** Maximum total tokens (input + output) for this job. Forwarded from DispatchOptions.maxTokens. */
267
+ maxTokens?: number;
172
268
  }
173
269
  interface WebhookPayload {
174
270
  jobId: string;
@@ -190,6 +286,8 @@ interface WebhookPayload {
190
286
  * @param outputSchema - Optional Zod schema for output validation
191
287
  * @returns A Lambda handler function
192
288
  */
193
- declare function createLambdaHandler<INPUT, OUTPUT>(handler: WorkerHandler<INPUT, OUTPUT>, outputSchema?: ZodType<OUTPUT>): (event: SQSEvent, context: Context) => Promise<void>;
289
+ declare function createLambdaHandler<INPUT, OUTPUT>(handler: WorkerHandler<INPUT, OUTPUT>, outputSchema?: ZodType<OUTPUT>, options?: {
290
+ retry?: SmartRetryConfig;
291
+ }): (event: SQSEvent, context: Context) => Promise<void>;
194
292
 
195
- export { type DispatchWorkerOptions, type JobRecord, type JobStore, type JobStoreUpdate, type QueueNextStep, type QueueRuntime, type QueueStepOutput, type SQSMessageBody, SQS_MAX_DELAY_SECONDS, type WebhookPayload, type WorkerHandler, type WorkerHandlerParams, type WorkerLogger, createLambdaHandler, createWorkerLogger, wrapHandlerForQueue };
293
+ export { ChainContext, type DispatchWorkerOptions, HitlResumeContext, type JobRecord, type JobStore, type JobStoreUpdate, LoopContext, type MapStepInputContext, type QueueNextStep, type QueueRuntime, QueueStepOutput, RetryContext, type SQSMessageBody, SQS_MAX_DELAY_SECONDS, SmartRetryConfig, TokenBudgetExceededError, type TokenBudgetState, type TokenUsage, type WebhookPayload, type WorkerHandler, type WorkerHandlerParams, type WorkerLogger, createLambdaHandler, createWorkerLogger, wrapHandlerForQueue };