@microfox/ai-worker 1.0.1 → 1.0.3

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # @microfox/ai-worker
2
2
 
3
+ ## 1.0.3
4
+
5
+ ### Patch Changes
6
+
7
+ - d79d331: Changes from PR #55: ai-worker-wrapup-and-docs
8
+ - Updated dependencies [d79d331]
9
+ - @microfox/ai-router@2.1.5
10
+
11
+ ## 1.0.2
12
+
13
+ ### Patch Changes
14
+
15
+ - ab4a506: Changes from PR #52: add_workers-dispatch-queue
16
+
3
17
  ## 1.0.1
4
18
 
5
19
  ### Patch Changes
package/README.md CHANGED
@@ -103,15 +103,17 @@ npx @microfox/ai-worker-cli@latest push
103
103
  ### Environment Variables
104
104
 
105
105
  **Required for Next.js:**
106
- - `WORKER_BASE_URL` - Base URL of your workers service (server-side). We append `/workers/trigger` and `/workers/config` internally when needed (e.g. `https://.../prod`).
107
- - `NEXT_PUBLIC_WORKER_BASE_URL` - Same as `WORKER_BASE_URL`, but exposed to the browser (use this if you call `dispatch()` from client-side code).
106
+ - `WORKER_BASE_URL` - Base URL of your workers service (server-side only). We append `/workers/trigger` and `/workers/config` internally when needed (e.g. `https://.../prod`). For client-side, use `useWorkflowJob` which calls your app's `/api/workflows/*` routes.
108
107
  - `WORKERS_TRIGGER_API_KEY` - Optional API key for trigger authentication (sent as `x-workers-trigger-key`)
109
108
 
110
109
  **Required for Lambda (set via deploy script):**
111
110
  - `AWS_REGION` - AWS region for SQS/Lambda
112
111
  - `STAGE` - Deployment stage (dev/stage/prod)
112
+ - `MONGODB_URI` or `DATABASE_MONGODB_URI` - For job store (and internalJobs / await polling).
113
113
  - Any secrets your workers need (OPENAI_KEY, DATABASE_URL, etc.)
114
114
 
115
+ **Worker-to-worker (Lambda):** When a worker calls another via `ctx.dispatchWorker`, the CLI injects `WORKER_QUEUE_URL_<SANITIZED_ID>` (e.g. `WORKER_QUEUE_URL_COST_USAGE_AI`) into that function’s environment. Same-service callees get this automatically; cross-service callees require setting the env var manually.
116
+
115
117
  ### Worker Configuration
116
118
 
117
119
  **Best Practice**: Export `workerConfig` as a separate const from your worker file:
@@ -180,6 +182,21 @@ Dispatches a job to the background worker.
180
182
 
181
183
  **Returns:** `Promise<{ messageId: string, status: 'queued', jobId: string }>`
182
184
 
185
+ ### Worker-to-worker: `ctx.dispatchWorker(workerId, input, options?)`
186
+
187
+ Inside a worker handler, call another worker (fire-and-forget or await):
188
+
189
+ ```typescript
190
+ handler: async ({ ctx }) => {
191
+ await ctx.dispatchWorker('other-worker', {}, { await: true });
192
+ };
193
+ ```
194
+
195
+ - **Fire-and-forget**: `ctx.dispatchWorker(id, input)` — enqueues and returns `{ jobId, messageId }`. Parent job’s `internalJobs` is appended.
196
+ - **Await**: `ctx.dispatchWorker(id, input, { await: true })` — enqueues, appends to `internalJobs`, then polls the job store until the child completes or fails. Returns `{ jobId, messageId, output }` or throws. Optional `pollIntervalMs`, `pollTimeoutMs`.
197
+
198
+ The CLI detects `ctx.dispatchWorker('id', ...)` and adds `WORKER_QUEUE_URL_<ID>` to that Lambda’s env. Local dev uses the HTTP trigger when queue URL is not set.
199
+
183
200
  ## License
184
201
 
185
202
  MIT
@@ -0,0 +1,163 @@
1
+ // src/client.ts
2
+ function getWorkersTriggerUrl() {
3
+ const raw = process.env.WORKER_BASE_URL || process.env.WORKERS_TRIGGER_API_URL || process.env.WORKERS_CONFIG_API_URL;
4
+ if (!raw) {
5
+ throw new Error(
6
+ "WORKER_BASE_URL is required for background workers. Set it server-side only."
7
+ );
8
+ }
9
+ const url = new URL(raw);
10
+ url.search = "";
11
+ url.hash = "";
12
+ const path = url.pathname || "";
13
+ url.pathname = path.replace(/\/?workers\/(trigger|config)\/?$/, "");
14
+ const basePath = url.pathname.replace(/\/+$/, "");
15
+ url.pathname = `${basePath}/workers/trigger`.replace(/\/+$/, "");
16
+ return url.toString();
17
+ }
18
+ function getQueueStartUrl(queueId) {
19
+ const raw = process.env.WORKER_BASE_URL || process.env.WORKERS_TRIGGER_API_URL || process.env.WORKERS_CONFIG_API_URL;
20
+ if (!raw) {
21
+ throw new Error(
22
+ "WORKER_BASE_URL is required for background workers. Set it server-side only."
23
+ );
24
+ }
25
+ const url = new URL(raw);
26
+ url.search = "";
27
+ url.hash = "";
28
+ const path = url.pathname || "";
29
+ url.pathname = path.replace(/\/?workers\/(trigger|config)\/?$/, "");
30
+ const basePath = url.pathname.replace(/\/+$/, "");
31
+ const safeSegment = encodeURIComponent(queueId);
32
+ url.pathname = `${basePath}/queues/${safeSegment}/start`.replace(/\/+$/, "");
33
+ return url.toString();
34
+ }
35
+ function serializeContext(ctx) {
36
+ const serialized = {};
37
+ if (ctx.requestId) {
38
+ serialized.requestId = ctx.requestId;
39
+ }
40
+ if (ctx.metadata && typeof ctx.metadata === "object") {
41
+ Object.assign(serialized, ctx.metadata);
42
+ }
43
+ if (ctx._serializeContext && typeof ctx._serializeContext === "function") {
44
+ const custom = ctx._serializeContext();
45
+ Object.assign(serialized, custom);
46
+ }
47
+ return serialized;
48
+ }
49
+ async function dispatch(workerId, input, inputSchema, options, ctx) {
50
+ const validatedInput = inputSchema.parse(input);
51
+ const jobId = options.jobId || `job-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
52
+ const triggerUrl = getWorkersTriggerUrl();
53
+ const serializedContext = ctx ? serializeContext(ctx) : {};
54
+ const messageBody = {
55
+ workerId,
56
+ jobId,
57
+ input: validatedInput,
58
+ context: serializedContext,
59
+ webhookUrl: options.webhookUrl,
60
+ metadata: options.metadata || {},
61
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
62
+ };
63
+ const headers = {
64
+ "Content-Type": "application/json"
65
+ };
66
+ const triggerKey = process.env.WORKERS_TRIGGER_API_KEY;
67
+ if (triggerKey) {
68
+ headers["x-workers-trigger-key"] = triggerKey;
69
+ }
70
+ const response = await fetch(triggerUrl, {
71
+ method: "POST",
72
+ headers,
73
+ body: JSON.stringify({
74
+ workerId,
75
+ body: messageBody
76
+ })
77
+ });
78
+ if (!response.ok) {
79
+ const text = await response.text().catch(() => "");
80
+ throw new Error(
81
+ `Failed to trigger worker "${workerId}": ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`
82
+ );
83
+ }
84
+ const data = await response.json().catch(() => ({}));
85
+ const messageId = data?.messageId ? String(data.messageId) : `trigger-${jobId}`;
86
+ return {
87
+ messageId,
88
+ status: "queued",
89
+ jobId
90
+ };
91
+ }
92
+ async function dispatchWorker(workerId, input, options = {}, ctx) {
93
+ const jobId = options.jobId || `job-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
94
+ const triggerUrl = getWorkersTriggerUrl();
95
+ const serializedContext = ctx ? serializeContext(ctx) : {};
96
+ const messageBody = {
97
+ workerId,
98
+ jobId,
99
+ input: input ?? {},
100
+ context: serializedContext,
101
+ webhookUrl: options.webhookUrl,
102
+ metadata: options.metadata || {},
103
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
104
+ };
105
+ const headers = { "Content-Type": "application/json" };
106
+ const triggerKey = process.env.WORKERS_TRIGGER_API_KEY;
107
+ if (triggerKey) headers["x-workers-trigger-key"] = triggerKey;
108
+ const response = await fetch(triggerUrl, {
109
+ method: "POST",
110
+ headers,
111
+ body: JSON.stringify({ workerId, body: messageBody })
112
+ });
113
+ if (!response.ok) {
114
+ const text = await response.text().catch(() => "");
115
+ throw new Error(
116
+ `Failed to trigger worker "${workerId}": ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`
117
+ );
118
+ }
119
+ const data = await response.json().catch(() => ({}));
120
+ const messageId = data?.messageId ? String(data.messageId) : `trigger-${jobId}`;
121
+ return { messageId, status: "queued", jobId };
122
+ }
123
+ async function dispatchLocal(handler, input, ctx) {
124
+ return handler({ input, ctx: ctx || {} });
125
+ }
126
+ async function dispatchQueue(queueId, initialInput, options = {}, _ctx) {
127
+ const jobId = options.jobId || `job-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
128
+ const queueStartUrl = getQueueStartUrl(queueId);
129
+ const normalizedInput = initialInput !== null && typeof initialInput === "object" ? initialInput : { value: initialInput };
130
+ const headers = { "Content-Type": "application/json" };
131
+ const triggerKey = process.env.WORKERS_TRIGGER_API_KEY;
132
+ if (triggerKey) headers["x-workers-trigger-key"] = triggerKey;
133
+ const response = await fetch(queueStartUrl, {
134
+ method: "POST",
135
+ headers,
136
+ body: JSON.stringify({
137
+ input: normalizedInput,
138
+ initialInput: normalizedInput,
139
+ metadata: options.metadata ?? {},
140
+ jobId,
141
+ ...options.webhookUrl ? { webhookUrl: options.webhookUrl } : {}
142
+ })
143
+ });
144
+ if (!response.ok) {
145
+ const text = await response.text().catch(() => "");
146
+ throw new Error(
147
+ `Failed to start queue "${queueId}": ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`
148
+ );
149
+ }
150
+ const data = await response.json().catch(() => ({}));
151
+ const messageId = data?.messageId ?? data?.jobId ?? `queue-${jobId}`;
152
+ return { queueId, messageId, status: "queued", jobId };
153
+ }
154
+
155
+ export {
156
+ getWorkersTriggerUrl,
157
+ getQueueStartUrl,
158
+ dispatch,
159
+ dispatchWorker,
160
+ dispatchLocal,
161
+ dispatchQueue
162
+ };
163
+ //# sourceMappingURL=chunk-72XGFZCE.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["/**\n * Client for dispatching background worker jobs.\n *\n * In production, dispatching happens via the workers HTTP API:\n * POST /workers/trigger -> enqueues message to SQS on the workers service side\n *\n * This avoids requiring AWS credentials in your Next.js app.\n */\n\nimport type { ZodType, z } from 'zod';\nimport type { WorkerQueueConfig } from './queue.js';\n\nexport interface WorkerQueueRegistry {\n getQueueById(queueId: string): WorkerQueueConfig | undefined;\n /** (initialInput, previousOutputs) for best DX: derive next input from original request and all prior step outputs. */\n invokeMapInput?: (\n queueId: string,\n stepIndex: number,\n initialInput: unknown,\n previousOutputs: Array<{ stepIndex: number; workerId: string; output: unknown }>\n ) => Promise<unknown> | unknown;\n}\n\nexport interface DispatchOptions {\n /**\n * Optional webhook callback URL to notify when the job finishes.\n * Only called when provided. Default: no webhook (use job store / MongoDB only).\n */\n webhookUrl?: string;\n /**\n * Controls how dispatch executes.\n * - \"auto\" (default): local inline execution in development unless WORKERS_LOCAL_MODE=false.\n * - \"local\": force inline execution (no SQS).\n * - \"remote\": force SQS/Lambda dispatch even in development.\n */\n mode?: 'auto' | 'local' | 'remote';\n jobId?: string;\n metadata?: Record<string, any>;\n /**\n * In-memory queue registry for dispatchQueue. Required when using dispatchQueue.\n * Pass a registry that imports from your .queue.ts definitions (works on Vercel/serverless).\n */\n registry?: WorkerQueueRegistry;\n /**\n * Optional callback to create a queue job record before dispatching.\n * Called with queueJobId (= first worker's jobId), queueId, and firstStep.\n */\n onCreateQueueJob?: (params: {\n queueJobId: string;\n queueId: string;\n firstStep: { workerId: string; workerJobId: string };\n metadata?: Record<string, unknown>;\n }) => Promise<void>;\n}\n\nexport interface DispatchResult {\n messageId: string;\n status: 'queued';\n jobId: string;\n}\n\nexport interface DispatchQueueResult extends DispatchResult {\n queueId: string;\n}\n\nexport interface SerializedContext {\n requestId?: string;\n userId?: string;\n traceId?: string;\n [key: string]: any;\n}\n\n/**\n * Derives the full /workers/trigger URL from env.\n * Exported for use by local dispatchWorker (worker-to-worker in dev).\n * Server-side only; clients should use useWorkflowJob with your app's /api/workflows routes.\n *\n * Env vars:\n * - WORKER_BASE_URL: base URL of the workers service (e.g. https://.../prod)\n * - WORKERS_TRIGGER_API_URL / WORKERS_CONFIG_API_URL: legacy, still supported\n */\nexport function getWorkersTriggerUrl(): string {\n const raw =\n process.env.WORKER_BASE_URL ||\n process.env.WORKERS_TRIGGER_API_URL ||\n process.env.WORKERS_CONFIG_API_URL;\n\n if (!raw) {\n throw new Error(\n 'WORKER_BASE_URL is required for background workers. Set it server-side only.'\n );\n }\n\n const url = new URL(raw);\n url.search = '';\n url.hash = '';\n\n const path = url.pathname || '';\n\n // If the user pointed at a specific endpoint, normalize back to the service root.\n url.pathname = path.replace(/\\/?workers\\/(trigger|config)\\/?$/, '');\n\n const basePath = url.pathname.replace(/\\/+$/, '');\n url.pathname = `${basePath}/workers/trigger`.replace(/\\/+$/, '');\n\n return url.toString();\n}\n\n/**\n * URL for the queue start endpoint (dispatch proxy). Use this so queue starts\n * go through the queue handler Lambda for easier debugging (one log stream per queue).\n */\nexport function getQueueStartUrl(queueId: string): string {\n const raw =\n process.env.WORKER_BASE_URL ||\n process.env.WORKERS_TRIGGER_API_URL ||\n process.env.WORKERS_CONFIG_API_URL;\n\n if (!raw) {\n throw new Error(\n 'WORKER_BASE_URL is required for background workers. Set it server-side only.'\n );\n }\n\n const url = new URL(raw);\n url.search = '';\n url.hash = '';\n\n const path = url.pathname || '';\n url.pathname = path.replace(/\\/?workers\\/(trigger|config)\\/?$/, '');\n const basePath = url.pathname.replace(/\\/+$/, '');\n const safeSegment = encodeURIComponent(queueId);\n url.pathname = `${basePath}/queues/${safeSegment}/start`.replace(/\\/+$/, '');\n\n return url.toString();\n}\n\n/**\n * Serializes context data for transmission to Lambda.\n * Only serializes safe, JSON-compatible properties.\n */\nfunction serializeContext(ctx: any): SerializedContext {\n const serialized: SerializedContext = {};\n\n if (ctx.requestId) {\n serialized.requestId = ctx.requestId;\n }\n\n // Extract any additional serializable metadata\n if (ctx.metadata && typeof ctx.metadata === 'object') {\n Object.assign(serialized, ctx.metadata);\n }\n\n // Allow custom context serialization via a helper property\n if (ctx._serializeContext && typeof ctx._serializeContext === 'function') {\n const custom = ctx._serializeContext();\n Object.assign(serialized, custom);\n }\n\n return serialized;\n}\n\n\n/**\n * Dispatches a background worker job to SQS.\n *\n * @param workerId - The ID of the worker to dispatch\n * @param input - The input data for the worker (will be validated against inputSchema)\n * @param inputSchema - Zod schema for input validation\n * @param options - Dispatch options including webhook URL\n * @param ctx - Optional context object (only serializable parts will be sent)\n * @returns Promise resolving to dispatch result with messageId and jobId\n */\nexport async function dispatch<INPUT_SCHEMA extends ZodType<any>>(\n workerId: string,\n input: z.input<INPUT_SCHEMA>,\n inputSchema: INPUT_SCHEMA,\n options: DispatchOptions,\n ctx?: any\n): Promise<DispatchResult> {\n // Validate input against schema\n const validatedInput = inputSchema.parse(input);\n\n // Generate job ID if not provided\n const jobId =\n options.jobId || `job-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n // Resolve /workers/trigger endpoint URL\n const triggerUrl = getWorkersTriggerUrl();\n\n // Serialize context (only safe, JSON-compatible parts)\n const serializedContext = ctx ? serializeContext(ctx) : {};\n\n // Job updates use MongoDB only; never pass jobStoreUrl/origin URL.\n const messageBody = {\n workerId,\n jobId,\n input: validatedInput,\n context: serializedContext,\n webhookUrl: options.webhookUrl,\n metadata: options.metadata || {},\n timestamp: new Date().toISOString(),\n };\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n const triggerKey = process.env.WORKERS_TRIGGER_API_KEY;\n if (triggerKey) {\n headers['x-workers-trigger-key'] = triggerKey;\n }\n\n const response = await fetch(triggerUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n workerId,\n body: messageBody,\n }),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Failed to trigger worker \"${workerId}\": ${response.status} ${response.statusText}${text ? ` - ${text}` : ''}`\n );\n }\n\n const data = (await response.json().catch(() => ({}))) as any;\n const messageId = data?.messageId ? String(data.messageId) : `trigger-${jobId}`;\n\n return {\n messageId,\n status: 'queued',\n jobId,\n };\n}\n\n/**\n * Dispatch a worker by ID without importing the worker module.\n * Sends to the workers trigger API (WORKER_BASE_URL). No input schema validation at call site.\n *\n * @param workerId - The worker ID (e.g. 'echo', 'data-processor')\n * @param input - Input payload (object or undefined)\n * @param options - Optional jobId, webhookUrl, metadata\n * @param ctx - Optional context (serializable parts sent in the request)\n * @returns Promise resolving to { messageId, status: 'queued', jobId }\n */\nexport async function dispatchWorker(\n workerId: string,\n input?: Record<string, unknown>,\n options: DispatchOptions = {},\n ctx?: any\n): Promise<DispatchResult> {\n const jobId =\n options.jobId || `job-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n const triggerUrl = getWorkersTriggerUrl();\n const serializedContext = ctx ? serializeContext(ctx) : {};\n const messageBody = {\n workerId,\n jobId,\n input: input ?? {},\n context: serializedContext,\n webhookUrl: options.webhookUrl,\n metadata: options.metadata || {},\n timestamp: new Date().toISOString(),\n };\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n const triggerKey = process.env.WORKERS_TRIGGER_API_KEY;\n if (triggerKey) headers['x-workers-trigger-key'] = triggerKey;\n const response = await fetch(triggerUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify({ workerId, body: messageBody }),\n });\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Failed to trigger worker \"${workerId}\": ${response.status} ${response.statusText}${text ? ` - ${text}` : ''}`\n );\n }\n const data = (await response.json().catch(() => ({}))) as any;\n const messageId = data?.messageId ? String(data.messageId) : `trigger-${jobId}`;\n return { messageId, status: 'queued', jobId };\n}\n\n/**\n * Local development mode: runs the handler immediately in the same process.\n * This bypasses SQS and Lambda for faster iteration during development.\n *\n * @param handler - The worker handler function\n * @param input - The input data\n * @param ctx - The context object\n * @returns The handler result\n */\nexport async function dispatchLocal<INPUT, OUTPUT>(\n handler: (params: { input: INPUT; ctx: any }) => Promise<OUTPUT>,\n input: INPUT,\n ctx?: any\n): Promise<OUTPUT> {\n return handler({ input, ctx: ctx || {} });\n}\n\n/**\n * Dispatches a queue by ID. POSTs to the queue-start API; the queue-start handler creates the queue job.\n * Pass the first worker's input directly (no registry required).\n */\nexport async function dispatchQueue<InitialInput = any>(\n queueId: string,\n initialInput?: InitialInput,\n options: DispatchOptions = {},\n _ctx?: any\n): Promise<DispatchQueueResult> {\n const jobId =\n options.jobId || `job-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n const queueStartUrl = getQueueStartUrl(queueId);\n const normalizedInput =\n initialInput !== null && typeof initialInput === 'object'\n ? (initialInput as Record<string, unknown>)\n : { value: initialInput };\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n const triggerKey = process.env.WORKERS_TRIGGER_API_KEY;\n if (triggerKey) headers['x-workers-trigger-key'] = triggerKey;\n const response = await fetch(queueStartUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify({\n input: normalizedInput,\n initialInput: normalizedInput,\n metadata: options.metadata ?? {},\n jobId,\n ...(options.webhookUrl ? { webhookUrl: options.webhookUrl } : {}),\n }),\n });\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Failed to start queue \"${queueId}\": ${response.status} ${response.statusText}${text ? ` - ${text}` : ''}`\n );\n }\n const data = (await response.json().catch(() => ({}))) as any;\n const messageId = data?.messageId ?? data?.jobId ?? `queue-${jobId}`;\n return { queueId, messageId, status: 'queued', jobId };\n}\n\n"],"mappings":";AAiFO,SAAS,uBAA+B;AAC7C,QAAM,MACJ,QAAQ,IAAI,mBACZ,QAAQ,IAAI,2BACZ,QAAQ,IAAI;AAEd,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,MAAM,IAAI,IAAI,GAAG;AACvB,MAAI,SAAS;AACb,MAAI,OAAO;AAEX,QAAM,OAAO,IAAI,YAAY;AAG7B,MAAI,WAAW,KAAK,QAAQ,oCAAoC,EAAE;AAElE,QAAM,WAAW,IAAI,SAAS,QAAQ,QAAQ,EAAE;AAChD,MAAI,WAAW,GAAG,QAAQ,mBAAmB,QAAQ,QAAQ,EAAE;AAE/D,SAAO,IAAI,SAAS;AACtB;AAMO,SAAS,iBAAiB,SAAyB;AACxD,QAAM,MACJ,QAAQ,IAAI,mBACZ,QAAQ,IAAI,2BACZ,QAAQ,IAAI;AAEd,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAEA,QAAM,MAAM,IAAI,IA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