agenttwin 0.3.28 → 0.3.30
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/README.md +12 -12
- package/dist/api.js +3328 -757
- package/dist/dashboard/assets/next/static/chunks/7796-dcf7d396bd4449c0.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-abd7b06b013b863e.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/about/page-f24aa0d77f7fa73c.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/account/password/page-5775ac3aa5e4562f.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/auth/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/blog/{layout-70bc4f31b68866ba.js → layout-c4d11b2d8403020d.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/compare/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/contact/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-039b7665231d6e02.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-651d698c70c4751d.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/demo/{page-9d65014623ef427a.js → page-823ab04e4ce3d98d.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/developers/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-257fb2b60b9c51ea.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/dpa/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/enterprise/{page-7e1eac02bcf83a2e.js → page-3b10665bd391180f.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/guides/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/layout-d5b27156a3186b08.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/login/page-b7e1d396e6b8f1e5.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/not-found-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-3a50aee18c830bd9.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/page-f8bd9dabf8d184f0.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/pricing/{page-f850766346c187ef.js → page-832b691ac0762fc1.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/privacy/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/security/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/signup/page-b7e1d396e6b8f1e5.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/status/{page-a9757d09bc1b44b8.js → page-7ce6f0e1c434b71e.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/terms/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/{layout-bc5e1f82967fb4ad.js → layout-3578b0057d2de8c7.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-7bb4b6860280b5cc.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/layout-fbf2197ee73a9b94.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-830a35428306a169.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-8f78f1d869d1c720.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/page-e538ea410a189bb5.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-830a35428306a169.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-4a176798090a08d6.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/{webpack-4bacefbda663942c.js → webpack-cf0b56829d9b93b8.js} +1 -1
- package/dist/dashboard/index.html +2 -2
- package/dist/engine.js +19611 -18250
- package/dist/gateway.js +3328 -757
- package/dist/worker.js +1694 -245
- package/dist/world-host.js +2928 -376
- package/package.json +1 -1
- package/dist/dashboard/assets/next/static/chunks/7796-fc89ddade1486b74.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-7e4cb85118372f1c.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/about/page-e200f2e2ee9de57c.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/account/password/page-4da5d90343fe147c.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/auth/page-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/compare/page-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/contact/page-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-5a5b80af0abc55f1.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-7abea2a754ac1e4b.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/developers/page-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-230de6cb268dc69a.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/dpa/page-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/guides/page-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/layout-d602b4869a6cbb05.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/login/page-a95c756e144a6331.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/not-found-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-351f0547ef1b26be.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/page-2ba5d9bd6c160bda.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/privacy/page-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/security/page-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/signup/page-a95c756e144a6331.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/terms/page-da1214e21c84a275.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-f3cab3a18644b226.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/layout-a32bac062bbc8f9f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-decb55bb59df2e0a.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-c854e517be15a4ac.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/page-778d815d61a3c9aa.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-decb55bb59df2e0a.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-da1214e21c84a275.js +0 -1
- /package/dist/dashboard/assets/next/static/{KYQHhyUSq0YJb83IAIjYO → c1e-XsXauzTgZ5LPHO9qr}/_buildManifest.js +0 -0
- /package/dist/dashboard/assets/next/static/{KYQHhyUSq0YJb83IAIjYO → c1e-XsXauzTgZ5LPHO9qr}/_ssgManifest.js +0 -0
package/dist/worker.js
CHANGED
|
@@ -341,19 +341,19 @@ var twinNowSeconds = (fallback) => Math.floor(twinNowMs(fallback * 1e3) / 1e3);
|
|
|
341
341
|
var twinClockEvidence = (clock) => clock ? { now: clock.now, scope: "twin-wall-clock" } : void 0;
|
|
342
342
|
|
|
343
343
|
// src/runtime/hosted-worker.ts
|
|
344
|
-
import { readFile as
|
|
345
|
-
import { promisify as
|
|
346
|
-
import { execFile as
|
|
347
|
-
import { spawn } from "child_process";
|
|
344
|
+
import { readFile as readFile3, chmod as chmod2, chown as chown2, realpath as realpath2, writeFile as writeFile5 } from "fs/promises";
|
|
345
|
+
import { promisify as promisify5 } from "util";
|
|
346
|
+
import { execFile as execFile5 } from "child_process";
|
|
347
|
+
import { spawn as spawn2 } from "child_process";
|
|
348
348
|
|
|
349
349
|
// src/runtime/http-world.ts
|
|
350
|
-
import { createServer } from "http";
|
|
350
|
+
import { createServer as createServer3 } from "http";
|
|
351
351
|
import { isDeepStrictEqual } from "util";
|
|
352
352
|
import { createHash as createHash5 } from "crypto";
|
|
353
353
|
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
354
354
|
|
|
355
355
|
// src/runtime/request-source.ts
|
|
356
|
-
import { mkdtemp as mkdtemp2, writeFile as writeFile2,
|
|
356
|
+
import { mkdtemp as mkdtemp2, writeFile as writeFile2, rm as rm2, realpath, open } from "fs/promises";
|
|
357
357
|
import { tmpdir as tmpdir2 } from "os";
|
|
358
358
|
import { join as join2, resolve } from "path";
|
|
359
359
|
function parseRequestSource(raw, spec) {
|
|
@@ -366,15 +366,60 @@ function parseRequestSource(raw, spec) {
|
|
|
366
366
|
return;
|
|
367
367
|
}
|
|
368
368
|
}
|
|
369
|
+
async function readBounded(path, limit = 4 * 1024 * 1024) {
|
|
370
|
+
const file = await open(path, "r");
|
|
371
|
+
try {
|
|
372
|
+
const size = Math.min((await file.stat()).size, limit);
|
|
373
|
+
const buffer = Buffer.alloc(size);
|
|
374
|
+
const { bytesRead } = await file.read(buffer, 0, size, 0);
|
|
375
|
+
const text2 = buffer.subarray(0, bytesRead).toString("utf8");
|
|
376
|
+
return bytesRead < limit ? text2 : text2.slice(0, text2.lastIndexOf("\n") + 1);
|
|
377
|
+
} finally {
|
|
378
|
+
await file.close();
|
|
379
|
+
}
|
|
380
|
+
}
|
|
369
381
|
async function createRequestSourceHook(app, spec, credentials, runtime) {
|
|
370
382
|
const dir = await mkdtemp2(join2(tmpdir2(), "agenttwin-source-hook-"));
|
|
371
383
|
const path = join2(dir, "hook.cjs");
|
|
372
384
|
const violationsPath = join2(dir, "blocked.jsonl");
|
|
373
385
|
const config = { root: runtime?.root ?? await realpath(resolve(app)), files: spec.files, origins: Object.values(credentials).map((c) => new URL(c.endpoint).origin), routes: Object.fromEntries((spec.fetchRoutes ?? []).map((r) => [r.origin, credentials[r.service]])), routing: !!spec.fetchRoutes, violationsFd: runtime?.violationsFd, stdioViolations: !!runtime?.stdioViolations, violationsPath: runtime?.violationsPath ?? violationsPath };
|
|
374
|
-
const
|
|
386
|
+
const guard = "const hookKey=Symbol.for('agenttwin.requestHook.v1');if(globalThis[hookKey])return;Object.defineProperty(globalThis,hookKey,{value:true});\n";
|
|
387
|
+
const hook = guard + applicationClockHook(spec.applicationClock) + `const config=${JSON.stringify(config)};
|
|
375
388
|
` + String.raw`
|
|
376
389
|
const http=require('node:http'),https=require('node:https'),path=require('node:path'),{fileURLToPath}=require('node:url');
|
|
377
390
|
const origins=new Set(config.origins),files=new Set(config.files);
|
|
391
|
+
// Violations go to the run's channel; a child process without the parent's descriptor appends to the shared file.
|
|
392
|
+
// A child's inherited descriptor numbers and stdout are not the run's channel, so children use the shared file.
|
|
393
|
+
const isChild=process.env.AGENTTWIN_HOOK_CHILD==='1';
|
|
394
|
+
const nodeFs=require('node:fs');
|
|
395
|
+
function writeViolation(violation){const line=JSON.stringify(violation)+'\n';if(isChild){try{nodeFs.appendFileSync(config.violationsPath,line);}catch{}return;}if(config.violationsFd!==undefined){nodeFs.writeSync(config.violationsFd,line);return;}if(config.stdioViolations){process.stdout.write('\n\x1eAGENTTWIN_FETCH_V1:'+JSON.stringify({kind:'violation',...violation})+'\n');return;}nodeFs.appendFileSync(config.violationsPath,line);}
|
|
396
|
+
// Child processes: Node descendants inherit this hook through NODE_OPTIONS, even when the app passes its own env.
|
|
397
|
+
// Any other executable runs outside the hook, so it is recorded and the run cannot be complete.
|
|
398
|
+
const childProcess=require('node:child_process');
|
|
399
|
+
const hookOption='--require '+JSON.stringify(__filename);
|
|
400
|
+
// Trust is decided from the file that would run, never its name: the Node binary itself, a script whose shebang runs
|
|
401
|
+
// that binary (node_modules/.bin CLIs, npm, npx), or esbuild's own binary inside its package. Results are cached per real path and PATH.
|
|
402
|
+
const executableTrust=new Map();
|
|
403
|
+
let nodeReal;try{nodeReal=nodeFs.realpathSync(process.execPath);}catch{nodeReal=process.execPath;}
|
|
404
|
+
function envPath(env){if(process.platform!=='win32')return env.PATH;const key=Object.keys(env).find(k=>k.toUpperCase()==='PATH');return key&&env[key];}
|
|
405
|
+
function spawnCwd(options){const cwd=options&&options.cwd;if(!cwd)return process.cwd();return path.resolve(process.cwd(),cwd instanceof URL?fileURLToPath(cwd):String(cwd));}
|
|
406
|
+
function isRunnable(file){try{const stat=nodeFs.statSync(file);if(!stat.isFile())return false;if(process.platform!=='win32')nodeFs.accessSync(file,nodeFs.constants.X_OK);return true;}catch{return false;}}
|
|
407
|
+
// Resolves a command the way spawn does: paths against cwd, bare names through the child's PATH.
|
|
408
|
+
function resolveCommand(command,options){const cwd=spawnCwd(options);if(/[\/\\]/.test(command))return path.resolve(cwd,command);const env=(options&&options.env)||process.env;const exts=process.platform==='win32'?['',...String(env.PATHEXT||'.EXE;.CMD;.BAT').split(';').filter(Boolean)]:[''];for(const dir of String(envPath(env)||'').split(path.delimiter)){if(!dir)continue;for(const ext of exts){const candidate=path.resolve(cwd,dir,command+ext);if(isRunnable(candidate))return candidate;}}}
|
|
409
|
+
function runsHookedNode(interpreter,options){const file=resolveCommand(interpreter,options);if(!file)return false;try{return nodeFs.realpathSync(file)===nodeReal;}catch{return false;}}
|
|
410
|
+
// '#!/path/to/node', '#!/usr/bin/env node' and '#!/usr/bin/env -S node --flags' run Node; anything else does not.
|
|
411
|
+
function nodeShebang(head,options){if(!head.startsWith('#!'))return false;const tokens=head.slice(2).split('\n')[0].replace(/\r$/,'').trim().split(/[ \t]+/).filter(Boolean);if(!tokens.length)return false;let program=tokens[0];if(path.basename(program)==='env'){program=tokens.slice(1).find(t=>!t.startsWith('-')&&!/^[A-Za-z_][A-Za-z0-9_]*=/.test(t));if(!program)return false;}else if(!path.isAbsolute(program))return false;return runsHookedNode(program,options);}
|
|
412
|
+
function esbuildBinary(real){const match=real.match(/^(.*[\/\\]node_modules[\/\\](?:esbuild|@esbuild[\/\\][^\/\\]+))(?:[\/\\]bin)?[\/\\]esbuild(?:\.exe)?$/);if(!match)return false;try{const name=JSON.parse(nodeFs.readFileSync(path.join(match[1],'package.json'),'utf8')).name;return name==='esbuild'||(typeof name==='string'&&name.startsWith('@esbuild/'));}catch{return false;}}
|
|
413
|
+
function trustedExecutable(file,options){const real=nodeFs.realpathSync(file);const key=real+'\0'+String(envPath((options&&options.env)||process.env)||'');if(executableTrust.has(key))return executableTrust.get(key);let trusted=real===nodeReal||esbuildBinary(real);if(!trusted&&isRunnable(real)){const fd=nodeFs.openSync(real,'r');try{const head=Buffer.alloc(256);const read=nodeFs.readSync(fd,head,0,256,0);trusted=nodeShebang(head.subarray(0,read).toString('latin1'),options);}finally{nodeFs.closeSync(fd);}}if(executableTrust.size<1000)executableTrust.set(key,trusted);return trusted;}
|
|
414
|
+
const reportedSubprocesses=new Set();
|
|
415
|
+
function hookedEnv(options){const env={...((options&&options.env)||process.env)};const current=env.NODE_OPTIONS||'';if(!current.includes(__filename))env.NODE_OPTIONS=(current+' '+hookOption).trim();env.AGENTTWIN_HOOK_CHILD='1';return {...(options||{}),env};}
|
|
416
|
+
// Never throws: an unclassifiable command is reported, and the application's spawn proceeds unchanged.
|
|
417
|
+
// Shell commands are judged by their first word, so 'sh -c' style wrappers are reported as non-Node.
|
|
418
|
+
function checkExecutable(command,shell,options){let name='unknown',trusted=false;try{const text=String(command).trim();const first=(shell?(text.split(/\s+/).find(token=>!/^[A-Za-z_][A-Za-z0-9_]*=/.test(token))||''):text).replace(/^["']|["']$/g,'');name=path.basename(first).replace(/\.(exe|cmd)$/i,'')||'unknown';if(reportedSubprocesses.has(name)||reportedSubprocesses.size>=100)return;const file=first&&resolveCommand(first,options);trusted=!!file&&trustedExecutable(file,options);}catch{trusted=false;}if(trusted||reportedSubprocesses.has(name)||reportedSubprocesses.size>=100)return;reportedSubprocesses.add(name);try{writeViolation({origin:('subprocess:'+name).slice(0,2048),reason:'unhooked-subprocess'});}catch{}}
|
|
419
|
+
// Puts the hooked env into the options argument at index i, inserting an options object when there is none.
|
|
420
|
+
function withOptions(args,i){const out=[...args];const o=out[i];if(o&&typeof o==='object'&&!Array.isArray(o))out[i]=hookedEnv(o);else out.splice(Math.min(i,out.length),o==null&&i<out.length?1:0,hookedEnv({}));return out;}
|
|
421
|
+
for(const name of ['spawn','spawnSync','execFile','execFileSync','fork']){const original=childProcess[name];if(typeof original!=='function')continue;childProcess[name]=function(file,...rest){const optionsAt=Array.isArray(rest[0])||(rest[0]==null&&rest.length>1)?2:1;const patched=withOptions([file,...rest],optionsAt);if(name!=='fork')checkExecutable(file,!!patched[optionsAt].shell,patched[optionsAt]);return original.apply(this,patched);};}
|
|
422
|
+
for(const name of ['exec','execSync']){const original=childProcess[name];if(typeof original!=='function')continue;childProcess[name]=function(command,...rest){const patched=withOptions([command,...rest],1);checkExecutable(command,true,patched[1]);return original.apply(this,patched);};}
|
|
378
423
|
function source(){for(const frame of new Error().stack.split('\n').slice(2)){const match=frame.match(/(?:\(|\s)(file:\/\/[^\s)]+|\/[^\s)]+):(\d+):(\d+)\)?$/);if(!match)continue;let file;try{file=match[1].startsWith('file:')?fileURLToPath(match[1]):match[1];}catch{continue;}file=path.relative(config.root,file);if(files.has(file))return JSON.stringify({file,line:Number(match[2]),column:Number(match[3])});}}
|
|
379
424
|
const blockedOrigins=new Set();
|
|
380
425
|
const originalFetch=globalThis.fetch;
|
|
@@ -382,7 +427,7 @@ if(originalFetch)globalThis.fetch=async function(input,init){
|
|
|
382
427
|
let url;try{url=new URL(typeof input==='string'||input instanceof URL?input:input.url);}catch{throw new Error('AgentTwin fetch requires an absolute URL');}
|
|
383
428
|
const route=Object.hasOwn(config.routes,url.origin)?config.routes[url.origin]:undefined;
|
|
384
429
|
if(config.routing&&!route&&!origins.has(url.origin)){
|
|
385
|
-
if(!blockedOrigins.has(url.origin)&&blockedOrigins.size<100){blockedOrigins.add(url.origin);
|
|
430
|
+
if(!blockedOrigins.has(url.origin)&&blockedOrigins.size<100){blockedOrigins.add(url.origin);writeViolation({origin:url.origin.slice(0,2048),reason:'unmapped-fetch-origin'});}
|
|
386
431
|
throw new Error('AgentTwin blocked fetch to an unmapped origin: '+url.origin);
|
|
387
432
|
}
|
|
388
433
|
if(!route&&!origins.has(url.origin))return originalFetch(input,init);
|
|
@@ -392,11 +437,13 @@ if(originalFetch)globalThis.fetch=async function(input,init){
|
|
|
392
437
|
if(route){headers.delete('cookie');headers.delete('proxy-authorization');headers.set('authorization','Bearer '+route.token);}
|
|
393
438
|
const location=source();if(location)headers.set('x-agenttwin-source',location);
|
|
394
439
|
const target=route?route.endpoint+url.pathname+url.search:url.href;
|
|
395
|
-
|
|
440
|
+
// Forward the body as bytes: copying a keepalive Request whose body is a stream throws in Node's fetch.
|
|
441
|
+
const body=request.method==='GET'||request.method==='HEAD'?undefined:await request.arrayBuffer();
|
|
442
|
+
return originalFetch(target,{method:request.method,headers,body,signal:request.signal,redirect:'error'});
|
|
396
443
|
};
|
|
397
444
|
const plainHttp={request:http.request,get:http.get};
|
|
398
445
|
const loopback=host=>['127.0.0.1','localhost','::1','[::1]'].includes(host);
|
|
399
|
-
function blockNode(origin){if(!blockedOrigins.has(origin)&&blockedOrigins.size<100){blockedOrigins.add(origin);
|
|
446
|
+
function blockNode(origin){if(!blockedOrigins.has(origin)&&blockedOrigins.size<100){blockedOrigins.add(origin);writeViolation({origin:origin.slice(0,2048),reason:'unmapped-http-origin'});}throw new Error('AgentTwin blocked a request to an unmapped origin: '+origin);}
|
|
400
447
|
// SDKs on node:http/https (Stripe, Slack via axios) reach mapped vendor origins only through their twin.
|
|
401
448
|
function routeNode(method,route,url,options,index,args){
|
|
402
449
|
const target=new URL(route.endpoint),headers={};
|
|
@@ -422,7 +469,13 @@ require('node:module').syncBuiltinESMExports();
|
|
|
422
469
|
await writeFile2(path, hook, { mode: 384 });
|
|
423
470
|
return { path, violationsPath, readViolations: async () => {
|
|
424
471
|
try {
|
|
425
|
-
|
|
472
|
+
const seen = /* @__PURE__ */ new Set();
|
|
473
|
+
return (await readBounded(violationsPath)).trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)).filter((v) => {
|
|
474
|
+
const key2 = v.reason + " " + v.origin;
|
|
475
|
+
if (seen.has(key2)) return false;
|
|
476
|
+
seen.add(key2);
|
|
477
|
+
return true;
|
|
478
|
+
});
|
|
426
479
|
} catch (error) {
|
|
427
480
|
if (error.code === "ENOENT") return [];
|
|
428
481
|
throw error;
|
|
@@ -624,10 +677,10 @@ function parsedInput(value) {
|
|
|
624
677
|
}
|
|
625
678
|
var arg = (value) => typeof value === "string" ? value : JSON.stringify(value ?? {});
|
|
626
679
|
var SSE = { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache" };
|
|
627
|
-
var pieces = (
|
|
680
|
+
var pieces = (text2) => {
|
|
628
681
|
const out = [];
|
|
629
|
-
const size = Math.max(1, Math.ceil(
|
|
630
|
-
for (let i = 0; i <
|
|
682
|
+
const size = Math.max(1, Math.ceil(text2.length / 3));
|
|
683
|
+
for (let i = 0; i < text2.length; i += size) out.push(text2.slice(i, i + size));
|
|
631
684
|
return out.length ? out : [""];
|
|
632
685
|
};
|
|
633
686
|
var frame = (data, event) => `${event ? `event: ${event}
|
|
@@ -656,11 +709,11 @@ function responsesStream(body) {
|
|
|
656
709
|
let out = ev("response.created", { response: pending }) + ev("response.in_progress", { response: pending });
|
|
657
710
|
body.output.forEach((item, output_index) => {
|
|
658
711
|
if (item.type === "message") {
|
|
659
|
-
const
|
|
712
|
+
const text2 = item.content[0]?.text ?? "";
|
|
660
713
|
out += ev("response.output_item.added", { output_index, item: { ...item, status: "in_progress", content: [] } });
|
|
661
714
|
out += ev("response.content_part.added", { item_id: item.id, output_index, content_index: 0, part: { type: "output_text", text: "", annotations: [] } });
|
|
662
|
-
for (const delta of pieces(
|
|
663
|
-
out += ev("response.output_text.done", { item_id: item.id, output_index, content_index: 0, text, logprobs: [] });
|
|
715
|
+
for (const delta of pieces(text2)) out += ev("response.output_text.delta", { item_id: item.id, output_index, content_index: 0, delta, logprobs: [] });
|
|
716
|
+
out += ev("response.output_text.done", { item_id: item.id, output_index, content_index: 0, text: text2, logprobs: [] });
|
|
664
717
|
out += ev("response.content_part.done", { item_id: item.id, output_index, content_index: 0, part: item.content[0] });
|
|
665
718
|
} else {
|
|
666
719
|
out += ev("response.output_item.added", { output_index, item: { ...item, arguments: "", status: "in_progress" } });
|
|
@@ -677,7 +730,7 @@ function anthropicStream(body) {
|
|
|
677
730
|
body.content.forEach((block, index) => {
|
|
678
731
|
if (block.type === "text") {
|
|
679
732
|
out += ev("content_block_start", { index, content_block: { type: "text", text: "" } });
|
|
680
|
-
for (const
|
|
733
|
+
for (const text2 of pieces(block.text)) out += ev("content_block_delta", { index, delta: { type: "text_delta", text: text2 } });
|
|
681
734
|
} else {
|
|
682
735
|
out += ev("content_block_start", { index, content_block: { type: "tool_use", id: block.id, name: block.name, input: {} } });
|
|
683
736
|
for (const partial_json of pieces(JSON.stringify(block.input ?? {}))) out += ev("content_block_delta", { index, delta: { type: "input_json_delta", partial_json } });
|
|
@@ -813,9 +866,9 @@ var composioOperation = (method, path, params, _headers, data, sequence) => {
|
|
|
813
866
|
for (const [left, right] of [["to", "recipient_email"], ["body", "message"], ["threadId", "thread_id"]]) if (args[left] !== void 0 && args[right] !== void 0 && args[left] !== args[right]) return error(400, "Conflicting message aliases");
|
|
814
867
|
const to = args.to ?? args.recipient_email, body = args.body ?? args.message, threadId = args.threadId ?? args.thread_id;
|
|
815
868
|
if (typeof to !== "string" || !to || typeof args.subject !== "string" || typeof body !== "string" || threadId !== void 0 && typeof threadId !== "string") return error(400, "Message fields required");
|
|
816
|
-
const id = "composio_message_" + sequence,
|
|
817
|
-
data["/messages"].push(
|
|
818
|
-
return { status: 200, collection: "/messages", operation: "write", record:
|
|
869
|
+
const id = "composio_message_" + sequence, record3 = { id, to, subject: args.subject, body, user_id: params.user_id, connected_account_id: selected.id, ...threadId === void 0 ? {} : { threadId } };
|
|
870
|
+
data["/messages"].push(record3);
|
|
871
|
+
return { status: 200, collection: "/messages", operation: "write", record: record3, body: { successful: true, error: null, data: { id, messageId: id }, log_id: "synthetic-log-" + sequence } };
|
|
819
872
|
};
|
|
820
873
|
|
|
821
874
|
// src/runtime/rest-adapters.ts
|
|
@@ -837,11 +890,802 @@ var googleOAuthOperation = (method, path, params, headers, data, sequence) => {
|
|
|
837
890
|
if (typeof grant.scope !== "string" || !grant.scope || !Number.isInteger(grant.expires_in) || Number(grant.expires_in) < 1 || Number(grant.expires_in) > 86400) return;
|
|
838
891
|
const access_token = "synthetic-access-" + createHash("sha256").update(JSON.stringify([params.client_id, params.refresh_token, sequence])).digest("hex").slice(0, 24);
|
|
839
892
|
const body = { access_token, token_type: "Bearer", expires_in: grant.expires_in, scope: grant.scope };
|
|
840
|
-
const
|
|
841
|
-
data["/tokens"].push(
|
|
842
|
-
return { status: 200, collection: "/tokens", body, record:
|
|
893
|
+
const record3 = { id: "issuance_" + sequence, client_id: params.client_id, ...body };
|
|
894
|
+
data["/tokens"].push(record3);
|
|
895
|
+
return { status: 200, collection: "/tokens", body, record: record3, operation: "write" };
|
|
896
|
+
};
|
|
897
|
+
|
|
898
|
+
// src/runtime/engines/redis.ts
|
|
899
|
+
import { createServer as createServer2, connect as connect2 } from "net";
|
|
900
|
+
import { spawn } from "child_process";
|
|
901
|
+
import { mkdtemp as mkdtemp3, rm as rm3 } from "fs/promises";
|
|
902
|
+
import { tmpdir as tmpdir3 } from "os";
|
|
903
|
+
import { join as join4 } from "path";
|
|
904
|
+
|
|
905
|
+
// src/runtime/engines/resp.ts
|
|
906
|
+
import { connect } from "net";
|
|
907
|
+
var CRLF = Buffer.from("\r\n");
|
|
908
|
+
function parseResp(buf, at = 0, inline = false) {
|
|
909
|
+
if (at >= buf.length) return;
|
|
910
|
+
const line = buf.indexOf(CRLF, at);
|
|
911
|
+
if (line < 0) return;
|
|
912
|
+
const prefix = String.fromCharCode(buf[at]), text2 = buf.toString("utf8", at + 1, line), next = line + 2;
|
|
913
|
+
switch (prefix) {
|
|
914
|
+
case "+":
|
|
915
|
+
return { value: { simple: text2 }, end: next };
|
|
916
|
+
case "-":
|
|
917
|
+
return { value: { error: text2 }, end: next };
|
|
918
|
+
case ":":
|
|
919
|
+
case "(":
|
|
920
|
+
return { value: Number(text2), end: next };
|
|
921
|
+
case ",":
|
|
922
|
+
return { value: { simple: text2 }, end: next };
|
|
923
|
+
case "#":
|
|
924
|
+
return { value: text2 === "t", end: next };
|
|
925
|
+
case "_":
|
|
926
|
+
return { value: null, end: next };
|
|
927
|
+
case "$":
|
|
928
|
+
case "!":
|
|
929
|
+
case "=": {
|
|
930
|
+
const n = Number(text2);
|
|
931
|
+
if (n < 0) return { value: null, end: next };
|
|
932
|
+
if (buf.length < next + n + 2) return;
|
|
933
|
+
const data = Buffer.from(buf.subarray(next, next + n));
|
|
934
|
+
return { value: prefix === "!" ? { error: data.toString() } : data, end: next + n + 2 };
|
|
935
|
+
}
|
|
936
|
+
case "*":
|
|
937
|
+
case "~":
|
|
938
|
+
case ">":
|
|
939
|
+
case "%":
|
|
940
|
+
case "|": {
|
|
941
|
+
const n = Number(text2);
|
|
942
|
+
if (n < 0) return { value: null, end: next };
|
|
943
|
+
const count = prefix === "%" || prefix === "|" ? n * 2 : n;
|
|
944
|
+
const items = [];
|
|
945
|
+
let end = next;
|
|
946
|
+
for (let i = 0; i < count; i++) {
|
|
947
|
+
const item = parseResp(buf, end);
|
|
948
|
+
if (!item) return;
|
|
949
|
+
items.push(item.value);
|
|
950
|
+
end = item.end;
|
|
951
|
+
}
|
|
952
|
+
if (prefix === "|") {
|
|
953
|
+
const value = parseResp(buf, end);
|
|
954
|
+
return value && { value: value.value, end: value.end };
|
|
955
|
+
}
|
|
956
|
+
return { value: items, end };
|
|
957
|
+
}
|
|
958
|
+
default:
|
|
959
|
+
if (!inline) throw new Error(`Invalid RESP prefix ${JSON.stringify(prefix)}`);
|
|
960
|
+
return { value: buf.toString("utf8", at, line).trim().split(/\s+/).filter(Boolean).map((s) => Buffer.from(s)), end: next };
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
var encode = {
|
|
964
|
+
simple: (s) => Buffer.from(`+${s}\r
|
|
965
|
+
`),
|
|
966
|
+
error: (s) => Buffer.from(`-${s.replace(/[\r\n]+/g, " ")}\r
|
|
967
|
+
`),
|
|
968
|
+
int: (n) => Buffer.from(`:${Math.trunc(n)}\r
|
|
969
|
+
`),
|
|
970
|
+
bulk: (v) => v === null || v === void 0 ? Buffer.from("$-1\r\n") : (() => {
|
|
971
|
+
const b = typeof v === "string" ? Buffer.from(v, "latin1") : v;
|
|
972
|
+
return Buffer.concat([Buffer.from(`$${b.length}\r
|
|
973
|
+
`), b, CRLF]);
|
|
974
|
+
})(),
|
|
975
|
+
array: (items) => items === null ? Buffer.from("*-1\r\n") : Buffer.concat([Buffer.from(`*${items.length}\r
|
|
976
|
+
`), ...items]),
|
|
977
|
+
command: (args) => Buffer.concat([Buffer.from(`*${args.length}\r
|
|
978
|
+
`), ...args.map((a) => {
|
|
979
|
+
const b = Buffer.isBuffer(a) ? a : Buffer.from(String(a));
|
|
980
|
+
return Buffer.concat([Buffer.from(`$${b.length}\r
|
|
981
|
+
`), b, CRLF]);
|
|
982
|
+
})])
|
|
843
983
|
};
|
|
844
984
|
|
|
985
|
+
// src/runtime/engines/types.ts
|
|
986
|
+
var POSTGRES_EXTENSIONS = ["uuid-ossp", "btree_gist", "btree_gin", "citext", "pg_trgm", "hstore", "ltree", "cube", "earthdistance", "fuzzystrmatch", "tablefunc", "isn", "lo", "seg", "tcn", "unaccent", "bloom", "intarray", "pgcrypto"];
|
|
987
|
+
|
|
988
|
+
// src/runtime/engines/host.ts
|
|
989
|
+
import { execFile as execFile4 } from "child_process";
|
|
990
|
+
import { access, constants } from "fs/promises";
|
|
991
|
+
import { createServer } from "net";
|
|
992
|
+
import { delimiter, join as join3 } from "path";
|
|
993
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
994
|
+
import { promisify as promisify4 } from "util";
|
|
995
|
+
var exec4 = promisify4(execFile4);
|
|
996
|
+
|
|
997
|
+
// src/runtime/engines/redis.ts
|
|
998
|
+
var WRITES = new Set("set setnx setex psetex getset getdel getex mset msetnx incr incrby incrbyfloat decr decrby append setrange del unlink expire pexpire expireat pexpireat persist rename renamenx copy move hset hsetnx hmset hdel hincrby hincrbyfloat lpush rpush lpushx rpushx lpop rpop lset lrem ltrim linsert lmove rpoplpush blpop brpop sadd srem spop smove zadd zrem zincrby zpopmin zpopmax zremrangebyscore zremrangebyrank xadd xdel xtrim flushdb flushall restore eval evalsha pfadd setbit geoadd json.set json.del".split(" "));
|
|
999
|
+
var MULTI_KEY = /* @__PURE__ */ new Set(["del", "unlink", "exists", "mget", "watch", "touch", "sinter", "sunion", "sdiff"]);
|
|
1000
|
+
function commandKeys(name, args) {
|
|
1001
|
+
if (name === "mset" || name === "msetnx") return args.filter((_, i) => i % 2 === 0);
|
|
1002
|
+
if (MULTI_KEY.has(name)) return args;
|
|
1003
|
+
if (name === "rename" || name === "renamenx" || name === "copy" || name === "lmove" || name === "rpoplpush" || name === "smove") return args.slice(0, 2);
|
|
1004
|
+
if (name === "eval" || name === "evalsha") {
|
|
1005
|
+
const n = Number(args[1]);
|
|
1006
|
+
return Number.isInteger(n) ? args.slice(2, 2 + n) : [];
|
|
1007
|
+
}
|
|
1008
|
+
if (["ping", "echo", "info", "select", "auth", "hello", "client", "command", "config", "multi", "exec", "discard", "quit", "dbsize", "flushdb", "flushall", "time", "scan", "keys", "unwatch", "readonly", "memory", "script", "publish", "subscribe", "psubscribe"].includes(name)) return [];
|
|
1009
|
+
return args.length ? [args[0]] : [];
|
|
1010
|
+
}
|
|
1011
|
+
var WRONGTYPE = "WRONGTYPE Operation against a key holding the wrong kind of value";
|
|
1012
|
+
var NOT_INT = "ERR value is not an integer or out of range";
|
|
1013
|
+
var glob = (pattern) => new RegExp("^" + pattern.replace(/[.+^${}()|\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".") + "$", "s");
|
|
1014
|
+
var fmt = (n) => Number.isInteger(n) ? String(n) : String(Number(n.toPrecision(17)));
|
|
1015
|
+
var InProcessRedis = class {
|
|
1016
|
+
data = /* @__PURE__ */ new Map();
|
|
1017
|
+
versions = /* @__PURE__ */ new Map();
|
|
1018
|
+
unsupported = [];
|
|
1019
|
+
server;
|
|
1020
|
+
live(key2) {
|
|
1021
|
+
const e = this.data.get(key2);
|
|
1022
|
+
if (e?.expireAt !== void 0 && e.expireAt <= Date.now()) {
|
|
1023
|
+
this.data.delete(key2);
|
|
1024
|
+
return void 0;
|
|
1025
|
+
}
|
|
1026
|
+
return e;
|
|
1027
|
+
}
|
|
1028
|
+
touch(key2) {
|
|
1029
|
+
this.versions.set(key2, (this.versions.get(key2) ?? 0) + 1);
|
|
1030
|
+
}
|
|
1031
|
+
typed(key2, type, create) {
|
|
1032
|
+
const e = this.live(key2);
|
|
1033
|
+
if (e) {
|
|
1034
|
+
if (e.type !== type) throw new Error(WRONGTYPE);
|
|
1035
|
+
return e.value;
|
|
1036
|
+
}
|
|
1037
|
+
const value = create();
|
|
1038
|
+
this.data.set(key2, { type, value });
|
|
1039
|
+
return value;
|
|
1040
|
+
}
|
|
1041
|
+
get(key2, type) {
|
|
1042
|
+
const e = this.live(key2);
|
|
1043
|
+
if (!e) return void 0;
|
|
1044
|
+
if (e.type !== type) throw new Error(WRONGTYPE);
|
|
1045
|
+
return e.value;
|
|
1046
|
+
}
|
|
1047
|
+
clean(key2) {
|
|
1048
|
+
const e = this.data.get(key2);
|
|
1049
|
+
if (!e) return;
|
|
1050
|
+
const v = e.value;
|
|
1051
|
+
if ((v instanceof Map || v instanceof Set) && !v.size || Array.isArray(v) && !v.length) this.data.delete(key2);
|
|
1052
|
+
}
|
|
1053
|
+
async start() {
|
|
1054
|
+
this.server = createServer2((s) => this.accept(s));
|
|
1055
|
+
await new Promise((resolve3, reject) => {
|
|
1056
|
+
this.server.once("error", reject);
|
|
1057
|
+
this.server.listen(0, "127.0.0.1", resolve3);
|
|
1058
|
+
});
|
|
1059
|
+
return this.server.address().port;
|
|
1060
|
+
}
|
|
1061
|
+
async stop() {
|
|
1062
|
+
if (this.server) await new Promise((resolve3) => this.server.close(() => resolve3()));
|
|
1063
|
+
}
|
|
1064
|
+
accept(socket) {
|
|
1065
|
+
let buffer = Buffer.alloc(0);
|
|
1066
|
+
const session = { watched: /* @__PURE__ */ new Map(), dirty: false };
|
|
1067
|
+
socket.on("error", () => {
|
|
1068
|
+
});
|
|
1069
|
+
socket.on("data", (chunk) => {
|
|
1070
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
1071
|
+
const out = [];
|
|
1072
|
+
try {
|
|
1073
|
+
for (; ; ) {
|
|
1074
|
+
const frame2 = parseResp(buffer, 0, true);
|
|
1075
|
+
if (!frame2) break;
|
|
1076
|
+
buffer = buffer.subarray(frame2.end);
|
|
1077
|
+
const args = frame2.value.map((b) => b.toString("latin1"));
|
|
1078
|
+
if (!args.length) continue;
|
|
1079
|
+
if (args[0].toLowerCase() === "quit") {
|
|
1080
|
+
out.push(encode.simple("OK"));
|
|
1081
|
+
socket.end(Buffer.concat(out));
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1084
|
+
out.push(this.dispatch(args, session));
|
|
1085
|
+
}
|
|
1086
|
+
} catch {
|
|
1087
|
+
out.push(encode.error("ERR Protocol error"));
|
|
1088
|
+
socket.end(Buffer.concat(out));
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
if (out.length) socket.write(Buffer.concat(out));
|
|
1092
|
+
});
|
|
1093
|
+
}
|
|
1094
|
+
dispatch(args, session) {
|
|
1095
|
+
const name = args[0].toLowerCase();
|
|
1096
|
+
if (session.multi && !["exec", "discard", "multi", "watch"].includes(name)) {
|
|
1097
|
+
session.multi.push(args);
|
|
1098
|
+
return encode.simple("QUEUED");
|
|
1099
|
+
}
|
|
1100
|
+
if (name === "multi") {
|
|
1101
|
+
if (session.multi) return encode.error("ERR MULTI calls can not be nested");
|
|
1102
|
+
session.multi = [];
|
|
1103
|
+
return encode.simple("OK");
|
|
1104
|
+
}
|
|
1105
|
+
if (name === "discard") {
|
|
1106
|
+
if (!session.multi) return encode.error("ERR DISCARD without MULTI");
|
|
1107
|
+
session.multi = void 0;
|
|
1108
|
+
session.watched.clear();
|
|
1109
|
+
return encode.simple("OK");
|
|
1110
|
+
}
|
|
1111
|
+
if (name === "watch") {
|
|
1112
|
+
for (const k of args.slice(1)) session.watched.set(k, this.versions.get(k) ?? 0);
|
|
1113
|
+
return encode.simple("OK");
|
|
1114
|
+
}
|
|
1115
|
+
if (name === "unwatch") {
|
|
1116
|
+
session.watched.clear();
|
|
1117
|
+
return encode.simple("OK");
|
|
1118
|
+
}
|
|
1119
|
+
if (name === "exec") {
|
|
1120
|
+
if (!session.multi) return encode.error("ERR EXEC without MULTI");
|
|
1121
|
+
const queued = session.multi;
|
|
1122
|
+
session.multi = void 0;
|
|
1123
|
+
const conflict = [...session.watched].some(([k, v]) => (this.versions.get(k) ?? 0) !== v);
|
|
1124
|
+
session.watched.clear();
|
|
1125
|
+
if (conflict) return encode.array(null);
|
|
1126
|
+
return encode.array(queued.map((cmd) => this.run(cmd)));
|
|
1127
|
+
}
|
|
1128
|
+
return this.run(args);
|
|
1129
|
+
}
|
|
1130
|
+
run(args) {
|
|
1131
|
+
const name = args[0].toLowerCase(), a = args.slice(1);
|
|
1132
|
+
try {
|
|
1133
|
+
const reply = this.command(name, a);
|
|
1134
|
+
if (WRITES.has(name)) for (const k of commandKeys(name, a)) this.touch(k);
|
|
1135
|
+
return reply;
|
|
1136
|
+
} catch (error) {
|
|
1137
|
+
return encode.error(error instanceof Error ? error.message : String(error));
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
int(s) {
|
|
1141
|
+
if (s === void 0 || !/^-?\d+$/.test(s)) throw new Error(NOT_INT);
|
|
1142
|
+
return Number(s);
|
|
1143
|
+
}
|
|
1144
|
+
command(name, a) {
|
|
1145
|
+
const now = Date.now(), ok2 = encode.simple("OK"), key2 = a[0];
|
|
1146
|
+
const str2 = (k) => this.get(k, "string");
|
|
1147
|
+
const bulks = (list2) => encode.array(list2.map((v) => encode.bulk(v ?? null)));
|
|
1148
|
+
const setString = (k, v, expireAt) => this.data.set(k, { type: "string", value: v, ...expireAt !== void 0 ? { expireAt } : {} });
|
|
1149
|
+
const incr = (k, by) => {
|
|
1150
|
+
const cur = str2(k) ?? "0";
|
|
1151
|
+
if (!/^-?\d+$/.test(cur)) throw new Error(NOT_INT);
|
|
1152
|
+
const n = Number(cur) + by;
|
|
1153
|
+
const e = this.live(k);
|
|
1154
|
+
setString(k, String(n), e?.expireAt);
|
|
1155
|
+
return encode.int(n);
|
|
1156
|
+
};
|
|
1157
|
+
const range = (len, start, stop) => {
|
|
1158
|
+
if (start < 0) start = Math.max(0, len + start);
|
|
1159
|
+
if (stop < 0) stop = len + stop;
|
|
1160
|
+
stop = Math.min(stop, len - 1);
|
|
1161
|
+
return [start, stop];
|
|
1162
|
+
};
|
|
1163
|
+
switch (name) {
|
|
1164
|
+
case "ping":
|
|
1165
|
+
return a.length ? encode.bulk(a[0]) : encode.simple("PONG");
|
|
1166
|
+
case "echo":
|
|
1167
|
+
return encode.bulk(a[0]);
|
|
1168
|
+
case "select":
|
|
1169
|
+
return a[0] === "0" ? ok2 : encode.error("ERR DB index is out of range (AgentTwin serves database 0)");
|
|
1170
|
+
case "auth":
|
|
1171
|
+
case "readonly":
|
|
1172
|
+
return ok2;
|
|
1173
|
+
case "client": {
|
|
1174
|
+
const sub = (a[0] ?? "").toLowerCase();
|
|
1175
|
+
return sub === "getname" ? encode.bulk(null) : sub === "id" ? encode.int(1) : sub === "list" || sub === "info" ? encode.bulk("id=1 addr=127.0.0.1 name= db=0\n") : ok2;
|
|
1176
|
+
}
|
|
1177
|
+
case "hello": {
|
|
1178
|
+
if (a[0] && a[0] !== "2") return encode.error("NOPROTO this AgentTwin Redis engine speaks RESP2 only");
|
|
1179
|
+
return encode.array(["server", "redis", "version", "7.2.0", "proto", "2", "id", "1", "mode", "standalone", "role", "master"].map((s) => s === "2" || s === "1" ? encode.int(Number(s)) : encode.bulk(s)).concat(encode.bulk("modules"), encode.array([])));
|
|
1180
|
+
}
|
|
1181
|
+
case "info":
|
|
1182
|
+
return encode.bulk("# Server\r\nredis_version:7.2.0\r\nredis_mode:standalone\r\nagenttwin_engine:in-process\r\n# Persistence\r\nloading:0\r\n# Replication\r\nrole:master\r\n# Keyspace\r\n" + (this.data.size ? `db0:keys=${this.data.size},expires=0\r
|
|
1183
|
+
` : ""));
|
|
1184
|
+
case "command":
|
|
1185
|
+
return encode.array([]);
|
|
1186
|
+
case "config":
|
|
1187
|
+
return (a[0] ?? "").toLowerCase() === "get" ? encode.array([]) : ok2;
|
|
1188
|
+
case "time":
|
|
1189
|
+
return bulks([String(Math.floor(now / 1e3)), String(now % 1e3 * 1e3)]);
|
|
1190
|
+
case "dbsize":
|
|
1191
|
+
return encode.int([...this.data.keys()].filter((k) => this.live(k)).length);
|
|
1192
|
+
case "flushdb":
|
|
1193
|
+
case "flushall":
|
|
1194
|
+
this.data.clear();
|
|
1195
|
+
return ok2;
|
|
1196
|
+
case "get":
|
|
1197
|
+
return encode.bulk(str2(key2));
|
|
1198
|
+
case "set": {
|
|
1199
|
+
let expireAt, nx = false, xx = false, get = false, keep = false;
|
|
1200
|
+
for (let i = 2; i < a.length; i++) {
|
|
1201
|
+
const o = a[i].toLowerCase();
|
|
1202
|
+
if (o === "nx") nx = true;
|
|
1203
|
+
else if (o === "xx") xx = true;
|
|
1204
|
+
else if (o === "get") get = true;
|
|
1205
|
+
else if (o === "keepttl") keep = true;
|
|
1206
|
+
else if (o === "ex") expireAt = now + this.int(a[++i]) * 1e3;
|
|
1207
|
+
else if (o === "px") expireAt = now + this.int(a[++i]);
|
|
1208
|
+
else if (o === "exat") expireAt = this.int(a[++i]) * 1e3;
|
|
1209
|
+
else if (o === "pxat") expireAt = this.int(a[++i]);
|
|
1210
|
+
else return encode.error("ERR syntax error");
|
|
1211
|
+
}
|
|
1212
|
+
const existing = this.live(key2);
|
|
1213
|
+
if (get && existing && existing.type !== "string") throw new Error(WRONGTYPE);
|
|
1214
|
+
const old = existing?.value;
|
|
1215
|
+
if (nx && existing || xx && !existing) return get ? encode.bulk(old) : encode.bulk(null);
|
|
1216
|
+
setString(key2, a[1], keep ? existing?.expireAt : expireAt);
|
|
1217
|
+
return get ? encode.bulk(old) : ok2;
|
|
1218
|
+
}
|
|
1219
|
+
case "setnx":
|
|
1220
|
+
if (this.live(key2)) return encode.int(0);
|
|
1221
|
+
setString(key2, a[1]);
|
|
1222
|
+
return encode.int(1);
|
|
1223
|
+
case "setex":
|
|
1224
|
+
setString(key2, a[2], now + this.int(a[1]) * 1e3);
|
|
1225
|
+
return ok2;
|
|
1226
|
+
case "psetex":
|
|
1227
|
+
setString(key2, a[2], now + this.int(a[1]));
|
|
1228
|
+
return ok2;
|
|
1229
|
+
case "getset": {
|
|
1230
|
+
const old = str2(key2);
|
|
1231
|
+
setString(key2, a[1]);
|
|
1232
|
+
return encode.bulk(old);
|
|
1233
|
+
}
|
|
1234
|
+
case "getdel": {
|
|
1235
|
+
const old = str2(key2);
|
|
1236
|
+
this.data.delete(key2);
|
|
1237
|
+
return encode.bulk(old);
|
|
1238
|
+
}
|
|
1239
|
+
case "mget":
|
|
1240
|
+
return bulks(a.map((k) => {
|
|
1241
|
+
const e = this.live(k);
|
|
1242
|
+
return e?.type === "string" ? e.value : null;
|
|
1243
|
+
}));
|
|
1244
|
+
case "mset":
|
|
1245
|
+
for (let i = 0; i < a.length; i += 2) setString(a[i], a[i + 1]);
|
|
1246
|
+
return ok2;
|
|
1247
|
+
case "msetnx":
|
|
1248
|
+
if (a.some((k, i) => i % 2 === 0 && this.live(k))) return encode.int(0);
|
|
1249
|
+
for (let i = 0; i < a.length; i += 2) setString(a[i], a[i + 1]);
|
|
1250
|
+
return encode.int(1);
|
|
1251
|
+
case "incr":
|
|
1252
|
+
return incr(key2, 1);
|
|
1253
|
+
case "decr":
|
|
1254
|
+
return incr(key2, -1);
|
|
1255
|
+
case "incrby":
|
|
1256
|
+
return incr(key2, this.int(a[1]));
|
|
1257
|
+
case "decrby":
|
|
1258
|
+
return incr(key2, -this.int(a[1]));
|
|
1259
|
+
case "incrbyfloat": {
|
|
1260
|
+
const n = Number(str2(key2) ?? "0") + Number(a[1]);
|
|
1261
|
+
if (!Number.isFinite(n)) throw new Error("ERR value is not a valid float");
|
|
1262
|
+
setString(key2, fmt(n), this.live(key2)?.expireAt);
|
|
1263
|
+
return encode.bulk(fmt(n));
|
|
1264
|
+
}
|
|
1265
|
+
case "append": {
|
|
1266
|
+
const v = (str2(key2) ?? "") + a[1];
|
|
1267
|
+
setString(key2, v, this.live(key2)?.expireAt);
|
|
1268
|
+
return encode.int(Buffer.byteLength(v, "latin1"));
|
|
1269
|
+
}
|
|
1270
|
+
case "strlen":
|
|
1271
|
+
return encode.int(Buffer.byteLength(str2(key2) ?? "", "latin1"));
|
|
1272
|
+
case "del":
|
|
1273
|
+
case "unlink": {
|
|
1274
|
+
let n = 0;
|
|
1275
|
+
for (const k of a) if (this.live(k)) {
|
|
1276
|
+
this.data.delete(k);
|
|
1277
|
+
n++;
|
|
1278
|
+
}
|
|
1279
|
+
return encode.int(n);
|
|
1280
|
+
}
|
|
1281
|
+
case "exists":
|
|
1282
|
+
return encode.int(a.filter((k) => this.live(k)).length);
|
|
1283
|
+
case "type":
|
|
1284
|
+
return encode.simple(this.live(key2)?.type ?? "none");
|
|
1285
|
+
case "expire":
|
|
1286
|
+
case "pexpire":
|
|
1287
|
+
case "expireat":
|
|
1288
|
+
case "pexpireat": {
|
|
1289
|
+
const e = this.live(key2);
|
|
1290
|
+
if (!e) return encode.int(0);
|
|
1291
|
+
const n = this.int(a[1]);
|
|
1292
|
+
e.expireAt = name === "expire" ? now + n * 1e3 : name === "pexpire" ? now + n : name === "expireat" ? n * 1e3 : n;
|
|
1293
|
+
if (e.expireAt <= now) this.data.delete(key2);
|
|
1294
|
+
return encode.int(1);
|
|
1295
|
+
}
|
|
1296
|
+
case "ttl":
|
|
1297
|
+
case "pttl": {
|
|
1298
|
+
const e = this.live(key2);
|
|
1299
|
+
if (!e) return encode.int(-2);
|
|
1300
|
+
if (e.expireAt === void 0) return encode.int(-1);
|
|
1301
|
+
const ms = e.expireAt - now;
|
|
1302
|
+
return encode.int(name === "ttl" ? Math.round(ms / 1e3) : ms);
|
|
1303
|
+
}
|
|
1304
|
+
case "persist": {
|
|
1305
|
+
const e = this.live(key2);
|
|
1306
|
+
if (!e || e.expireAt === void 0) return encode.int(0);
|
|
1307
|
+
delete e.expireAt;
|
|
1308
|
+
return encode.int(1);
|
|
1309
|
+
}
|
|
1310
|
+
case "keys": {
|
|
1311
|
+
const re = glob(key2 ?? "*");
|
|
1312
|
+
return bulks([...this.data.keys()].filter((k) => this.live(k) && re.test(k)));
|
|
1313
|
+
}
|
|
1314
|
+
case "scan": {
|
|
1315
|
+
let match = "*", type;
|
|
1316
|
+
for (let i = 1; i < a.length; i++) {
|
|
1317
|
+
const o = a[i].toLowerCase();
|
|
1318
|
+
if (o === "match") match = a[++i];
|
|
1319
|
+
else if (o === "count") i++;
|
|
1320
|
+
else if (o === "type") type = a[++i];
|
|
1321
|
+
}
|
|
1322
|
+
const re = glob(match);
|
|
1323
|
+
return encode.array([encode.bulk("0"), bulks([...this.data.keys()].filter((k) => {
|
|
1324
|
+
const e = this.live(k);
|
|
1325
|
+
return e && re.test(k) && (!type || e.type === type);
|
|
1326
|
+
}))]);
|
|
1327
|
+
}
|
|
1328
|
+
case "rename":
|
|
1329
|
+
case "renamenx": {
|
|
1330
|
+
const e = this.live(key2);
|
|
1331
|
+
if (!e) return encode.error("ERR no such key");
|
|
1332
|
+
if (name === "renamenx" && this.live(a[1])) return encode.int(0);
|
|
1333
|
+
this.data.delete(key2);
|
|
1334
|
+
this.data.set(a[1], e);
|
|
1335
|
+
return name === "rename" ? ok2 : encode.int(1);
|
|
1336
|
+
}
|
|
1337
|
+
case "hset":
|
|
1338
|
+
case "hmset": {
|
|
1339
|
+
const h = this.typed(key2, "hash", () => /* @__PURE__ */ new Map());
|
|
1340
|
+
let n = 0;
|
|
1341
|
+
for (let i = 1; i < a.length; i += 2) {
|
|
1342
|
+
if (!h.has(a[i])) n++;
|
|
1343
|
+
h.set(a[i], a[i + 1]);
|
|
1344
|
+
}
|
|
1345
|
+
return name === "hmset" ? ok2 : encode.int(n);
|
|
1346
|
+
}
|
|
1347
|
+
case "hsetnx": {
|
|
1348
|
+
const h = this.typed(key2, "hash", () => /* @__PURE__ */ new Map());
|
|
1349
|
+
if (h.has(a[1])) return encode.int(0);
|
|
1350
|
+
h.set(a[1], a[2]);
|
|
1351
|
+
return encode.int(1);
|
|
1352
|
+
}
|
|
1353
|
+
case "hget":
|
|
1354
|
+
return encode.bulk(this.get(key2, "hash")?.get(a[1]));
|
|
1355
|
+
case "hmget": {
|
|
1356
|
+
const h = this.get(key2, "hash");
|
|
1357
|
+
return bulks(a.slice(1).map((f) => h?.get(f)));
|
|
1358
|
+
}
|
|
1359
|
+
case "hgetall": {
|
|
1360
|
+
const h = this.get(key2, "hash");
|
|
1361
|
+
return bulks([...h ?? /* @__PURE__ */ new Map()].flat());
|
|
1362
|
+
}
|
|
1363
|
+
case "hkeys":
|
|
1364
|
+
return bulks([...(this.get(key2, "hash") ?? /* @__PURE__ */ new Map()).keys()]);
|
|
1365
|
+
case "hvals":
|
|
1366
|
+
return bulks([...(this.get(key2, "hash") ?? /* @__PURE__ */ new Map()).values()]);
|
|
1367
|
+
case "hlen":
|
|
1368
|
+
return encode.int(this.get(key2, "hash")?.size ?? 0);
|
|
1369
|
+
case "hexists":
|
|
1370
|
+
return encode.int(this.get(key2, "hash")?.has(a[1]) ? 1 : 0);
|
|
1371
|
+
case "hdel": {
|
|
1372
|
+
const h = this.get(key2, "hash");
|
|
1373
|
+
const n = a.slice(1).filter((f) => h?.delete(f)).length;
|
|
1374
|
+
this.clean(key2);
|
|
1375
|
+
return encode.int(n);
|
|
1376
|
+
}
|
|
1377
|
+
case "hincrby": {
|
|
1378
|
+
const h = this.typed(key2, "hash", () => /* @__PURE__ */ new Map());
|
|
1379
|
+
const cur = h.get(a[1]) ?? "0";
|
|
1380
|
+
if (!/^-?\d+$/.test(cur)) throw new Error("ERR hash value is not an integer");
|
|
1381
|
+
const n = Number(cur) + this.int(a[2]);
|
|
1382
|
+
h.set(a[1], String(n));
|
|
1383
|
+
return encode.int(n);
|
|
1384
|
+
}
|
|
1385
|
+
case "hincrbyfloat": {
|
|
1386
|
+
const h = this.typed(key2, "hash", () => /* @__PURE__ */ new Map());
|
|
1387
|
+
const n = Number(h.get(a[1]) ?? "0") + Number(a[2]);
|
|
1388
|
+
h.set(a[1], fmt(n));
|
|
1389
|
+
return encode.bulk(fmt(n));
|
|
1390
|
+
}
|
|
1391
|
+
case "lpush":
|
|
1392
|
+
case "rpush":
|
|
1393
|
+
case "lpushx":
|
|
1394
|
+
case "rpushx": {
|
|
1395
|
+
if (name.endsWith("x") && !this.live(key2)) return encode.int(0);
|
|
1396
|
+
const l = this.typed(key2, "list", () => []);
|
|
1397
|
+
for (const v of a.slice(1)) name.startsWith("l") ? l.unshift(v) : l.push(v);
|
|
1398
|
+
return encode.int(l.length);
|
|
1399
|
+
}
|
|
1400
|
+
case "lpop":
|
|
1401
|
+
case "rpop": {
|
|
1402
|
+
const l = this.get(key2, "list");
|
|
1403
|
+
if (!l) return a[1] ? encode.array(null) : encode.bulk(null);
|
|
1404
|
+
const count = a[1] ? this.int(a[1]) : void 0;
|
|
1405
|
+
const taken = name === "lpop" ? l.splice(0, count ?? 1) : l.splice(-(count ?? 1)).reverse();
|
|
1406
|
+
this.clean(key2);
|
|
1407
|
+
return count === void 0 ? encode.bulk(taken[0]) : bulks(taken);
|
|
1408
|
+
}
|
|
1409
|
+
case "llen":
|
|
1410
|
+
return encode.int(this.get(key2, "list")?.length ?? 0);
|
|
1411
|
+
case "lrange": {
|
|
1412
|
+
const l = this.get(key2, "list") ?? [];
|
|
1413
|
+
const [s, e] = range(l.length, this.int(a[1]), this.int(a[2]));
|
|
1414
|
+
return bulks(s > e ? [] : l.slice(s, e + 1));
|
|
1415
|
+
}
|
|
1416
|
+
case "lindex": {
|
|
1417
|
+
const l = this.get(key2, "list") ?? [];
|
|
1418
|
+
const i = this.int(a[1]);
|
|
1419
|
+
return encode.bulk(l.at(i) ?? null);
|
|
1420
|
+
}
|
|
1421
|
+
case "lset": {
|
|
1422
|
+
const l = this.get(key2, "list");
|
|
1423
|
+
if (!l) return encode.error("ERR no such key");
|
|
1424
|
+
let i = this.int(a[1]);
|
|
1425
|
+
if (i < 0) i += l.length;
|
|
1426
|
+
if (i < 0 || i >= l.length) return encode.error("ERR index out of range");
|
|
1427
|
+
l[i] = a[2];
|
|
1428
|
+
return ok2;
|
|
1429
|
+
}
|
|
1430
|
+
case "lrem": {
|
|
1431
|
+
const l = this.get(key2, "list");
|
|
1432
|
+
if (!l) return encode.int(0);
|
|
1433
|
+
let count = this.int(a[1]), n = 0;
|
|
1434
|
+
const keep = [];
|
|
1435
|
+
const items = count < 0 ? [...l].reverse() : l;
|
|
1436
|
+
for (const v of items) {
|
|
1437
|
+
if (v === a[2] && (count === 0 || n < Math.abs(count))) {
|
|
1438
|
+
n++;
|
|
1439
|
+
continue;
|
|
1440
|
+
}
|
|
1441
|
+
keep.push(v);
|
|
1442
|
+
}
|
|
1443
|
+
l.splice(0, l.length, ...count < 0 ? keep.reverse() : keep);
|
|
1444
|
+
this.clean(key2);
|
|
1445
|
+
return encode.int(n);
|
|
1446
|
+
}
|
|
1447
|
+
case "ltrim": {
|
|
1448
|
+
const l = this.get(key2, "list");
|
|
1449
|
+
if (!l) return ok2;
|
|
1450
|
+
const [s, e] = range(l.length, this.int(a[1]), this.int(a[2]));
|
|
1451
|
+
l.splice(0, l.length, ...s > e ? [] : l.slice(s, e + 1));
|
|
1452
|
+
this.clean(key2);
|
|
1453
|
+
return ok2;
|
|
1454
|
+
}
|
|
1455
|
+
case "sadd": {
|
|
1456
|
+
const s = this.typed(key2, "set", () => /* @__PURE__ */ new Set());
|
|
1457
|
+
let n = 0;
|
|
1458
|
+
for (const v of a.slice(1)) if (!s.has(v)) {
|
|
1459
|
+
s.add(v);
|
|
1460
|
+
n++;
|
|
1461
|
+
}
|
|
1462
|
+
return encode.int(n);
|
|
1463
|
+
}
|
|
1464
|
+
case "srem": {
|
|
1465
|
+
const s = this.get(key2, "set");
|
|
1466
|
+
const n = a.slice(1).filter((v) => s?.delete(v)).length;
|
|
1467
|
+
this.clean(key2);
|
|
1468
|
+
return encode.int(n);
|
|
1469
|
+
}
|
|
1470
|
+
case "smembers":
|
|
1471
|
+
return bulks([...this.get(key2, "set") ?? []]);
|
|
1472
|
+
case "sismember":
|
|
1473
|
+
return encode.int(this.get(key2, "set")?.has(a[1]) ? 1 : 0);
|
|
1474
|
+
case "scard":
|
|
1475
|
+
return encode.int(this.get(key2, "set")?.size ?? 0);
|
|
1476
|
+
case "zadd": {
|
|
1477
|
+
const z = this.typed(key2, "zset", () => /* @__PURE__ */ new Map());
|
|
1478
|
+
let i = 1, nx = false, xx = false, ch = false;
|
|
1479
|
+
for (; i < a.length && /^(nx|xx|ch|gt|lt)$/i.test(a[i]); i++) {
|
|
1480
|
+
const o = a[i].toLowerCase();
|
|
1481
|
+
if (o === "nx") nx = true;
|
|
1482
|
+
if (o === "xx") xx = true;
|
|
1483
|
+
if (o === "ch") ch = true;
|
|
1484
|
+
}
|
|
1485
|
+
let n = 0;
|
|
1486
|
+
for (; i < a.length; i += 2) {
|
|
1487
|
+
const score = Number(a[i]), member = a[i + 1];
|
|
1488
|
+
if (Number.isNaN(score)) throw new Error("ERR value is not a valid float");
|
|
1489
|
+
const had = z.has(member);
|
|
1490
|
+
if (nx && had || xx && !had) continue;
|
|
1491
|
+
if (!had || ch && z.get(member) !== score) n++;
|
|
1492
|
+
z.set(member, score);
|
|
1493
|
+
}
|
|
1494
|
+
this.clean(key2);
|
|
1495
|
+
return encode.int(n);
|
|
1496
|
+
}
|
|
1497
|
+
case "zincrby": {
|
|
1498
|
+
const z = this.typed(key2, "zset", () => /* @__PURE__ */ new Map());
|
|
1499
|
+
const n = (z.get(a[2]) ?? 0) + Number(a[1]);
|
|
1500
|
+
z.set(a[2], n);
|
|
1501
|
+
return encode.bulk(fmt(n));
|
|
1502
|
+
}
|
|
1503
|
+
case "zscore": {
|
|
1504
|
+
const v = this.get(key2, "zset")?.get(a[1]);
|
|
1505
|
+
return encode.bulk(v === void 0 ? null : fmt(v));
|
|
1506
|
+
}
|
|
1507
|
+
case "zcard":
|
|
1508
|
+
return encode.int(this.get(key2, "zset")?.size ?? 0);
|
|
1509
|
+
case "zrem": {
|
|
1510
|
+
const z = this.get(key2, "zset");
|
|
1511
|
+
const n = a.slice(1).filter((m) => z?.delete(m)).length;
|
|
1512
|
+
this.clean(key2);
|
|
1513
|
+
return encode.int(n);
|
|
1514
|
+
}
|
|
1515
|
+
case "zrange":
|
|
1516
|
+
case "zrevrange":
|
|
1517
|
+
case "zrangebyscore": {
|
|
1518
|
+
const z = this.get(key2, "zset") ?? /* @__PURE__ */ new Map();
|
|
1519
|
+
const opts = a.slice(3).map((o) => o.toLowerCase());
|
|
1520
|
+
let sorted = [...z].sort((x, y) => x[1] - y[1] || (x[0] < y[0] ? -1 : 1));
|
|
1521
|
+
if (name === "zrevrange" || opts.includes("rev")) sorted.reverse();
|
|
1522
|
+
if (name === "zrangebyscore" || opts.includes("byscore")) {
|
|
1523
|
+
const bound = (s, lo2) => s === "-inf" ? -Infinity : s === "+inf" || s === "inf" ? Infinity : s.startsWith("(") ? Number(s.slice(1)) + (lo2 ? 1e-12 : -1e-12) : Number(s);
|
|
1524
|
+
const lo = bound(a[1], true), hi = bound(a[2], false);
|
|
1525
|
+
sorted = sorted.filter(([, s]) => s >= lo && s <= hi);
|
|
1526
|
+
} else {
|
|
1527
|
+
const [s, e] = range(sorted.length, this.int(a[1]), this.int(a[2]));
|
|
1528
|
+
sorted = s > e ? [] : sorted.slice(s, e + 1);
|
|
1529
|
+
}
|
|
1530
|
+
return bulks(opts.includes("withscores") ? sorted.flatMap(([m, s]) => [m, fmt(s)]) : sorted.map(([m]) => m));
|
|
1531
|
+
}
|
|
1532
|
+
case "publish":
|
|
1533
|
+
return encode.int(0);
|
|
1534
|
+
default: {
|
|
1535
|
+
const text2 = `redis: ${name.toUpperCase()} is outside the AgentTwin in-process Redis engine`;
|
|
1536
|
+
if (this.unsupported.length < 1e3 && !this.unsupported.includes(text2)) this.unsupported.push(text2);
|
|
1537
|
+
return encode.error(`ERR unknown command '${name}' (AgentTwin in-process Redis; use a redis-server binary or Docker for full Redis)`);
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
};
|
|
1542
|
+
|
|
1543
|
+
// src/runtime/upstash-redis-twin.ts
|
|
1544
|
+
var UPSTASH_KEYS = "/keys";
|
|
1545
|
+
var WRITE_COMMANDS = new Set("set setnx setex psetex getset getdel getex mset msetnx incr incrby incrbyfloat decr decrby append setrange del unlink expire pexpire expireat pexpireat persist rename renamenx hset hsetnx hmset hdel hincrby hincrbyfloat lpush rpush lpushx rpushx lpop rpop lset lrem ltrim linsert lmove rpoplpush sadd srem spop smove zadd zrem zincrby zpopmin zpopmax zremrangebyscore zremrangebyrank flushdb flushall".split(" "));
|
|
1546
|
+
var REJECTED = /* @__PURE__ */ new Set(["eval", "evalsha", "eval_ro", "evalsha_ro", "script", "subscribe", "psubscribe", "blpop", "brpop", "blmove", "monitor", "multi", "exec", "watch"]);
|
|
1547
|
+
var toBytes = (v) => Buffer.from(v, "utf8").toString("latin1");
|
|
1548
|
+
var fromBytes = (v) => Buffer.from(v, "latin1").toString("utf8");
|
|
1549
|
+
function toEntry(row) {
|
|
1550
|
+
const value = row.value;
|
|
1551
|
+
switch (row.type) {
|
|
1552
|
+
case "string":
|
|
1553
|
+
return typeof value === "string" ? { type: "string", value: toBytes(value), ...row.expireAt ? { expireAt: row.expireAt } : {} } : void 0;
|
|
1554
|
+
case "hash":
|
|
1555
|
+
return value && typeof value === "object" && !Array.isArray(value) ? { type: "hash", value: new Map(Object.entries(value).map(([k, v]) => [toBytes(k), toBytes(String(v))])), ...row.expireAt ? { expireAt: row.expireAt } : {} } : void 0;
|
|
1556
|
+
case "list":
|
|
1557
|
+
return Array.isArray(value) ? { type: "list", value: value.map((v) => toBytes(String(v))), ...row.expireAt ? { expireAt: row.expireAt } : {} } : void 0;
|
|
1558
|
+
case "set":
|
|
1559
|
+
return Array.isArray(value) ? { type: "set", value: new Set(value.map((v) => toBytes(String(v)))), ...row.expireAt ? { expireAt: row.expireAt } : {} } : void 0;
|
|
1560
|
+
case "zset":
|
|
1561
|
+
return value && typeof value === "object" && !Array.isArray(value) ? { type: "zset", value: new Map(Object.entries(value).map(([k, v]) => [toBytes(k), Number(v)])), ...row.expireAt ? { expireAt: row.expireAt } : {} } : void 0;
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
function toRow(key2, entry) {
|
|
1565
|
+
const v = entry.value;
|
|
1566
|
+
const text2 = (x) => typeof x === "string" ? fromBytes(x) : x;
|
|
1567
|
+
const value = v instanceof Map ? Object.fromEntries([...v].map(([k, x]) => [fromBytes(k), text2(x)])) : v instanceof Set ? [...v].map(text2) : Array.isArray(v) ? v.map(text2) : text2(v);
|
|
1568
|
+
return { key: fromBytes(key2), type: entry.type, value, ...entry.expireAt !== void 0 ? { expireAt: entry.expireAt } : {} };
|
|
1569
|
+
}
|
|
1570
|
+
var caches = /* @__PURE__ */ new WeakMap();
|
|
1571
|
+
var GLOBAL_WRITES = /* @__PURE__ */ new Set(["flushdb", "flushall"]);
|
|
1572
|
+
var consistent = (rows2, cache2) => rows2.length === cache2.mirror.length && rows2.every((r, i) => r === cache2.mirror[i]);
|
|
1573
|
+
function resync(rows2, cache2) {
|
|
1574
|
+
const now = Date.now();
|
|
1575
|
+
for (const [k, e] of cache2.engine.data) if (e.expireAt !== void 0 && e.expireAt <= now) cache2.engine.data.delete(k);
|
|
1576
|
+
rows2.splice(0, rows2.length, ...[...cache2.engine.data].map(([k, e]) => toRow(k, e)));
|
|
1577
|
+
cache2.mirror = rows2.slice();
|
|
1578
|
+
cache2.index = new Map([...cache2.engine.data.keys()].map((k, i) => [k, i]));
|
|
1579
|
+
cache2.nextExpiry = rows2.reduce((min, r) => r.expireAt !== void 0 && r.expireAt < min ? r.expireAt : min, Infinity);
|
|
1580
|
+
}
|
|
1581
|
+
function remove(rows2, cache2, key2) {
|
|
1582
|
+
const at = cache2.index.get(key2);
|
|
1583
|
+
if (at === void 0) return;
|
|
1584
|
+
cache2.index.delete(key2);
|
|
1585
|
+
const last = rows2.length - 1;
|
|
1586
|
+
if (at !== last) {
|
|
1587
|
+
rows2[at] = rows2[last];
|
|
1588
|
+
cache2.mirror[at] = rows2[last];
|
|
1589
|
+
cache2.index.set(toBytes(rows2[at].key), at);
|
|
1590
|
+
}
|
|
1591
|
+
rows2.pop();
|
|
1592
|
+
cache2.mirror.pop();
|
|
1593
|
+
}
|
|
1594
|
+
function syncKey(rows2, cache2, key2, now) {
|
|
1595
|
+
const entry = cache2.engine.data.get(key2);
|
|
1596
|
+
if (!entry || entry.expireAt !== void 0 && entry.expireAt <= now) {
|
|
1597
|
+
if (entry) cache2.engine.data.delete(key2);
|
|
1598
|
+
remove(rows2, cache2, key2);
|
|
1599
|
+
return;
|
|
1600
|
+
}
|
|
1601
|
+
const row = toRow(key2, entry);
|
|
1602
|
+
const at = cache2.index.get(key2);
|
|
1603
|
+
if (at === void 0) {
|
|
1604
|
+
cache2.index.set(key2, rows2.length);
|
|
1605
|
+
rows2.push(row);
|
|
1606
|
+
cache2.mirror.push(row);
|
|
1607
|
+
} else {
|
|
1608
|
+
rows2[at] = row;
|
|
1609
|
+
cache2.mirror[at] = row;
|
|
1610
|
+
}
|
|
1611
|
+
if (row.expireAt !== void 0) cache2.nextExpiry = Math.min(cache2.nextExpiry, row.expireAt);
|
|
1612
|
+
}
|
|
1613
|
+
function engineFor(rows2) {
|
|
1614
|
+
const cached2 = caches.get(rows2);
|
|
1615
|
+
if (cached2 && consistent(rows2, cached2)) return cached2;
|
|
1616
|
+
const engine = new InProcessRedis();
|
|
1617
|
+
for (const row of rows2) {
|
|
1618
|
+
const entry = row && typeof row.key === "string" ? toEntry(row) : void 0;
|
|
1619
|
+
if (!entry) {
|
|
1620
|
+
caches.delete(rows2);
|
|
1621
|
+
return { error: `ERR invalid seeded key row ${JSON.stringify(row?.key)}` };
|
|
1622
|
+
}
|
|
1623
|
+
engine.data.set(toBytes(row.key), entry);
|
|
1624
|
+
}
|
|
1625
|
+
const cache2 = { engine, mirror: [], index: /* @__PURE__ */ new Map(), nextExpiry: Infinity };
|
|
1626
|
+
resync(rows2, cache2);
|
|
1627
|
+
caches.set(rows2, cache2);
|
|
1628
|
+
return cache2;
|
|
1629
|
+
}
|
|
1630
|
+
function upstashReply(reply, base64) {
|
|
1631
|
+
const frame2 = parseResp(reply);
|
|
1632
|
+
const json = (value) => {
|
|
1633
|
+
if (value === null || typeof value === "number" || typeof value === "boolean") return value;
|
|
1634
|
+
if (Buffer.isBuffer(value)) return base64 ? value.toString("base64") : value.toString("utf8");
|
|
1635
|
+
if (Array.isArray(value)) return value.map(json);
|
|
1636
|
+
if ("simple" in value) return base64 && value.simple !== "OK" ? Buffer.from(value.simple).toString("base64") : value.simple;
|
|
1637
|
+
throw new Error(value.error);
|
|
1638
|
+
};
|
|
1639
|
+
if (!frame2) return { error: "ERR empty reply" };
|
|
1640
|
+
if (frame2.value && typeof frame2.value === "object" && !Array.isArray(frame2.value) && !Buffer.isBuffer(frame2.value) && "error" in frame2.value) return { error: frame2.value.error };
|
|
1641
|
+
return { result: json(frame2.value) };
|
|
1642
|
+
}
|
|
1643
|
+
function upstashRedisOperation(method, path, params, headers, data, _sequence, raw) {
|
|
1644
|
+
if (method !== "POST" || !["/", "/pipeline", "/multi-exec"].includes(path) || raw === void 0 || Object.keys(params).length) return void 0;
|
|
1645
|
+
let body;
|
|
1646
|
+
try {
|
|
1647
|
+
body = JSON.parse(raw);
|
|
1648
|
+
} catch {
|
|
1649
|
+
return { status: 400, body: { error: "ERR failed to parse command" }, collection: UPSTASH_KEYS };
|
|
1650
|
+
}
|
|
1651
|
+
const single = path === "/";
|
|
1652
|
+
const commands = single ? [body] : body;
|
|
1653
|
+
const valid = (c) => Array.isArray(c) && c.length > 0 && c.length <= 1e3 && c.every((a) => ["string", "number", "boolean"].includes(typeof a)) && typeof c[0] === "string";
|
|
1654
|
+
if (!Array.isArray(commands) || !commands.length || commands.length > 1e3 || !commands.every(valid)) return { status: 400, body: { error: "ERR command must be a non-empty array of strings" }, collection: UPSTASH_KEYS };
|
|
1655
|
+
const args = commands.map((c) => c.map((a) => toBytes(String(a))));
|
|
1656
|
+
if (args.some((c) => REJECTED.has(c[0].toLowerCase()))) return void 0;
|
|
1657
|
+
const rows2 = data[UPSTASH_KEYS];
|
|
1658
|
+
const cache2 = engineFor(rows2);
|
|
1659
|
+
if ("error" in cache2) return { status: 500, body: { error: cache2.error }, collection: UPSTASH_KEYS };
|
|
1660
|
+
const { engine } = cache2;
|
|
1661
|
+
engine.unsupported.length = 0;
|
|
1662
|
+
const replies = args.map((c) => engine.run(c));
|
|
1663
|
+
if (engine.unsupported.length) {
|
|
1664
|
+
caches.delete(rows2);
|
|
1665
|
+
return void 0;
|
|
1666
|
+
}
|
|
1667
|
+
const now = Date.now();
|
|
1668
|
+
const touched = /* @__PURE__ */ new Set();
|
|
1669
|
+
let full = false;
|
|
1670
|
+
for (const c of args) {
|
|
1671
|
+
const name = c[0].toLowerCase(), keys = commandKeys(name, c.slice(1));
|
|
1672
|
+
if (GLOBAL_WRITES.has(name) || !keys.length && WRITE_COMMANDS.has(name)) full = true;
|
|
1673
|
+
for (const k of keys) touched.add(k);
|
|
1674
|
+
}
|
|
1675
|
+
if (full || cache2.nextExpiry <= now) resync(rows2, cache2);
|
|
1676
|
+
else for (const k of touched) syncKey(rows2, cache2, k, now);
|
|
1677
|
+
const encoding = headers["upstash-encoding"];
|
|
1678
|
+
const base64 = typeof encoding === "string" && encoding.toLowerCase() === "base64";
|
|
1679
|
+
const results = replies.map((r) => upstashReply(r, base64));
|
|
1680
|
+
const wrote = args.some((c) => WRITE_COMMANDS.has(c[0].toLowerCase()));
|
|
1681
|
+
const record3 = { commands: args.map((c) => c[0].toUpperCase()), keys: args.map((c) => c[1] === void 0 ? null : fromBytes(c[1])) };
|
|
1682
|
+
if (single) {
|
|
1683
|
+
const result = results[0];
|
|
1684
|
+
return { status: "error" in result ? 400 : 200, body: result, collection: UPSTASH_KEYS, operation: wrote ? "write" : "read", record: record3 };
|
|
1685
|
+
}
|
|
1686
|
+
return { status: 200, body: results, collection: UPSTASH_KEYS, operation: wrote ? "write" : "read", record: record3 };
|
|
1687
|
+
}
|
|
1688
|
+
|
|
845
1689
|
// src/runtime/gmail-mime.ts
|
|
846
1690
|
function parseGmailRaw(raw) {
|
|
847
1691
|
if (!/^[A-Za-z0-9_-]+={0,2}$/.test(raw)) return { error: "raw must be a base64url MIME message", unsupported: false };
|
|
@@ -863,8 +1707,187 @@ function parseGmailRaw(raw) {
|
|
|
863
1707
|
if (!header3("to")) return { error: "MIME To header is required", unsupported: false };
|
|
864
1708
|
if (header3("content-type") && !/^text\/plain(?:\s*;\s*charset=(?:"?utf-8"?|"?us-ascii"?))?$/i.test(header3("content-type"))) return { error: "Only text/plain UTF-8 MIME is supported", unsupported: true };
|
|
865
1709
|
if (header3("content-transfer-encoding") && !/^(7bit|8bit)$/i.test(header3("content-transfer-encoding"))) return { error: "Encoded MIME bodies are outside the verified subset", unsupported: true };
|
|
866
|
-
const
|
|
867
|
-
return { headers, text, encodedBody: Buffer.from(
|
|
1710
|
+
const text2 = mime.slice(boundary + 4);
|
|
1711
|
+
return { headers, text: text2, encodedBody: Buffer.from(text2).toString("base64url"), bytes: bytes.length };
|
|
1712
|
+
}
|
|
1713
|
+
var mimeError = (error, unsupported2) => ({ error, unsupported: unsupported2 });
|
|
1714
|
+
function decodeEncodedWords(value) {
|
|
1715
|
+
let failure;
|
|
1716
|
+
const decoded = value.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=(\s+(?==\?))?/g, (_all, charset, kind, text2) => {
|
|
1717
|
+
if (!/^(utf-8|us-ascii)$/i.test(charset)) {
|
|
1718
|
+
failure ??= mimeError(`Encoded header charset ${charset} is outside the verified subset`, true);
|
|
1719
|
+
return "";
|
|
1720
|
+
}
|
|
1721
|
+
if (kind.toUpperCase() === "B") return Buffer.from(text2, "base64").toString("utf8");
|
|
1722
|
+
return Buffer.from(text2.replace(/_/g, " ").replace(/=([0-9A-Fa-f]{2})/g, (_m, hex) => String.fromCharCode(parseInt(hex, 16))), "latin1").toString("utf8");
|
|
1723
|
+
});
|
|
1724
|
+
return failure ?? decoded;
|
|
1725
|
+
}
|
|
1726
|
+
function parseHeaderBlock(block) {
|
|
1727
|
+
const lines = block.split(/\r?\n/);
|
|
1728
|
+
const unfolded = [];
|
|
1729
|
+
for (const line of lines) {
|
|
1730
|
+
if (/^[ \t]/.test(line)) {
|
|
1731
|
+
if (!unfolded.length) return mimeError("MIME header block starts with a continuation line", false);
|
|
1732
|
+
unfolded[unfolded.length - 1] += " " + line.trim();
|
|
1733
|
+
} else if (line) unfolded.push(line);
|
|
1734
|
+
}
|
|
1735
|
+
if (unfolded.length > 200) return mimeError("More than 200 MIME headers", false);
|
|
1736
|
+
const headers = [];
|
|
1737
|
+
for (const line of unfolded) {
|
|
1738
|
+
const match = /^([!-9;-~]+):[ \t]*(.*)$/.exec(line);
|
|
1739
|
+
if (!match || match[2].length > 8192 || /[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(match[2])) return mimeError("Invalid MIME header", false);
|
|
1740
|
+
const value = decodeEncodedWords(match[2]);
|
|
1741
|
+
if (typeof value !== "string") return value;
|
|
1742
|
+
headers.push({ name: match[1], value });
|
|
1743
|
+
}
|
|
1744
|
+
return headers;
|
|
1745
|
+
}
|
|
1746
|
+
var headerValue = (headers, name) => headers.find((h) => h.name.toLowerCase() === name)?.value;
|
|
1747
|
+
function contentType(headers) {
|
|
1748
|
+
const value = headerValue(headers, "content-type") ?? "text/plain; charset=us-ascii";
|
|
1749
|
+
const [type, ...rest] = value.split(";");
|
|
1750
|
+
const params = {};
|
|
1751
|
+
for (const part of rest) {
|
|
1752
|
+
const m = /^\s*([A-Za-z0-9_-]+)\s*=\s*(?:"([^"]*)"|([^\s;]+))\s*$/.exec(part);
|
|
1753
|
+
if (m) params[m[1].toLowerCase()] = m[2] ?? m[3];
|
|
1754
|
+
}
|
|
1755
|
+
return { mimeType: type.trim().toLowerCase(), params };
|
|
1756
|
+
}
|
|
1757
|
+
function decodeBody(body, headers) {
|
|
1758
|
+
const encoding = (headerValue(headers, "content-transfer-encoding") ?? "7bit").trim().toLowerCase();
|
|
1759
|
+
if (["7bit", "8bit", "binary"].includes(encoding)) return Buffer.from(body, "utf8");
|
|
1760
|
+
if (encoding === "quoted-printable") {
|
|
1761
|
+
const bytes = [];
|
|
1762
|
+
const text2 = body.replace(/=\r?\n/g, "");
|
|
1763
|
+
for (let i = 0; i < text2.length; i++) {
|
|
1764
|
+
if (text2[i] === "=" && /^[0-9A-Fa-f]{2}$/.test(text2.slice(i + 1, i + 3))) {
|
|
1765
|
+
bytes.push(parseInt(text2.slice(i + 1, i + 3), 16));
|
|
1766
|
+
i += 2;
|
|
1767
|
+
} else bytes.push(...Buffer.from(text2[i], "utf8"));
|
|
1768
|
+
}
|
|
1769
|
+
return Buffer.from(bytes);
|
|
1770
|
+
}
|
|
1771
|
+
if (encoding === "base64") {
|
|
1772
|
+
const compact = body.replace(/\s+/g, "");
|
|
1773
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(compact)) return mimeError("Invalid base64 MIME body", false);
|
|
1774
|
+
return Buffer.from(compact, "base64");
|
|
1775
|
+
}
|
|
1776
|
+
return mimeError(`Content-Transfer-Encoding ${encoding} is outside the verified subset`, true);
|
|
1777
|
+
}
|
|
1778
|
+
function textPart(partId, headers, body) {
|
|
1779
|
+
const { mimeType, params } = contentType(headers);
|
|
1780
|
+
if (mimeType !== "text/plain" && mimeType !== "text/html") return mimeError(`MIME part ${mimeType} is outside the verified subset`, true);
|
|
1781
|
+
if (params.charset && !/^(utf-8|us-ascii)$/i.test(params.charset)) return mimeError(`Charset ${params.charset} is outside the verified subset`, true);
|
|
1782
|
+
const decoded = decodeBody(body, headers);
|
|
1783
|
+
if (!Buffer.isBuffer(decoded)) return decoded;
|
|
1784
|
+
if (Buffer.from(decoded.toString("utf8")).compare(decoded) !== 0) return mimeError("MIME text part is not valid UTF-8", true);
|
|
1785
|
+
return { partId, mimeType, filename: "", headers, body: { size: decoded.length, data: decoded.toString("base64url") } };
|
|
1786
|
+
}
|
|
1787
|
+
var splitHead = (text2) => {
|
|
1788
|
+
const m = /\r?\n\r?\n/.exec(text2);
|
|
1789
|
+
return m ? { head: text2.slice(0, m.index), body: text2.slice(m.index + m[0].length) } : void 0;
|
|
1790
|
+
};
|
|
1791
|
+
var partText = (part, type) => part.mimeType === type && part.body.data ? Buffer.from(part.body.data, "base64url").toString("utf8") : part.parts?.map((p) => partText(p, type)).find((t) => t !== void 0);
|
|
1792
|
+
function parseGmailDraftRaw(raw) {
|
|
1793
|
+
if (!/^[A-Za-z0-9_-]+={0,2}$/.test(raw)) return mimeError("raw must be a base64url MIME message", false);
|
|
1794
|
+
const bytes = Buffer.from(raw, "base64url");
|
|
1795
|
+
if (bytes.toString("base64url") !== raw.replace(/=+$/, "")) return mimeError("raw must be canonical base64url", false);
|
|
1796
|
+
if (bytes.length > 1024 * 1024) return mimeError("MIME message larger than 1 MiB", false);
|
|
1797
|
+
const mime = bytes.toString("utf8");
|
|
1798
|
+
if (Buffer.from(mime).compare(bytes) !== 0) return mimeError("Only UTF-8 MIME messages are supported", true);
|
|
1799
|
+
const top = splitHead(mime);
|
|
1800
|
+
if (!top) return mimeError("MIME headers and body need a blank-line separator", false);
|
|
1801
|
+
const headers = parseHeaderBlock(top.head);
|
|
1802
|
+
if (!Array.isArray(headers)) return headers;
|
|
1803
|
+
const { mimeType, params } = contentType(headers);
|
|
1804
|
+
let payload;
|
|
1805
|
+
if (mimeType === "multipart/alternative") {
|
|
1806
|
+
if (!params.boundary) return mimeError("multipart/alternative needs a boundary", false);
|
|
1807
|
+
const sections = top.body.split(new RegExp(`(?:^|\\r?\\n)--${params.boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`));
|
|
1808
|
+
const closing = sections.findIndex((s) => s.startsWith("--"));
|
|
1809
|
+
if (closing < 0) return mimeError("multipart/alternative has no closing boundary", false);
|
|
1810
|
+
const parts = [];
|
|
1811
|
+
for (const section of sections.slice(1, closing)) {
|
|
1812
|
+
const split = splitHead(section.replace(/^[ \t]*\r?\n/, ""));
|
|
1813
|
+
if (!split) return mimeError("MIME part headers and body need a blank-line separator", false);
|
|
1814
|
+
const partHeaders = parseHeaderBlock(split.head);
|
|
1815
|
+
if (!Array.isArray(partHeaders)) return partHeaders;
|
|
1816
|
+
const part = textPart(String(parts.length), partHeaders, split.body);
|
|
1817
|
+
if ("error" in part) return part;
|
|
1818
|
+
parts.push(part);
|
|
1819
|
+
}
|
|
1820
|
+
if (!parts.length || parts.length > 10) return mimeError("multipart/alternative needs 1 to 10 parts", false);
|
|
1821
|
+
payload = { partId: "", mimeType, filename: "", headers, body: { size: 0 }, parts };
|
|
1822
|
+
} else if (mimeType.startsWith("multipart/")) {
|
|
1823
|
+
return mimeError(`${mimeType} (attachments or nested parts) is outside the verified subset`, true);
|
|
1824
|
+
} else {
|
|
1825
|
+
const part = textPart("", headers, top.body);
|
|
1826
|
+
if ("error" in part) return part;
|
|
1827
|
+
payload = part;
|
|
1828
|
+
}
|
|
1829
|
+
const text2 = partText(payload, "text/plain") ?? partText(payload, "text/html")?.replace(/<[^>]*>/g, " ") ?? "";
|
|
1830
|
+
return { headers, payload, snippet: text2.replace(/\s+/g, " ").trim().slice(0, 200), bytes: bytes.length };
|
|
1831
|
+
}
|
|
1832
|
+
function headerAddresses(value) {
|
|
1833
|
+
return (value?.match(/[^\s<>,;:"()]+@[^\s<>,;:"()]+/g) ?? []).map((a) => a.toLowerCase());
|
|
1834
|
+
}
|
|
1835
|
+
function parseGmailBatch(raw, contentTypeHeader) {
|
|
1836
|
+
const boundary = /boundary=(?:"([^"]+)"|([^\s;]+))/i.exec(contentTypeHeader ?? "");
|
|
1837
|
+
if (!boundary) return mimeError("Batch Content-Type needs a boundary", false);
|
|
1838
|
+
const marker = `--${boundary[1] ?? boundary[2]}`;
|
|
1839
|
+
const sections = raw.split(marker);
|
|
1840
|
+
const closing = sections.findIndex((s, i) => i > 0 && s.startsWith("--"));
|
|
1841
|
+
if (closing < 0) return mimeError("Batch body has no closing boundary", false);
|
|
1842
|
+
const requests = [];
|
|
1843
|
+
for (const section of sections.slice(1, closing)) {
|
|
1844
|
+
const outer = splitHead(section.replace(/^[ \t]*\r?\n/, ""));
|
|
1845
|
+
if (!outer) return mimeError("Batch part needs headers and a request", false);
|
|
1846
|
+
const outerHeaders = parseHeaderBlock(outer.head);
|
|
1847
|
+
if (!Array.isArray(outerHeaders)) return outerHeaders;
|
|
1848
|
+
if (outerHeaders.some((h) => /[\x00-\x08\x0a-\x1f\x7f]/.test(h.value))) return mimeError("Invalid batch part header", false);
|
|
1849
|
+
if (contentType(outerHeaders).mimeType !== "application/http") return mimeError("Batch parts must be application/http", false);
|
|
1850
|
+
const lines = outer.body.split(/\r?\n/);
|
|
1851
|
+
const line = /^([A-Z]+) (\S+)(?: HTTP\/1\.1)?$/.exec(lines[0]?.trim() ?? "");
|
|
1852
|
+
if (!line) return mimeError("Invalid batch request line", false);
|
|
1853
|
+
const rest = lines.slice(1).join("\n");
|
|
1854
|
+
const innerBody = splitHead(rest)?.body ?? "";
|
|
1855
|
+
if (innerBody.trim()) return mimeError("Batch requests with bodies are outside the verified subset", true);
|
|
1856
|
+
const url = new URL(line[2], "http://batch.invalid");
|
|
1857
|
+
requests.push({ contentId: headerValue(outerHeaders, "content-id"), method: line[1], path: url.pathname, query: Object.fromEntries(url.searchParams) });
|
|
1858
|
+
}
|
|
1859
|
+
if (!requests.length || requests.length > 100) return mimeError("Batch needs 1 to 100 requests", false);
|
|
1860
|
+
return requests;
|
|
1861
|
+
}
|
|
1862
|
+
function parseGmailUpload(raw, contentTypeHeader) {
|
|
1863
|
+
const boundary = /boundary=(?:"([^"]+)"|([^\s;]+))/i.exec(contentTypeHeader ?? "");
|
|
1864
|
+
if (!/^multipart\/related\b/i.test(contentTypeHeader ?? "") || !boundary) return mimeError("Upload Content-Type must be multipart/related with a boundary", false);
|
|
1865
|
+
const marker = `--${boundary[1] ?? boundary[2]}`;
|
|
1866
|
+
const sections = raw.split(marker);
|
|
1867
|
+
const closing = sections.findIndex((s, i) => i > 0 && s.startsWith("--"));
|
|
1868
|
+
if (closing !== 3) return mimeError("Upload body must have exactly a metadata part and a message part", false);
|
|
1869
|
+
const parts = [];
|
|
1870
|
+
for (const section of sections.slice(1, closing)) {
|
|
1871
|
+
const split = splitHead(section.replace(/^[ \t]*\r?\n/, ""));
|
|
1872
|
+
if (!split) return mimeError("Upload part needs headers and a body", false);
|
|
1873
|
+
const headers = parseHeaderBlock(split.head);
|
|
1874
|
+
if (!Array.isArray(headers)) return headers;
|
|
1875
|
+
const encoding = headerValue(headers, "content-transfer-encoding")?.toLowerCase();
|
|
1876
|
+
if (encoding && !["7bit", "8bit", "binary"].includes(encoding)) return mimeError(`Upload part encoding ${encoding} is outside the verified subset`, true);
|
|
1877
|
+
parts.push({ type: contentType(headers).mimeType, body: split.body.replace(/\r?\n$/, "") });
|
|
1878
|
+
}
|
|
1879
|
+
const [meta, message] = parts;
|
|
1880
|
+
if (meta.type !== "application/json") return mimeError("First upload part must be application/json metadata", false);
|
|
1881
|
+
if (message.type !== "message/rfc822") return mimeError(`Upload media type ${message.type} is outside the verified subset`, true);
|
|
1882
|
+
let metadata;
|
|
1883
|
+
try {
|
|
1884
|
+
metadata = meta.body.trim() ? JSON.parse(meta.body) : {};
|
|
1885
|
+
} catch {
|
|
1886
|
+
return mimeError("Upload metadata must be JSON", false);
|
|
1887
|
+
}
|
|
1888
|
+
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return mimeError("Upload metadata must be a JSON object", false);
|
|
1889
|
+
if (!message.body.trim()) return mimeError("Upload message is empty", false);
|
|
1890
|
+
return { metadata, raw: Buffer.from(message.body, "utf8").toString("base64url") };
|
|
868
1891
|
}
|
|
869
1892
|
|
|
870
1893
|
// src/runtime/rest-adapters.ts
|
|
@@ -882,8 +1905,8 @@ var rows = (data, collection) => data[collection];
|
|
|
882
1905
|
var notFound = (collection, body) => ({ status: 404, body, collection });
|
|
883
1906
|
var badRequest = (collection, body) => ({ status: 400, body, collection });
|
|
884
1907
|
var ok = (collection, body, operation = "read") => ({ status: 200, body, collection, operation });
|
|
885
|
-
var created = (collection, body,
|
|
886
|
-
var write = (status, collection, body,
|
|
1908
|
+
var created = (collection, body, record3) => ({ status: 201, body, collection, record: structuredClone(record3), operation: "write" });
|
|
1909
|
+
var write = (status, collection, body, record3) => ({ status, body, collection, record: structuredClone(record3), operation: "write" });
|
|
887
1910
|
var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
888
1911
|
var str = (v) => typeof v === "string" ? v : void 0;
|
|
889
1912
|
var pagination = (params, limitDefault, limitMax) => {
|
|
@@ -1154,15 +2177,15 @@ function notionOperation(method, path, params, headers, data, sequence) {
|
|
|
1154
2177
|
if (!page && !block) return notionError("/blocks", 404, "object_not_found", "Could not find block with ID.");
|
|
1155
2178
|
const parent = page ? { type: "page_id", page_id: page.id } : { type: "block_id", block_id: block.id };
|
|
1156
2179
|
const createdBlocks = params.children.map((child, index) => {
|
|
1157
|
-
const
|
|
1158
|
-
rows(data, "/blocks").push(
|
|
1159
|
-
return
|
|
2180
|
+
const record3 = { object: "block", id: detUuid(`block:${sequence}:${index}`), parent, type: child.type, created_time: iso(), last_edited_time: iso(), has_children: false, archived: false, block: structuredClone(child) };
|
|
2181
|
+
rows(data, "/blocks").push(record3);
|
|
2182
|
+
return record3;
|
|
1160
2183
|
});
|
|
1161
2184
|
return write(200, "/blocks", { object: "list", results: structuredClone(createdBlocks), has_more: false, next_cursor: null, type: "block", block: {} }, createdBlocks[createdBlocks.length - 1]);
|
|
1162
2185
|
}
|
|
1163
2186
|
return void 0;
|
|
1164
2187
|
}
|
|
1165
|
-
var hubspotEnvelope = (
|
|
2188
|
+
var hubspotEnvelope = (record3) => ({ id: record3.id, properties: structuredClone(record3.properties), createdAt: record3.createdAt, updatedAt: record3.updatedAt, archived: false });
|
|
1166
2189
|
function hubspotOperation(method, path, params, _headers, data, sequence) {
|
|
1167
2190
|
const match = /^\/crm\/v3\/objects\/(contacts|companies|deals|tickets)(?:\/(search)|\/([^/]+))?$/.exec(path);
|
|
1168
2191
|
if (!match) return void 0;
|
|
@@ -1210,18 +2233,18 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
|
|
|
1210
2233
|
}
|
|
1211
2234
|
if (method !== "POST") return void 0;
|
|
1212
2235
|
if (Object.keys(params).some((k) => k !== "properties" && k !== "associations") || params.associations !== void 0 && !Array.isArray(params.associations) || !properties || !validProperties(properties)) return badRequest(collection, { status: "error", message: `Invalid input JSON on line 1: Unable to process JSON: properties required for ${object3}`, category: "VALIDATION_ERROR" });
|
|
1213
|
-
const
|
|
1214
|
-
rows(data, collection).push(
|
|
1215
|
-
return created(collection, hubspotEnvelope(
|
|
2236
|
+
const record4 = { id: uniqueId(rows(data, collection), 501 + sequence), properties: structuredClone(properties), createdAt: iso(), updatedAt: iso() };
|
|
2237
|
+
rows(data, collection).push(record4);
|
|
2238
|
+
return created(collection, hubspotEnvelope(record4), record4);
|
|
1216
2239
|
}
|
|
1217
|
-
const
|
|
1218
|
-
if (!
|
|
1219
|
-
if (method === "GET") return ok(collection, hubspotEnvelope(
|
|
2240
|
+
const record3 = rows(data, collection).find((r) => r.id === id);
|
|
2241
|
+
if (!record3) return { status: 404, body: { status: "error", message: `Object not found: ${object3} with id ${id}`, category: "OBJECT_NOT_FOUND" }, collection };
|
|
2242
|
+
if (method === "GET") return ok(collection, hubspotEnvelope(record3));
|
|
1220
2243
|
if (method === "PATCH") {
|
|
1221
2244
|
if (Object.keys(params).some((k) => k !== "properties") || !properties || !validProperties(properties)) return badRequest(collection, { status: "error", message: "Unable to process JSON: properties object required", category: "VALIDATION_ERROR" });
|
|
1222
|
-
Object.assign(
|
|
1223
|
-
|
|
1224
|
-
return write(200, collection, hubspotEnvelope(
|
|
2245
|
+
Object.assign(record3.properties, structuredClone(properties));
|
|
2246
|
+
record3.updatedAt = iso();
|
|
2247
|
+
return write(200, collection, hubspotEnvelope(record3), record3);
|
|
1225
2248
|
}
|
|
1226
2249
|
return void 0;
|
|
1227
2250
|
}
|
|
@@ -1235,7 +2258,7 @@ function shopifyOperation(method, path, params, _headers, data, sequence) {
|
|
|
1235
2258
|
const wrap = resource === "products" ? "product" : resource === "orders" ? "order" : "customer";
|
|
1236
2259
|
const rowsIn2 = rows(data, collection);
|
|
1237
2260
|
const notFoundShopify = () => notFound(collection, { errors: "Not Found" });
|
|
1238
|
-
const enriched = (
|
|
2261
|
+
const enriched = (record4) => ({ ...structuredClone(record4), created_at: record4.created_at ?? iso(), updated_at: iso() });
|
|
1239
2262
|
if (!id) {
|
|
1240
2263
|
if (method === "GET") {
|
|
1241
2264
|
if (Object.keys(params).some((k) => !["limit", "since_id"].includes(k))) return void 0;
|
|
@@ -1258,25 +2281,25 @@ function shopifyOperation(method, path, params, _headers, data, sequence) {
|
|
|
1258
2281
|
}
|
|
1259
2282
|
const allowed = { products: ["title", "body_html", "vendor", "product_type", "status", "tags", "variants", "options"], orders: ["email", "phone", "line_items", "financial_status", "fulfillment_status", "note", "total_price", "currency"], customers: ["first_name", "last_name", "email", "phone", "note", "tags"] }[resource];
|
|
1260
2283
|
if (Object.keys(body).some((k) => !allowed.includes(k))) return void 0;
|
|
1261
|
-
const
|
|
1262
|
-
if (resource === "products") Object.assign(
|
|
1263
|
-
if (resource === "orders") Object.assign(
|
|
1264
|
-
if (resource === "customers") Object.assign(
|
|
1265
|
-
rowsIn2.push(
|
|
1266
|
-
return created(collection, { [wrap]: enriched(
|
|
1267
|
-
}
|
|
1268
|
-
const
|
|
1269
|
-
if (!
|
|
1270
|
-
if (method === "GET") return ok(collection, { [wrap]: enriched(
|
|
2284
|
+
const record4 = { id: uniqueId(rowsIn2, { products: 632910392, orders: 450789469, customers: 207119551 }[resource] + sequence), created_at: iso(), updated_at: iso() };
|
|
2285
|
+
if (resource === "products") Object.assign(record4, { title: body.title, body_html: body.body_html ?? null, vendor: body.vendor ?? null, product_type: body.product_type ?? null, handle: shopifySlug(String(body.title)), status: str(body.status) ?? "active", tags: body.tags ?? "", variants: Array.isArray(body.variants) ? structuredClone(body.variants) : [], options: Array.isArray(body.options) ? structuredClone(body.options) : [], image: null, images: [] });
|
|
2286
|
+
if (resource === "orders") Object.assign(record4, { email: body.email ?? null, phone: body.phone ?? null, note: body.note ?? null, line_items: structuredClone(body.line_items), total_price: typeof body.total_price === "string" ? body.total_price : Number(Array.isArray(body.line_items) ? body.line_items.reduce((sum, item) => sum + Number(item.price ?? 0) * Number(item.quantity ?? 1), 0) : 0).toFixed(2), currency: str(body.currency) ?? "USD", financial_status: str(body.financial_status) ?? "pending", fulfillment_status: body.fulfillment_status ?? null });
|
|
2287
|
+
if (resource === "customers") Object.assign(record4, { first_name: body.first_name ?? null, last_name: body.last_name ?? null, email: body.email ?? null, phone: body.phone ?? null, note: body.note ?? null, tags: body.tags ?? "", state: "enabled", verified_email: true, accepts_marketing: false });
|
|
2288
|
+
rowsIn2.push(record4);
|
|
2289
|
+
return created(collection, { [wrap]: enriched(record4) }, record4);
|
|
2290
|
+
}
|
|
2291
|
+
const record3 = rowsIn2.find((r) => String(r.id) === id);
|
|
2292
|
+
if (!record3) return notFoundShopify();
|
|
2293
|
+
if (method === "GET") return ok(collection, { [wrap]: enriched(record3) });
|
|
1271
2294
|
if (method === "PUT") {
|
|
1272
2295
|
if (Object.keys(params).some((k) => k !== wrap) || !isObject(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
|
|
1273
2296
|
const body = params[wrap];
|
|
1274
2297
|
const allowed = { products: ["title", "body_html", "vendor", "product_type", "status", "tags"], orders: ["email", "phone", "note", "financial_status", "fulfillment_status"], customers: ["first_name", "last_name", "email", "phone", "note", "tags"] }[resource];
|
|
1275
2298
|
if (Object.keys(body).some((k) => !allowed.includes(k))) return void 0;
|
|
1276
|
-
for (const [k, v] of Object.entries(body))
|
|
1277
|
-
if (resource === "products" && body.title !== void 0)
|
|
1278
|
-
|
|
1279
|
-
return write(200, collection, { [wrap]: enriched(
|
|
2299
|
+
for (const [k, v] of Object.entries(body)) record3[k] = v;
|
|
2300
|
+
if (resource === "products" && body.title !== void 0) record3.handle = shopifySlug(String(body.title));
|
|
2301
|
+
record3.updated_at = iso();
|
|
2302
|
+
return write(200, collection, { [wrap]: enriched(record3) }, record3);
|
|
1280
2303
|
}
|
|
1281
2304
|
return void 0;
|
|
1282
2305
|
}
|
|
@@ -1349,27 +2372,317 @@ function datadogOperation(method, path, params, _headers, data, sequence) {
|
|
|
1349
2372
|
}
|
|
1350
2373
|
var googleError = (collection, status, message) => ({ status, body: { error: { code: status, message, status: status === 404 ? "NOT_FOUND" : "INVALID_ARGUMENT" } }, collection });
|
|
1351
2374
|
var rowsIn = (data, collection) => data[collection];
|
|
1352
|
-
|
|
1353
|
-
|
|
2375
|
+
var GMAIL_MESSAGES = "/gmail/v1/users/me/messages";
|
|
2376
|
+
var GMAIL_THREADS = "/gmail/v1/users/me/threads";
|
|
2377
|
+
var GMAIL_DRAFTS = "/gmail/v1/users/me/drafts";
|
|
2378
|
+
var GMAIL_SEND_AS = "/gmail/v1/users/me/settings/sendAs";
|
|
2379
|
+
var GMAIL_WATCH = "/gmail/v1/users/me/watch";
|
|
2380
|
+
var PUBSUB_SUBSCRIPTIONS = "/pubsub/subscriptions";
|
|
2381
|
+
var PUBSUB_MESSAGES = "/pubsub/messages";
|
|
2382
|
+
var gmailHeader = (message, name) => (message.payload?.headers ?? []).find((h) => h.name.toLowerCase() === name)?.value;
|
|
2383
|
+
var gmailDate = (message) => Number(message.internalDate ?? 0);
|
|
2384
|
+
var gmailThreadMessages = (data, threadId) => rowsIn(data, GMAIL_MESSAGES).filter((m) => m.threadId === threadId).sort((a, b) => gmailDate(a) - gmailDate(b));
|
|
2385
|
+
var GMAIL_SYSTEM_LABELS = /* @__PURE__ */ new Set(["INBOX", "SPAM", "TRASH", "UNREAD", "STARRED", "IMPORTANT", "SENT", "DRAFT", "CATEGORY_PERSONAL", "CATEGORY_SOCIAL", "CATEGORY_PROMOTIONS", "CATEGORY_UPDATES", "CATEGORY_FORUMS"]);
|
|
2386
|
+
var gmailLabelKnown = (data) => {
|
|
2387
|
+
const seeded = new Set(rowsIn(data, "/gmail/v1/users/me/labels").map((l) => l.id));
|
|
2388
|
+
return (id) => GMAIL_SYSTEM_LABELS.has(id) || seeded.has(id);
|
|
2389
|
+
};
|
|
2390
|
+
var gmailHistoryId = (messages) => messages.reduce((max, m) => BigInt(String(m.historyId ?? 0)) > BigInt(max) ? String(m.historyId) : max, "0");
|
|
2391
|
+
function gmailQueryMatcher(q) {
|
|
2392
|
+
const clauses = q.trim().split(/\s+OR\s+/);
|
|
2393
|
+
const parsed = [];
|
|
2394
|
+
for (const clause of clauses) {
|
|
2395
|
+
const terms = clause.trim().split(/\s+/).map((token) => /^(from|to):([^\s()"]+@[^\s()"]+)$/i.exec(token));
|
|
2396
|
+
if (!terms.length || terms.some((t) => !t)) return void 0;
|
|
2397
|
+
parsed.push(terms.map((t) => ({ field: t[1].toLowerCase(), address: t[2].toLowerCase() })));
|
|
2398
|
+
}
|
|
2399
|
+
return (message) => parsed.some((terms) => terms.every((t) => headerAddresses(gmailHeader(message, t.field)).includes(t.address)));
|
|
2400
|
+
}
|
|
2401
|
+
function gmailBatch(params, headers, data, sequence, raw) {
|
|
2402
|
+
if (raw === void 0 || Object.keys(params).length) return void 0;
|
|
2403
|
+
const contentType2 = headers["content-type"];
|
|
2404
|
+
const requests = parseGmailBatch(raw, typeof contentType2 === "string" ? contentType2 : void 0);
|
|
2405
|
+
if ("error" in requests) return requests.unsupported ? void 0 : googleError(GMAIL_MESSAGES, 400, requests.error);
|
|
2406
|
+
const responses = [];
|
|
2407
|
+
for (const request of requests) {
|
|
2408
|
+
if (request.method !== "GET" || !/^\/gmail\/v1\/users\/me\/(messages|threads)\/[^/]+$/.test(request.path)) return void 0;
|
|
2409
|
+
const result = gmailOperation("GET", request.path, request.query, {}, data, sequence);
|
|
2410
|
+
if (!result) return void 0;
|
|
2411
|
+
responses.push({ contentId: request.contentId, status: result.status, body: result.body });
|
|
2412
|
+
}
|
|
2413
|
+
const boundary = `batch_agenttwin_${sequence}`;
|
|
2414
|
+
const reason = { 200: "OK", 400: "Bad Request", 404: "Not Found" };
|
|
2415
|
+
const body = responses.map((r, i) => `--${boundary}\r
|
|
2416
|
+
Content-Type: application/http\r
|
|
2417
|
+
Content-ID: response-${(r.contentId ?? `item${i + 1}`).replace(/^<|>$/g, "")}\r
|
|
2418
|
+
\r
|
|
2419
|
+
HTTP/1.1 ${r.status} ${reason[r.status] ?? "Error"}\r
|
|
2420
|
+
Content-Type: application/json; charset=UTF-8\r
|
|
2421
|
+
\r
|
|
2422
|
+
${JSON.stringify(r.body)}\r
|
|
2423
|
+
`).join("") + `--${boundary}--\r
|
|
2424
|
+
`;
|
|
2425
|
+
return { status: 200, body, collection: GMAIL_MESSAGES, operation: "read", record: { batch: requests.map((r) => r.path), statuses: responses.map((r) => r.status) }, headers: { "content-type": `multipart/mixed; boundary=${boundary}` } };
|
|
2426
|
+
}
|
|
2427
|
+
function gmailPublish(data, labelIds, sequence) {
|
|
2428
|
+
const watch = rowsIn(data, GMAIL_WATCH)?.[0];
|
|
2429
|
+
if (!watch) return [];
|
|
2430
|
+
const watched = watch.labelIds ?? [];
|
|
2431
|
+
const matches2 = !watched.length || (watch.labelFilterBehavior === "exclude" ? !labelIds.some((l) => watched.includes(l)) : labelIds.some((l) => watched.includes(l)));
|
|
2432
|
+
if (!matches2) return [];
|
|
2433
|
+
const primary = rowsIn(data, GMAIL_SEND_AS)?.find((r) => r.isPrimary === true);
|
|
2434
|
+
const historyId = gmailHistoryId(rowsIn(data, GMAIL_MESSAGES));
|
|
2435
|
+
const deliveries = [];
|
|
2436
|
+
(rowsIn(data, PUBSUB_SUBSCRIPTIONS) ?? []).filter((sub) => sub.topic === watch.topicName).forEach((sub, i) => {
|
|
2437
|
+
const messageId = `pubsub_at_${sequence}_${i + 1}`, publishTime = new Date(twinNowMs(17e11)).toISOString();
|
|
2438
|
+
const encoded = Buffer.from(JSON.stringify({ emailAddress: primary?.sendAsEmail ?? null, historyId: Number(historyId) })).toString("base64");
|
|
2439
|
+
const row = { messageId, subscription: sub.name, topic: sub.topic, data: encoded, emailAddress: primary?.sendAsEmail ?? null, historyId, publishTime, pushEndpoint: sub.pushEndpoint, delivery: "pending" };
|
|
2440
|
+
rowsIn(data, PUBSUB_MESSAGES).push(row);
|
|
2441
|
+
if (!primary) {
|
|
2442
|
+
row.delivery = "skipped: the mailbox has no primary sendAs address";
|
|
2443
|
+
return;
|
|
2444
|
+
}
|
|
2445
|
+
deliveries.push({ url: String(sub.pushEndpoint), row, body: { message: { data: encoded, messageId, message_id: messageId, publishTime, publish_time: publishTime, attributes: {} }, subscription: sub.name } });
|
|
2446
|
+
});
|
|
2447
|
+
return deliveries;
|
|
2448
|
+
}
|
|
2449
|
+
var withPush = (result, deliveries) => deliveries.length ? { ...result, deliveries } : result;
|
|
2450
|
+
function gmailStoreDraft(data, mime, threadId, sequence, replaceIndex) {
|
|
2451
|
+
const messages = rowsIn(data, GMAIL_MESSAGES), drafts = rowsIn(data, GMAIL_DRAFTS);
|
|
2452
|
+
const existing = replaceIndex === void 0 ? void 0 : drafts[replaceIndex];
|
|
2453
|
+
const messageId = `gmail_draft_msg_at_${sequence}`, draftId = existing ? String(existing.id) : `r_at_${sequence}`;
|
|
2454
|
+
const message = { id: messageId, threadId: threadId ?? messageId, labelIds: ["DRAFT"], snippet: mime.snippet, payload: mime.payload, sizeEstimate: mime.bytes, internalDate: String(twinNowMs(17e11)), historyId: String(17e8 + sequence) };
|
|
2455
|
+
if (existing) {
|
|
2456
|
+
const old = messages.findIndex((m) => m.id === existing.message.id);
|
|
2457
|
+
if (old >= 0) messages.splice(old, 1);
|
|
2458
|
+
}
|
|
2459
|
+
messages.push(message);
|
|
2460
|
+
const value = (name) => mime.headers.find((h) => h.name.toLowerCase() === name)?.value ?? null;
|
|
2461
|
+
const draft = { id: draftId, message: structuredClone(message), threadId: message.threadId, to: value("to"), subject: value("subject"), inReplyTo: value("in-reply-to"), references: value("references"), ...existing ? { updated: Number(existing.updated ?? 0) + 1 } : {} };
|
|
2462
|
+
if (existing) drafts.splice(replaceIndex, 1, draft);
|
|
2463
|
+
else drafts.push(draft);
|
|
2464
|
+
return write(200, GMAIL_DRAFTS, { id: draftId, message: { id: messageId, threadId: message.threadId, labelIds: ["DRAFT"] } }, draft);
|
|
2465
|
+
}
|
|
2466
|
+
function gmailDraftWrite(data, raw, threadIdInput, sequence, index) {
|
|
2467
|
+
const draftFail = (status, message) => googleError(GMAIL_DRAFTS, status, message);
|
|
2468
|
+
if (typeof raw !== "string" || !raw) return draftFail(400, "message.raw must be a base64url MIME string.");
|
|
2469
|
+
if (threadIdInput !== void 0 && typeof threadIdInput !== "string") return draftFail(400, "message.threadId must be a string.");
|
|
2470
|
+
let threadId = threadIdInput;
|
|
2471
|
+
if (index !== void 0) {
|
|
2472
|
+
const current = rowsIn(data, GMAIL_DRAFTS)[index].threadId;
|
|
2473
|
+
if (threadId !== void 0 && threadId !== current) return void 0;
|
|
2474
|
+
threadId = current;
|
|
2475
|
+
} else if (threadId !== void 0 && !gmailThreadMessages(data, threadId).length) return draftFail(404, "Requested entity was not found.");
|
|
2476
|
+
const mime = parseGmailDraftRaw(raw);
|
|
2477
|
+
if ("error" in mime) return mime.unsupported ? void 0 : draftFail(400, mime.error);
|
|
2478
|
+
return gmailStoreDraft(data, mime, threadId, sequence, index);
|
|
2479
|
+
}
|
|
2480
|
+
function gmailOperation(method, path, params, headers, data, sequence, raw) {
|
|
2481
|
+
const MESSAGES = GMAIL_MESSAGES, LABELS = "/gmail/v1/users/me/labels";
|
|
1354
2482
|
const fail = (status, message) => googleError(MESSAGES, status, message);
|
|
2483
|
+
if (path === "/batch/gmail/v1") return method === "POST" ? gmailBatch(params, headers, data, sequence, raw) : void 0;
|
|
2484
|
+
const uploadMatch = /^\/upload\/gmail\/v1\/users\/me\/drafts(?:\/([^/]+))?$/.exec(path);
|
|
2485
|
+
if (uploadMatch) {
|
|
2486
|
+
const id = uploadMatch[1] === void 0 ? void 0 : decodeURIComponent(uploadMatch[1]);
|
|
2487
|
+
if ((id === void 0 ? method !== "POST" : method !== "PUT") || raw === void 0 || Object.keys(params).some((k) => k !== "uploadType") || params.uploadType !== "multipart") return void 0;
|
|
2488
|
+
const ctype = headers["content-type"];
|
|
2489
|
+
const upload = parseGmailUpload(raw, typeof ctype === "string" ? ctype : void 0);
|
|
2490
|
+
if ("error" in upload) return upload.unsupported ? void 0 : googleError(GMAIL_DRAFTS, 400, upload.error);
|
|
2491
|
+
if (Object.keys(upload.metadata).some((k) => !["id", "message"].includes(k))) return void 0;
|
|
2492
|
+
const meta = upload.metadata.message === void 0 ? {} : upload.metadata.message;
|
|
2493
|
+
if (!meta || typeof meta !== "object" || Array.isArray(meta)) return googleError(GMAIL_DRAFTS, 400, "message must be an object.");
|
|
2494
|
+
if (Object.keys(meta).some((k) => k !== "threadId")) return void 0;
|
|
2495
|
+
let index;
|
|
2496
|
+
if (id !== void 0) {
|
|
2497
|
+
if (upload.metadata.id !== void 0 && upload.metadata.id !== id) return googleError(GMAIL_DRAFTS, 400, "Draft id in the body does not match the URL.");
|
|
2498
|
+
index = rowsIn(data, GMAIL_DRAFTS).findIndex((d) => d.id === id);
|
|
2499
|
+
if (index < 0) return googleError(GMAIL_DRAFTS, 404, "Requested entity was not found.");
|
|
2500
|
+
} else if (upload.metadata.id !== void 0) return void 0;
|
|
2501
|
+
const threadId = meta.threadId;
|
|
2502
|
+
return gmailDraftWrite(data, upload.raw, threadId === null ? void 0 : threadId, sequence, index);
|
|
2503
|
+
}
|
|
2504
|
+
if (path === GMAIL_THREADS) {
|
|
2505
|
+
if (method !== "GET" || Object.keys(params).some((k) => !["q", "maxResults", "labelIds"].includes(k))) return void 0;
|
|
2506
|
+
if (params.q !== void 0 && typeof params.q !== "string") return googleError(GMAIL_THREADS, 400, "q must be a string.");
|
|
2507
|
+
const matcher = params.q === void 0 || params.q === "" ? () => true : gmailQueryMatcher(params.q);
|
|
2508
|
+
if (!matcher) return void 0;
|
|
2509
|
+
const max = params.maxResults === void 0 ? 100 : Number(params.maxResults);
|
|
2510
|
+
if (!Number.isInteger(max) || max < 1 || max > 500) return googleError(GMAIL_THREADS, 400, "maxResults must be an integer from 1 to 500.");
|
|
2511
|
+
const labels = params.labelIds === void 0 ? [] : Array.isArray(params.labelIds) ? params.labelIds.map(String) : [String(params.labelIds)];
|
|
2512
|
+
const latest = /* @__PURE__ */ new Map();
|
|
2513
|
+
for (const message of rowsIn(data, MESSAGES)) {
|
|
2514
|
+
const ids = Array.isArray(message.labelIds) ? message.labelIds : [];
|
|
2515
|
+
if (ids.includes("SPAM") || ids.includes("TRASH") || !labels.every((l) => ids.includes(l)) || !matcher(message)) continue;
|
|
2516
|
+
const thread = String(message.threadId ?? message.id);
|
|
2517
|
+
if (!latest.has(thread) || gmailDate(message) > gmailDate(latest.get(thread))) latest.set(thread, message);
|
|
2518
|
+
}
|
|
2519
|
+
const threads = [...latest.entries()].sort((a, b) => gmailDate(b[1]) - gmailDate(a[1])).slice(0, max).map(([id]) => {
|
|
2520
|
+
const messages = gmailThreadMessages(data, id);
|
|
2521
|
+
return { id, snippet: messages.at(-1)?.snippet ?? "", historyId: gmailHistoryId(messages) };
|
|
2522
|
+
});
|
|
2523
|
+
return ok(GMAIL_THREADS, threads.length ? { threads, resultSizeEstimate: threads.length } : { resultSizeEstimate: 0 });
|
|
2524
|
+
}
|
|
2525
|
+
const threadMatch = /^\/gmail\/v1\/users\/me\/threads\/([^/]+)$/.exec(path);
|
|
2526
|
+
if (threadMatch) {
|
|
2527
|
+
if (method !== "GET" || Object.keys(params).some((k) => k !== "format") || params.format !== void 0 && params.format !== "full") return void 0;
|
|
2528
|
+
const messages = gmailThreadMessages(data, decodeURIComponent(threadMatch[1]));
|
|
2529
|
+
if (!messages.length) return googleError(GMAIL_THREADS, 404, "Requested entity was not found.");
|
|
2530
|
+
return ok(GMAIL_THREADS, { id: decodeURIComponent(threadMatch[1]), historyId: gmailHistoryId(messages), messages: structuredClone(messages) });
|
|
2531
|
+
}
|
|
2532
|
+
if (path === "/gmail/v1/users/me/history") {
|
|
2533
|
+
if (method !== "GET" || Object.keys(params).some((k) => !["startHistoryId", "historyTypes", "maxResults"].includes(k))) return void 0;
|
|
2534
|
+
if (params.historyTypes !== void 0 && !["messageAdded", "labelAdded", "labelRemoved"].includes(String(params.historyTypes))) return void 0;
|
|
2535
|
+
if (typeof params.startHistoryId !== "string" || !/^\d{1,20}$/.test(params.startHistoryId)) return googleError(MESSAGES, 400, "startHistoryId is required.");
|
|
2536
|
+
const max = params.maxResults === void 0 ? 100 : Number(params.maxResults);
|
|
2537
|
+
if (!Number.isInteger(max) || max < 1 || max > 500) return googleError(MESSAGES, 400, "maxResults must be an integer from 1 to 500.");
|
|
2538
|
+
const start = BigInt(params.startHistoryId);
|
|
2539
|
+
const all = rowsIn(data, MESSAGES);
|
|
2540
|
+
const added = all.filter((m) => BigInt(String(m.historyId ?? 0)) > start).sort((a, b) => BigInt(String(a.historyId)) < BigInt(String(b.historyId)) ? -1 : 1);
|
|
2541
|
+
if (added.length > max) return void 0;
|
|
2542
|
+
const history = added.map((m) => ({ id: String(m.historyId), messages: [{ id: m.id, threadId: m.threadId }], messagesAdded: [{ message: { id: m.id, threadId: m.threadId, labelIds: structuredClone(m.labelIds ?? []) } }] }));
|
|
2543
|
+
const latest = gmailHistoryId(all);
|
|
2544
|
+
return ok(MESSAGES, { ...history.length ? { history } : {}, historyId: BigInt(latest) > start ? latest : params.startHistoryId });
|
|
2545
|
+
}
|
|
2546
|
+
if (path === GMAIL_SEND_AS) {
|
|
2547
|
+
if (method !== "GET" || Object.keys(params).length) return void 0;
|
|
2548
|
+
return ok(GMAIL_SEND_AS, { sendAs: rowsIn(data, GMAIL_SEND_AS).map((row) => structuredClone(row)) });
|
|
2549
|
+
}
|
|
2550
|
+
if (path === GMAIL_WATCH) {
|
|
2551
|
+
if (method !== "POST" || Object.keys(params).some((k) => !["topicName", "labelIds", "labelFilterBehavior", "labelFilterAction"].includes(k))) return void 0;
|
|
2552
|
+
if (typeof params.topicName !== "string" || !/^projects\/[^/]+\/topics\/[^/]+$/.test(params.topicName)) return googleError(GMAIL_WATCH, 400, "Invalid topicName: expected projects/<project>/topics/<topic>.");
|
|
2553
|
+
if (params.labelIds !== void 0 && (!Array.isArray(params.labelIds) || params.labelIds.some((l) => typeof l !== "string"))) return googleError(GMAIL_WATCH, 400, "labelIds must be an array of strings.");
|
|
2554
|
+
const behavior = params.labelFilterBehavior ?? params.labelFilterAction;
|
|
2555
|
+
if (behavior !== void 0 && !["include", "exclude"].includes(String(behavior))) return googleError(GMAIL_WATCH, 400, "Invalid labelFilterBehavior.");
|
|
2556
|
+
const known2 = gmailLabelKnown(data);
|
|
2557
|
+
const labelIds = params.labelIds ?? [];
|
|
2558
|
+
if (labelIds.some((l) => !known2(l))) return googleError(GMAIL_WATCH, 400, "Invalid label in labelIds.");
|
|
2559
|
+
const historyId = gmailHistoryId(rowsIn(data, GMAIL_MESSAGES));
|
|
2560
|
+
const expiration = String(twinNowMs(17e11) + 7 * 24 * 60 * 60 * 1e3);
|
|
2561
|
+
const watch = { topicName: params.topicName, labelIds, labelFilterBehavior: behavior ?? "include", historyId, expiration };
|
|
2562
|
+
rowsIn(data, GMAIL_WATCH).splice(0, Infinity, watch);
|
|
2563
|
+
return write(200, GMAIL_WATCH, { historyId, expiration }, watch);
|
|
2564
|
+
}
|
|
2565
|
+
if (path === "/gmail/v1/users/me/stop") {
|
|
2566
|
+
if (method !== "POST" || Object.keys(params).length) return void 0;
|
|
2567
|
+
const watches = rowsIn(data, GMAIL_WATCH), removed = watches.splice(0, Infinity);
|
|
2568
|
+
return { status: 204, body: null, collection: GMAIL_WATCH, record: { stopped: removed.length }, operation: "write" };
|
|
2569
|
+
}
|
|
2570
|
+
if (path === `${GMAIL_DRAFTS}/send`) {
|
|
2571
|
+
if (method !== "POST" || Object.keys(params).some((k) => !["id", "message"].includes(k))) return void 0;
|
|
2572
|
+
const sendFail = (status, message2) => googleError(GMAIL_DRAFTS, status, message2);
|
|
2573
|
+
if (typeof params.id !== "string" || !params.id) return sendFail(400, "Draft id is required.");
|
|
2574
|
+
const drafts = rowsIn(data, GMAIL_DRAFTS), index = drafts.findIndex((d) => d.id === params.id);
|
|
2575
|
+
if (index < 0) return sendFail(404, "Requested entity was not found.");
|
|
2576
|
+
const messages = rowsIn(data, MESSAGES), draft = drafts[index];
|
|
2577
|
+
const message = messages.find((m) => m.id === draft.message.id);
|
|
2578
|
+
if (!message) return sendFail(404, "Requested entity was not found.");
|
|
2579
|
+
let update;
|
|
2580
|
+
if (params.message !== void 0) {
|
|
2581
|
+
if (!params.message || typeof params.message !== "object" || Array.isArray(params.message)) return sendFail(400, "message must be an object.");
|
|
2582
|
+
const fields = params.message;
|
|
2583
|
+
if (Object.keys(fields).some((k) => !["raw", "threadId"].includes(k))) return void 0;
|
|
2584
|
+
if (fields.threadId !== void 0 && fields.threadId !== message.threadId) return void 0;
|
|
2585
|
+
if (fields.raw !== void 0) {
|
|
2586
|
+
if (typeof fields.raw !== "string" || !fields.raw) return sendFail(400, "message.raw must be a base64url MIME string.");
|
|
2587
|
+
const mime = parseGmailDraftRaw(fields.raw);
|
|
2588
|
+
if ("error" in mime) return mime.unsupported ? void 0 : sendFail(400, mime.error);
|
|
2589
|
+
update = { payload: mime.payload, snippet: mime.snippet, bytes: mime.bytes };
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
const payload = update?.payload ?? message.payload;
|
|
2593
|
+
if (!headerAddresses(payload.headers?.find((h) => h.name.toLowerCase() === "to")?.value).length) return sendFail(400, "Invalid To header: a sent draft needs at least one recipient.");
|
|
2594
|
+
drafts.splice(index, 1);
|
|
2595
|
+
Object.assign(message, update ? { payload: update.payload, snippet: update.snippet, sizeEstimate: update.bytes } : {}, { labelIds: ["SENT"], internalDate: String(twinNowMs(17e11)), historyId: String(17e8 + sequence) });
|
|
2596
|
+
return withPush(write(200, MESSAGES, { id: message.id, threadId: message.threadId, labelIds: ["SENT"] }, { ...structuredClone(message), sentFromDraft: draft.id }), gmailPublish(data, ["SENT"], sequence));
|
|
2597
|
+
}
|
|
2598
|
+
const draftMatch = /^\/gmail\/v1\/users\/me\/drafts\/([^/]+)$/.exec(path);
|
|
2599
|
+
if (draftMatch) {
|
|
2600
|
+
const id = decodeURIComponent(draftMatch[1]);
|
|
2601
|
+
const drafts = rowsIn(data, GMAIL_DRAFTS), index = drafts.findIndex((d) => d.id === id);
|
|
2602
|
+
if (method === "GET") {
|
|
2603
|
+
if (Object.keys(params).some((k) => k !== "format") || params.format !== void 0 && params.format !== "full") return void 0;
|
|
2604
|
+
if (index < 0) return googleError(GMAIL_DRAFTS, 404, "Requested entity was not found.");
|
|
2605
|
+
const draft = drafts[index], message = rowsIn(data, MESSAGES).find((m) => m.id === draft.message.id);
|
|
2606
|
+
return ok(GMAIL_DRAFTS, { id, message: structuredClone(message ?? draft.message) });
|
|
2607
|
+
}
|
|
2608
|
+
if (method === "PUT") {
|
|
2609
|
+
if (Object.keys(params).some((k) => !["id", "message"].includes(k))) return void 0;
|
|
2610
|
+
if (index < 0) return googleError(GMAIL_DRAFTS, 404, "Requested entity was not found.");
|
|
2611
|
+
if (params.id !== void 0 && params.id !== id) return googleError(GMAIL_DRAFTS, 400, "Draft id in the body does not match the URL.");
|
|
2612
|
+
const input = params.message;
|
|
2613
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return googleError(GMAIL_DRAFTS, 400, "Draft message is required.");
|
|
2614
|
+
const fields = input;
|
|
2615
|
+
if (Object.keys(fields).some((k) => !["raw", "threadId"].includes(k))) return void 0;
|
|
2616
|
+
return gmailDraftWrite(data, fields.raw, fields.threadId, sequence, index);
|
|
2617
|
+
}
|
|
2618
|
+
if (method === "DELETE") {
|
|
2619
|
+
if (Object.keys(params).length) return void 0;
|
|
2620
|
+
if (index < 0) return googleError(GMAIL_DRAFTS, 404, "Requested entity was not found.");
|
|
2621
|
+
const [removed] = drafts.splice(index, 1);
|
|
2622
|
+
const messages = rowsIn(data, MESSAGES), messageIndex = messages.findIndex((m) => m.id === removed.message.id);
|
|
2623
|
+
if (messageIndex >= 0) messages.splice(messageIndex, 1);
|
|
2624
|
+
return { status: 204, body: null, collection: GMAIL_DRAFTS, record: { id, deleted: true, threadId: removed.threadId ?? null }, operation: "write" };
|
|
2625
|
+
}
|
|
2626
|
+
return void 0;
|
|
2627
|
+
}
|
|
2628
|
+
if (path === GMAIL_DRAFTS && method === "GET") {
|
|
2629
|
+
if (Object.keys(params).some((k) => k !== "maxResults")) return void 0;
|
|
2630
|
+
const max = params.maxResults === void 0 ? 100 : Number(params.maxResults);
|
|
2631
|
+
if (!Number.isInteger(max) || max < 1 || max > 500) return googleError(GMAIL_DRAFTS, 400, "maxResults must be an integer from 1 to 500.");
|
|
2632
|
+
const drafts = rowsIn(data, GMAIL_DRAFTS).slice(-max).reverse().map((d) => {
|
|
2633
|
+
const m = d.message;
|
|
2634
|
+
return { id: d.id, message: { id: m.id, threadId: m.threadId } };
|
|
2635
|
+
});
|
|
2636
|
+
return ok(GMAIL_DRAFTS, drafts.length ? { drafts, resultSizeEstimate: drafts.length } : { resultSizeEstimate: 0 });
|
|
2637
|
+
}
|
|
2638
|
+
if (path === GMAIL_DRAFTS) {
|
|
2639
|
+
if (method !== "POST" || Object.keys(params).some((k) => k !== "message")) return void 0;
|
|
2640
|
+
const input = params.message;
|
|
2641
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return googleError(GMAIL_DRAFTS, 400, "Draft message is required.");
|
|
2642
|
+
const fields = input;
|
|
2643
|
+
if (Object.keys(fields).some((k) => !["raw", "threadId"].includes(k))) return void 0;
|
|
2644
|
+
return gmailDraftWrite(data, fields.raw, fields.threadId, sequence);
|
|
2645
|
+
}
|
|
1355
2646
|
if (path === `${MESSAGES}/send`) {
|
|
1356
2647
|
if (method !== "POST") return void 0;
|
|
1357
2648
|
if (Object.keys(params).some((k) => !["raw", "to", "subject", "text", "threadId"].includes(k))) return void 0;
|
|
1358
|
-
const
|
|
1359
|
-
if (params.raw !== void 0 &&
|
|
1360
|
-
if (params.text !== void 0 &&
|
|
1361
|
-
if (!
|
|
1362
|
-
if (params.text !== void 0 &&
|
|
2649
|
+
const text2 = str(params.text), raw2 = str(params.raw);
|
|
2650
|
+
if (params.raw !== void 0 && raw2 === void 0) return fail(400, "raw must be a string.");
|
|
2651
|
+
if (params.text !== void 0 && text2 === void 0) return fail(400, "text must be a string.");
|
|
2652
|
+
if (!text2 && !raw2) return fail(400, "Message body is required: provide `text` or a `raw` MIME string.");
|
|
2653
|
+
if (params.text !== void 0 && text2 === "") return fail(400, "Message text must not be empty.");
|
|
1363
2654
|
if (params.to !== void 0 && str(params.to) === void 0) return fail(400, "to must be a string.");
|
|
1364
2655
|
if (params.subject !== void 0 && str(params.subject) === void 0) return fail(400, "subject must be a string.");
|
|
1365
2656
|
if (params.threadId !== void 0 && str(params.threadId) === void 0) return fail(400, "threadId must be a string.");
|
|
1366
|
-
if (
|
|
1367
|
-
const mime =
|
|
2657
|
+
if (raw2 && text2 !== void 0) return fail(400, "Provide raw or text, not both.");
|
|
2658
|
+
const mime = raw2 ? parseGmailRaw(raw2) : void 0;
|
|
1368
2659
|
if (mime && "error" in mime) return mime.unsupported ? void 0 : fail(400, mime.error);
|
|
1369
|
-
const body = mime?.text ??
|
|
2660
|
+
const body = mime?.text ?? text2 ?? "";
|
|
1370
2661
|
const message = { id: `gmail_at_${sequence}`, threadId: str(params.threadId) ?? `gmail_at_${sequence}`, labelIds: ["SENT"], snippet: body.slice(0, 100), payload: { mimeType: "text/plain", headers: mime?.headers ?? [{ name: "To", value: str(params.to) ?? "" }, { name: "Subject", value: str(params.subject) ?? "" }], body: { data: mime?.encodedBody ?? body } }, sizeEstimate: mime?.bytes ?? body.length, internalDate: String(twinNowMs(17e11)), historyId: String(17e8 + sequence) };
|
|
1371
2662
|
rowsIn(data, MESSAGES).push(message);
|
|
1372
|
-
return write(200, MESSAGES, structuredClone(message), message);
|
|
2663
|
+
return withPush(write(200, MESSAGES, structuredClone(message), message), gmailPublish(data, ["SENT"], sequence));
|
|
2664
|
+
}
|
|
2665
|
+
if (path === MESSAGES && method === "POST") {
|
|
2666
|
+
if (Object.keys(params).some((k) => !["raw", "labelIds", "threadId", "internalDateSource"].includes(k))) return void 0;
|
|
2667
|
+
if (typeof params.raw !== "string" || !params.raw) return fail(400, "raw must be a base64url MIME string.");
|
|
2668
|
+
if (params.threadId !== void 0 && (typeof params.threadId !== "string" || !gmailThreadMessages(data, params.threadId).length)) return fail(404, "Requested entity was not found.");
|
|
2669
|
+
if (params.labelIds !== void 0 && (!Array.isArray(params.labelIds) || params.labelIds.some((l) => typeof l !== "string"))) return fail(400, "labelIds must be an array of strings.");
|
|
2670
|
+
const known2 = gmailLabelKnown(data);
|
|
2671
|
+
const labelIds = params.labelIds ?? [];
|
|
2672
|
+
if (labelIds.some((l) => !known2(l))) return fail(400, "Invalid label in labelIds.");
|
|
2673
|
+
if (params.internalDateSource !== void 0 && !["receivedTime", "dateHeader"].includes(String(params.internalDateSource))) return fail(400, "Invalid internalDateSource.");
|
|
2674
|
+
const mime = parseGmailDraftRaw(params.raw);
|
|
2675
|
+
if ("error" in mime) return mime.unsupported ? void 0 : fail(400, mime.error);
|
|
2676
|
+
let internalDate = twinNowMs(17e11);
|
|
2677
|
+
if (params.internalDateSource === "dateHeader") {
|
|
2678
|
+
const date = Date.parse(mime.headers.find((h) => h.name.toLowerCase() === "date")?.value ?? "");
|
|
2679
|
+
if (!Number.isFinite(date)) return fail(400, "internalDateSource dateHeader needs a valid Date header.");
|
|
2680
|
+
internalDate = date;
|
|
2681
|
+
}
|
|
2682
|
+
const id = `gmail_insert_at_${sequence}`;
|
|
2683
|
+
const message = { id, threadId: params.threadId ?? id, labelIds, snippet: mime.snippet, payload: mime.payload, sizeEstimate: mime.bytes, internalDate: String(internalDate), historyId: String(17e8 + sequence) };
|
|
2684
|
+
rowsIn(data, MESSAGES).push(message);
|
|
2685
|
+
return withPush(write(200, MESSAGES, { id, threadId: message.threadId, labelIds }, message), gmailPublish(data, labelIds, sequence));
|
|
1373
2686
|
}
|
|
1374
2687
|
if (path === MESSAGES) {
|
|
1375
2688
|
if (method !== "GET") return void 0;
|
|
@@ -1660,9 +2973,9 @@ function twilioOperation(method, path, params, _headers, data, sequence) {
|
|
|
1660
2973
|
if (missing.length) return fail(400, missing.length === allowed.length ? "21211" : "21606", `No parameter provided for ${allowed.filter((k) => missing.includes(k)).join(", ")}`);
|
|
1661
2974
|
const prefix = resource === "Messages" ? "SM" : "CA";
|
|
1662
2975
|
const sid = `${prefix}${sha(`${prefix.toLowerCase()}:${sequence}:${accountSid}`).slice(0, 32)}`;
|
|
1663
|
-
const
|
|
1664
|
-
records.push(
|
|
1665
|
-
return created(collection, structuredClone(
|
|
2976
|
+
const record3 = resource === "Messages" ? { account_sid: accountSid, api_version: "2010-04-01", sid, messaging_service_sid: null, status: "queued", to: params.To, from: params.From, body: params.Body, num_segments: "1", num_media: "0", direction: "outbound-api", error_code: null, error_message: null, date_created: stamp2(), date_updated: stamp2(), date_sent: null, price: null, price_unit: null, uri: `/2010-04-01/Accounts/${accountSid}/Messages/${sid}.json` } : { account_sid: accountSid, api_version: "2010-04-01", sid, status: "queued", to: params.To, from: params.From, url: params.Url, direction: "outbound-api", error_code: null, error_message: null, date_created: stamp2(), date_updated: stamp2(), start_time: null, duration: null, price: null, price_unit: null, uri: `/2010-04-01/Accounts/${accountSid}/Calls/${sid}.json` };
|
|
2977
|
+
records.push(record3);
|
|
2978
|
+
return created(collection, structuredClone(record3), record3);
|
|
1666
2979
|
}
|
|
1667
2980
|
if (method === "GET") {
|
|
1668
2981
|
if (Object.keys(params).some((k) => !["To", "From"].includes(k))) return void 0;
|
|
@@ -1739,7 +3052,8 @@ var UNSUPPORTED_BODIES = {
|
|
|
1739
3052
|
"google-oauth": { error: "unsupported_operation", error_description: "Outside the AgentTwin Google OAuth refresh subset", forwardedToProduction: false },
|
|
1740
3053
|
openai: { error: { type: "invalid_request_error", code: "unsupported_operation", message: "Outside the AgentTwin scripted OpenAI subset, or no scripted response is left" }, forwardedToProduction: false },
|
|
1741
3054
|
anthropic: { type: "error", error: { type: "invalid_request_error", message: "Outside the AgentTwin scripted Anthropic subset, or no scripted response is left" }, forwardedToProduction: false },
|
|
1742
|
-
zendesk: { error: "UnsupportedOperation", description: "Outside the verified AgentTwin Zendesk twin subset", forwardedToProduction: false }
|
|
3055
|
+
zendesk: { error: "UnsupportedOperation", description: "Outside the verified AgentTwin Zendesk twin subset", forwardedToProduction: false },
|
|
3056
|
+
"upstash-redis": { error: "ERR outside the verified AgentTwin Upstash Redis twin subset", forwardedToProduction: false }
|
|
1743
3057
|
};
|
|
1744
3058
|
var REST_ADAPTERS = {
|
|
1745
3059
|
openai: openaiOperation,
|
|
@@ -1758,7 +3072,8 @@ var REST_ADAPTERS = {
|
|
|
1758
3072
|
twilio: twilioOperation,
|
|
1759
3073
|
zendesk: zendeskOperation,
|
|
1760
3074
|
"google-oauth": googleOAuthOperation,
|
|
1761
|
-
composio: composioOperation
|
|
3075
|
+
composio: composioOperation,
|
|
3076
|
+
"upstash-redis": upstashRedisOperation
|
|
1762
3077
|
};
|
|
1763
3078
|
function restUnsupportedBody(adapter) {
|
|
1764
3079
|
return UNSUPPORTED_BODIES[adapter];
|
|
@@ -1771,10 +3086,10 @@ var SEED_PATTERN = /^[a-f0-9]{32}$/;
|
|
|
1771
3086
|
var normalizeHex = (value) => value.trim().toLowerCase();
|
|
1772
3087
|
function normalizeSeed(seed) {
|
|
1773
3088
|
if (seed === void 0 || seed.trim() === "") return randomBytes(16).toString("hex");
|
|
1774
|
-
const
|
|
1775
|
-
if (!/^[a-f0-9]+$/.test(
|
|
1776
|
-
if (
|
|
1777
|
-
return createHash3("sha256").update(
|
|
3089
|
+
const text2 = normalizeHex(seed);
|
|
3090
|
+
if (!/^[a-f0-9]+$/.test(text2) || text2.length > 256) throw new Error(`Seed must be up to 256 hex characters or empty to generate; got ${seed.slice(0, 40)}`);
|
|
3091
|
+
if (text2.length === 32) return text2;
|
|
3092
|
+
return createHash3("sha256").update(text2).digest("hex").slice(0, 32);
|
|
1778
3093
|
}
|
|
1779
3094
|
var SeedStream = class {
|
|
1780
3095
|
constructor(seed, purpose) {
|
|
@@ -1823,6 +3138,9 @@ function faultOrdinals(selection, seed) {
|
|
|
1823
3138
|
return all.slice(0, count).sort((a, b) => a - b);
|
|
1824
3139
|
}
|
|
1825
3140
|
|
|
3141
|
+
// src/runtime/spec.ts
|
|
3142
|
+
import { isAbsolute } from "path";
|
|
3143
|
+
|
|
1826
3144
|
// src/runtime/postgres-clock.ts
|
|
1827
3145
|
function validPostgresClock(value) {
|
|
1828
3146
|
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 1) return false;
|
|
@@ -2120,9 +3438,9 @@ function withParents(row, resource, op2, params) {
|
|
|
2120
3438
|
}
|
|
2121
3439
|
return out;
|
|
2122
3440
|
}
|
|
2123
|
-
function shape(op2, resource,
|
|
3441
|
+
function shape(op2, resource, record3, stream, sequence, params = {}) {
|
|
2124
3442
|
const r = op2.response;
|
|
2125
|
-
const out = withParents(
|
|
3443
|
+
const out = withParents(record3, resource, op2, params);
|
|
2126
3444
|
if (!r || r.type !== "object" || !r.properties || Object.hasOwn(r.properties, resource.idField) || r["x-ref"] && r["x-ref"] === resource.schema?.["x-ref"]) return out;
|
|
2127
3445
|
const holder = Object.entries(r.properties).find(([, s]) => s.type === "object" && (s["x-ref"] && s["x-ref"] === resource.schema?.["x-ref"] || s.properties && Object.hasOwn(s.properties, resource.idField)));
|
|
2128
3446
|
if (!holder) return out;
|
|
@@ -2237,19 +3555,19 @@ function handleRest(twin, req, data, ctx) {
|
|
|
2237
3555
|
}
|
|
2238
3556
|
if (op2.kind === "create" || op2.kind === "upsert" && findRow(scoped, resource, id) < 0) {
|
|
2239
3557
|
if (rows2.length >= 1e4) return fail(429, "capacity", "Twin collection is full");
|
|
2240
|
-
const
|
|
2241
|
-
overlay(
|
|
3558
|
+
const record3 = materialize(resource.schema ?? op2.response, "create", stream, ctx.sequence) ?? {};
|
|
3559
|
+
overlay(record3, body, resource.schema, true);
|
|
2242
3560
|
const supplied = Object.keys(body).find((k) => normName(k) === normName(resource.idField));
|
|
2243
|
-
if (id !== void 0)
|
|
2244
|
-
else if (!supplied)
|
|
2245
|
-
else if (findRow(scoped, resource, String(
|
|
3561
|
+
if (id !== void 0) record3[resource.idField] = id;
|
|
3562
|
+
else if (!supplied) record3[resource.idField] = newId(resource, rows2, stream);
|
|
3563
|
+
else if (findRow(scoped, resource, String(record3[resource.idField])) >= 0) return fail(409, "conflict", `${resource.name} ${record3[resource.idField]} already exists`);
|
|
2246
3564
|
for (const p of op2.parentParams ?? []) {
|
|
2247
3565
|
const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
|
|
2248
|
-
if (field &&
|
|
2249
|
-
else if (!field)
|
|
3566
|
+
if (field && record3[field] === void 0) record3[field] = params[p];
|
|
3567
|
+
else if (!field) record3[parentKey(p)] = params[p];
|
|
2250
3568
|
}
|
|
2251
|
-
rows2.push(
|
|
2252
|
-
return { status: op2.kind === "upsert" ? op2.status || 200 : op2.status, body: shape(op2, resource,
|
|
3569
|
+
rows2.push(record3);
|
|
3570
|
+
return { status: op2.kind === "upsert" ? op2.status || 200 : op2.status, body: shape(op2, resource, record3, stream, ctx.sequence, params), collection, operation: "write", record: visible(record3) };
|
|
2253
3571
|
}
|
|
2254
3572
|
const index = rows2.findIndex((r) => String(r[resource.idField]) === id && inScope(r, resource, params, op2));
|
|
2255
3573
|
if (index < 0) return { ...fail(404, "not_found", `No such ${singular(resource.name)}: ${id}`), operation: "read" };
|
|
@@ -2316,8 +3634,8 @@ function generatedAdapter(adapter) {
|
|
|
2316
3634
|
const m = matchOperation(twin, method, path);
|
|
2317
3635
|
return m ? m.op.resource : void 0;
|
|
2318
3636
|
})() : void 0,
|
|
2319
|
-
bodyMode: (
|
|
2320
|
-
const t = (
|
|
3637
|
+
bodyMode: (contentType2) => {
|
|
3638
|
+
const t = (contentType2 ?? "").toLowerCase();
|
|
2321
3639
|
return /json/.test(t) ? "json" : /x-www-form-urlencoded/.test(t) ? "form" : twin.protocol === "graphql" ? "json" : t || twin.protocol.startsWith("aws-rest") ? "raw" : "json";
|
|
2322
3640
|
}
|
|
2323
3641
|
};
|
|
@@ -2325,18 +3643,18 @@ function generatedAdapter(adapter) {
|
|
|
2325
3643
|
|
|
2326
3644
|
// src/runtime/packs.ts
|
|
2327
3645
|
import { existsSync, readFileSync } from "fs";
|
|
2328
|
-
import { dirname, join as
|
|
3646
|
+
import { dirname, join as join5, resolve as resolve2 } from "path";
|
|
2329
3647
|
import { fileURLToPath, pathToFileURL } from "url";
|
|
2330
3648
|
function packsDir() {
|
|
2331
3649
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
2332
|
-
const candidates = [process.env.AGENTTWIN_TWINS_DIR,
|
|
2333
|
-
return candidates.find((dir) => !!dir && existsSync(
|
|
3650
|
+
const candidates = [process.env.AGENTTWIN_TWINS_DIR, join5(here, "twins"), join5(here, "../twins"), resolve2(here, "../../../twins/dist")];
|
|
3651
|
+
return candidates.find((dir) => !!dir && existsSync(join5(dir, "catalog.json")));
|
|
2334
3652
|
}
|
|
2335
3653
|
var cached;
|
|
2336
3654
|
function packCatalog() {
|
|
2337
3655
|
if (cached !== void 0) return cached;
|
|
2338
3656
|
const dir = packsDir();
|
|
2339
|
-
cached = dir ? JSON.parse(readFileSync(
|
|
3657
|
+
cached = dir ? JSON.parse(readFileSync(join5(dir, "catalog.json"), "utf8")) : null;
|
|
2340
3658
|
return cached;
|
|
2341
3659
|
}
|
|
2342
3660
|
var PACK_PREFIX = "pack:";
|
|
@@ -2347,11 +3665,11 @@ var packRecord = (name) => {
|
|
|
2347
3665
|
};
|
|
2348
3666
|
var loaded = /* @__PURE__ */ new Map();
|
|
2349
3667
|
function loadPack(name) {
|
|
2350
|
-
const
|
|
2351
|
-
if (!
|
|
3668
|
+
const record3 = packRecord(name);
|
|
3669
|
+
if (!record3) throw new Error(`No twin pack named ${name}`);
|
|
2352
3670
|
let factory = loaded.get(name);
|
|
2353
3671
|
if (!factory) {
|
|
2354
|
-
const file =
|
|
3672
|
+
const file = join5(packsDir(), "packs", name, "index.mjs");
|
|
2355
3673
|
factory = import(pathToFileURL(file).href).then((mod) => {
|
|
2356
3674
|
if (typeof mod.createTwinFetch !== "function") throw new Error(`Twin pack ${name} exports no createTwinFetch`);
|
|
2357
3675
|
return mod.createTwinFetch;
|
|
@@ -2372,7 +3690,7 @@ var isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
|
2372
3690
|
var scalar = (v) => v === null || ["string", "number", "boolean"].includes(typeof v);
|
|
2373
3691
|
var flat = (v) => Object.values(v).every(scalar);
|
|
2374
3692
|
var read = (collection, body, status = 200, headers) => ({ status, body, collection, operation: "read", ...headers ? { headers } : {} });
|
|
2375
|
-
var write2 = (collection,
|
|
3693
|
+
var write2 = (collection, record3, body, status = 200, headers) => ({ status, body, collection, record: structuredClone(record3), operation: "write", ...headers ? { headers } : {} });
|
|
2376
3694
|
var table = (data, collection) => data[collection] ??= [];
|
|
2377
3695
|
var limitOf = (value, fallback, max) => {
|
|
2378
3696
|
if (value === void 0) return fallback;
|
|
@@ -2448,22 +3766,22 @@ var salesforce = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2448
3766
|
const missing = spec.required.filter((f) => body[f] === void 0 || body[f] === null || body[f] === "");
|
|
2449
3767
|
if (missing.length) return { ...sfError(400, "REQUIRED_FIELD_MISSING", `Required fields are missing: [${missing.join(", ")}]`, missing), collection };
|
|
2450
3768
|
const id = (spec.prefix + hash(`salesforce:${object3}:${sequence}:${rows2.length}`).slice(0, 12)).toUpperCase().replace(/^00Q/i, "00Q") + "AAA";
|
|
2451
|
-
const
|
|
2452
|
-
rows2.push(
|
|
2453
|
-
return write2(collection,
|
|
3769
|
+
const record4 = { Id: id, ...body, CreatedDate: iso2(sequence), LastModifiedDate: iso2(sequence), IsDeleted: false };
|
|
3770
|
+
rows2.push(record4);
|
|
3771
|
+
return write2(collection, record4, { id, success: true, errors: [] }, 201);
|
|
2454
3772
|
}
|
|
2455
3773
|
if (!s[2]) return;
|
|
2456
|
-
const
|
|
2457
|
-
if (!
|
|
2458
|
-
if (method === "GET") return read(collection, sfView(object3, version,
|
|
3774
|
+
const record3 = rows2.find((r) => r.Id === s[2] || String(r.Id).slice(0, 15) === s[2].slice(0, 15));
|
|
3775
|
+
if (!record3) return { ...sfError(404, "NOT_FOUND", "The requested resource does not exist"), collection };
|
|
3776
|
+
if (method === "GET") return read(collection, sfView(object3, version, record3));
|
|
2459
3777
|
if (method === "PATCH") {
|
|
2460
3778
|
if (!flat(body) || "Id" in body) return;
|
|
2461
|
-
Object.assign(
|
|
2462
|
-
return write2(collection,
|
|
3779
|
+
Object.assign(record3, body, { LastModifiedDate: iso2(sequence) });
|
|
3780
|
+
return write2(collection, record3, null, 204);
|
|
2463
3781
|
}
|
|
2464
3782
|
if (method === "DELETE") {
|
|
2465
|
-
rows2.splice(rows2.indexOf(
|
|
2466
|
-
return write2(collection, { ...
|
|
3783
|
+
rows2.splice(rows2.indexOf(record3), 1);
|
|
3784
|
+
return write2(collection, { ...record3, IsDeleted: true }, null, 204);
|
|
2467
3785
|
}
|
|
2468
3786
|
};
|
|
2469
3787
|
var SN_TABLES = { incident: "INC", change_request: "CHG", problem: "PRB", sc_request: "REQ", sys_user: null };
|
|
@@ -2492,7 +3810,7 @@ var servicenow = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2492
3810
|
if (!sysId && method === "POST") {
|
|
2493
3811
|
if (!flat(body) || "sys_id" in body) return;
|
|
2494
3812
|
const prefix = SN_TABLES[name];
|
|
2495
|
-
const
|
|
3813
|
+
const record4 = {
|
|
2496
3814
|
sys_id: hash(`servicenow:${name}:${sequence}:${rows2.length}`).slice(0, 32),
|
|
2497
3815
|
...prefix ? { number: `${prefix}${String(nextNumber(rows2, "number", 10001)).padStart(7, "0")}` } : {},
|
|
2498
3816
|
...name === "incident" ? { state: "1", impact: "3", urgency: "3", priority: "5" } : {},
|
|
@@ -2501,21 +3819,21 @@ var servicenow = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2501
3819
|
sys_updated_on: snTime(sequence),
|
|
2502
3820
|
sys_mod_count: "0"
|
|
2503
3821
|
};
|
|
2504
|
-
rows2.push(
|
|
2505
|
-
return write2(collection,
|
|
3822
|
+
rows2.push(record4);
|
|
3823
|
+
return write2(collection, record4, { result: record4 }, 201);
|
|
2506
3824
|
}
|
|
2507
3825
|
if (!sysId) return;
|
|
2508
|
-
const
|
|
2509
|
-
if (!
|
|
2510
|
-
if (method === "GET") return read(collection, { result:
|
|
3826
|
+
const record3 = rows2.find((r) => r.sys_id === sysId);
|
|
3827
|
+
if (!record3) return { ...snError(404, "No Record found", "Record doesn't exist or ACL restricts the record retrieval"), collection };
|
|
3828
|
+
if (method === "GET") return read(collection, { result: record3 });
|
|
2511
3829
|
if (method === "PATCH" || method === "PUT") {
|
|
2512
3830
|
if (!flat(body) || "sys_id" in body || "number" in body) return;
|
|
2513
|
-
Object.assign(
|
|
2514
|
-
return write2(collection,
|
|
3831
|
+
Object.assign(record3, Object.fromEntries(Object.entries(body).map(([k, v]) => [k, v === null ? "" : String(v)])), { sys_updated_on: snTime(sequence), sys_mod_count: String(Number(record3.sys_mod_count ?? 0) + 1) });
|
|
3832
|
+
return write2(collection, record3, { result: record3 });
|
|
2515
3833
|
}
|
|
2516
3834
|
if (method === "DELETE") {
|
|
2517
|
-
rows2.splice(rows2.indexOf(
|
|
2518
|
-
return write2(collection,
|
|
3835
|
+
rows2.splice(rows2.indexOf(record3), 1);
|
|
3836
|
+
return write2(collection, record3, null, 204);
|
|
2519
3837
|
}
|
|
2520
3838
|
};
|
|
2521
3839
|
var wdError = (status, error, errors = []) => ({ status, body: { error, errors } });
|
|
@@ -2544,7 +3862,7 @@ var workday = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2544
3862
|
const taken = new Set(requests.filter((r) => r.worker?.id === workerId && r.status !== "Canceled").flatMap((r) => r.days.map((d) => d.date)));
|
|
2545
3863
|
const clash = days.find((d) => taken.has(d.date));
|
|
2546
3864
|
if (clash) return { ...wdError(400, "Validation error", [{ error: `Time off has already been requested for ${clash.date}.`, field: "days" }]), collection: "/timeOffRequests" };
|
|
2547
|
-
const
|
|
3865
|
+
const record3 = {
|
|
2548
3866
|
id: hash(`workday:timeoff:${sequence}:${requests.length}`).slice(0, 32),
|
|
2549
3867
|
descriptor: `Time Off Request: ${worker.descriptor}`,
|
|
2550
3868
|
worker: { id: workerId, descriptor: worker.descriptor },
|
|
@@ -2553,8 +3871,8 @@ var workday = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2553
3871
|
businessProcessParameters: { overallStatus: "In Progress", comment: isObject2(body.businessProcessParameters) ? body.businessProcessParameters.comment ?? null : null },
|
|
2554
3872
|
createdOn: iso2(sequence)
|
|
2555
3873
|
};
|
|
2556
|
-
requests.push(
|
|
2557
|
-
return write2("/timeOffRequests",
|
|
3874
|
+
requests.push(record3);
|
|
3875
|
+
return write2("/timeOffRequests", record3, record3, 201);
|
|
2558
3876
|
}
|
|
2559
3877
|
};
|
|
2560
3878
|
var SAP_SETS = { A_BusinessPartner: { service: "API_BUSINESS_PARTNER", key: "BusinessPartner" }, A_SalesOrder: { service: "API_SALES_ORDER_SRV", key: "SalesOrder" } };
|
|
@@ -2567,8 +3885,8 @@ var sap = (method, path, body, query, headers, data, sequence) => {
|
|
|
2567
3885
|
if (method === "GET") {
|
|
2568
3886
|
const issued = header2(headers, "x-csrf-token")?.toLowerCase() === "fetch" ? { "x-csrf-token": csrf } : void 0;
|
|
2569
3887
|
if (key2) {
|
|
2570
|
-
const
|
|
2571
|
-
return
|
|
3888
|
+
const record4 = rows2.find((r) => r[SAP_SETS[set].key] === key2);
|
|
3889
|
+
return record4 ? read(collection, { d: sapView(set, record4) }, 200, issued) : { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection };
|
|
2572
3890
|
}
|
|
2573
3891
|
const where = query.$filter ? eqFilter(query.$filter, "'") : () => true;
|
|
2574
3892
|
const top = limitOf(query.$top, 1e3, 5e3), skip = Number(query.$skip ?? 0);
|
|
@@ -2579,16 +3897,16 @@ var sap = (method, path, body, query, headers, data, sequence) => {
|
|
|
2579
3897
|
if (method === "POST" && !key2) {
|
|
2580
3898
|
if (set === "A_BusinessPartner") {
|
|
2581
3899
|
if (!flat(body) || !["1", "2"].includes(String(body.BusinessPartnerCategory))) return { ...sapError(400, "R11/005", "Enter a valid business partner category (1 = person, 2 = organization)"), collection };
|
|
2582
|
-
const
|
|
2583
|
-
rows2.push(
|
|
2584
|
-
return write2(collection,
|
|
3900
|
+
const record5 = { BusinessPartner: String(nextNumber(rows2, "BusinessPartner", 10000001)), ...body, CreationDate: `/Date(${twinNowMs((EPOCH2 + sequence) * 1e3)})/`, BusinessPartnerIsBlocked: false };
|
|
3901
|
+
rows2.push(record5);
|
|
3902
|
+
return write2(collection, record5, { d: sapView(set, record5) }, 201);
|
|
2585
3903
|
}
|
|
2586
3904
|
const items = isObject2(body.to_Item) && Array.isArray(body.to_Item.results) ? body.to_Item.results : null;
|
|
2587
3905
|
if (!body.SalesOrderType || !body.SoldToParty || !items?.length || !items.every((i) => isObject2(i) && i.Material && i.RequestedQuantity)) return { ...sapError(400, "V1/320", "Sales order requires SalesOrderType, SoldToParty and at least one item with Material and RequestedQuantity"), collection };
|
|
2588
3906
|
if (!table(data, "/A_BusinessPartner").some((p) => p.BusinessPartner === String(body.SoldToParty))) return { ...sapError(400, "V1/302", `Sold-to party ${body.SoldToParty} does not exist`), collection };
|
|
2589
3907
|
const total = items.reduce((sum, i) => sum + Number(i.NetAmount ?? 0), 0);
|
|
2590
3908
|
const { to_Item: _items, ...header_ } = body;
|
|
2591
|
-
const
|
|
3909
|
+
const record4 = {
|
|
2592
3910
|
SalesOrder: String(nextNumber(rows2, "SalesOrder", 1)).padStart(10, "0"),
|
|
2593
3911
|
...header_,
|
|
2594
3912
|
TransactionCurrency: body.TransactionCurrency ?? "USD",
|
|
@@ -2597,15 +3915,15 @@ var sap = (method, path, body, query, headers, data, sequence) => {
|
|
|
2597
3915
|
CreationDate: `/Date(${twinNowMs((EPOCH2 + sequence) * 1e3)})/`,
|
|
2598
3916
|
to_Item: { results: items.map((i, n) => ({ SalesOrderItem: String((n + 1) * 10), ...i })) }
|
|
2599
3917
|
};
|
|
2600
|
-
rows2.push(
|
|
2601
|
-
return write2(collection,
|
|
3918
|
+
rows2.push(record4);
|
|
3919
|
+
return write2(collection, record4, { d: sapView(set, record4) }, 201);
|
|
2602
3920
|
}
|
|
2603
|
-
const
|
|
2604
|
-
if (!
|
|
3921
|
+
const record3 = key2 ? rows2.find((r) => r[SAP_SETS[set].key] === key2) : void 0;
|
|
3922
|
+
if (!record3) return key2 ? { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection } : void 0;
|
|
2605
3923
|
if (method === "PATCH" || method === "MERGE") {
|
|
2606
3924
|
if (!flat(body) || SAP_SETS[set].key in body) return;
|
|
2607
|
-
Object.assign(
|
|
2608
|
-
return write2(collection,
|
|
3925
|
+
Object.assign(record3, body);
|
|
3926
|
+
return write2(collection, record3, null, 204);
|
|
2609
3927
|
}
|
|
2610
3928
|
};
|
|
2611
3929
|
var graphError = (status, code, message, sequence) => ({ status, body: { error: { code, message, innerError: { date: iso2(sequence), "request-id": hash(`graph:${sequence}:${code}`).slice(0, 36) } } } });
|
|
@@ -2636,7 +3954,7 @@ var teams = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2636
3954
|
if (!isObject2(body.body) || typeof body.body.content !== "string" || !body.body.content.trim()) return { ...graphError(400, "BadRequest", "Missing body content", sequence), collection: "/messages" };
|
|
2637
3955
|
if (body.body.contentType !== void 0 && !["text", "html"].includes(body.body.contentType)) return;
|
|
2638
3956
|
if (parentId && !messages.some((r) => scope(r) && r.id === parentId)) return { ...graphError(404, "NotFound", "Resource not found", sequence), collection: "/messages" };
|
|
2639
|
-
const
|
|
3957
|
+
const record3 = {
|
|
2640
3958
|
id: String(twinNowMs((EPOCH2 + sequence) * 1e3) + messages.length),
|
|
2641
3959
|
replyToId: parentId ?? null,
|
|
2642
3960
|
messageType: "message",
|
|
@@ -2650,8 +3968,8 @@ var teams = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2650
3968
|
attachments: [],
|
|
2651
3969
|
mentions: []
|
|
2652
3970
|
};
|
|
2653
|
-
messages.push(
|
|
2654
|
-
return write2("/messages",
|
|
3971
|
+
messages.push(record3);
|
|
3972
|
+
return write2("/messages", record3, record3, 201);
|
|
2655
3973
|
};
|
|
2656
3974
|
var address = (r) => isObject2(r) && isObject2(r.emailAddress) && typeof r.emailAddress.address === "string" && /^[^@\s]+@[^@\s]+$/.test(r.emailAddress.address);
|
|
2657
3975
|
var outlook = (method, path, body, query, _headers, data, sequence) => {
|
|
@@ -2659,7 +3977,7 @@ var outlook = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2659
3977
|
if (!m) return;
|
|
2660
3978
|
const messages = table(data, "/messages"), [, route, folder, id, reply] = m;
|
|
2661
3979
|
const store = (message, parentFolderId) => {
|
|
2662
|
-
const
|
|
3980
|
+
const record4 = {
|
|
2663
3981
|
id: Buffer.from(hash(`outlook:${sequence}:${messages.length}`).slice(0, 30)).toString("base64url"),
|
|
2664
3982
|
createdDateTime: iso2(sequence),
|
|
2665
3983
|
sentDateTime: iso2(sequence),
|
|
@@ -2675,8 +3993,8 @@ var outlook = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2675
3993
|
parentFolderId,
|
|
2676
3994
|
conversationId: message.conversationId ?? graphId(`conv:${sequence}`)
|
|
2677
3995
|
};
|
|
2678
|
-
messages.push(
|
|
2679
|
-
return
|
|
3996
|
+
messages.push(record4);
|
|
3997
|
+
return record4;
|
|
2680
3998
|
};
|
|
2681
3999
|
if (route === "sendMail" && method === "POST") {
|
|
2682
4000
|
const message = body.message;
|
|
@@ -2690,17 +4008,17 @@ var outlook = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2690
4008
|
const page = graphPage(messages.filter((r) => !folder || r.parentFolderId === folder), query);
|
|
2691
4009
|
return page ? read("/messages", { value: page }) : void 0;
|
|
2692
4010
|
}
|
|
2693
|
-
const
|
|
2694
|
-
if (!
|
|
2695
|
-
if (!reply && method === "GET") return read("/messages",
|
|
4011
|
+
const record3 = id ? messages.find((r) => r.id === id) : void 0;
|
|
4012
|
+
if (!record3) return id ? { ...graphError(404, "ErrorItemNotFound", "The specified object was not found in the store.", sequence), collection: "/messages" } : void 0;
|
|
4013
|
+
if (!reply && method === "GET") return read("/messages", record3);
|
|
2696
4014
|
if (!reply && method === "PATCH") {
|
|
2697
4015
|
if (Object.keys(body).some((k) => !["isRead", "categories", "importance", "flag"].includes(k))) return;
|
|
2698
|
-
Object.assign(
|
|
2699
|
-
return write2("/messages",
|
|
4016
|
+
Object.assign(record3, body);
|
|
4017
|
+
return write2("/messages", record3, record3);
|
|
2700
4018
|
}
|
|
2701
4019
|
if (reply && method === "POST") {
|
|
2702
|
-
const to =
|
|
2703
|
-
return write2("/messages", store({ subject: `RE: ${
|
|
4020
|
+
const to = record3.parentFolderId === "sentitems" ? record3.toRecipients : [record3.from];
|
|
4021
|
+
return write2("/messages", store({ subject: `RE: ${record3.subject}`, body: { contentType: "text", content: String(body.comment ?? "") }, toRecipients: to, conversationId: record3.conversationId }, "sentitems"), null, 202);
|
|
2704
4022
|
}
|
|
2705
4023
|
};
|
|
2706
4024
|
var entra = (method, path, body, query, _headers, data, sequence) => {
|
|
@@ -2720,9 +4038,9 @@ var entra = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2720
4038
|
if (users.some((u) => String(u.userPrincipalName).toLowerCase() === String(body.userPrincipalName).toLowerCase()))
|
|
2721
4039
|
return { ...graphError(400, "Request_BadRequest", "Another object with the same value for property userPrincipalName already exists.", sequence), collection: "/users" };
|
|
2722
4040
|
const { passwordProfile: _secret, ...profile } = body;
|
|
2723
|
-
const
|
|
2724
|
-
users.push(
|
|
2725
|
-
return write2("/users",
|
|
4041
|
+
const record3 = { id: graphId(`entra:user:${sequence}:${users.length}`), ...profile, mail: profile.mail ?? null, jobTitle: profile.jobTitle ?? null, department: profile.department ?? null, createdDateTime: iso2(sequence) };
|
|
4042
|
+
users.push(record3);
|
|
4043
|
+
return write2("/users", record3, record3, 201);
|
|
2726
4044
|
}
|
|
2727
4045
|
if (kind === "groups" && !key2 && method === "GET") {
|
|
2728
4046
|
const page = graphPage(groups2, query);
|
|
@@ -2795,9 +4113,9 @@ var okta = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2795
4113
|
if (users.some((u) => String(u.profile?.login).toLowerCase() === String(profile.login).toLowerCase()))
|
|
2796
4114
|
return { ...oktaError(400, "E0000001", "Api validation failed: login", ["login: An object with this field already exists in the current organization"]), collection: "/users" };
|
|
2797
4115
|
const active = query.activate !== "false";
|
|
2798
|
-
const
|
|
2799
|
-
users.push(
|
|
2800
|
-
return write2("/users",
|
|
4116
|
+
const record3 = { id: oktaId("00u", `okta:user:${sequence}:${users.length}`), status: active ? "ACTIVE" : "STAGED", created: iso2(sequence), activated: active ? iso2(sequence) : null, statusChanged: active ? iso2(sequence) : null, lastUpdated: iso2(sequence), profile: { ...profile } };
|
|
4117
|
+
users.push(record3);
|
|
4118
|
+
return write2("/users", record3, record3);
|
|
2801
4119
|
}
|
|
2802
4120
|
if (kind === "groups" && !key2 && method === "GET") {
|
|
2803
4121
|
const q = query.q?.toLowerCase();
|
|
@@ -2866,9 +4184,9 @@ var confluence = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2866
4184
|
const page2 = pages.find((p) => p.id === String(body.pageId) && p.status !== "trashed");
|
|
2867
4185
|
if (!page2) return { ...cfError(404, "NOT_FOUND", "Page not found"), collection: "/comments" };
|
|
2868
4186
|
if (!storage(body.body)) return { ...cfError(400, "INVALID_REQUEST_PARAMETER", "Comment body must use the storage representation"), collection: "/comments" };
|
|
2869
|
-
const
|
|
2870
|
-
comments.push(
|
|
2871
|
-
return write2("/comments",
|
|
4187
|
+
const record3 = { id: nextId2(), pageId: page2.id, status: "current", title: `Re: ${page2.title}`, version: { number: 1, createdAt: iso2(sequence) }, body: body.body };
|
|
4188
|
+
comments.push(record3);
|
|
4189
|
+
return write2("/comments", record3, record3);
|
|
2872
4190
|
}
|
|
2873
4191
|
if (kind !== "pages") return;
|
|
2874
4192
|
if (!id && method === "GET") {
|
|
@@ -2882,9 +4200,9 @@ var confluence = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2882
4200
|
if (typeof body.title !== "string" || !body.title.trim() || !storage(body.body)) return { ...cfError(400, "INVALID_REQUEST_PARAMETER", "A page requires a title and a storage-format body"), collection: "/pages" };
|
|
2883
4201
|
if (pages.some((p) => p.spaceId === String(body.spaceId) && p.title === body.title && p.status !== "trashed"))
|
|
2884
4202
|
return { ...cfError(400, "BAD_REQUEST", "A page with this title already exists: A page already exists with the same TITLE in this space"), collection: "/pages" };
|
|
2885
|
-
const
|
|
2886
|
-
pages.push(
|
|
2887
|
-
return write2("/pages",
|
|
4203
|
+
const record3 = { id: nextId2(), status: body.status === "draft" ? "draft" : "current", title: body.title, spaceId: String(body.spaceId), parentId: body.parentId ?? null, authorId: "agenttwin-agent", createdAt: iso2(sequence), version: { number: 1, createdAt: iso2(sequence), message: "" }, body: body.body };
|
|
4204
|
+
pages.push(record3);
|
|
4205
|
+
return write2("/pages", record3, view(record3));
|
|
2888
4206
|
}
|
|
2889
4207
|
const page = pages.find((p) => p.id === id && p.status !== "trashed");
|
|
2890
4208
|
if (!page) return { ...cfError(404, "NOT_FOUND", "Page not found"), collection: "/pages" };
|
|
@@ -2916,9 +4234,9 @@ var sharepoint = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2916
4234
|
while (files.some((f) => f.siteId === siteId && f.name === `${body.name} ${n}`)) n++;
|
|
2917
4235
|
name = `${body.name} ${n}`;
|
|
2918
4236
|
}
|
|
2919
|
-
const
|
|
2920
|
-
files.push(
|
|
2921
|
-
return write2("/driveItems",
|
|
4237
|
+
const record3 = { id: hash(`sp:drive:${sequence}:${files.length}`).slice(0, 34).toUpperCase(), siteId, name, folder: { childCount: 0 }, createdDateTime: iso2(sequence), lastModifiedDateTime: iso2(sequence), webUrl: `https://contoso.sharepoint.test/sites/${siteId}/Shared%20Documents/${encodeURIComponent(name)}` };
|
|
4238
|
+
files.push(record3);
|
|
4239
|
+
return write2("/driveItems", record3, record3, 201);
|
|
2922
4240
|
}
|
|
2923
4241
|
if (!listKey) return method === "GET" ? read("/lists", { value: lists.filter((l) => l.siteId === siteId) }) : void 0;
|
|
2924
4242
|
const list2 = lists.find((l) => l.siteId === siteId && (l.id === listKey || l.displayName === decodeURIComponent(listKey)));
|
|
@@ -2935,9 +4253,9 @@ var sharepoint = (method, path, body, query, _headers, data, sequence) => {
|
|
|
2935
4253
|
if (!itemId && method === "POST") {
|
|
2936
4254
|
if (!isObject2(body.fields) || !flat(body.fields)) return { ...graphError(400, "invalidRequest", "Invalid request: fields are required.", sequence), collection: "/listItems" };
|
|
2937
4255
|
const id = String(nextNumber(own, "id", 1));
|
|
2938
|
-
const
|
|
2939
|
-
items.push(
|
|
2940
|
-
return write2("/listItems",
|
|
4256
|
+
const record3 = { id, listId: list2.id, siteId, createdDateTime: iso2(sequence), lastModifiedDateTime: iso2(sequence), webUrl: `https://contoso.sharepoint.test/sites/${siteId}/Lists/${list2.displayName}/DispForm.aspx?ID=${id}`, fields: { id, Title: body.fields.Title ?? null, ...body.fields } };
|
|
4257
|
+
items.push(record3);
|
|
4258
|
+
return write2("/listItems", record3, view(record3, true), 201);
|
|
2941
4259
|
}
|
|
2942
4260
|
const item = own.find((i) => i.id === itemId);
|
|
2943
4261
|
if (!item) return { ...graphError(404, "itemNotFound", "The resource could not be found.", sequence), collection: "/listItems" };
|
|
@@ -3004,9 +4322,9 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
|
|
|
3004
4322
|
message: "Statement executed successfully.",
|
|
3005
4323
|
createdOn: twinNowMs((EPOCH2 + sequence) * 1e3)
|
|
3006
4324
|
});
|
|
3007
|
-
const remember = (collection, res, operation,
|
|
4325
|
+
const remember = (collection, res, operation, record3) => {
|
|
3008
4326
|
log.push({ statementHandle: handle, statement, result: res, createdOn: iso2(sequence) });
|
|
3009
|
-
return operation === "read" ? read(collection, res) : write2(collection,
|
|
4327
|
+
return operation === "read" ? read(collection, res) : write2(collection, record3 ?? { statement }, res);
|
|
3010
4328
|
};
|
|
3011
4329
|
let s;
|
|
3012
4330
|
if (s = /^SELECT\s+(.+?)\s+FROM\s+("?[\w$]+"?)(?:\s+WHERE\s+(.+?))?(?:\s+ORDER\s+BY\s+("?[\w$]+"?)(?:\s+(ASC|DESC))?)?(?:\s+LIMIT\s+(\d+))?$/is.exec(statement)) {
|
|
@@ -3097,31 +4415,31 @@ var netsuite = (method, path, body, query, _headers, data, sequence) => {
|
|
|
3097
4415
|
total = lines.reduce((sum, l) => sum + Number(l.quantity) * Number(l.rate ?? 0), 0);
|
|
3098
4416
|
}
|
|
3099
4417
|
const newId2 = String(nextNumber(rows2, "id", 1001));
|
|
3100
|
-
const
|
|
3101
|
-
rows2.push(
|
|
3102
|
-
return write2(collection,
|
|
4418
|
+
const record4 = { id: newId2, ...body, ...total !== void 0 ? { total, currency: body.currency ?? { id: "1", refName: "USD" }, tranId: `${type === "salesOrder" ? "SO" : type === "invoice" ? "INV" : "BILL"}${newId2}` } : {}, dateCreated: iso2(sequence), lastModifiedDate: iso2(sequence) };
|
|
4419
|
+
rows2.push(record4);
|
|
4420
|
+
return write2(collection, record4, null, 204, { location: `/services/rest/record/v1/${type}/${newId2}` });
|
|
3103
4421
|
}
|
|
3104
|
-
const
|
|
3105
|
-
if (!
|
|
3106
|
-
if (method === "GET") return read(collection, { links: nsLink(type,
|
|
4422
|
+
const record3 = id ? rows2.find((r) => r.id === id) : void 0;
|
|
4423
|
+
if (!record3) return { ...nsError(404, "Record Not Found", "The record instance does not exist. Provide a valid record instance ID.", "NONEXISTENT_ID"), collection };
|
|
4424
|
+
if (method === "GET") return read(collection, { links: nsLink(type, record3.id), ...record3 });
|
|
3107
4425
|
if (method === "PATCH") {
|
|
3108
4426
|
if ("id" in body) return;
|
|
3109
|
-
Object.assign(
|
|
3110
|
-
return write2(collection,
|
|
4427
|
+
Object.assign(record3, body, { lastModifiedDate: iso2(sequence) });
|
|
4428
|
+
return write2(collection, record3, null, 204);
|
|
3111
4429
|
}
|
|
3112
4430
|
if (method === "DELETE") {
|
|
3113
|
-
rows2.splice(rows2.indexOf(
|
|
3114
|
-
return write2(collection,
|
|
4431
|
+
rows2.splice(rows2.indexOf(record3), 1);
|
|
4432
|
+
return write2(collection, record3, null, 204);
|
|
3115
4433
|
}
|
|
3116
4434
|
};
|
|
3117
4435
|
var pdError = (status, message, code, errors = []) => ({ status, body: { error: { message, code, errors } } });
|
|
3118
4436
|
var pdId = (seed) => "P" + hash(seed).replace(/[^A-Z0-9]/gi, "").toUpperCase().slice(0, 6);
|
|
3119
4437
|
var pagerduty = (method, path, body, query, headers, data, sequence) => {
|
|
3120
4438
|
const services = table(data, "/services"), incidents = table(data, "/incidents"), notes = table(data, "/notes"), events = table(data, "/events");
|
|
3121
|
-
const
|
|
4439
|
+
const open2 = (serviceId, key2) => incidents.find((i) => i.service.id === serviceId && i.incident_key === key2 && i.status !== "resolved");
|
|
3122
4440
|
const create = (service, title, urgency, key2, details) => {
|
|
3123
4441
|
const id2 = pdId(`pd:incident:${sequence}:${incidents.length}`);
|
|
3124
|
-
const
|
|
4442
|
+
const record3 = {
|
|
3125
4443
|
id: id2,
|
|
3126
4444
|
type: "incident",
|
|
3127
4445
|
summary: `[#${incidents.length + 1}] ${title}`,
|
|
@@ -3136,8 +4454,8 @@ var pagerduty = (method, path, body, query, headers, data, sequence) => {
|
|
|
3136
4454
|
html_url: `https://contoso.pagerduty.test/incidents/${id2}`,
|
|
3137
4455
|
...details === void 0 ? {} : { body: { type: "incident_body", details } }
|
|
3138
4456
|
};
|
|
3139
|
-
incidents.push(
|
|
3140
|
-
return
|
|
4457
|
+
incidents.push(record3);
|
|
4458
|
+
return record3;
|
|
3141
4459
|
};
|
|
3142
4460
|
if (path === "/v2/enqueue" && method === "POST") {
|
|
3143
4461
|
const service = services.find((s) => s.integration_key && s.integration_key === body.routing_key);
|
|
@@ -3148,7 +4466,7 @@ var pagerduty = (method, path, body, query, headers, data, sequence) => {
|
|
|
3148
4466
|
return { status: 400, collection: "/events", body: { status: "invalid event", message: "Event object is invalid", errors: ["'payload.summary', 'payload.source' and 'payload.severity' are required"] } };
|
|
3149
4467
|
if (action !== "trigger" && !body.dedup_key) return { status: 400, collection: "/events", body: { status: "invalid event", message: "Event object is invalid", errors: ["'dedup_key' is required for acknowledge and resolve"] } };
|
|
3150
4468
|
const key2 = String(body.dedup_key ?? hash(`pd:dedup:${sequence}`).slice(0, 32));
|
|
3151
|
-
const existing =
|
|
4469
|
+
const existing = open2(service.id, key2);
|
|
3152
4470
|
if (action === "trigger" && !existing) create(service, payload.summary, payload.severity === "critical" || payload.severity === "error" ? "high" : "low", key2, payload.custom_details);
|
|
3153
4471
|
if (action !== "trigger" && existing) Object.assign(existing, { status: action === "acknowledge" ? "acknowledged" : "resolved", updated_at: iso2(sequence) });
|
|
3154
4472
|
const event = { id: hash(`pd:event:${sequence}:${events.length}`).slice(0, 24), service: service.id, event_action: action, dedup_key: key2, grouped: action === "trigger" && !!existing, summary: isObject2(payload) ? payload.summary ?? null : null, received_at: iso2(sequence) };
|
|
@@ -3173,9 +4491,9 @@ var pagerduty = (method, path, body, query, headers, data, sequence) => {
|
|
|
3173
4491
|
if (!isObject2(input) || input.type !== "incident" || typeof input.title !== "string" || !isObject2(input.service)) return { ...pdError(400, "Invalid Input Provided", 2001, ["Incident type, title and service are required."]), collection: "/incidents" };
|
|
3174
4492
|
const service = services.find((s) => s.id === input.service.id);
|
|
3175
4493
|
if (!service) return { ...pdError(400, "Invalid Input Provided", 2001, ["Service not found"]), collection: "/incidents" };
|
|
3176
|
-
if (input.incident_key &&
|
|
3177
|
-
const
|
|
3178
|
-
return write2("/incidents",
|
|
4494
|
+
if (input.incident_key && open2(service.id, String(input.incident_key))) return { ...pdError(400, "Invalid Input Provided", 2001, ["Open incident with matching dedup key already exists on this service"]), collection: "/incidents" };
|
|
4495
|
+
const record3 = create(service, input.title, input.urgency === "low" ? "low" : "high", String(input.incident_key ?? hash(`pd:key:${sequence}`).slice(0, 32)), isObject2(input.body) ? input.body.details : void 0);
|
|
4496
|
+
return write2("/incidents", record3, { incident: record3 }, 201);
|
|
3179
4497
|
}
|
|
3180
4498
|
const incident = incidents.find((i) => i.id === id);
|
|
3181
4499
|
if (!incident) return { ...pdError(404, "Not Found", 2100), collection: "/incidents" };
|
|
@@ -3336,6 +4654,7 @@ var ENTERPRISE_CONTRACTS = {
|
|
|
3336
4654
|
var RUNTIMES = /^(?:\/[\w./-]+\/)?(?:node|python[0-9.]*|uv|poetry|pipenv|go|ruby|bundle|deno|bun|curl)$/;
|
|
3337
4655
|
var ADAPTER_OPTIONAL_COLLECTIONS = {
|
|
3338
4656
|
stripe: ["/v1/charges", "/v1/refunds", "/v1/events"],
|
|
4657
|
+
gmail: ["/gmail/v1/users/me/drafts", "/gmail/v1/users/me/settings/sendAs", "/gmail/v1/users/me/watch", "/pubsub/subscriptions", "/pubsub/messages"],
|
|
3339
4658
|
...ENTERPRISE_OPTIONAL_COLLECTIONS
|
|
3340
4659
|
};
|
|
3341
4660
|
var ADAPTER_COLLECTIONS = {
|
|
@@ -3357,12 +4676,15 @@ var ADAPTER_COLLECTIONS = {
|
|
|
3357
4676
|
twilio: ["/2010-04-01/Messages", "/2010-04-01/Calls"],
|
|
3358
4677
|
composio: ["/connected_accounts", "/tools", "/messages"],
|
|
3359
4678
|
"google-oauth": ["/clients", "/grants", "/tokens"],
|
|
4679
|
+
"upstash-redis": ["/keys"],
|
|
3360
4680
|
zendesk: ["/api/v2/tickets", "/api/v2/users", "/api/v2/organizations"],
|
|
3361
4681
|
// Enterprise twins: any subset of their optional collections; Snowflake tables are free-form.
|
|
3362
4682
|
...Object.fromEntries(ENTERPRISE_ADAPTERS.filter((a) => !FREEFORM_COLLECTION_ADAPTERS.includes(a)).map((a) => [a, []]))
|
|
3363
4683
|
};
|
|
3364
4684
|
var FAULT_TYPES = ["timeout-after-write", "blackhole", "server-error", "duplicate-write", "slow-response"];
|
|
3365
4685
|
var PROPERTY_KINDS = ["unique-per-act", "no-loss", "effect-count"];
|
|
4686
|
+
var RESERVED_ENV = /^(PATH|NODE_OPTIONS|AGENTTWIN_.*|DATABASE_URL|POSTGRES_URL|PG_URL|PG(HOST|PORT|USER|PASSWORD|DATABASE|SSLMODE)|REDIS_(URL|HOST|PORT|TLS_URL)|REDISHOST|REDISPORT|KV_URL|HTTPS?_PROXY|ALL_PROXY|NO_PROXY|SSL_CERT_FILE|REQUESTS_CA_BUNDLE|CURL_CA_BUNDLE|NODE_EXTRA_CA_CERTS|GRPC_DEFAULT_SSL_ROOTS_FILE_PATH)$/i;
|
|
4687
|
+
var isServerPath = (path) => typeof path === "string" && path.length <= 4096 && path.startsWith("/") && !path.startsWith("//") && !path.includes("\\") && !/[\u0000-\u001f\u007f]/.test(path);
|
|
3366
4688
|
var object2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
3367
4689
|
var namePattern = /^[a-z][a-z0-9_]{0,39}$/;
|
|
3368
4690
|
var inRangeInt = (x, min, max) => Number.isInteger(x) && Number(x) >= min && Number(x) <= max;
|
|
@@ -3387,7 +4709,7 @@ function parseWorld(value) {
|
|
|
3387
4709
|
if (!object2(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid("service names must be unique lowercase identifiers");
|
|
3388
4710
|
const item = service;
|
|
3389
4711
|
if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
|
|
3390
|
-
if (item.adapter !== void 0 && !["json-collection", "slack", "stripe", "openai", "anthropic", "github", "linear", "notion", "hubspot", "shopify", "datadog", "gmail", "google-calendar", "gitlab", "jira", "discord", "twilio", "zendesk", "google-oauth", "composio", ...ENTERPRISE_ADAPTERS].includes(String(item.adapter)) && !isGeneratedAdapter(item.adapter) && !isPackAdapter(item.adapter)) invalid("unsupported service adapter");
|
|
4712
|
+
if (item.adapter !== void 0 && !["json-collection", "slack", "stripe", "openai", "anthropic", "github", "linear", "notion", "hubspot", "shopify", "datadog", "gmail", "google-calendar", "gitlab", "jira", "discord", "twilio", "zendesk", "google-oauth", "composio", "upstash-redis", ...ENTERPRISE_ADAPTERS].includes(String(item.adapter)) && !isGeneratedAdapter(item.adapter) && !isPackAdapter(item.adapter)) invalid("unsupported service adapter");
|
|
3391
4713
|
const paths = /* @__PURE__ */ new Set();
|
|
3392
4714
|
for (const entry of item.collections) {
|
|
3393
4715
|
if (!object2(entry) || typeof entry.path !== "string" || !/^\/[a-zA-Z0-9_/-]+$/.test(entry.path) || entry.path.includes("//") || paths.has(entry.path)) invalid("collection paths must be unique absolute HTTP paths");
|
|
@@ -3421,6 +4743,8 @@ function parseWorld(value) {
|
|
|
3421
4743
|
if (v.scenario !== void 0 && (!object2(v.scenario) || typeof v.scenario.id !== "string" || !namePattern.test(v.scenario.id) || !Number.isSafeInteger(v.scenario.version) || Number(v.scenario.version) < 1 || typeof v.scenario.digest !== "string" || !/^[a-f0-9]{64}$/.test(v.scenario.digest) || Object.keys(v.scenario).some((k) => !["id", "version", "digest"].includes(k)))) invalid("scenario requires id, positive version and SHA-256 digest");
|
|
3422
4744
|
if (v.postgres !== void 0) {
|
|
3423
4745
|
if (!object2(v.postgres) || v.postgres.seedFile !== void 0 && !v.files.includes(String(v.postgres.seedFile)) || !Array.isArray(v.postgres.assertions) || !v.postgres.assertions.length || v.postgres.assertions.length > 100) invalid("postgres requires assertions and seedFile must be listed in files");
|
|
4746
|
+
const extensions = v.postgres.extensions;
|
|
4747
|
+
if (extensions !== void 0 && (!Array.isArray(extensions) || extensions.length > POSTGRES_EXTENSIONS.length || new Set(extensions).size !== extensions.length || !extensions.every((e) => POSTGRES_EXTENSIONS.includes(e)))) invalid(`postgres.extensions must list distinct supported extensions: ${POSTGRES_EXTENSIONS.join(", ")}`);
|
|
3424
4748
|
const clock = v.postgres.clock;
|
|
3425
4749
|
if (clock !== void 0 && !validPostgresClock(clock)) invalid("postgres.clock requires only now, a canonical UTC timestamp such as 2026-01-01T00:00:00.000Z");
|
|
3426
4750
|
for (const a of v.postgres.assertions) {
|
|
@@ -3517,6 +4841,39 @@ function parseWorld(value) {
|
|
|
3517
4841
|
}
|
|
3518
4842
|
}
|
|
3519
4843
|
if (v.background !== void 0 && (!object2(v.background) || !known2(v.background) || !Number.isSafeInteger(v.background.count) || Number(v.background.count) < 0 || !Number.isInteger(v.background.timeoutMs) || Number(v.background.timeoutMs) < 1 || Number(v.background.timeoutMs) > Number(v.timeoutSeconds) * 1e3 || v.background.where !== void 0 && !object2(v.background.where) || Object.keys(v.background).some((k) => !["service", "path", "count", "where", "timeoutMs"].includes(k)))) invalid("background requires a known collection, expected count, optional where, and bounded timeoutMs");
|
|
4844
|
+
if (v.directory !== void 0 && (typeof v.directory !== "string" || !v.directory || v.directory.length > 1024 || /\0/.test(v.directory) || isAbsolute(v.directory))) invalid("directory must be a relative path to the application folder");
|
|
4845
|
+
if (v.env !== void 0) {
|
|
4846
|
+
if (!object2(v.env) || Object.keys(v.env).length > 200) invalid("env must be an object of at most 200 string variables");
|
|
4847
|
+
for (const [key2, value2] of Object.entries(v.env)) {
|
|
4848
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(key2) || typeof value2 !== "string" || value2.length > 8192 || /\0/.test(value2)) invalid("env needs variable names and string values");
|
|
4849
|
+
if (RESERVED_ENV.test(key2)) invalid(`env cannot set ${key2}: AgentTwin sets it for the run`);
|
|
4850
|
+
}
|
|
4851
|
+
}
|
|
4852
|
+
if (v.server !== void 0) {
|
|
4853
|
+
const server = v.server;
|
|
4854
|
+
if (!object2(server) || Object.keys(server).some((k) => !["baseUrl", "readyPath", "readyTimeoutSeconds", "steps"].includes(k))) invalid("server needs baseUrl, optional readyPath and readyTimeoutSeconds, and steps");
|
|
4855
|
+
let u;
|
|
4856
|
+
try {
|
|
4857
|
+
u = new URL(String(server.baseUrl));
|
|
4858
|
+
} catch {
|
|
4859
|
+
u = void 0;
|
|
4860
|
+
}
|
|
4861
|
+
if (!u || u.protocol !== "http:" || u.hostname !== "127.0.0.1" || !u.port || u.username || u.password || u.pathname !== "/" || u.search || u.hash) invalid("server baseUrl must be http://127.0.0.1:<port>");
|
|
4862
|
+
if (server.readyPath !== void 0 && !isServerPath(server.readyPath)) invalid("server readyPath must start with a single / and contain no backslash or control characters");
|
|
4863
|
+
if (server.readyTimeoutSeconds !== void 0 && (!Number.isInteger(server.readyTimeoutSeconds) || Number(server.readyTimeoutSeconds) < 1 || Number(server.readyTimeoutSeconds) > 240)) invalid("server readyTimeoutSeconds must be 1\u2013240");
|
|
4864
|
+
if (!Array.isArray(server.steps) || !server.steps.length || server.steps.length > 50) invalid("server needs 1\u201350 steps");
|
|
4865
|
+
for (const raw of server.steps) {
|
|
4866
|
+
const step = raw;
|
|
4867
|
+
if (!object2(step) || step.action !== "request" || Object.keys(step).some((k) => !["action", "target", "method", "path", "headers", "body", "expectStatus"].includes(k))) invalid("server steps are request actions with target, method, path, optional headers, body and expectStatus");
|
|
4868
|
+
if (typeof step.target !== "string" || step.target !== "app" && !services.has(step.target)) invalid('server step target must be "app" or a service name');
|
|
4869
|
+
if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(String(step.method))) invalid("server step method must be GET, POST, PUT, PATCH or DELETE");
|
|
4870
|
+
if (!isServerPath(step.path)) invalid("server step path must start with a single / and contain no backslash or control characters");
|
|
4871
|
+
if (step.headers !== void 0 && (!object2(step.headers) || Object.entries(step.headers).some(([k, h]) => !/^[A-Za-z0-9-]{1,128}$/.test(k) || typeof h !== "string" || /[\r\n]/.test(h) || ["host", "content-length"].includes(k.toLowerCase())))) invalid("server step headers must be string values without host or content-length");
|
|
4872
|
+
if (step.body !== void 0 && (step.method === "GET" || JSON.stringify(step.body).length > 1024 * 1024)) invalid("server step body needs a non-GET method and at most 1 MiB of JSON");
|
|
4873
|
+
if (step.expectStatus !== void 0 && (!Number.isInteger(step.expectStatus) || Number(step.expectStatus) < 100 || Number(step.expectStatus) > 599)) invalid("server step expectStatus must be an HTTP status");
|
|
4874
|
+
}
|
|
4875
|
+
if (v.browser !== void 0) invalid("use either browser or server, not both");
|
|
4876
|
+
}
|
|
3520
4877
|
if (v.fetchRoutes !== void 0) {
|
|
3521
4878
|
if (!Array.isArray(v.fetchRoutes) || !v.fetchRoutes.length || v.fetchRoutes.length > 10) invalid("fetchRoutes needs 1\u201310 explicit origin/service mappings");
|
|
3522
4879
|
const origins = /* @__PURE__ */ new Set();
|
|
@@ -3533,14 +4890,14 @@ function parseWorld(value) {
|
|
|
3533
4890
|
origins.add(mapping.origin);
|
|
3534
4891
|
}
|
|
3535
4892
|
}
|
|
3536
|
-
const keys = ["schema", "name", "workflowId", "sourceBuild", "applicationClock", "twinClock", "files", "command", "timeoutSeconds", "browser", "background", "services", "fetchRoutes", "assertions", "forbiddenEffects", "preservedState", "properties", "scenario", "postgres", "redis", "fault", "faults", "latency"];
|
|
4893
|
+
const keys = ["schema", "name", "workflowId", "sourceBuild", "applicationClock", "twinClock", "files", "command", "timeoutSeconds", "browser", "background", "directory", "env", "server", "services", "fetchRoutes", "assertions", "forbiddenEffects", "preservedState", "properties", "scenario", "postgres", "redis", "fault", "faults", "latency"];
|
|
3537
4894
|
if (Object.keys(v).some((k) => !keys.includes(k))) invalid("unknown world field");
|
|
3538
4895
|
return v;
|
|
3539
4896
|
}
|
|
3540
4897
|
|
|
3541
4898
|
// src/runtime/pack-log.ts
|
|
3542
4899
|
import { closeSync, existsSync as existsSync2, openSync, readdirSync, readSync, statSync } from "fs";
|
|
3543
|
-
import { join as
|
|
4900
|
+
import { join as join6 } from "path";
|
|
3544
4901
|
var PackActionTail = class {
|
|
3545
4902
|
constructor(root) {
|
|
3546
4903
|
this.root = root;
|
|
@@ -3550,7 +4907,7 @@ var PackActionTail = class {
|
|
|
3550
4907
|
partial = /* @__PURE__ */ new Map();
|
|
3551
4908
|
files() {
|
|
3552
4909
|
if (!existsSync2(this.root)) return [];
|
|
3553
|
-
return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) =>
|
|
4910
|
+
return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join6(this.root, f)).sort();
|
|
3554
4911
|
}
|
|
3555
4912
|
drain() {
|
|
3556
4913
|
const out = [];
|
|
@@ -3564,8 +4921,8 @@ var PackActionTail = class {
|
|
|
3564
4921
|
closeSync(fd);
|
|
3565
4922
|
}
|
|
3566
4923
|
this.offsets.set(file, size);
|
|
3567
|
-
const
|
|
3568
|
-
const lines =
|
|
4924
|
+
const text2 = (this.partial.get(file) ?? "") + buffer.toString("utf8");
|
|
4925
|
+
const lines = text2.split("\n");
|
|
3569
4926
|
this.partial.set(file, lines.pop() ?? "");
|
|
3570
4927
|
for (const line of lines) if (line.trim()) try {
|
|
3571
4928
|
out.push(JSON.parse(line));
|
|
@@ -3606,9 +4963,9 @@ function seedActions(service, collections, at, tenant = {}) {
|
|
|
3606
4963
|
}
|
|
3607
4964
|
|
|
3608
4965
|
// src/runtime/http-world.ts
|
|
3609
|
-
import { mkdir, mkdtemp as
|
|
3610
|
-
import { tmpdir as
|
|
3611
|
-
import { join as
|
|
4966
|
+
import { mkdir, mkdtemp as mkdtemp4, rm as rm4, writeFile as writeFile3 } from "fs/promises";
|
|
4967
|
+
import { tmpdir as tmpdir4 } from "os";
|
|
4968
|
+
import { join as join7 } from "path";
|
|
3612
4969
|
var idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash5("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
|
|
3613
4970
|
var HttpWorld = class {
|
|
3614
4971
|
/** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
|
|
@@ -3635,10 +4992,46 @@ var HttpWorld = class {
|
|
|
3635
4992
|
epoch = 0;
|
|
3636
4993
|
replayKeys = /* @__PURE__ */ new Map();
|
|
3637
4994
|
sourceContext = new AsyncLocalStorage2();
|
|
3638
|
-
record(service, operation, path, detail,
|
|
4995
|
+
record(service, operation, path, detail, record3) {
|
|
3639
4996
|
if (this.events.length >= 5e4) return;
|
|
3640
4997
|
const source = this.sourceContext.getStore();
|
|
3641
|
-
this.events.push({ sequence: this.events.length + 1, service, operation, path, detail, ...
|
|
4998
|
+
this.events.push({ sequence: this.events.length + 1, service, operation, path, detail, ...record3 ? { record: structuredClone(record3) } : {}, ...source ? { source } : {} });
|
|
4999
|
+
}
|
|
5000
|
+
/**
|
|
5001
|
+
* Delivers twin-initiated pushes (Gmail watch → Pub/Sub push subscription) to the application under test, once
|
|
5002
|
+
* each, after the triggering response. Only loopback http endpoints are allowed, so a push can never leave the
|
|
5003
|
+
* machine; the outcome is written to the push row and recorded as a `push` event.
|
|
5004
|
+
*/
|
|
5005
|
+
push(service, deliveries, epoch) {
|
|
5006
|
+
for (const delivery of deliveries) {
|
|
5007
|
+
const timer = setTimeout(async () => {
|
|
5008
|
+
this.timers.delete(timer);
|
|
5009
|
+
if (epoch !== this.epoch) return;
|
|
5010
|
+
let target;
|
|
5011
|
+
try {
|
|
5012
|
+
target = new URL(delivery.url);
|
|
5013
|
+
} catch {
|
|
5014
|
+
target = void 0;
|
|
5015
|
+
}
|
|
5016
|
+
if (!target || target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || target.username || target.password) {
|
|
5017
|
+
delivery.row.delivery = "rejected: pushEndpoint must be a loopback http URL";
|
|
5018
|
+
this.record(service, "push", "/pubsub/messages", `push rejected: ${String(delivery.row.messageId)} endpoint is not loopback http`);
|
|
5019
|
+
return;
|
|
5020
|
+
}
|
|
5021
|
+
try {
|
|
5022
|
+
const response = await fetch(target, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(delivery.body), redirect: "error", signal: AbortSignal.timeout(6e4) });
|
|
5023
|
+
await response.arrayBuffer().catch(() => void 0);
|
|
5024
|
+
if (epoch !== this.epoch) return;
|
|
5025
|
+
delivery.row.delivery = response.status;
|
|
5026
|
+
this.record(service, "push", "/pubsub/messages", `push ${String(delivery.row.messageId)} delivered: HTTP ${response.status}`, { messageId: delivery.row.messageId, status: response.status });
|
|
5027
|
+
} catch (error) {
|
|
5028
|
+
if (epoch !== this.epoch) return;
|
|
5029
|
+
delivery.row.delivery = `failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
5030
|
+
this.record(service, "push", "/pubsub/messages", `push ${String(delivery.row.messageId)} failed`);
|
|
5031
|
+
}
|
|
5032
|
+
}, 25);
|
|
5033
|
+
this.timers.add(timer);
|
|
5034
|
+
}
|
|
3642
5035
|
}
|
|
3643
5036
|
/** Tags the event just recorded with the request's idempotency key digest. */
|
|
3644
5037
|
keyed(key2) {
|
|
@@ -3692,7 +5085,7 @@ var HttpWorld = class {
|
|
|
3692
5085
|
this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server2.address().port}`, token };
|
|
3693
5086
|
continue;
|
|
3694
5087
|
}
|
|
3695
|
-
const server =
|
|
5088
|
+
const server = createServer3((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
|
|
3696
5089
|
const epoch = this.epoch;
|
|
3697
5090
|
const send = (code, body, headers = {}) => {
|
|
3698
5091
|
if (!res.destroyed) {
|
|
@@ -3814,33 +5207,43 @@ var HttpWorld = class {
|
|
|
3814
5207
|
}
|
|
3815
5208
|
chunks.push(Buffer.from(chunk));
|
|
3816
5209
|
}
|
|
3817
|
-
const
|
|
5210
|
+
const text2 = Buffer.concat(chunks).toString("utf8");
|
|
3818
5211
|
let parsed;
|
|
3819
5212
|
const mode = generated?.bodyMode(req.headers["content-type"]);
|
|
3820
|
-
if ((enterprise || generated) && !
|
|
5213
|
+
if ((enterprise || generated) && !text2.trim()) parsed = {};
|
|
3821
5214
|
else if (mode === "form") {
|
|
3822
|
-
const form = new URLSearchParams(
|
|
5215
|
+
const form = new URLSearchParams(text2);
|
|
3823
5216
|
parsed = {};
|
|
3824
5217
|
for (const key3 of new Set(form.keys())) {
|
|
3825
5218
|
const all = form.getAll(key3);
|
|
3826
5219
|
parsed[key3] = all.length > 1 ? all : all[0];
|
|
3827
5220
|
}
|
|
3828
5221
|
} else if (mode === "raw") {
|
|
3829
|
-
rawBody =
|
|
5222
|
+
rawBody = text2;
|
|
5223
|
+
parsed = {};
|
|
5224
|
+
} else if (service.adapter === "gmail" && /^multipart\/mixed\b/i.test(String(req.headers["content-type"] ?? ""))) {
|
|
5225
|
+
rawBody = text2;
|
|
3830
5226
|
parsed = {};
|
|
3831
|
-
} else if (service.adapter === "
|
|
5227
|
+
} else if (service.adapter === "gmail" && /^multipart\/related\b/i.test(String(req.headers["content-type"] ?? ""))) {
|
|
5228
|
+
rawBody = text2;
|
|
5229
|
+
parsed = Object.fromEntries(url.searchParams);
|
|
5230
|
+
} else if (service.adapter === "upstash-redis") {
|
|
5231
|
+
rawBody = text2;
|
|
5232
|
+
parsed = {};
|
|
5233
|
+
} else if (service.adapter === "gmail" && !text2.trim()) parsed = {};
|
|
5234
|
+
else if (service.adapter === "google-oauth") {
|
|
3832
5235
|
if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
|
|
3833
5236
|
respond(400, { error: "invalid_request" });
|
|
3834
5237
|
return;
|
|
3835
5238
|
}
|
|
3836
|
-
const form = new URLSearchParams(
|
|
5239
|
+
const form = new URLSearchParams(text2);
|
|
3837
5240
|
if ([...form.keys()].some((key3) => form.getAll(key3).length !== 1)) {
|
|
3838
5241
|
respond(400, { error: "invalid_request" });
|
|
3839
5242
|
return;
|
|
3840
5243
|
}
|
|
3841
5244
|
parsed = Object.fromEntries(form);
|
|
3842
5245
|
} else try {
|
|
3843
|
-
parsed = (slack || service.adapter === "stripe" || service.adapter === "twilio") && req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(
|
|
5246
|
+
parsed = (slack || service.adapter === "stripe" || service.adapter === "twilio") && req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(text2)) : JSON.parse(text2);
|
|
3844
5247
|
} catch {
|
|
3845
5248
|
respond(400, { error: "expected_json_object" });
|
|
3846
5249
|
return;
|
|
@@ -3873,7 +5276,7 @@ var HttpWorld = class {
|
|
|
3873
5276
|
return;
|
|
3874
5277
|
}
|
|
3875
5278
|
const query = Object.fromEntries(url.searchParams);
|
|
3876
|
-
const invoke = (sequence) => generated ? generated.handle({ method: req.method ?? "", path, query, headers: req.headers, ...payload ? { body: structuredClone(payload) } : {}, ...rawBody !== void 0 ? { raw: rawBody } : {} }, data, sequence, this.seed) : enterprise ? ENTERPRISE_OPERATIONS[enterprise](req.method ?? "", path, structuredClone(payload ?? {}), query, req.headers, data, sequence) : restAdapter ? restAdapter(req.method ?? "", path, params, req.headers, data, sequence) : stripeOperation(req.method ?? "", path, params, data, sequence);
|
|
5279
|
+
const invoke = (sequence) => generated ? generated.handle({ method: req.method ?? "", path, query, headers: req.headers, ...payload ? { body: structuredClone(payload) } : {}, ...rawBody !== void 0 ? { raw: rawBody } : {} }, data, sequence, this.seed) : enterprise ? ENTERPRISE_OPERATIONS[enterprise](req.method ?? "", path, structuredClone(payload ?? {}), query, req.headers, data, sequence) : restAdapter ? restAdapter(req.method ?? "", path, params, req.headers, data, sequence, rawBody) : stripeOperation(req.method ?? "", path, params, data, sequence);
|
|
3877
5280
|
const headers = (r) => "headers" in r ? r.headers : void 0;
|
|
3878
5281
|
const result = invoke(this.events.length + 1);
|
|
3879
5282
|
if (!result) {
|
|
@@ -3888,15 +5291,19 @@ var HttpWorld = class {
|
|
|
3888
5291
|
if (key3 && (result.status === 200 || result.status === 201 || enterprise && (result.status === 202 || result.status === 204))) keys.set(key3, { body: signature2, record: structuredClone(result.body), status: result.status, ...headers(result) ? { headers: headers(result) } : {} });
|
|
3889
5292
|
const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result.operation === "write" && !key3 && matchesFault(result.collection);
|
|
3890
5293
|
const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
|
|
5294
|
+
const pushes = (r) => "deliveries" in r ? [...r.deliveries ?? []] : [];
|
|
5295
|
+
const deliveries = pushes(result);
|
|
3891
5296
|
if (duplicate2) {
|
|
3892
5297
|
const second = invoke(this.events.length + 1);
|
|
3893
5298
|
if (second?.operation === "write") {
|
|
5299
|
+
deliveries.push(...pushes(second));
|
|
3894
5300
|
this.record(service.name, second.operation, second.collection, path, "record" in second ? second.record : second.body);
|
|
3895
5301
|
this.faultActions++;
|
|
3896
5302
|
this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${result.collection})`);
|
|
3897
5303
|
} else if (second) {
|
|
3898
5304
|
this.record(service.name, "fault", fault.path, `duplicate-write: second delivery replaced by ${second.operation ?? "failure"}`);
|
|
3899
5305
|
respond(second.status, second.body, headers(second));
|
|
5306
|
+
if (deliveries.length) this.push(service.name, deliveries, epoch);
|
|
3900
5307
|
return;
|
|
3901
5308
|
}
|
|
3902
5309
|
}
|
|
@@ -3911,6 +5318,7 @@ var HttpWorld = class {
|
|
|
3911
5318
|
}, fault.delayMs);
|
|
3912
5319
|
this.timers.add(timer);
|
|
3913
5320
|
} else respondSlowly(result.collection, result.operation ?? "request", result.status, result.body, headers(result));
|
|
5321
|
+
if (deliveries.length) this.push(service.name, deliveries, epoch);
|
|
3914
5322
|
return;
|
|
3915
5323
|
}
|
|
3916
5324
|
if (slack) {
|
|
@@ -4032,26 +5440,26 @@ var HttpWorld = class {
|
|
|
4032
5440
|
async startPack(service, token, faultOrdinalsFor, faultKey, data, latencyMs) {
|
|
4033
5441
|
const name = service.adapter.slice(PACK_PREFIX.length), meta = packRecord(name);
|
|
4034
5442
|
if (this.twinClock && packCatalog()?.engine[meta.generation]?.clockSupport !== "async-context-v1") throw new Error("Twin packs need rebuilding for per-run clock support");
|
|
4035
|
-
const root = await
|
|
5443
|
+
const root = await mkdtemp4(join7(tmpdir4(), `agenttwin-pack-${name}-`));
|
|
4036
5444
|
this.packRoots.push(root);
|
|
4037
5445
|
const worldSeed = meta.logService ? JSON.stringify({ id: `twin:${meta.logService}:world_seed.record:seed:agenttwin`, service: meta.logService, op: "set", operation: "world_seed.record", subject: { type: "_world_seed", id: "seed" }, occurredAt: new Date(twinNowMs(Date.now())).toISOString(), actor: { kind: "system" }, fields: { value: new SeedStream(this.seed, `pack-world:${service.name}`).nextHex(64) } }) + "\n" : "";
|
|
4038
|
-
const writeSeedLog = async (dir,
|
|
4039
|
-
if (!
|
|
4040
|
-
await mkdir(
|
|
4041
|
-
await writeFile3(
|
|
5446
|
+
const writeSeedLog = async (dir, text2) => {
|
|
5447
|
+
if (!text2) return;
|
|
5448
|
+
await mkdir(join7(dir, ".volter/world", meta.logService), { recursive: true });
|
|
5449
|
+
await writeFile3(join7(dir, ".volter/world", meta.logService, "actions.jsonl"), text2);
|
|
4042
5450
|
};
|
|
4043
5451
|
let tenant = {}, credential;
|
|
4044
5452
|
if (meta.logService && meta.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account)) {
|
|
4045
|
-
const probe = await
|
|
5453
|
+
const probe = await mkdtemp4(join7(tmpdir4(), `agenttwin-pack-${name}-probe-`));
|
|
4046
5454
|
try {
|
|
4047
5455
|
await writeSeedLog(probe, worldSeed);
|
|
4048
5456
|
const scratch = await (await loadPack(name))({ root: probe });
|
|
4049
5457
|
await (await scratch(new Request(`https://${meta.hosts[0]?.host ?? `${name}.twin.test`}${meta.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta.credentialDoor.body ?? {}) }))).arrayBuffer();
|
|
4050
|
-
const probed = new PackActionTail(
|
|
5458
|
+
const probed = new PackActionTail(join7(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
|
|
4051
5459
|
tenant = tenantFields(probed);
|
|
4052
5460
|
credential = credentialAction(probed);
|
|
4053
5461
|
} finally {
|
|
4054
|
-
await
|
|
5462
|
+
await rm4(probe, { recursive: true, force: true });
|
|
4055
5463
|
}
|
|
4056
5464
|
}
|
|
4057
5465
|
const account = credential && service.account ? JSON.stringify({ ...credential, id: `${credential.id ?? "credential"}:preset`, fields: { ...credential.fields, ...service.account } }) + "\n" : "";
|
|
@@ -4059,7 +5467,7 @@ var HttpWorld = class {
|
|
|
4059
5467
|
await writeSeedLog(root, seeded);
|
|
4060
5468
|
const twin = await (await loadPack(name))({ root });
|
|
4061
5469
|
const baseHost = meta.hosts[0]?.host ?? `${name}.twin.test`;
|
|
4062
|
-
const log = new PackActionTail(
|
|
5470
|
+
const log = new PackActionTail(join7(root, ".volter"));
|
|
4063
5471
|
let issued = {};
|
|
4064
5472
|
if (meta.credentialDoor) {
|
|
4065
5473
|
const r = await twin(new Request(`https://${baseHost}${meta.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta.credentialDoor.body ?? {}) }));
|
|
@@ -4116,7 +5524,7 @@ var HttpWorld = class {
|
|
|
4116
5524
|
chain = run2.then(() => void 0, () => void 0);
|
|
4117
5525
|
return run2;
|
|
4118
5526
|
};
|
|
4119
|
-
const server =
|
|
5527
|
+
const server = createServer3((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
|
|
4120
5528
|
const epoch = this.epoch;
|
|
4121
5529
|
const send = (status, headers, body) => {
|
|
4122
5530
|
if (!res.destroyed) {
|
|
@@ -4299,7 +5707,7 @@ var HttpWorld = class {
|
|
|
4299
5707
|
server.closeAllConnections();
|
|
4300
5708
|
})));
|
|
4301
5709
|
this.servers.length = 0;
|
|
4302
|
-
await Promise.all(this.packRoots.splice(0).map((root) =>
|
|
5710
|
+
await Promise.all(this.packRoots.splice(0).map((root) => rm4(root, { recursive: true, force: true })));
|
|
4303
5711
|
}
|
|
4304
5712
|
};
|
|
4305
5713
|
|
|
@@ -4389,9 +5797,9 @@ function evaluateProperty(policy, final, events) {
|
|
|
4389
5797
|
const writes = eventsFor("write", policy.params?.where);
|
|
4390
5798
|
const lost = writes.filter((e) => {
|
|
4391
5799
|
if (!e.record) return false;
|
|
4392
|
-
const
|
|
4393
|
-
if (typeof
|
|
4394
|
-
return !rows2.some((row) => isDeepStrictEqual2(row,
|
|
5800
|
+
const record3 = e.record;
|
|
5801
|
+
if (typeof record3.id === "string" && record3.id) return !rows2.some((row) => row.id === record3.id);
|
|
5802
|
+
return !rows2.some((row) => isDeepStrictEqual2(row, record3));
|
|
4395
5803
|
});
|
|
4396
5804
|
const unknown2 = writes.some((e) => !e.record);
|
|
4397
5805
|
return {
|
|
@@ -4580,9 +5988,35 @@ var CONTRACTS = {
|
|
|
4580
5988
|
{ method: "POST", endpoint: "/gmail/v1/users/me/messages/send", effect: "append a sent message", parameters: ["text", "raw", "to", "subject", "threadId"], errors: ["400 body required", "400 invalid field type"] },
|
|
4581
5989
|
{ method: "GET", endpoint: "/gmail/v1/users/me/messages", effect: "list message ids with a snippet q filter", parameters: ["q"], errors: ["400 validation"] },
|
|
4582
5990
|
{ method: "GET", endpoint: "/gmail/v1/users/me/messages/<id>", effect: "retrieve message", parameters: [], errors: ["404 NOT_FOUND"] },
|
|
4583
|
-
{ method: "GET", endpoint: "/gmail/v1/users/me/labels", effect: "list seeded labels", parameters: [], errors: [] }
|
|
5991
|
+
{ method: "GET", endpoint: "/gmail/v1/users/me/labels", effect: "list seeded labels", parameters: [], errors: [] },
|
|
5992
|
+
{ method: "GET", endpoint: "/gmail/v1/users/me/threads", effect: "list threads, newest first, excluding SPAM/TRASH", parameters: ["q (from:/to: address terms, OR-joined)", "maxResults", "labelIds"], errors: ["400 validation"] },
|
|
5993
|
+
{ method: "GET", endpoint: "/gmail/v1/users/me/threads/<id>", effect: "retrieve a thread with its messages, oldest first", parameters: ["format=full"], errors: ["404 NOT_FOUND"] },
|
|
5994
|
+
{ method: "GET", endpoint: "/gmail/v1/users/me/history", effect: "messagesAdded records for messages whose historyId is after startHistoryId", parameters: ["startHistoryId", "historyTypes", "maxResults"], errors: ["400 validation"] },
|
|
5995
|
+
{ method: "GET", endpoint: "/gmail/v1/users/me/settings/sendAs", effect: "list seeded send-as aliases", parameters: [], errors: [] },
|
|
5996
|
+
{ method: "POST", endpoint: "/gmail/v1/users/me/drafts", effect: "create a draft; its DRAFT-labelled message joins the thread", parameters: ["message.raw", "message.threadId"], errors: ["400 invalid MIME or fields", "404 unknown threadId"] },
|
|
5997
|
+
{ method: "GET", endpoint: "/gmail/v1/users/me/drafts", effect: "list drafts, newest first", parameters: ["maxResults"], errors: ["400 validation"] },
|
|
5998
|
+
{ method: "GET", endpoint: "/gmail/v1/users/me/drafts/<id>", effect: "retrieve a draft with its full message", parameters: ["format=full"], errors: ["404 NOT_FOUND"] },
|
|
5999
|
+
{ method: "DELETE", endpoint: "/gmail/v1/users/me/drafts/<id>", effect: "delete a draft and its message (204)", parameters: [], errors: ["404 NOT_FOUND"] },
|
|
6000
|
+
{ method: "POST", endpoint: "/gmail/v1/users/me/messages", effect: "insert a received message (messages.insert) into the mailbox, optionally into an existing thread; nothing is sent", parameters: ["raw", "threadId", "labelIds", "internalDateSource"], errors: ["400 invalid MIME, label or internalDateSource", "404 unknown thread"] },
|
|
6001
|
+
{ method: "POST", endpoint: "/gmail/v1/users/me/watch", effect: "record one push registration with the current historyId and an expiration seven days after the twin clock; no Pub/Sub notifications are delivered", parameters: ["topicName", "labelIds", "labelFilterBehavior"], errors: ["400 invalid topicName, label or labelFilterBehavior"] },
|
|
6002
|
+
{ method: "PUSH", endpoint: "seeded /pubsub/subscriptions pushEndpoint", effect: "while a watch is active, an inserted or sent message with a watched label publishes {emailAddress, historyId} to each subscription on the watch topic; the world POSTs it once to a loopback http pushEndpoint after the response and records the HTTP status in /pubsub/messages", parameters: ["subscription name", "topic", "pushEndpoint (http://127.0.0.1, localhost or [::1] only)"], errors: ["non-loopback endpoints are rejected and recorded, never called"] },
|
|
6003
|
+
{ method: "POST", endpoint: "/gmail/v1/users/me/stop", effect: "remove the push registration", parameters: [], errors: [] },
|
|
6004
|
+
{ method: "PUT", endpoint: "/gmail/v1/users/me/drafts/{id}", effect: "update a draft: replace its message (new message id) in the same thread, keeping the draft id", parameters: ["id", "message.raw", "message.threadId (same thread only)"], errors: ["400 invalid MIME or mismatched id", "404 unknown draft"] },
|
|
6005
|
+
{ method: "POST/PUT", endpoint: "/upload/gmail/v1/users/me/drafts[/{id}]?uploadType=multipart", effect: "media-upload form of drafts create/update: multipart/related JSON metadata plus a message/rfc822 part, as googleapis sends with media", parameters: ["uploadType=multipart", "metadata message.threadId", "message/rfc822 body"], errors: ["400 malformed multipart body", "404 unknown draft"] },
|
|
6006
|
+
{ method: "POST", endpoint: "/gmail/v1/users/me/drafts/send", effect: "send a draft: its message becomes SENT in the same thread and the draft is removed", parameters: ["id", "message.raw", "message.threadId (same thread only)"], errors: ["400 missing id, invalid MIME or no recipient", "404 unknown draft"] },
|
|
6007
|
+
{ method: "POST", endpoint: "/batch/gmail/v1", effect: "multipart batch of up to 100 body-less GET messages/<id> or threads/<id> requests", parameters: ["multipart/mixed body"], errors: ["400 malformed batch"] }
|
|
4584
6008
|
],
|
|
4585
|
-
limitations: ["Bounded Gmail v1 subset: send, list, get and
|
|
6009
|
+
limitations: ["Bounded Gmail v1 subset: send, messages list/get, labels, threads list/get, sendAs list, drafts create/list/get/update/delete/send (JSON and media upload), history list, messages insert, watch/stop with loopback Pub/Sub push and read-only batch", "Send parses plain-text MIME only; drafts accept folded/UTF-8 encoded headers, quoted-printable/base64 bodies and text or multipart/alternative text+html, without attachments", "Thread search supports only from:/to: address terms; no pageToken or history paging, label-change history, modify or trash; Pub/Sub push is delivered once with no retry, ack deadline or ordering guarantees, and only to loopback endpoints", "Draft records add flat threadId, to, subject, inReplyTo and references evidence fields for assertions", "Unknown fields and operations return 501 and make coverage incomplete"]
|
|
6010
|
+
},
|
|
6011
|
+
"upstash-redis": {
|
|
6012
|
+
version: "1.0.0",
|
|
6013
|
+
authentication: "Bearer run-scoped test token (the Upstash REST token header)",
|
|
6014
|
+
operations: [
|
|
6015
|
+
{ method: "POST", endpoint: "/", effect: "run one Redis command given as a JSON array", parameters: ['["COMMAND", ...args]', "Upstash-Encoding: base64"], errors: ["400 Redis error reply or malformed command"] },
|
|
6016
|
+
{ method: "POST", endpoint: "/pipeline", effect: "run commands in order; one {result}|{error} per command", parameters: ["[[...], ...] up to 1000 commands"], errors: ["400 malformed body"] },
|
|
6017
|
+
{ method: "POST", endpoint: "/multi-exec", effect: "run commands in order as one transaction", parameters: ["[[...], ...] up to 1000 commands"], errors: ["400 malformed body"] }
|
|
6018
|
+
],
|
|
6019
|
+
limitations: ["Commands run on AgentTwin's in-process Redis engine (strings, hashes, lists, sets, sorted sets, expiry), not Redis itself", "Keys are mirrored in /keys as {key, type, value, expireAt?} rows", "EVAL/EVALSHA/scripts, blocking pops, pub/sub subscriptions, MULTI/EXEC/WATCH inside a request and any engine-unknown command return 501", "Expiry uses the host clock; no replication, persistence, ACLs or read-your-writes sync tokens"]
|
|
4586
6020
|
},
|
|
4587
6021
|
"google-calendar": {
|
|
4588
6022
|
version: "1.1.0",
|
|
@@ -4685,14 +6119,14 @@ function packContract(name, adapter) {
|
|
|
4685
6119
|
}
|
|
4686
6120
|
|
|
4687
6121
|
// src/runtime/browser-directories.ts
|
|
4688
|
-
import { mkdtemp as
|
|
4689
|
-
import { tmpdir as
|
|
4690
|
-
import { join as
|
|
6122
|
+
import { mkdtemp as mkdtemp5, mkdir as mkdir2, chown, chmod, rm as rm5 } from "fs/promises";
|
|
6123
|
+
import { tmpdir as tmpdir5 } from "os";
|
|
6124
|
+
import { join as join8 } from "path";
|
|
4691
6125
|
async function createBrowserDirectories(identity) {
|
|
4692
6126
|
if (!Number.isSafeInteger(identity.uid) || identity.uid < 0 || !Number.isSafeInteger(identity.gid) || identity.gid < 0) throw new Error("Invalid browser identity");
|
|
4693
|
-
const root = await
|
|
4694
|
-
const profile =
|
|
4695
|
-
const close = () =>
|
|
6127
|
+
const root = await mkdtemp5(join8(tmpdir5(), "agenttwin-browser-"));
|
|
6128
|
+
const profile = join8(root, "profile"), artifacts = join8(root, "artifacts");
|
|
6129
|
+
const close = () => rm5(root, { recursive: true, force: true });
|
|
4696
6130
|
try {
|
|
4697
6131
|
await mkdir2(profile, { mode: 448 });
|
|
4698
6132
|
await mkdir2(artifacts, { mode: 448 });
|
|
@@ -4879,8 +6313,8 @@ async function waitBackground(spec, world, signal) {
|
|
|
4879
6313
|
}
|
|
4880
6314
|
|
|
4881
6315
|
// src/runtime/cost-model.ts
|
|
4882
|
-
import { readFile as
|
|
4883
|
-
import { join as
|
|
6316
|
+
import { readFile as readFile2, writeFile as writeFile4 } from "fs/promises";
|
|
6317
|
+
import { join as join9 } from "path";
|
|
4884
6318
|
|
|
4885
6319
|
// src/runtime/run-summary.ts
|
|
4886
6320
|
var formatMoney = (m) => new Intl.NumberFormat("en-US", { style: "currency", currency: m.currency.length === 3 ? m.currency : "USD" }).format(m.amount);
|
|
@@ -4996,7 +6430,7 @@ var SUCCESS = /\b(done|complete[d]?|success(ful(ly)?)?|refunded|closed|created|u
|
|
|
4996
6430
|
var FAILURE = /\b(fail(ed|ure)?|error|unable|could ?n[o']t|cannot|can't|did ?n[o']t|not (?:been )?(?:\w+ed)|retry(ing)?|escalat\w*|pending|try again|sorry)\b/i;
|
|
4997
6431
|
var TEXT_FIELDS = /^(text|body|message|content|subject|summary|description|Body|Message|html|markdown|note|comment)$/;
|
|
4998
6432
|
var MESSAGING = /(message|messages|sms|mail|email|emails|notification|notifications|notify|send|postMessage|comments?|reply|replies)(\.json)?$/i;
|
|
4999
|
-
var polarityOf = (
|
|
6433
|
+
var polarityOf = (text2) => FAILURE.test(text2) ? "failure" : SUCCESS.test(text2) ? "success" : "neutral";
|
|
5000
6434
|
function textOf(body, depth = 0) {
|
|
5001
6435
|
if (!body || typeof body !== "object" || depth > 3) return "";
|
|
5002
6436
|
return Object.entries(body).map(([k, v]) => typeof v === "string" && TEXT_FIELDS.test(k) ? v : v && typeof v === "object" ? textOf(v, depth + 1) : "").filter(Boolean).join(" ").trim();
|
|
@@ -5009,11 +6443,11 @@ function recipientsOf(body, depth = 0) {
|
|
|
5009
6443
|
var isAnnouncement = (c) => c.isWrite && !!textOf(c.body) && (MESSAGING.test(c.path) || recipientsOf(c.body).length > 0);
|
|
5010
6444
|
function claimsOf(calls, output = []) {
|
|
5011
6445
|
const claims = calls.filter(isAnnouncement).map((c) => {
|
|
5012
|
-
const
|
|
5013
|
-
return { sequence: c.sequence, text, polarity: polarityOf(
|
|
6446
|
+
const text2 = textOf(c.body);
|
|
6447
|
+
return { sequence: c.sequence, text: text2, polarity: polarityOf(text2), via: c.sequence, ...c.source ? { source: c.source } : {} };
|
|
5014
6448
|
});
|
|
5015
6449
|
const end = Math.max(0, ...calls.map((c) => c.sequence)) + 1;
|
|
5016
|
-
output.map((t) => t.trim()).filter(Boolean).slice(0, 50).forEach((
|
|
6450
|
+
output.map((t) => t.trim()).filter(Boolean).slice(0, 50).forEach((text2, i) => claims.push({ sequence: end + i, text: text2.slice(0, 500), polarity: polarityOf(text2) }));
|
|
5017
6451
|
return claims;
|
|
5018
6452
|
}
|
|
5019
6453
|
var AMOUNT = /^(amount|total|price|unit_amount|amount_total|grand_total|subtotal|value|amount_cents|amount_minor|total_cents|price_cents)$/i;
|
|
@@ -5362,7 +6796,7 @@ var gmailText = (r) => {
|
|
|
5362
6796
|
function messageChecks(adapter, path) {
|
|
5363
6797
|
const noun = adapter === "slack" ? "Slack message" : "email", name = PROVIDER[adapter];
|
|
5364
6798
|
const signature = (r) => adapter === "slack" ? typeof r.text === "string" ? canonical3({ channel: r.channel, text: r.text }) : void 0 : Array.isArray(r.labelIds) && !r.labelIds.includes("SENT") ? void 0 : canonical3(gmailText(r));
|
|
5365
|
-
const
|
|
6799
|
+
const text2 = (r) => adapter === "slack" ? String(r.text ?? "") : `${gmailText(r).subject} ${gmailText(r).body}`;
|
|
5366
6800
|
const target = (r) => adapter === "slack" ? String(r.channel ?? "the channel") : gmailText(r).to || "the recipient";
|
|
5367
6801
|
return [{
|
|
5368
6802
|
id: `${adapter}.no-duplicate-message`,
|
|
@@ -5376,7 +6810,7 @@ function messageChecks(adapter, path) {
|
|
|
5376
6810
|
const s = ctx.service.name;
|
|
5377
6811
|
return groups(addedRows(rowsOf(ctx.initialState, s, path), rowsOf(ctx.finalState, s, path)), signature).map((group) => ({
|
|
5378
6812
|
path,
|
|
5379
|
-
actual: { messages: group.map((r) => r.id), to: target(group[0]), text:
|
|
6813
|
+
actual: { messages: group.map((r) => r.id), to: target(group[0]), text: text2(group[0]).slice(0, 200) },
|
|
5380
6814
|
finding: `Your agent sent the same ${noun} to ${target(group[0])} ${times2(group.length)}${faultPhrase(ctx)}`,
|
|
5381
6815
|
impact: { count: group.length - 1 },
|
|
5382
6816
|
evidence: writeSequences(ctx, s, group.map((r) => r.id))
|
|
@@ -5394,7 +6828,7 @@ function messageChecks(adapter, path) {
|
|
|
5394
6828
|
const sent = ctx.events.filter((e) => e.service === s && e.operation === "write" && e.path === path && e.record);
|
|
5395
6829
|
const failed = ctx.events.filter((e) => e.service !== s && e.operation === "fault" && /^(server-error|blackhole)\b.*\((POST|PUT|PATCH|DELETE)\)$/.test(e.detail));
|
|
5396
6830
|
for (const message of sent) {
|
|
5397
|
-
const words =
|
|
6831
|
+
const words = text2(message.record);
|
|
5398
6832
|
if (NEGATIVE.test(words)) continue;
|
|
5399
6833
|
const unrecovered = failed.find((f) => f.sequence < message.sequence && !ctx.events.some((e) => e.service === f.service && e.sequence > f.sequence && e.sequence < message.sequence && (e.operation === "write" || e.operation === "replay") && (e.path === f.path || e.path.startsWith(`${f.path}/`))));
|
|
5400
6834
|
if (!unrecovered) continue;
|
|
@@ -5525,14 +6959,14 @@ function runDefaultChecks(input) {
|
|
|
5525
6959
|
}
|
|
5526
6960
|
|
|
5527
6961
|
// src/runtime/hosted-worker.ts
|
|
5528
|
-
import { join as
|
|
6962
|
+
import { join as join10, dirname as dirname2 } from "path";
|
|
5529
6963
|
async function executeHostedWorker(input = "/input", identity = { uid: 1e3, gid: 1e3 }) {
|
|
5530
6964
|
input = await realpath2(input);
|
|
5531
6965
|
const secrets = [];
|
|
5532
|
-
const spec = parseWorld(JSON.parse(await
|
|
6966
|
+
const spec = parseWorld(JSON.parse(await readFile3(join10(input, "world.json"), "utf8")));
|
|
5533
6967
|
let suppliedSeed;
|
|
5534
6968
|
try {
|
|
5535
|
-
suppliedSeed = normalizeSeed(JSON.parse(await
|
|
6969
|
+
suppliedSeed = normalizeSeed(JSON.parse(await readFile3(join10(input, "seed.json"), "utf8")).seed);
|
|
5536
6970
|
} catch {
|
|
5537
6971
|
}
|
|
5538
6972
|
const world = new HttpWorld(spec, suppliedSeed);
|
|
@@ -5542,7 +6976,7 @@ async function executeHostedWorker(input = "/input", identity = { uid: 1e3, gid:
|
|
|
5542
6976
|
const credentials = await world.start();
|
|
5543
6977
|
secrets.push(...Object.values(credentials).map((c) => c.token));
|
|
5544
6978
|
const initialState = world.snapshot();
|
|
5545
|
-
const runtimeEnv = JSON.parse(await
|
|
6979
|
+
const runtimeEnv = JSON.parse(await readFile3(join10(input, "runtime.json"), "utf8"));
|
|
5546
6980
|
secrets.push(...Object.values(runtimeEnv));
|
|
5547
6981
|
const packEnv = Object.assign({}, ...Object.values(world.packEnv));
|
|
5548
6982
|
secrets.push(...Object.values(packEnv));
|
|
@@ -5552,13 +6986,20 @@ async function executeHostedWorker(input = "/input", identity = { uid: 1e3, gid:
|
|
|
5552
6986
|
env[`AGENTTWIN_${name.toUpperCase()}_TOKEN`] = credential.token;
|
|
5553
6987
|
}
|
|
5554
6988
|
if (spec.command[0] !== "node") throw new Error(`The isolated runner runs Node applications; run ${spec.command[0]} workflows locally with npx agenttwin (they use the twin proxy).`);
|
|
5555
|
-
hook = await createRequestSourceHook(
|
|
6989
|
+
hook = await createRequestSourceHook(join10(input, "app"), spec, credentials, { root: join10(input, "app"), violationsFd: 3 });
|
|
5556
6990
|
await chmod2(dirname2(hook.path), 493);
|
|
5557
6991
|
await chmod2(hook.path, 420);
|
|
6992
|
+
await writeFile5(hook.violationsPath, "", { mode: 384 });
|
|
6993
|
+
await chown2(hook.violationsPath, identity.uid, identity.gid);
|
|
5558
6994
|
const blockedFetches = [];
|
|
6995
|
+
const violationReasons = ["unmapped-fetch-origin", "unmapped-http-origin", "unhooked-subprocess"];
|
|
6996
|
+
const recordViolation = (entry) => {
|
|
6997
|
+
if (entry.reason === "unhooked-subprocess") return;
|
|
6998
|
+
if (blockedFetches.length < 100 && !blockedFetches.some((b) => b.origin === entry.origin && b.reason === entry.reason)) blockedFetches.push(entry);
|
|
6999
|
+
};
|
|
5559
7000
|
let violationBuffer = "";
|
|
5560
7001
|
let stdout = "", stderr = "", timedOut = false;
|
|
5561
|
-
const child =
|
|
7002
|
+
const child = spawn2(process.execPath, ["--require", hook.path, ...spec.command.slice(1)], { cwd: join10(input, "app"), env, stdio: ["ignore", "pipe", "pipe", "pipe"], detached: true, ...identity });
|
|
5562
7003
|
child.stdout.on("data", (b) => {
|
|
5563
7004
|
stdout = (stdout + b.toString()).slice(-65536);
|
|
5564
7005
|
});
|
|
@@ -5575,8 +7016,8 @@ async function executeHostedWorker(input = "/input", identity = { uid: 1e3, gid:
|
|
|
5575
7016
|
if (blockedFetches.length >= 100) continue;
|
|
5576
7017
|
try {
|
|
5577
7018
|
const entry = JSON.parse(line);
|
|
5578
|
-
if (typeof entry.origin !== "string" || entry.origin.length > 2048 || !
|
|
5579
|
-
|
|
7019
|
+
if (typeof entry.origin !== "string" || entry.origin.length > 2048 || !violationReasons.includes(entry.reason)) throw new Error("Invalid routing evidence");
|
|
7020
|
+
recordViolation({ origin: entry.origin, reason: entry.reason });
|
|
5580
7021
|
} catch {
|
|
5581
7022
|
blockedFetches.push({ origin: "unknown", reason: "unmapped-fetch-origin" });
|
|
5582
7023
|
}
|
|
@@ -5648,17 +7089,25 @@ async function executeHostedWorker(input = "/input", identity = { uid: 1e3, gid:
|
|
|
5648
7089
|
}
|
|
5649
7090
|
}
|
|
5650
7091
|
if (violationBuffer && blockedFetches.length < 100) blockedFetches.push({ origin: "unknown", reason: "unmapped-fetch-origin" });
|
|
7092
|
+
try {
|
|
7093
|
+
for (const entry of await hook.readViolations()) {
|
|
7094
|
+
if (typeof entry?.origin !== "string" || entry.origin.length > 2048 || !violationReasons.includes(entry.reason)) throw new Error("Invalid routing evidence");
|
|
7095
|
+
recordViolation({ origin: entry.origin, reason: entry.reason });
|
|
7096
|
+
}
|
|
7097
|
+
} catch {
|
|
7098
|
+
recordViolation({ origin: "unknown", reason: "unmapped-fetch-origin" });
|
|
7099
|
+
}
|
|
5651
7100
|
await world.close();
|
|
5652
7101
|
const assertions = world.assertions();
|
|
5653
7102
|
const infrastructureAssertions = [];
|
|
5654
7103
|
for (const assertion of spec.postgres?.assertions ?? []) {
|
|
5655
|
-
const { stdout: output } = await
|
|
7104
|
+
const { stdout: output } = await promisify5(execFile5)("psql", [runtimeEnv.DATABASE_URL, "-qAt", "-v", "ON_ERROR_STOP=1", "-c", "BEGIN READ ONLY", "-c", `SELECT COALESCE(json_agg(t), '[]'::json) FROM (${assertion.query}) t`, "-c", "COMMIT"], { env: { ...env, PGOPTIONS: "-c statement_timeout=5000" }, timeout: 7e3 });
|
|
5656
7105
|
const actual = JSON.parse(output.trim());
|
|
5657
7106
|
infrastructureAssertions.push({ service: "postgres", query: assertion.query, expected: assertion.equals, actual, passed: JSON.stringify(actual) === JSON.stringify(assertion.equals) });
|
|
5658
7107
|
}
|
|
5659
7108
|
for (const assertion of spec.redis?.assertions ?? []) {
|
|
5660
|
-
const { stdout: exists } = await
|
|
5661
|
-
const { stdout: output } = await
|
|
7109
|
+
const { stdout: exists } = await promisify5(execFile5)("redis-cli", ["--raw", "EXISTS", assertion.key], { env, timeout: 5e3 });
|
|
7110
|
+
const { stdout: output } = await promisify5(execFile5)("redis-cli", ["--raw", "GET", assertion.key], { env, timeout: 5e3 });
|
|
5662
7111
|
const actual = exists.trim() === "0" ? null : output.replace(/\n$/, "");
|
|
5663
7112
|
infrastructureAssertions.push({ service: "redis", key: assertion.key, expected: assertion.equals, actual, passed: actual === assertion.equals });
|
|
5664
7113
|
}
|