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/world-host.js
CHANGED
|
@@ -61,7 +61,7 @@ var init_twin_clock = __esm({
|
|
|
61
61
|
});
|
|
62
62
|
|
|
63
63
|
// src/runtime/request-source.ts
|
|
64
|
-
import { mkdtemp, writeFile,
|
|
64
|
+
import { mkdtemp, writeFile, rm, realpath, open } from "fs/promises";
|
|
65
65
|
import { tmpdir } from "os";
|
|
66
66
|
import { join, resolve } from "path";
|
|
67
67
|
function parseRequestSource(raw, spec) {
|
|
@@ -74,15 +74,60 @@ function parseRequestSource(raw, spec) {
|
|
|
74
74
|
return;
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
|
+
async function readBounded(path, limit = 4 * 1024 * 1024) {
|
|
78
|
+
const file = await open(path, "r");
|
|
79
|
+
try {
|
|
80
|
+
const size = Math.min((await file.stat()).size, limit);
|
|
81
|
+
const buffer = Buffer.alloc(size);
|
|
82
|
+
const { bytesRead } = await file.read(buffer, 0, size, 0);
|
|
83
|
+
const text2 = buffer.subarray(0, bytesRead).toString("utf8");
|
|
84
|
+
return bytesRead < limit ? text2 : text2.slice(0, text2.lastIndexOf("\n") + 1);
|
|
85
|
+
} finally {
|
|
86
|
+
await file.close();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
77
89
|
async function createRequestSourceHook(app, spec, credentials, runtime) {
|
|
78
90
|
const dir = await mkdtemp(join(tmpdir(), "agenttwin-source-hook-"));
|
|
79
91
|
const path = join(dir, "hook.cjs");
|
|
80
92
|
const violationsPath = join(dir, "blocked.jsonl");
|
|
81
93
|
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 };
|
|
82
|
-
const
|
|
94
|
+
const guard = "const hookKey=Symbol.for('agenttwin.requestHook.v1');if(globalThis[hookKey])return;Object.defineProperty(globalThis,hookKey,{value:true});\n";
|
|
95
|
+
const hook = guard + applicationClockHook(spec.applicationClock) + `const config=${JSON.stringify(config)};
|
|
83
96
|
` + String.raw`
|
|
84
97
|
const http=require('node:http'),https=require('node:https'),path=require('node:path'),{fileURLToPath}=require('node:url');
|
|
85
98
|
const origins=new Set(config.origins),files=new Set(config.files);
|
|
99
|
+
// Violations go to the run's channel; a child process without the parent's descriptor appends to the shared file.
|
|
100
|
+
// A child's inherited descriptor numbers and stdout are not the run's channel, so children use the shared file.
|
|
101
|
+
const isChild=process.env.AGENTTWIN_HOOK_CHILD==='1';
|
|
102
|
+
const nodeFs=require('node:fs');
|
|
103
|
+
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);}
|
|
104
|
+
// Child processes: Node descendants inherit this hook through NODE_OPTIONS, even when the app passes its own env.
|
|
105
|
+
// Any other executable runs outside the hook, so it is recorded and the run cannot be complete.
|
|
106
|
+
const childProcess=require('node:child_process');
|
|
107
|
+
const hookOption='--require '+JSON.stringify(__filename);
|
|
108
|
+
// Trust is decided from the file that would run, never its name: the Node binary itself, a script whose shebang runs
|
|
109
|
+
// that binary (node_modules/.bin CLIs, npm, npx), or esbuild's own binary inside its package. Results are cached per real path and PATH.
|
|
110
|
+
const executableTrust=new Map();
|
|
111
|
+
let nodeReal;try{nodeReal=nodeFs.realpathSync(process.execPath);}catch{nodeReal=process.execPath;}
|
|
112
|
+
function envPath(env){if(process.platform!=='win32')return env.PATH;const key=Object.keys(env).find(k=>k.toUpperCase()==='PATH');return key&&env[key];}
|
|
113
|
+
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));}
|
|
114
|
+
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;}}
|
|
115
|
+
// Resolves a command the way spawn does: paths against cwd, bare names through the child's PATH.
|
|
116
|
+
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;}}}
|
|
117
|
+
function runsHookedNode(interpreter,options){const file=resolveCommand(interpreter,options);if(!file)return false;try{return nodeFs.realpathSync(file)===nodeReal;}catch{return false;}}
|
|
118
|
+
// '#!/path/to/node', '#!/usr/bin/env node' and '#!/usr/bin/env -S node --flags' run Node; anything else does not.
|
|
119
|
+
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);}
|
|
120
|
+
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;}}
|
|
121
|
+
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;}
|
|
122
|
+
const reportedSubprocesses=new Set();
|
|
123
|
+
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};}
|
|
124
|
+
// Never throws: an unclassifiable command is reported, and the application's spawn proceeds unchanged.
|
|
125
|
+
// Shell commands are judged by their first word, so 'sh -c' style wrappers are reported as non-Node.
|
|
126
|
+
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{}}
|
|
127
|
+
// Puts the hooked env into the options argument at index i, inserting an options object when there is none.
|
|
128
|
+
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;}
|
|
129
|
+
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);};}
|
|
130
|
+
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);};}
|
|
86
131
|
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])});}}
|
|
87
132
|
const blockedOrigins=new Set();
|
|
88
133
|
const originalFetch=globalThis.fetch;
|
|
@@ -90,7 +135,7 @@ if(originalFetch)globalThis.fetch=async function(input,init){
|
|
|
90
135
|
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');}
|
|
91
136
|
const route=Object.hasOwn(config.routes,url.origin)?config.routes[url.origin]:undefined;
|
|
92
137
|
if(config.routing&&!route&&!origins.has(url.origin)){
|
|
93
|
-
if(!blockedOrigins.has(url.origin)&&blockedOrigins.size<100){blockedOrigins.add(url.origin);
|
|
138
|
+
if(!blockedOrigins.has(url.origin)&&blockedOrigins.size<100){blockedOrigins.add(url.origin);writeViolation({origin:url.origin.slice(0,2048),reason:'unmapped-fetch-origin'});}
|
|
94
139
|
throw new Error('AgentTwin blocked fetch to an unmapped origin: '+url.origin);
|
|
95
140
|
}
|
|
96
141
|
if(!route&&!origins.has(url.origin))return originalFetch(input,init);
|
|
@@ -100,11 +145,13 @@ if(originalFetch)globalThis.fetch=async function(input,init){
|
|
|
100
145
|
if(route){headers.delete('cookie');headers.delete('proxy-authorization');headers.set('authorization','Bearer '+route.token);}
|
|
101
146
|
const location=source();if(location)headers.set('x-agenttwin-source',location);
|
|
102
147
|
const target=route?route.endpoint+url.pathname+url.search:url.href;
|
|
103
|
-
|
|
148
|
+
// Forward the body as bytes: copying a keepalive Request whose body is a stream throws in Node's fetch.
|
|
149
|
+
const body=request.method==='GET'||request.method==='HEAD'?undefined:await request.arrayBuffer();
|
|
150
|
+
return originalFetch(target,{method:request.method,headers,body,signal:request.signal,redirect:'error'});
|
|
104
151
|
};
|
|
105
152
|
const plainHttp={request:http.request,get:http.get};
|
|
106
153
|
const loopback=host=>['127.0.0.1','localhost','::1','[::1]'].includes(host);
|
|
107
|
-
function blockNode(origin){if(!blockedOrigins.has(origin)&&blockedOrigins.size<100){blockedOrigins.add(origin);
|
|
154
|
+
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);}
|
|
108
155
|
// SDKs on node:http/https (Stripe, Slack via axios) reach mapped vendor origins only through their twin.
|
|
109
156
|
function routeNode(method,route,url,options,index,args){
|
|
110
157
|
const target=new URL(route.endpoint),headers={};
|
|
@@ -130,7 +177,13 @@ require('node:module').syncBuiltinESMExports();
|
|
|
130
177
|
await writeFile(path, hook, { mode: 384 });
|
|
131
178
|
return { path, violationsPath, readViolations: async () => {
|
|
132
179
|
try {
|
|
133
|
-
|
|
180
|
+
const seen = /* @__PURE__ */ new Set();
|
|
181
|
+
return (await readBounded(violationsPath)).trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)).filter((v) => {
|
|
182
|
+
const key2 = v.reason + " " + v.origin;
|
|
183
|
+
if (seen.has(key2)) return false;
|
|
184
|
+
seen.add(key2);
|
|
185
|
+
return true;
|
|
186
|
+
});
|
|
134
187
|
} catch (error) {
|
|
135
188
|
if (error.code === "ENOENT") return [];
|
|
136
189
|
throw error;
|
|
@@ -365,11 +418,11 @@ function responsesStream(body) {
|
|
|
365
418
|
let out = ev("response.created", { response: pending }) + ev("response.in_progress", { response: pending });
|
|
366
419
|
body.output.forEach((item, output_index) => {
|
|
367
420
|
if (item.type === "message") {
|
|
368
|
-
const
|
|
421
|
+
const text2 = item.content[0]?.text ?? "";
|
|
369
422
|
out += ev("response.output_item.added", { output_index, item: { ...item, status: "in_progress", content: [] } });
|
|
370
423
|
out += ev("response.content_part.added", { item_id: item.id, output_index, content_index: 0, part: { type: "output_text", text: "", annotations: [] } });
|
|
371
|
-
for (const delta of pieces(
|
|
372
|
-
out += ev("response.output_text.done", { item_id: item.id, output_index, content_index: 0, text, logprobs: [] });
|
|
424
|
+
for (const delta of pieces(text2)) out += ev("response.output_text.delta", { item_id: item.id, output_index, content_index: 0, delta, logprobs: [] });
|
|
425
|
+
out += ev("response.output_text.done", { item_id: item.id, output_index, content_index: 0, text: text2, logprobs: [] });
|
|
373
426
|
out += ev("response.content_part.done", { item_id: item.id, output_index, content_index: 0, part: item.content[0] });
|
|
374
427
|
} else {
|
|
375
428
|
out += ev("response.output_item.added", { output_index, item: { ...item, arguments: "", status: "in_progress" } });
|
|
@@ -386,7 +439,7 @@ function anthropicStream(body) {
|
|
|
386
439
|
body.content.forEach((block, index) => {
|
|
387
440
|
if (block.type === "text") {
|
|
388
441
|
out += ev("content_block_start", { index, content_block: { type: "text", text: "" } });
|
|
389
|
-
for (const
|
|
442
|
+
for (const text2 of pieces(block.text)) out += ev("content_block_delta", { index, delta: { type: "text_delta", text: text2 } });
|
|
390
443
|
} else {
|
|
391
444
|
out += ev("content_block_start", { index, content_block: { type: "tool_use", id: block.id, name: block.name, input: {} } });
|
|
392
445
|
for (const partial_json of pieces(JSON.stringify(block.input ?? {}))) out += ev("content_block_delta", { index, delta: { type: "input_json_delta", partial_json } });
|
|
@@ -479,10 +532,10 @@ var init_llm_adapter = __esm({
|
|
|
479
532
|
"use strict";
|
|
480
533
|
arg = (value) => typeof value === "string" ? value : JSON.stringify(value ?? {});
|
|
481
534
|
SSE = { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache" };
|
|
482
|
-
pieces = (
|
|
535
|
+
pieces = (text2) => {
|
|
483
536
|
const out = [];
|
|
484
|
-
const size = Math.max(1, Math.ceil(
|
|
485
|
-
for (let i = 0; i <
|
|
537
|
+
const size = Math.max(1, Math.ceil(text2.length / 3));
|
|
538
|
+
for (let i = 0; i < text2.length; i += size) out.push(text2.slice(i, i + size));
|
|
486
539
|
return out.length ? out : [""];
|
|
487
540
|
};
|
|
488
541
|
frame = (data, event) => `${event ? `event: ${event}
|
|
@@ -544,9 +597,9 @@ var init_composio_twin = __esm({
|
|
|
544
597
|
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");
|
|
545
598
|
const to = args.to ?? args.recipient_email, body = args.body ?? args.message, threadId = args.threadId ?? args.thread_id;
|
|
546
599
|
if (typeof to !== "string" || !to || typeof args.subject !== "string" || typeof body !== "string" || threadId !== void 0 && typeof threadId !== "string") return error(400, "Message fields required");
|
|
547
|
-
const id = "composio_message_" + sequence,
|
|
548
|
-
data["/messages"].push(
|
|
549
|
-
return { status: 200, collection: "/messages", operation: "write", record:
|
|
600
|
+
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 } };
|
|
601
|
+
data["/messages"].push(record3);
|
|
602
|
+
return { status: 200, collection: "/messages", operation: "write", record: record3, body: { successful: true, error: null, data: { id, messageId: id }, log_id: "synthetic-log-" + sequence } };
|
|
550
603
|
};
|
|
551
604
|
}
|
|
552
605
|
});
|
|
@@ -571,13 +624,1278 @@ var init_google_oauth_twin = __esm({
|
|
|
571
624
|
if (typeof grant.scope !== "string" || !grant.scope || !Number.isInteger(grant.expires_in) || Number(grant.expires_in) < 1 || Number(grant.expires_in) > 86400) return;
|
|
572
625
|
const access_token = "synthetic-access-" + createHash("sha256").update(JSON.stringify([params.client_id, params.refresh_token, sequence])).digest("hex").slice(0, 24);
|
|
573
626
|
const body = { access_token, token_type: "Bearer", expires_in: grant.expires_in, scope: grant.scope };
|
|
574
|
-
const
|
|
575
|
-
data["/tokens"].push(
|
|
576
|
-
return { status: 200, collection: "/tokens", body, record:
|
|
627
|
+
const record3 = { id: "issuance_" + sequence, client_id: params.client_id, ...body };
|
|
628
|
+
data["/tokens"].push(record3);
|
|
629
|
+
return { status: 200, collection: "/tokens", body, record: record3, operation: "write" };
|
|
577
630
|
};
|
|
578
631
|
}
|
|
579
632
|
});
|
|
580
633
|
|
|
634
|
+
// src/runtime/engines/resp.ts
|
|
635
|
+
import { connect } from "net";
|
|
636
|
+
function parseResp(buf, at = 0, inline = false) {
|
|
637
|
+
if (at >= buf.length) return;
|
|
638
|
+
const line = buf.indexOf(CRLF, at);
|
|
639
|
+
if (line < 0) return;
|
|
640
|
+
const prefix = String.fromCharCode(buf[at]), text2 = buf.toString("utf8", at + 1, line), next = line + 2;
|
|
641
|
+
switch (prefix) {
|
|
642
|
+
case "+":
|
|
643
|
+
return { value: { simple: text2 }, end: next };
|
|
644
|
+
case "-":
|
|
645
|
+
return { value: { error: text2 }, end: next };
|
|
646
|
+
case ":":
|
|
647
|
+
case "(":
|
|
648
|
+
return { value: Number(text2), end: next };
|
|
649
|
+
case ",":
|
|
650
|
+
return { value: { simple: text2 }, end: next };
|
|
651
|
+
case "#":
|
|
652
|
+
return { value: text2 === "t", end: next };
|
|
653
|
+
case "_":
|
|
654
|
+
return { value: null, end: next };
|
|
655
|
+
case "$":
|
|
656
|
+
case "!":
|
|
657
|
+
case "=": {
|
|
658
|
+
const n = Number(text2);
|
|
659
|
+
if (n < 0) return { value: null, end: next };
|
|
660
|
+
if (buf.length < next + n + 2) return;
|
|
661
|
+
const data = Buffer.from(buf.subarray(next, next + n));
|
|
662
|
+
return { value: prefix === "!" ? { error: data.toString() } : data, end: next + n + 2 };
|
|
663
|
+
}
|
|
664
|
+
case "*":
|
|
665
|
+
case "~":
|
|
666
|
+
case ">":
|
|
667
|
+
case "%":
|
|
668
|
+
case "|": {
|
|
669
|
+
const n = Number(text2);
|
|
670
|
+
if (n < 0) return { value: null, end: next };
|
|
671
|
+
const count = prefix === "%" || prefix === "|" ? n * 2 : n;
|
|
672
|
+
const items = [];
|
|
673
|
+
let end = next;
|
|
674
|
+
for (let i = 0; i < count; i++) {
|
|
675
|
+
const item = parseResp(buf, end);
|
|
676
|
+
if (!item) return;
|
|
677
|
+
items.push(item.value);
|
|
678
|
+
end = item.end;
|
|
679
|
+
}
|
|
680
|
+
if (prefix === "|") {
|
|
681
|
+
const value = parseResp(buf, end);
|
|
682
|
+
return value && { value: value.value, end: value.end };
|
|
683
|
+
}
|
|
684
|
+
return { value: items, end };
|
|
685
|
+
}
|
|
686
|
+
default:
|
|
687
|
+
if (!inline) throw new Error(`Invalid RESP prefix ${JSON.stringify(prefix)}`);
|
|
688
|
+
return { value: buf.toString("utf8", at, line).trim().split(/\s+/).filter(Boolean).map((s) => Buffer.from(s)), end: next };
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
var CRLF, encode, text, RespClient;
|
|
692
|
+
var init_resp = __esm({
|
|
693
|
+
"src/runtime/engines/resp.ts"() {
|
|
694
|
+
"use strict";
|
|
695
|
+
CRLF = Buffer.from("\r\n");
|
|
696
|
+
encode = {
|
|
697
|
+
simple: (s) => Buffer.from(`+${s}\r
|
|
698
|
+
`),
|
|
699
|
+
error: (s) => Buffer.from(`-${s.replace(/[\r\n]+/g, " ")}\r
|
|
700
|
+
`),
|
|
701
|
+
int: (n) => Buffer.from(`:${Math.trunc(n)}\r
|
|
702
|
+
`),
|
|
703
|
+
bulk: (v) => v === null || v === void 0 ? Buffer.from("$-1\r\n") : (() => {
|
|
704
|
+
const b = typeof v === "string" ? Buffer.from(v, "latin1") : v;
|
|
705
|
+
return Buffer.concat([Buffer.from(`$${b.length}\r
|
|
706
|
+
`), b, CRLF]);
|
|
707
|
+
})(),
|
|
708
|
+
array: (items) => items === null ? Buffer.from("*-1\r\n") : Buffer.concat([Buffer.from(`*${items.length}\r
|
|
709
|
+
`), ...items]),
|
|
710
|
+
command: (args) => Buffer.concat([Buffer.from(`*${args.length}\r
|
|
711
|
+
`), ...args.map((a) => {
|
|
712
|
+
const b = Buffer.isBuffer(a) ? a : Buffer.from(String(a));
|
|
713
|
+
return Buffer.concat([Buffer.from(`$${b.length}\r
|
|
714
|
+
`), b, CRLF]);
|
|
715
|
+
})])
|
|
716
|
+
};
|
|
717
|
+
text = (v) => Buffer.isBuffer(v) ? v.toString("utf8") : v && typeof v === "object" && "simple" in v ? v.simple : String(v);
|
|
718
|
+
RespClient = class {
|
|
719
|
+
constructor(port, host = "127.0.0.1") {
|
|
720
|
+
this.port = port;
|
|
721
|
+
this.host = host;
|
|
722
|
+
}
|
|
723
|
+
port;
|
|
724
|
+
host;
|
|
725
|
+
socket;
|
|
726
|
+
buffer = Buffer.alloc(0);
|
|
727
|
+
waiting = [];
|
|
728
|
+
async open() {
|
|
729
|
+
if (this.socket && !this.socket.destroyed) return this.socket;
|
|
730
|
+
const socket = connect(this.port, this.host);
|
|
731
|
+
await new Promise((resolve8, reject) => {
|
|
732
|
+
socket.once("connect", resolve8);
|
|
733
|
+
socket.once("error", reject);
|
|
734
|
+
});
|
|
735
|
+
socket.on("data", (chunk) => {
|
|
736
|
+
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
737
|
+
for (; ; ) {
|
|
738
|
+
const frame2 = parseResp(this.buffer);
|
|
739
|
+
if (!frame2) break;
|
|
740
|
+
this.buffer = this.buffer.subarray(frame2.end);
|
|
741
|
+
const w = this.waiting.shift();
|
|
742
|
+
if (!w) continue;
|
|
743
|
+
const v = frame2.value;
|
|
744
|
+
if (v && typeof v === "object" && "error" in v) w.reject(new Error(v.error));
|
|
745
|
+
else w.resolve(v);
|
|
746
|
+
}
|
|
747
|
+
});
|
|
748
|
+
socket.on("error", () => {
|
|
749
|
+
});
|
|
750
|
+
socket.on("close", () => {
|
|
751
|
+
for (const w of this.waiting.splice(0)) w.reject(new Error("Redis connection closed"));
|
|
752
|
+
});
|
|
753
|
+
this.socket = socket;
|
|
754
|
+
return socket;
|
|
755
|
+
}
|
|
756
|
+
async call(...args) {
|
|
757
|
+
const socket = await this.open();
|
|
758
|
+
return new Promise((resolve8, reject) => {
|
|
759
|
+
this.waiting.push({ resolve: resolve8, reject });
|
|
760
|
+
socket.write(encode.command(args));
|
|
761
|
+
});
|
|
762
|
+
}
|
|
763
|
+
close() {
|
|
764
|
+
this.socket?.destroy();
|
|
765
|
+
}
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
});
|
|
769
|
+
|
|
770
|
+
// src/runtime/engines/types.ts
|
|
771
|
+
function record2(events, event) {
|
|
772
|
+
if (events.length < 5e4) events.push({ sequence: events.length + 1, ...event });
|
|
773
|
+
}
|
|
774
|
+
var POSTGRES_EXTENSIONS, EngineUnavailable, FaultGate, sleep;
|
|
775
|
+
var init_types = __esm({
|
|
776
|
+
"src/runtime/engines/types.ts"() {
|
|
777
|
+
"use strict";
|
|
778
|
+
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"];
|
|
779
|
+
EngineUnavailable = class extends Error {
|
|
780
|
+
constructor(kind, message) {
|
|
781
|
+
super(message);
|
|
782
|
+
this.kind = kind;
|
|
783
|
+
}
|
|
784
|
+
kind;
|
|
785
|
+
};
|
|
786
|
+
FaultGate = class {
|
|
787
|
+
constructor(kind, events) {
|
|
788
|
+
this.kind = kind;
|
|
789
|
+
this.events = events;
|
|
790
|
+
}
|
|
791
|
+
kind;
|
|
792
|
+
events;
|
|
793
|
+
fault = null;
|
|
794
|
+
triggered = 0;
|
|
795
|
+
set(fault) {
|
|
796
|
+
this.fault = fault;
|
|
797
|
+
this.triggered = 0;
|
|
798
|
+
}
|
|
799
|
+
/** The fault to apply to this operation, counted, or undefined. */
|
|
800
|
+
take(operation, resources, types) {
|
|
801
|
+
const f = this.fault;
|
|
802
|
+
if (!f || types && !types.includes(f.type)) return;
|
|
803
|
+
const on = f.on ?? "write";
|
|
804
|
+
if (on !== "any" && on !== operation) return;
|
|
805
|
+
if (f.resource && !resources.some((r) => r === f.resource || r.startsWith(f.resource))) return;
|
|
806
|
+
if (this.triggered >= (f.times ?? 1)) return;
|
|
807
|
+
this.triggered++;
|
|
808
|
+
record2(this.events, { engine: this.kind, operation: "fault", resource: resources[0] ?? "", detail: `${f.type} on ${operation}${resources.length ? " " + resources.join(",") : ""}` });
|
|
809
|
+
return f;
|
|
810
|
+
}
|
|
811
|
+
};
|
|
812
|
+
sleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
|
|
813
|
+
}
|
|
814
|
+
});
|
|
815
|
+
|
|
816
|
+
// src/runtime/engines/host.ts
|
|
817
|
+
import { execFile } from "child_process";
|
|
818
|
+
import { access, constants } from "fs/promises";
|
|
819
|
+
import { createServer } from "net";
|
|
820
|
+
import { delimiter, join as join2 } from "path";
|
|
821
|
+
import { randomUUID } from "crypto";
|
|
822
|
+
import { promisify } from "util";
|
|
823
|
+
async function findBinary(names) {
|
|
824
|
+
for (const dir of (process.env.PATH ?? "").split(delimiter).filter(Boolean)) for (const name of names) {
|
|
825
|
+
const path = join2(dir, name);
|
|
826
|
+
try {
|
|
827
|
+
await access(path, constants.X_OK);
|
|
828
|
+
return path;
|
|
829
|
+
} catch {
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
async function freePort() {
|
|
834
|
+
const server = createServer();
|
|
835
|
+
await new Promise((resolve8) => server.listen(0, "127.0.0.1", resolve8));
|
|
836
|
+
const port = server.address().port;
|
|
837
|
+
await new Promise((resolve8) => server.close(() => resolve8()));
|
|
838
|
+
return port;
|
|
839
|
+
}
|
|
840
|
+
async function waitFor(probe, timeoutMs) {
|
|
841
|
+
const deadline = Date.now() + timeoutMs;
|
|
842
|
+
let last;
|
|
843
|
+
while (Date.now() < deadline) {
|
|
844
|
+
try {
|
|
845
|
+
await probe();
|
|
846
|
+
return;
|
|
847
|
+
} catch (error) {
|
|
848
|
+
last = error;
|
|
849
|
+
await sleep(50);
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
throw last instanceof Error ? last : new Error("timed out");
|
|
853
|
+
}
|
|
854
|
+
function dockerAvailable() {
|
|
855
|
+
if (process.env.AGENTTWIN_DOCKER === "0") return Promise.resolve(false);
|
|
856
|
+
return dockerChecked ??= exec("docker", ["info", "--format", "{{.ServerVersion}}"], { timeout: 5e3 }).then((r) => !!r.stdout.trim(), () => false);
|
|
857
|
+
}
|
|
858
|
+
async function dockerRun(opts) {
|
|
859
|
+
const name = "agenttwin-engine-" + randomUUID();
|
|
860
|
+
await exec("docker", ["run", "--detach", "--rm", "--name", name, "--publish", `127.0.0.1::${opts.port}`, "--memory", "512m", "--pids-limit", "256", "--security-opt", "no-new-privileges", ...Object.entries(opts.env ?? {}).flatMap(([k, v]) => ["--env", `${k}=${v}`]), opts.image, ...opts.args ?? []], { timeout: 18e4 });
|
|
861
|
+
const stop = async () => {
|
|
862
|
+
await exec("docker", ["rm", "-f", name], { timeout: 15e3 }).catch(() => {
|
|
863
|
+
});
|
|
864
|
+
};
|
|
865
|
+
try {
|
|
866
|
+
const out = (await exec("docker", ["port", name, `${opts.port}/tcp`], { timeout: 1e4 })).stdout.trim().split("\n")[0];
|
|
867
|
+
const port = Number(out.split(":").at(-1));
|
|
868
|
+
if (!port) throw new Error(`no published port for ${opts.image}`);
|
|
869
|
+
return { name, port, stop };
|
|
870
|
+
} catch (error) {
|
|
871
|
+
await stop();
|
|
872
|
+
throw error;
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
var exec, dockerChecked;
|
|
876
|
+
var init_host = __esm({
|
|
877
|
+
"src/runtime/engines/host.ts"() {
|
|
878
|
+
"use strict";
|
|
879
|
+
init_types();
|
|
880
|
+
exec = promisify(execFile);
|
|
881
|
+
}
|
|
882
|
+
});
|
|
883
|
+
|
|
884
|
+
// src/runtime/engines/redis.ts
|
|
885
|
+
import { createServer as createServer2, connect as connect2 } from "net";
|
|
886
|
+
import { spawn } from "child_process";
|
|
887
|
+
import { mkdtemp as mkdtemp2, rm as rm2 } from "fs/promises";
|
|
888
|
+
import { tmpdir as tmpdir2 } from "os";
|
|
889
|
+
import { join as join3 } from "path";
|
|
890
|
+
function commandKeys(name, args) {
|
|
891
|
+
if (name === "mset" || name === "msetnx") return args.filter((_, i) => i % 2 === 0);
|
|
892
|
+
if (MULTI_KEY.has(name)) return args;
|
|
893
|
+
if (name === "rename" || name === "renamenx" || name === "copy" || name === "lmove" || name === "rpoplpush" || name === "smove") return args.slice(0, 2);
|
|
894
|
+
if (name === "eval" || name === "evalsha") {
|
|
895
|
+
const n = Number(args[1]);
|
|
896
|
+
return Number.isInteger(n) ? args.slice(2, 2 + n) : [];
|
|
897
|
+
}
|
|
898
|
+
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 [];
|
|
899
|
+
return args.length ? [args[0]] : [];
|
|
900
|
+
}
|
|
901
|
+
function respFrontEnd(upstreamPort, gate, events, commit) {
|
|
902
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
903
|
+
const server = createServer2((client) => {
|
|
904
|
+
sockets.add(client);
|
|
905
|
+
client.setNoDelay(true);
|
|
906
|
+
const upstream = connect2(upstreamPort, "127.0.0.1");
|
|
907
|
+
upstream.setNoDelay(true);
|
|
908
|
+
let inbound = Buffer.alloc(0), outbound = Buffer.alloc(0), passthrough = false, multi = null, draining = false;
|
|
909
|
+
const pending = [];
|
|
910
|
+
const close = () => {
|
|
911
|
+
client.destroy();
|
|
912
|
+
upstream.destroy();
|
|
913
|
+
sockets.delete(client);
|
|
914
|
+
};
|
|
915
|
+
client.on("error", close);
|
|
916
|
+
upstream.on("error", close);
|
|
917
|
+
client.on("close", close);
|
|
918
|
+
upstream.on("close", () => client.destroy());
|
|
919
|
+
const drain = async () => {
|
|
920
|
+
if (draining) return;
|
|
921
|
+
draining = true;
|
|
922
|
+
try {
|
|
923
|
+
while (pending.length && (pending[0].local || pending[0].reply)) {
|
|
924
|
+
const p = pending.shift();
|
|
925
|
+
if (p.local) {
|
|
926
|
+
client.write(p.local);
|
|
927
|
+
continue;
|
|
928
|
+
}
|
|
929
|
+
const reply = p.replace ?? p.reply;
|
|
930
|
+
const committed = p.write && !p.error && !(p.name === "exec" && reply.equals(encode.array(null)));
|
|
931
|
+
if (committed) {
|
|
932
|
+
record2(events, { engine: "redis", operation: "write", resource: p.keys.join(","), detail: `${p.name.toUpperCase()} ${p.keys.join(" ")}`.trim().slice(0, 200) });
|
|
933
|
+
await commit(p.keys);
|
|
934
|
+
const f = gate.take("write", p.keys, ["drop-after-commit", "timeout", "latency"]);
|
|
935
|
+
if (f?.type === "drop-after-commit") {
|
|
936
|
+
close();
|
|
937
|
+
return;
|
|
938
|
+
}
|
|
939
|
+
if (f?.type === "timeout") {
|
|
940
|
+
await sleep(f.delayMs ?? 1e4);
|
|
941
|
+
close();
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
if (f?.type === "latency") await sleep(f.delayMs ?? 1e3);
|
|
945
|
+
} else if (!p.write && p.keys.length) {
|
|
946
|
+
record2(events, { engine: "redis", operation: "read", resource: p.keys.join(","), detail: p.name.toUpperCase() });
|
|
947
|
+
const f = gate.take("read", p.keys, ["latency", "timeout"]);
|
|
948
|
+
if (f) await sleep(f.delayMs ?? 1e3);
|
|
949
|
+
if (f?.type === "timeout") {
|
|
950
|
+
close();
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
client.write(reply);
|
|
955
|
+
}
|
|
956
|
+
} finally {
|
|
957
|
+
draining = false;
|
|
958
|
+
}
|
|
959
|
+
if (pending.length && (pending[0].local || pending[0].reply)) void drain();
|
|
960
|
+
};
|
|
961
|
+
client.on("data", (chunk) => {
|
|
962
|
+
if (passthrough) {
|
|
963
|
+
upstream.write(chunk);
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
inbound = Buffer.concat([inbound, chunk]);
|
|
967
|
+
const forward = [];
|
|
968
|
+
for (; ; ) {
|
|
969
|
+
let frame2;
|
|
970
|
+
try {
|
|
971
|
+
frame2 = parseResp(inbound, 0, true);
|
|
972
|
+
} catch {
|
|
973
|
+
close();
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
976
|
+
if (!frame2) break;
|
|
977
|
+
const bytes = inbound.subarray(0, frame2.end);
|
|
978
|
+
inbound = inbound.subarray(frame2.end);
|
|
979
|
+
const args = frame2.value.map((b) => b.toString("utf8"));
|
|
980
|
+
if (!args.length) continue;
|
|
981
|
+
const name = args[0].toLowerCase(), rest = args.slice(1);
|
|
982
|
+
if (["subscribe", "psubscribe", "ssubscribe", "monitor"].includes(name)) {
|
|
983
|
+
passthrough = true;
|
|
984
|
+
forward.push(bytes, inbound);
|
|
985
|
+
inbound = Buffer.alloc(0);
|
|
986
|
+
break;
|
|
987
|
+
}
|
|
988
|
+
let write3 = WRITES.has(name), keys = commandKeys(name, rest);
|
|
989
|
+
if (name === "multi") multi = [];
|
|
990
|
+
else if (multi && !["exec", "discard"].includes(name)) {
|
|
991
|
+
if (write3) multi.push(...keys);
|
|
992
|
+
write3 = false;
|
|
993
|
+
keys = [];
|
|
994
|
+
} else if (name === "exec") {
|
|
995
|
+
write3 = !!multi?.length;
|
|
996
|
+
keys = [...new Set(multi ?? [])];
|
|
997
|
+
multi = null;
|
|
998
|
+
} else if (name === "discard") multi = null;
|
|
999
|
+
const p = { name, write: write3, keys };
|
|
1000
|
+
const rejected = write3 ? gate.take("write", keys, ["error"]) : keys.length ? gate.take("read", keys, ["error"]) : void 0;
|
|
1001
|
+
if (rejected) {
|
|
1002
|
+
const error = encode.error("ERR AgentTwin injected fault: connection to Redis reset before the command ran (retryable)");
|
|
1003
|
+
if (name === "exec") {
|
|
1004
|
+
p.replace = error;
|
|
1005
|
+
p.error = true;
|
|
1006
|
+
pending.push(p);
|
|
1007
|
+
forward.push(encode.command(["DISCARD"]));
|
|
1008
|
+
} else {
|
|
1009
|
+
p.local = error;
|
|
1010
|
+
p.error = true;
|
|
1011
|
+
pending.push(p);
|
|
1012
|
+
}
|
|
1013
|
+
continue;
|
|
1014
|
+
}
|
|
1015
|
+
pending.push(p);
|
|
1016
|
+
forward.push(bytes);
|
|
1017
|
+
}
|
|
1018
|
+
if (forward.length) upstream.write(Buffer.concat(forward));
|
|
1019
|
+
void drain();
|
|
1020
|
+
});
|
|
1021
|
+
upstream.on("data", (chunk) => {
|
|
1022
|
+
if (passthrough) {
|
|
1023
|
+
client.write(chunk);
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
outbound = Buffer.concat([outbound, chunk]);
|
|
1027
|
+
for (; ; ) {
|
|
1028
|
+
let frame2;
|
|
1029
|
+
try {
|
|
1030
|
+
frame2 = parseResp(outbound);
|
|
1031
|
+
} catch {
|
|
1032
|
+
close();
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
if (!frame2) break;
|
|
1036
|
+
const bytes = Buffer.from(outbound.subarray(0, frame2.end));
|
|
1037
|
+
outbound = outbound.subarray(frame2.end);
|
|
1038
|
+
const p = pending.find((x) => !x.local && !x.reply);
|
|
1039
|
+
if (!p) {
|
|
1040
|
+
client.write(bytes);
|
|
1041
|
+
continue;
|
|
1042
|
+
}
|
|
1043
|
+
p.reply = bytes;
|
|
1044
|
+
const v = frame2.value;
|
|
1045
|
+
if (v && typeof v === "object" && "error" in v) p.error = true;
|
|
1046
|
+
}
|
|
1047
|
+
void drain();
|
|
1048
|
+
});
|
|
1049
|
+
});
|
|
1050
|
+
return {
|
|
1051
|
+
async listen() {
|
|
1052
|
+
await new Promise((resolve8, reject) => {
|
|
1053
|
+
server.once("error", reject);
|
|
1054
|
+
server.listen(0, "127.0.0.1", resolve8);
|
|
1055
|
+
});
|
|
1056
|
+
return server.address().port;
|
|
1057
|
+
},
|
|
1058
|
+
disconnect() {
|
|
1059
|
+
for (const s of sockets) s.destroy();
|
|
1060
|
+
sockets.clear();
|
|
1061
|
+
},
|
|
1062
|
+
async close() {
|
|
1063
|
+
for (const s of sockets) s.destroy();
|
|
1064
|
+
await new Promise((resolve8) => server.close(() => resolve8()));
|
|
1065
|
+
}
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
async function readRedis(client) {
|
|
1069
|
+
const keys = [];
|
|
1070
|
+
let cursor = "0";
|
|
1071
|
+
do {
|
|
1072
|
+
const [next, batch] = await client.call("SCAN", cursor, "COUNT", "1000");
|
|
1073
|
+
cursor = next.toString();
|
|
1074
|
+
keys.push(...batch.map((b) => b.toString("utf8")));
|
|
1075
|
+
} while (cursor !== "0" && keys.length < 1e4);
|
|
1076
|
+
const out = [];
|
|
1077
|
+
for (const key2 of [...new Set(keys)].sort()) {
|
|
1078
|
+
const type = text(await client.call("TYPE", key2));
|
|
1079
|
+
if (type === "none") continue;
|
|
1080
|
+
const strings = (v) => v.map((b) => b.toString("utf8"));
|
|
1081
|
+
const value = type === "string" ? text(await client.call("GET", key2)) : type === "hash" ? (() => {
|
|
1082
|
+
return client.call("HGETALL", key2).then((v) => {
|
|
1083
|
+
const l = strings(v);
|
|
1084
|
+
return Object.fromEntries(l.flatMap((_, i) => i % 2 ? [] : [[l[i], l[i + 1]]]));
|
|
1085
|
+
});
|
|
1086
|
+
})() : type === "list" ? strings(await client.call("LRANGE", key2, 0, -1)) : type === "set" ? strings(await client.call("SMEMBERS", key2)).sort() : type === "zset" ? (() => client.call("ZRANGE", key2, 0, -1, "WITHSCORES").then((v) => {
|
|
1087
|
+
const l = strings(v);
|
|
1088
|
+
return l.flatMap((_, i) => i % 2 ? [] : [{ member: l[i], score: Number(l[i + 1]) }]);
|
|
1089
|
+
}))() : null;
|
|
1090
|
+
const ttl = Number(await client.call("PTTL", key2));
|
|
1091
|
+
out.push({ key: key2, type, value: await value, ttlMs: ttl >= 0 ? ttl : null });
|
|
1092
|
+
}
|
|
1093
|
+
return out;
|
|
1094
|
+
}
|
|
1095
|
+
async function restoreRedis(client, entries) {
|
|
1096
|
+
await client.call("FLUSHALL");
|
|
1097
|
+
for (const e of entries) {
|
|
1098
|
+
const v = e.value;
|
|
1099
|
+
if (e.type === "string") await client.call("SET", e.key, String(v));
|
|
1100
|
+
else if (e.type === "hash") await client.call("HSET", e.key, ...Object.entries(v).flat());
|
|
1101
|
+
else if (e.type === "list") await client.call("RPUSH", e.key, ...v);
|
|
1102
|
+
else if (e.type === "set") await client.call("SADD", e.key, ...v);
|
|
1103
|
+
else if (e.type === "zset") await client.call("ZADD", e.key, ...v.flatMap((m) => [m.score, m.member]));
|
|
1104
|
+
if (e.ttlMs) await client.call("PEXPIRE", e.key, e.ttlMs);
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
async function startRedisEngine(options = {}) {
|
|
1108
|
+
const started = Date.now(), prefer = options.prefer ?? "auto";
|
|
1109
|
+
const events = [], gate = new FaultGate("redis", events), listeners = [];
|
|
1110
|
+
let backend, upstreamPort, stopBackend, inProcess;
|
|
1111
|
+
const binary = prefer === "auto" || prefer === "binary" ? await findBinary(["redis-server", "valkey-server"]) : void 0;
|
|
1112
|
+
if (binary) {
|
|
1113
|
+
upstreamPort = await freePort();
|
|
1114
|
+
const dir = await mkdtemp2(join3(tmpdir2(), "agenttwin-redis-"));
|
|
1115
|
+
const child = spawn(binary, ["--port", String(upstreamPort), "--bind", "127.0.0.1", "--save", "", "--appendonly", "no", "--protected-mode", "yes", "--dir", dir, "--loglevel", "warning"], { stdio: "ignore" });
|
|
1116
|
+
const client = new RespClient(upstreamPort);
|
|
1117
|
+
try {
|
|
1118
|
+
await waitFor(async () => {
|
|
1119
|
+
await client.call("PING");
|
|
1120
|
+
}, 5e3);
|
|
1121
|
+
} catch (error) {
|
|
1122
|
+
child.kill("SIGKILL");
|
|
1123
|
+
await rm2(dir, { recursive: true, force: true });
|
|
1124
|
+
throw new EngineUnavailable("redis", `${binary} did not start: ${error.message}`);
|
|
1125
|
+
} finally {
|
|
1126
|
+
client.close();
|
|
1127
|
+
}
|
|
1128
|
+
backend = "binary";
|
|
1129
|
+
stopBackend = async () => {
|
|
1130
|
+
child.kill("SIGTERM");
|
|
1131
|
+
await rm2(dir, { recursive: true, force: true });
|
|
1132
|
+
};
|
|
1133
|
+
} else if ((prefer === "auto" || prefer === "docker") && await dockerAvailable()) {
|
|
1134
|
+
const c = await dockerRun({ image: "redis:7-alpine", port: 6379, args: ["redis-server", "--save", "", "--appendonly", "no"] });
|
|
1135
|
+
upstreamPort = c.port;
|
|
1136
|
+
const client = new RespClient(upstreamPort);
|
|
1137
|
+
try {
|
|
1138
|
+
await waitFor(async () => {
|
|
1139
|
+
await client.call("PING");
|
|
1140
|
+
}, 2e4);
|
|
1141
|
+
} finally {
|
|
1142
|
+
client.close();
|
|
1143
|
+
}
|
|
1144
|
+
backend = "docker";
|
|
1145
|
+
stopBackend = c.stop;
|
|
1146
|
+
} else if (prefer === "docker" || prefer === "binary") {
|
|
1147
|
+
throw new EngineUnavailable("redis", prefer === "docker" ? "Docker is not running" : "No redis-server or valkey-server on PATH");
|
|
1148
|
+
} else {
|
|
1149
|
+
inProcess = new InProcessRedis();
|
|
1150
|
+
upstreamPort = await inProcess.start();
|
|
1151
|
+
backend = "in-process";
|
|
1152
|
+
stopBackend = () => inProcess.stop();
|
|
1153
|
+
}
|
|
1154
|
+
const control = new RespClient(upstreamPort);
|
|
1155
|
+
const front = respFrontEnd(upstreamPort, gate, events, async (keys) => {
|
|
1156
|
+
for (const l of listeners) await l(keys);
|
|
1157
|
+
});
|
|
1158
|
+
const port = await front.listen();
|
|
1159
|
+
const url = `redis://127.0.0.1:${port}`;
|
|
1160
|
+
let baseline = [];
|
|
1161
|
+
const seed = async (data) => {
|
|
1162
|
+
const entries = seedEntries(data);
|
|
1163
|
+
const current = await readRedis(control);
|
|
1164
|
+
await restoreRedis(control, [...current.filter((e) => !entries.some((x) => x.key === e.key)), ...entries]);
|
|
1165
|
+
baseline = await readRedis(control);
|
|
1166
|
+
};
|
|
1167
|
+
if (options.seed) await seed(options.seed);
|
|
1168
|
+
const handle = {
|
|
1169
|
+
kind: "redis",
|
|
1170
|
+
backend,
|
|
1171
|
+
fidelity: backend === "in-process" ? "compatible" : "real",
|
|
1172
|
+
tier: "real-engine",
|
|
1173
|
+
url,
|
|
1174
|
+
startupMs: Date.now() - started,
|
|
1175
|
+
events,
|
|
1176
|
+
unsupported: inProcess ? inProcess.unsupported : [],
|
|
1177
|
+
env: { REDIS_URL: url, REDIS_HOST: "127.0.0.1", REDIS_PORT: String(port), REDISHOST: "127.0.0.1", REDISPORT: String(port), KV_URL: url, REDIS_TLS_URL: url },
|
|
1178
|
+
get faultTriggered() {
|
|
1179
|
+
return gate.triggered;
|
|
1180
|
+
},
|
|
1181
|
+
seed,
|
|
1182
|
+
snapshot: () => readRedis(control),
|
|
1183
|
+
async reset(snapshot) {
|
|
1184
|
+
front.disconnect();
|
|
1185
|
+
await restoreRedis(control, snapshot ?? baseline);
|
|
1186
|
+
gate.set(gate.fault);
|
|
1187
|
+
},
|
|
1188
|
+
readState: async () => ({ engine: "redis", keys: await readRedis(control) }),
|
|
1189
|
+
inject: (fault) => gate.set(fault),
|
|
1190
|
+
onCommit: (listener) => {
|
|
1191
|
+
listeners.push(listener);
|
|
1192
|
+
},
|
|
1193
|
+
async stop() {
|
|
1194
|
+
control.close();
|
|
1195
|
+
await front.close();
|
|
1196
|
+
await stopBackend();
|
|
1197
|
+
}
|
|
1198
|
+
};
|
|
1199
|
+
return handle;
|
|
1200
|
+
}
|
|
1201
|
+
var WRITES, MULTI_KEY, WRONGTYPE, NOT_INT, glob, fmt, InProcessRedis, seedEntries;
|
|
1202
|
+
var init_redis = __esm({
|
|
1203
|
+
"src/runtime/engines/redis.ts"() {
|
|
1204
|
+
"use strict";
|
|
1205
|
+
init_resp();
|
|
1206
|
+
init_types();
|
|
1207
|
+
init_host();
|
|
1208
|
+
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(" "));
|
|
1209
|
+
MULTI_KEY = /* @__PURE__ */ new Set(["del", "unlink", "exists", "mget", "watch", "touch", "sinter", "sunion", "sdiff"]);
|
|
1210
|
+
WRONGTYPE = "WRONGTYPE Operation against a key holding the wrong kind of value";
|
|
1211
|
+
NOT_INT = "ERR value is not an integer or out of range";
|
|
1212
|
+
glob = (pattern) => new RegExp("^" + pattern.replace(/[.+^${}()|\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".") + "$", "s");
|
|
1213
|
+
fmt = (n) => Number.isInteger(n) ? String(n) : String(Number(n.toPrecision(17)));
|
|
1214
|
+
InProcessRedis = class {
|
|
1215
|
+
data = /* @__PURE__ */ new Map();
|
|
1216
|
+
versions = /* @__PURE__ */ new Map();
|
|
1217
|
+
unsupported = [];
|
|
1218
|
+
server;
|
|
1219
|
+
live(key2) {
|
|
1220
|
+
const e = this.data.get(key2);
|
|
1221
|
+
if (e?.expireAt !== void 0 && e.expireAt <= Date.now()) {
|
|
1222
|
+
this.data.delete(key2);
|
|
1223
|
+
return void 0;
|
|
1224
|
+
}
|
|
1225
|
+
return e;
|
|
1226
|
+
}
|
|
1227
|
+
touch(key2) {
|
|
1228
|
+
this.versions.set(key2, (this.versions.get(key2) ?? 0) + 1);
|
|
1229
|
+
}
|
|
1230
|
+
typed(key2, type, create) {
|
|
1231
|
+
const e = this.live(key2);
|
|
1232
|
+
if (e) {
|
|
1233
|
+
if (e.type !== type) throw new Error(WRONGTYPE);
|
|
1234
|
+
return e.value;
|
|
1235
|
+
}
|
|
1236
|
+
const value = create();
|
|
1237
|
+
this.data.set(key2, { type, value });
|
|
1238
|
+
return value;
|
|
1239
|
+
}
|
|
1240
|
+
get(key2, type) {
|
|
1241
|
+
const e = this.live(key2);
|
|
1242
|
+
if (!e) return void 0;
|
|
1243
|
+
if (e.type !== type) throw new Error(WRONGTYPE);
|
|
1244
|
+
return e.value;
|
|
1245
|
+
}
|
|
1246
|
+
clean(key2) {
|
|
1247
|
+
const e = this.data.get(key2);
|
|
1248
|
+
if (!e) return;
|
|
1249
|
+
const v = e.value;
|
|
1250
|
+
if ((v instanceof Map || v instanceof Set) && !v.size || Array.isArray(v) && !v.length) this.data.delete(key2);
|
|
1251
|
+
}
|
|
1252
|
+
async start() {
|
|
1253
|
+
this.server = createServer2((s) => this.accept(s));
|
|
1254
|
+
await new Promise((resolve8, reject) => {
|
|
1255
|
+
this.server.once("error", reject);
|
|
1256
|
+
this.server.listen(0, "127.0.0.1", resolve8);
|
|
1257
|
+
});
|
|
1258
|
+
return this.server.address().port;
|
|
1259
|
+
}
|
|
1260
|
+
async stop() {
|
|
1261
|
+
if (this.server) await new Promise((resolve8) => this.server.close(() => resolve8()));
|
|
1262
|
+
}
|
|
1263
|
+
accept(socket) {
|
|
1264
|
+
let buffer = Buffer.alloc(0);
|
|
1265
|
+
const session = { watched: /* @__PURE__ */ new Map(), dirty: false };
|
|
1266
|
+
socket.on("error", () => {
|
|
1267
|
+
});
|
|
1268
|
+
socket.on("data", (chunk) => {
|
|
1269
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
1270
|
+
const out = [];
|
|
1271
|
+
try {
|
|
1272
|
+
for (; ; ) {
|
|
1273
|
+
const frame2 = parseResp(buffer, 0, true);
|
|
1274
|
+
if (!frame2) break;
|
|
1275
|
+
buffer = buffer.subarray(frame2.end);
|
|
1276
|
+
const args = frame2.value.map((b) => b.toString("latin1"));
|
|
1277
|
+
if (!args.length) continue;
|
|
1278
|
+
if (args[0].toLowerCase() === "quit") {
|
|
1279
|
+
out.push(encode.simple("OK"));
|
|
1280
|
+
socket.end(Buffer.concat(out));
|
|
1281
|
+
return;
|
|
1282
|
+
}
|
|
1283
|
+
out.push(this.dispatch(args, session));
|
|
1284
|
+
}
|
|
1285
|
+
} catch {
|
|
1286
|
+
out.push(encode.error("ERR Protocol error"));
|
|
1287
|
+
socket.end(Buffer.concat(out));
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
if (out.length) socket.write(Buffer.concat(out));
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1293
|
+
dispatch(args, session) {
|
|
1294
|
+
const name = args[0].toLowerCase();
|
|
1295
|
+
if (session.multi && !["exec", "discard", "multi", "watch"].includes(name)) {
|
|
1296
|
+
session.multi.push(args);
|
|
1297
|
+
return encode.simple("QUEUED");
|
|
1298
|
+
}
|
|
1299
|
+
if (name === "multi") {
|
|
1300
|
+
if (session.multi) return encode.error("ERR MULTI calls can not be nested");
|
|
1301
|
+
session.multi = [];
|
|
1302
|
+
return encode.simple("OK");
|
|
1303
|
+
}
|
|
1304
|
+
if (name === "discard") {
|
|
1305
|
+
if (!session.multi) return encode.error("ERR DISCARD without MULTI");
|
|
1306
|
+
session.multi = void 0;
|
|
1307
|
+
session.watched.clear();
|
|
1308
|
+
return encode.simple("OK");
|
|
1309
|
+
}
|
|
1310
|
+
if (name === "watch") {
|
|
1311
|
+
for (const k of args.slice(1)) session.watched.set(k, this.versions.get(k) ?? 0);
|
|
1312
|
+
return encode.simple("OK");
|
|
1313
|
+
}
|
|
1314
|
+
if (name === "unwatch") {
|
|
1315
|
+
session.watched.clear();
|
|
1316
|
+
return encode.simple("OK");
|
|
1317
|
+
}
|
|
1318
|
+
if (name === "exec") {
|
|
1319
|
+
if (!session.multi) return encode.error("ERR EXEC without MULTI");
|
|
1320
|
+
const queued = session.multi;
|
|
1321
|
+
session.multi = void 0;
|
|
1322
|
+
const conflict = [...session.watched].some(([k, v]) => (this.versions.get(k) ?? 0) !== v);
|
|
1323
|
+
session.watched.clear();
|
|
1324
|
+
if (conflict) return encode.array(null);
|
|
1325
|
+
return encode.array(queued.map((cmd) => this.run(cmd)));
|
|
1326
|
+
}
|
|
1327
|
+
return this.run(args);
|
|
1328
|
+
}
|
|
1329
|
+
run(args) {
|
|
1330
|
+
const name = args[0].toLowerCase(), a = args.slice(1);
|
|
1331
|
+
try {
|
|
1332
|
+
const reply = this.command(name, a);
|
|
1333
|
+
if (WRITES.has(name)) for (const k of commandKeys(name, a)) this.touch(k);
|
|
1334
|
+
return reply;
|
|
1335
|
+
} catch (error) {
|
|
1336
|
+
return encode.error(error instanceof Error ? error.message : String(error));
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
int(s) {
|
|
1340
|
+
if (s === void 0 || !/^-?\d+$/.test(s)) throw new Error(NOT_INT);
|
|
1341
|
+
return Number(s);
|
|
1342
|
+
}
|
|
1343
|
+
command(name, a) {
|
|
1344
|
+
const now = Date.now(), ok2 = encode.simple("OK"), key2 = a[0];
|
|
1345
|
+
const str2 = (k) => this.get(k, "string");
|
|
1346
|
+
const bulks = (list2) => encode.array(list2.map((v) => encode.bulk(v ?? null)));
|
|
1347
|
+
const setString = (k, v, expireAt) => this.data.set(k, { type: "string", value: v, ...expireAt !== void 0 ? { expireAt } : {} });
|
|
1348
|
+
const incr = (k, by) => {
|
|
1349
|
+
const cur = str2(k) ?? "0";
|
|
1350
|
+
if (!/^-?\d+$/.test(cur)) throw new Error(NOT_INT);
|
|
1351
|
+
const n = Number(cur) + by;
|
|
1352
|
+
const e = this.live(k);
|
|
1353
|
+
setString(k, String(n), e?.expireAt);
|
|
1354
|
+
return encode.int(n);
|
|
1355
|
+
};
|
|
1356
|
+
const range = (len, start, stop) => {
|
|
1357
|
+
if (start < 0) start = Math.max(0, len + start);
|
|
1358
|
+
if (stop < 0) stop = len + stop;
|
|
1359
|
+
stop = Math.min(stop, len - 1);
|
|
1360
|
+
return [start, stop];
|
|
1361
|
+
};
|
|
1362
|
+
switch (name) {
|
|
1363
|
+
case "ping":
|
|
1364
|
+
return a.length ? encode.bulk(a[0]) : encode.simple("PONG");
|
|
1365
|
+
case "echo":
|
|
1366
|
+
return encode.bulk(a[0]);
|
|
1367
|
+
case "select":
|
|
1368
|
+
return a[0] === "0" ? ok2 : encode.error("ERR DB index is out of range (AgentTwin serves database 0)");
|
|
1369
|
+
case "auth":
|
|
1370
|
+
case "readonly":
|
|
1371
|
+
return ok2;
|
|
1372
|
+
case "client": {
|
|
1373
|
+
const sub = (a[0] ?? "").toLowerCase();
|
|
1374
|
+
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;
|
|
1375
|
+
}
|
|
1376
|
+
case "hello": {
|
|
1377
|
+
if (a[0] && a[0] !== "2") return encode.error("NOPROTO this AgentTwin Redis engine speaks RESP2 only");
|
|
1378
|
+
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([])));
|
|
1379
|
+
}
|
|
1380
|
+
case "info":
|
|
1381
|
+
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
|
|
1382
|
+
` : ""));
|
|
1383
|
+
case "command":
|
|
1384
|
+
return encode.array([]);
|
|
1385
|
+
case "config":
|
|
1386
|
+
return (a[0] ?? "").toLowerCase() === "get" ? encode.array([]) : ok2;
|
|
1387
|
+
case "time":
|
|
1388
|
+
return bulks([String(Math.floor(now / 1e3)), String(now % 1e3 * 1e3)]);
|
|
1389
|
+
case "dbsize":
|
|
1390
|
+
return encode.int([...this.data.keys()].filter((k) => this.live(k)).length);
|
|
1391
|
+
case "flushdb":
|
|
1392
|
+
case "flushall":
|
|
1393
|
+
this.data.clear();
|
|
1394
|
+
return ok2;
|
|
1395
|
+
case "get":
|
|
1396
|
+
return encode.bulk(str2(key2));
|
|
1397
|
+
case "set": {
|
|
1398
|
+
let expireAt, nx = false, xx = false, get = false, keep = false;
|
|
1399
|
+
for (let i = 2; i < a.length; i++) {
|
|
1400
|
+
const o = a[i].toLowerCase();
|
|
1401
|
+
if (o === "nx") nx = true;
|
|
1402
|
+
else if (o === "xx") xx = true;
|
|
1403
|
+
else if (o === "get") get = true;
|
|
1404
|
+
else if (o === "keepttl") keep = true;
|
|
1405
|
+
else if (o === "ex") expireAt = now + this.int(a[++i]) * 1e3;
|
|
1406
|
+
else if (o === "px") expireAt = now + this.int(a[++i]);
|
|
1407
|
+
else if (o === "exat") expireAt = this.int(a[++i]) * 1e3;
|
|
1408
|
+
else if (o === "pxat") expireAt = this.int(a[++i]);
|
|
1409
|
+
else return encode.error("ERR syntax error");
|
|
1410
|
+
}
|
|
1411
|
+
const existing = this.live(key2);
|
|
1412
|
+
if (get && existing && existing.type !== "string") throw new Error(WRONGTYPE);
|
|
1413
|
+
const old = existing?.value;
|
|
1414
|
+
if (nx && existing || xx && !existing) return get ? encode.bulk(old) : encode.bulk(null);
|
|
1415
|
+
setString(key2, a[1], keep ? existing?.expireAt : expireAt);
|
|
1416
|
+
return get ? encode.bulk(old) : ok2;
|
|
1417
|
+
}
|
|
1418
|
+
case "setnx":
|
|
1419
|
+
if (this.live(key2)) return encode.int(0);
|
|
1420
|
+
setString(key2, a[1]);
|
|
1421
|
+
return encode.int(1);
|
|
1422
|
+
case "setex":
|
|
1423
|
+
setString(key2, a[2], now + this.int(a[1]) * 1e3);
|
|
1424
|
+
return ok2;
|
|
1425
|
+
case "psetex":
|
|
1426
|
+
setString(key2, a[2], now + this.int(a[1]));
|
|
1427
|
+
return ok2;
|
|
1428
|
+
case "getset": {
|
|
1429
|
+
const old = str2(key2);
|
|
1430
|
+
setString(key2, a[1]);
|
|
1431
|
+
return encode.bulk(old);
|
|
1432
|
+
}
|
|
1433
|
+
case "getdel": {
|
|
1434
|
+
const old = str2(key2);
|
|
1435
|
+
this.data.delete(key2);
|
|
1436
|
+
return encode.bulk(old);
|
|
1437
|
+
}
|
|
1438
|
+
case "mget":
|
|
1439
|
+
return bulks(a.map((k) => {
|
|
1440
|
+
const e = this.live(k);
|
|
1441
|
+
return e?.type === "string" ? e.value : null;
|
|
1442
|
+
}));
|
|
1443
|
+
case "mset":
|
|
1444
|
+
for (let i = 0; i < a.length; i += 2) setString(a[i], a[i + 1]);
|
|
1445
|
+
return ok2;
|
|
1446
|
+
case "msetnx":
|
|
1447
|
+
if (a.some((k, i) => i % 2 === 0 && this.live(k))) return encode.int(0);
|
|
1448
|
+
for (let i = 0; i < a.length; i += 2) setString(a[i], a[i + 1]);
|
|
1449
|
+
return encode.int(1);
|
|
1450
|
+
case "incr":
|
|
1451
|
+
return incr(key2, 1);
|
|
1452
|
+
case "decr":
|
|
1453
|
+
return incr(key2, -1);
|
|
1454
|
+
case "incrby":
|
|
1455
|
+
return incr(key2, this.int(a[1]));
|
|
1456
|
+
case "decrby":
|
|
1457
|
+
return incr(key2, -this.int(a[1]));
|
|
1458
|
+
case "incrbyfloat": {
|
|
1459
|
+
const n = Number(str2(key2) ?? "0") + Number(a[1]);
|
|
1460
|
+
if (!Number.isFinite(n)) throw new Error("ERR value is not a valid float");
|
|
1461
|
+
setString(key2, fmt(n), this.live(key2)?.expireAt);
|
|
1462
|
+
return encode.bulk(fmt(n));
|
|
1463
|
+
}
|
|
1464
|
+
case "append": {
|
|
1465
|
+
const v = (str2(key2) ?? "") + a[1];
|
|
1466
|
+
setString(key2, v, this.live(key2)?.expireAt);
|
|
1467
|
+
return encode.int(Buffer.byteLength(v, "latin1"));
|
|
1468
|
+
}
|
|
1469
|
+
case "strlen":
|
|
1470
|
+
return encode.int(Buffer.byteLength(str2(key2) ?? "", "latin1"));
|
|
1471
|
+
case "del":
|
|
1472
|
+
case "unlink": {
|
|
1473
|
+
let n = 0;
|
|
1474
|
+
for (const k of a) if (this.live(k)) {
|
|
1475
|
+
this.data.delete(k);
|
|
1476
|
+
n++;
|
|
1477
|
+
}
|
|
1478
|
+
return encode.int(n);
|
|
1479
|
+
}
|
|
1480
|
+
case "exists":
|
|
1481
|
+
return encode.int(a.filter((k) => this.live(k)).length);
|
|
1482
|
+
case "type":
|
|
1483
|
+
return encode.simple(this.live(key2)?.type ?? "none");
|
|
1484
|
+
case "expire":
|
|
1485
|
+
case "pexpire":
|
|
1486
|
+
case "expireat":
|
|
1487
|
+
case "pexpireat": {
|
|
1488
|
+
const e = this.live(key2);
|
|
1489
|
+
if (!e) return encode.int(0);
|
|
1490
|
+
const n = this.int(a[1]);
|
|
1491
|
+
e.expireAt = name === "expire" ? now + n * 1e3 : name === "pexpire" ? now + n : name === "expireat" ? n * 1e3 : n;
|
|
1492
|
+
if (e.expireAt <= now) this.data.delete(key2);
|
|
1493
|
+
return encode.int(1);
|
|
1494
|
+
}
|
|
1495
|
+
case "ttl":
|
|
1496
|
+
case "pttl": {
|
|
1497
|
+
const e = this.live(key2);
|
|
1498
|
+
if (!e) return encode.int(-2);
|
|
1499
|
+
if (e.expireAt === void 0) return encode.int(-1);
|
|
1500
|
+
const ms = e.expireAt - now;
|
|
1501
|
+
return encode.int(name === "ttl" ? Math.round(ms / 1e3) : ms);
|
|
1502
|
+
}
|
|
1503
|
+
case "persist": {
|
|
1504
|
+
const e = this.live(key2);
|
|
1505
|
+
if (!e || e.expireAt === void 0) return encode.int(0);
|
|
1506
|
+
delete e.expireAt;
|
|
1507
|
+
return encode.int(1);
|
|
1508
|
+
}
|
|
1509
|
+
case "keys": {
|
|
1510
|
+
const re = glob(key2 ?? "*");
|
|
1511
|
+
return bulks([...this.data.keys()].filter((k) => this.live(k) && re.test(k)));
|
|
1512
|
+
}
|
|
1513
|
+
case "scan": {
|
|
1514
|
+
let match = "*", type;
|
|
1515
|
+
for (let i = 1; i < a.length; i++) {
|
|
1516
|
+
const o = a[i].toLowerCase();
|
|
1517
|
+
if (o === "match") match = a[++i];
|
|
1518
|
+
else if (o === "count") i++;
|
|
1519
|
+
else if (o === "type") type = a[++i];
|
|
1520
|
+
}
|
|
1521
|
+
const re = glob(match);
|
|
1522
|
+
return encode.array([encode.bulk("0"), bulks([...this.data.keys()].filter((k) => {
|
|
1523
|
+
const e = this.live(k);
|
|
1524
|
+
return e && re.test(k) && (!type || e.type === type);
|
|
1525
|
+
}))]);
|
|
1526
|
+
}
|
|
1527
|
+
case "rename":
|
|
1528
|
+
case "renamenx": {
|
|
1529
|
+
const e = this.live(key2);
|
|
1530
|
+
if (!e) return encode.error("ERR no such key");
|
|
1531
|
+
if (name === "renamenx" && this.live(a[1])) return encode.int(0);
|
|
1532
|
+
this.data.delete(key2);
|
|
1533
|
+
this.data.set(a[1], e);
|
|
1534
|
+
return name === "rename" ? ok2 : encode.int(1);
|
|
1535
|
+
}
|
|
1536
|
+
case "hset":
|
|
1537
|
+
case "hmset": {
|
|
1538
|
+
const h = this.typed(key2, "hash", () => /* @__PURE__ */ new Map());
|
|
1539
|
+
let n = 0;
|
|
1540
|
+
for (let i = 1; i < a.length; i += 2) {
|
|
1541
|
+
if (!h.has(a[i])) n++;
|
|
1542
|
+
h.set(a[i], a[i + 1]);
|
|
1543
|
+
}
|
|
1544
|
+
return name === "hmset" ? ok2 : encode.int(n);
|
|
1545
|
+
}
|
|
1546
|
+
case "hsetnx": {
|
|
1547
|
+
const h = this.typed(key2, "hash", () => /* @__PURE__ */ new Map());
|
|
1548
|
+
if (h.has(a[1])) return encode.int(0);
|
|
1549
|
+
h.set(a[1], a[2]);
|
|
1550
|
+
return encode.int(1);
|
|
1551
|
+
}
|
|
1552
|
+
case "hget":
|
|
1553
|
+
return encode.bulk(this.get(key2, "hash")?.get(a[1]));
|
|
1554
|
+
case "hmget": {
|
|
1555
|
+
const h = this.get(key2, "hash");
|
|
1556
|
+
return bulks(a.slice(1).map((f) => h?.get(f)));
|
|
1557
|
+
}
|
|
1558
|
+
case "hgetall": {
|
|
1559
|
+
const h = this.get(key2, "hash");
|
|
1560
|
+
return bulks([...h ?? /* @__PURE__ */ new Map()].flat());
|
|
1561
|
+
}
|
|
1562
|
+
case "hkeys":
|
|
1563
|
+
return bulks([...(this.get(key2, "hash") ?? /* @__PURE__ */ new Map()).keys()]);
|
|
1564
|
+
case "hvals":
|
|
1565
|
+
return bulks([...(this.get(key2, "hash") ?? /* @__PURE__ */ new Map()).values()]);
|
|
1566
|
+
case "hlen":
|
|
1567
|
+
return encode.int(this.get(key2, "hash")?.size ?? 0);
|
|
1568
|
+
case "hexists":
|
|
1569
|
+
return encode.int(this.get(key2, "hash")?.has(a[1]) ? 1 : 0);
|
|
1570
|
+
case "hdel": {
|
|
1571
|
+
const h = this.get(key2, "hash");
|
|
1572
|
+
const n = a.slice(1).filter((f) => h?.delete(f)).length;
|
|
1573
|
+
this.clean(key2);
|
|
1574
|
+
return encode.int(n);
|
|
1575
|
+
}
|
|
1576
|
+
case "hincrby": {
|
|
1577
|
+
const h = this.typed(key2, "hash", () => /* @__PURE__ */ new Map());
|
|
1578
|
+
const cur = h.get(a[1]) ?? "0";
|
|
1579
|
+
if (!/^-?\d+$/.test(cur)) throw new Error("ERR hash value is not an integer");
|
|
1580
|
+
const n = Number(cur) + this.int(a[2]);
|
|
1581
|
+
h.set(a[1], String(n));
|
|
1582
|
+
return encode.int(n);
|
|
1583
|
+
}
|
|
1584
|
+
case "hincrbyfloat": {
|
|
1585
|
+
const h = this.typed(key2, "hash", () => /* @__PURE__ */ new Map());
|
|
1586
|
+
const n = Number(h.get(a[1]) ?? "0") + Number(a[2]);
|
|
1587
|
+
h.set(a[1], fmt(n));
|
|
1588
|
+
return encode.bulk(fmt(n));
|
|
1589
|
+
}
|
|
1590
|
+
case "lpush":
|
|
1591
|
+
case "rpush":
|
|
1592
|
+
case "lpushx":
|
|
1593
|
+
case "rpushx": {
|
|
1594
|
+
if (name.endsWith("x") && !this.live(key2)) return encode.int(0);
|
|
1595
|
+
const l = this.typed(key2, "list", () => []);
|
|
1596
|
+
for (const v of a.slice(1)) name.startsWith("l") ? l.unshift(v) : l.push(v);
|
|
1597
|
+
return encode.int(l.length);
|
|
1598
|
+
}
|
|
1599
|
+
case "lpop":
|
|
1600
|
+
case "rpop": {
|
|
1601
|
+
const l = this.get(key2, "list");
|
|
1602
|
+
if (!l) return a[1] ? encode.array(null) : encode.bulk(null);
|
|
1603
|
+
const count = a[1] ? this.int(a[1]) : void 0;
|
|
1604
|
+
const taken = name === "lpop" ? l.splice(0, count ?? 1) : l.splice(-(count ?? 1)).reverse();
|
|
1605
|
+
this.clean(key2);
|
|
1606
|
+
return count === void 0 ? encode.bulk(taken[0]) : bulks(taken);
|
|
1607
|
+
}
|
|
1608
|
+
case "llen":
|
|
1609
|
+
return encode.int(this.get(key2, "list")?.length ?? 0);
|
|
1610
|
+
case "lrange": {
|
|
1611
|
+
const l = this.get(key2, "list") ?? [];
|
|
1612
|
+
const [s, e] = range(l.length, this.int(a[1]), this.int(a[2]));
|
|
1613
|
+
return bulks(s > e ? [] : l.slice(s, e + 1));
|
|
1614
|
+
}
|
|
1615
|
+
case "lindex": {
|
|
1616
|
+
const l = this.get(key2, "list") ?? [];
|
|
1617
|
+
const i = this.int(a[1]);
|
|
1618
|
+
return encode.bulk(l.at(i) ?? null);
|
|
1619
|
+
}
|
|
1620
|
+
case "lset": {
|
|
1621
|
+
const l = this.get(key2, "list");
|
|
1622
|
+
if (!l) return encode.error("ERR no such key");
|
|
1623
|
+
let i = this.int(a[1]);
|
|
1624
|
+
if (i < 0) i += l.length;
|
|
1625
|
+
if (i < 0 || i >= l.length) return encode.error("ERR index out of range");
|
|
1626
|
+
l[i] = a[2];
|
|
1627
|
+
return ok2;
|
|
1628
|
+
}
|
|
1629
|
+
case "lrem": {
|
|
1630
|
+
const l = this.get(key2, "list");
|
|
1631
|
+
if (!l) return encode.int(0);
|
|
1632
|
+
let count = this.int(a[1]), n = 0;
|
|
1633
|
+
const keep = [];
|
|
1634
|
+
const items = count < 0 ? [...l].reverse() : l;
|
|
1635
|
+
for (const v of items) {
|
|
1636
|
+
if (v === a[2] && (count === 0 || n < Math.abs(count))) {
|
|
1637
|
+
n++;
|
|
1638
|
+
continue;
|
|
1639
|
+
}
|
|
1640
|
+
keep.push(v);
|
|
1641
|
+
}
|
|
1642
|
+
l.splice(0, l.length, ...count < 0 ? keep.reverse() : keep);
|
|
1643
|
+
this.clean(key2);
|
|
1644
|
+
return encode.int(n);
|
|
1645
|
+
}
|
|
1646
|
+
case "ltrim": {
|
|
1647
|
+
const l = this.get(key2, "list");
|
|
1648
|
+
if (!l) return ok2;
|
|
1649
|
+
const [s, e] = range(l.length, this.int(a[1]), this.int(a[2]));
|
|
1650
|
+
l.splice(0, l.length, ...s > e ? [] : l.slice(s, e + 1));
|
|
1651
|
+
this.clean(key2);
|
|
1652
|
+
return ok2;
|
|
1653
|
+
}
|
|
1654
|
+
case "sadd": {
|
|
1655
|
+
const s = this.typed(key2, "set", () => /* @__PURE__ */ new Set());
|
|
1656
|
+
let n = 0;
|
|
1657
|
+
for (const v of a.slice(1)) if (!s.has(v)) {
|
|
1658
|
+
s.add(v);
|
|
1659
|
+
n++;
|
|
1660
|
+
}
|
|
1661
|
+
return encode.int(n);
|
|
1662
|
+
}
|
|
1663
|
+
case "srem": {
|
|
1664
|
+
const s = this.get(key2, "set");
|
|
1665
|
+
const n = a.slice(1).filter((v) => s?.delete(v)).length;
|
|
1666
|
+
this.clean(key2);
|
|
1667
|
+
return encode.int(n);
|
|
1668
|
+
}
|
|
1669
|
+
case "smembers":
|
|
1670
|
+
return bulks([...this.get(key2, "set") ?? []]);
|
|
1671
|
+
case "sismember":
|
|
1672
|
+
return encode.int(this.get(key2, "set")?.has(a[1]) ? 1 : 0);
|
|
1673
|
+
case "scard":
|
|
1674
|
+
return encode.int(this.get(key2, "set")?.size ?? 0);
|
|
1675
|
+
case "zadd": {
|
|
1676
|
+
const z = this.typed(key2, "zset", () => /* @__PURE__ */ new Map());
|
|
1677
|
+
let i = 1, nx = false, xx = false, ch = false;
|
|
1678
|
+
for (; i < a.length && /^(nx|xx|ch|gt|lt)$/i.test(a[i]); i++) {
|
|
1679
|
+
const o = a[i].toLowerCase();
|
|
1680
|
+
if (o === "nx") nx = true;
|
|
1681
|
+
if (o === "xx") xx = true;
|
|
1682
|
+
if (o === "ch") ch = true;
|
|
1683
|
+
}
|
|
1684
|
+
let n = 0;
|
|
1685
|
+
for (; i < a.length; i += 2) {
|
|
1686
|
+
const score = Number(a[i]), member = a[i + 1];
|
|
1687
|
+
if (Number.isNaN(score)) throw new Error("ERR value is not a valid float");
|
|
1688
|
+
const had = z.has(member);
|
|
1689
|
+
if (nx && had || xx && !had) continue;
|
|
1690
|
+
if (!had || ch && z.get(member) !== score) n++;
|
|
1691
|
+
z.set(member, score);
|
|
1692
|
+
}
|
|
1693
|
+
this.clean(key2);
|
|
1694
|
+
return encode.int(n);
|
|
1695
|
+
}
|
|
1696
|
+
case "zincrby": {
|
|
1697
|
+
const z = this.typed(key2, "zset", () => /* @__PURE__ */ new Map());
|
|
1698
|
+
const n = (z.get(a[2]) ?? 0) + Number(a[1]);
|
|
1699
|
+
z.set(a[2], n);
|
|
1700
|
+
return encode.bulk(fmt(n));
|
|
1701
|
+
}
|
|
1702
|
+
case "zscore": {
|
|
1703
|
+
const v = this.get(key2, "zset")?.get(a[1]);
|
|
1704
|
+
return encode.bulk(v === void 0 ? null : fmt(v));
|
|
1705
|
+
}
|
|
1706
|
+
case "zcard":
|
|
1707
|
+
return encode.int(this.get(key2, "zset")?.size ?? 0);
|
|
1708
|
+
case "zrem": {
|
|
1709
|
+
const z = this.get(key2, "zset");
|
|
1710
|
+
const n = a.slice(1).filter((m) => z?.delete(m)).length;
|
|
1711
|
+
this.clean(key2);
|
|
1712
|
+
return encode.int(n);
|
|
1713
|
+
}
|
|
1714
|
+
case "zrange":
|
|
1715
|
+
case "zrevrange":
|
|
1716
|
+
case "zrangebyscore": {
|
|
1717
|
+
const z = this.get(key2, "zset") ?? /* @__PURE__ */ new Map();
|
|
1718
|
+
const opts = a.slice(3).map((o) => o.toLowerCase());
|
|
1719
|
+
let sorted = [...z].sort((x, y) => x[1] - y[1] || (x[0] < y[0] ? -1 : 1));
|
|
1720
|
+
if (name === "zrevrange" || opts.includes("rev")) sorted.reverse();
|
|
1721
|
+
if (name === "zrangebyscore" || opts.includes("byscore")) {
|
|
1722
|
+
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);
|
|
1723
|
+
const lo = bound(a[1], true), hi = bound(a[2], false);
|
|
1724
|
+
sorted = sorted.filter(([, s]) => s >= lo && s <= hi);
|
|
1725
|
+
} else {
|
|
1726
|
+
const [s, e] = range(sorted.length, this.int(a[1]), this.int(a[2]));
|
|
1727
|
+
sorted = s > e ? [] : sorted.slice(s, e + 1);
|
|
1728
|
+
}
|
|
1729
|
+
return bulks(opts.includes("withscores") ? sorted.flatMap(([m, s]) => [m, fmt(s)]) : sorted.map(([m]) => m));
|
|
1730
|
+
}
|
|
1731
|
+
case "publish":
|
|
1732
|
+
return encode.int(0);
|
|
1733
|
+
default: {
|
|
1734
|
+
const text2 = `redis: ${name.toUpperCase()} is outside the AgentTwin in-process Redis engine`;
|
|
1735
|
+
if (this.unsupported.length < 1e3 && !this.unsupported.includes(text2)) this.unsupported.push(text2);
|
|
1736
|
+
return encode.error(`ERR unknown command '${name}' (AgentTwin in-process Redis; use a redis-server binary or Docker for full Redis)`);
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
}
|
|
1740
|
+
};
|
|
1741
|
+
seedEntries = (seed) => Object.entries(seed.keys ?? {}).map(([key2, value]) => ({ key: key2, ttlMs: null, ...Array.isArray(value) ? { type: "list", value } : typeof value === "object" ? { type: "hash", value } : { type: "string", value: String(value) } }));
|
|
1742
|
+
}
|
|
1743
|
+
});
|
|
1744
|
+
|
|
1745
|
+
// src/runtime/upstash-redis-twin.ts
|
|
1746
|
+
function toEntry(row) {
|
|
1747
|
+
const value = row.value;
|
|
1748
|
+
switch (row.type) {
|
|
1749
|
+
case "string":
|
|
1750
|
+
return typeof value === "string" ? { type: "string", value: toBytes(value), ...row.expireAt ? { expireAt: row.expireAt } : {} } : void 0;
|
|
1751
|
+
case "hash":
|
|
1752
|
+
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;
|
|
1753
|
+
case "list":
|
|
1754
|
+
return Array.isArray(value) ? { type: "list", value: value.map((v) => toBytes(String(v))), ...row.expireAt ? { expireAt: row.expireAt } : {} } : void 0;
|
|
1755
|
+
case "set":
|
|
1756
|
+
return Array.isArray(value) ? { type: "set", value: new Set(value.map((v) => toBytes(String(v)))), ...row.expireAt ? { expireAt: row.expireAt } : {} } : void 0;
|
|
1757
|
+
case "zset":
|
|
1758
|
+
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;
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
function toRow(key2, entry) {
|
|
1762
|
+
const v = entry.value;
|
|
1763
|
+
const text2 = (x) => typeof x === "string" ? fromBytes(x) : x;
|
|
1764
|
+
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);
|
|
1765
|
+
return { key: fromBytes(key2), type: entry.type, value, ...entry.expireAt !== void 0 ? { expireAt: entry.expireAt } : {} };
|
|
1766
|
+
}
|
|
1767
|
+
function resync(rows2, cache2) {
|
|
1768
|
+
const now = Date.now();
|
|
1769
|
+
for (const [k, e] of cache2.engine.data) if (e.expireAt !== void 0 && e.expireAt <= now) cache2.engine.data.delete(k);
|
|
1770
|
+
rows2.splice(0, rows2.length, ...[...cache2.engine.data].map(([k, e]) => toRow(k, e)));
|
|
1771
|
+
cache2.mirror = rows2.slice();
|
|
1772
|
+
cache2.index = new Map([...cache2.engine.data.keys()].map((k, i) => [k, i]));
|
|
1773
|
+
cache2.nextExpiry = rows2.reduce((min, r) => r.expireAt !== void 0 && r.expireAt < min ? r.expireAt : min, Infinity);
|
|
1774
|
+
}
|
|
1775
|
+
function remove(rows2, cache2, key2) {
|
|
1776
|
+
const at = cache2.index.get(key2);
|
|
1777
|
+
if (at === void 0) return;
|
|
1778
|
+
cache2.index.delete(key2);
|
|
1779
|
+
const last = rows2.length - 1;
|
|
1780
|
+
if (at !== last) {
|
|
1781
|
+
rows2[at] = rows2[last];
|
|
1782
|
+
cache2.mirror[at] = rows2[last];
|
|
1783
|
+
cache2.index.set(toBytes(rows2[at].key), at);
|
|
1784
|
+
}
|
|
1785
|
+
rows2.pop();
|
|
1786
|
+
cache2.mirror.pop();
|
|
1787
|
+
}
|
|
1788
|
+
function syncKey(rows2, cache2, key2, now) {
|
|
1789
|
+
const entry = cache2.engine.data.get(key2);
|
|
1790
|
+
if (!entry || entry.expireAt !== void 0 && entry.expireAt <= now) {
|
|
1791
|
+
if (entry) cache2.engine.data.delete(key2);
|
|
1792
|
+
remove(rows2, cache2, key2);
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
const row = toRow(key2, entry);
|
|
1796
|
+
const at = cache2.index.get(key2);
|
|
1797
|
+
if (at === void 0) {
|
|
1798
|
+
cache2.index.set(key2, rows2.length);
|
|
1799
|
+
rows2.push(row);
|
|
1800
|
+
cache2.mirror.push(row);
|
|
1801
|
+
} else {
|
|
1802
|
+
rows2[at] = row;
|
|
1803
|
+
cache2.mirror[at] = row;
|
|
1804
|
+
}
|
|
1805
|
+
if (row.expireAt !== void 0) cache2.nextExpiry = Math.min(cache2.nextExpiry, row.expireAt);
|
|
1806
|
+
}
|
|
1807
|
+
function engineFor(rows2) {
|
|
1808
|
+
const cached2 = caches.get(rows2);
|
|
1809
|
+
if (cached2 && consistent(rows2, cached2)) return cached2;
|
|
1810
|
+
const engine = new InProcessRedis();
|
|
1811
|
+
for (const row of rows2) {
|
|
1812
|
+
const entry = row && typeof row.key === "string" ? toEntry(row) : void 0;
|
|
1813
|
+
if (!entry) {
|
|
1814
|
+
caches.delete(rows2);
|
|
1815
|
+
return { error: `ERR invalid seeded key row ${JSON.stringify(row?.key)}` };
|
|
1816
|
+
}
|
|
1817
|
+
engine.data.set(toBytes(row.key), entry);
|
|
1818
|
+
}
|
|
1819
|
+
const cache2 = { engine, mirror: [], index: /* @__PURE__ */ new Map(), nextExpiry: Infinity };
|
|
1820
|
+
resync(rows2, cache2);
|
|
1821
|
+
caches.set(rows2, cache2);
|
|
1822
|
+
return cache2;
|
|
1823
|
+
}
|
|
1824
|
+
function upstashReply(reply, base64) {
|
|
1825
|
+
const frame2 = parseResp(reply);
|
|
1826
|
+
const json = (value) => {
|
|
1827
|
+
if (value === null || typeof value === "number" || typeof value === "boolean") return value;
|
|
1828
|
+
if (Buffer.isBuffer(value)) return base64 ? value.toString("base64") : value.toString("utf8");
|
|
1829
|
+
if (Array.isArray(value)) return value.map(json);
|
|
1830
|
+
if ("simple" in value) return base64 && value.simple !== "OK" ? Buffer.from(value.simple).toString("base64") : value.simple;
|
|
1831
|
+
throw new Error(value.error);
|
|
1832
|
+
};
|
|
1833
|
+
if (!frame2) return { error: "ERR empty reply" };
|
|
1834
|
+
if (frame2.value && typeof frame2.value === "object" && !Array.isArray(frame2.value) && !Buffer.isBuffer(frame2.value) && "error" in frame2.value) return { error: frame2.value.error };
|
|
1835
|
+
return { result: json(frame2.value) };
|
|
1836
|
+
}
|
|
1837
|
+
function upstashRedisOperation(method, path, params, headers, data, _sequence, raw) {
|
|
1838
|
+
if (method !== "POST" || !["/", "/pipeline", "/multi-exec"].includes(path) || raw === void 0 || Object.keys(params).length) return void 0;
|
|
1839
|
+
let body;
|
|
1840
|
+
try {
|
|
1841
|
+
body = JSON.parse(raw);
|
|
1842
|
+
} catch {
|
|
1843
|
+
return { status: 400, body: { error: "ERR failed to parse command" }, collection: UPSTASH_KEYS };
|
|
1844
|
+
}
|
|
1845
|
+
const single = path === "/";
|
|
1846
|
+
const commands = single ? [body] : body;
|
|
1847
|
+
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";
|
|
1848
|
+
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 };
|
|
1849
|
+
const args = commands.map((c) => c.map((a) => toBytes(String(a))));
|
|
1850
|
+
if (args.some((c) => REJECTED.has(c[0].toLowerCase()))) return void 0;
|
|
1851
|
+
const rows2 = data[UPSTASH_KEYS];
|
|
1852
|
+
const cache2 = engineFor(rows2);
|
|
1853
|
+
if ("error" in cache2) return { status: 500, body: { error: cache2.error }, collection: UPSTASH_KEYS };
|
|
1854
|
+
const { engine } = cache2;
|
|
1855
|
+
engine.unsupported.length = 0;
|
|
1856
|
+
const replies = args.map((c) => engine.run(c));
|
|
1857
|
+
if (engine.unsupported.length) {
|
|
1858
|
+
caches.delete(rows2);
|
|
1859
|
+
return void 0;
|
|
1860
|
+
}
|
|
1861
|
+
const now = Date.now();
|
|
1862
|
+
const touched = /* @__PURE__ */ new Set();
|
|
1863
|
+
let full = false;
|
|
1864
|
+
for (const c of args) {
|
|
1865
|
+
const name = c[0].toLowerCase(), keys = commandKeys(name, c.slice(1));
|
|
1866
|
+
if (GLOBAL_WRITES.has(name) || !keys.length && WRITE_COMMANDS.has(name)) full = true;
|
|
1867
|
+
for (const k of keys) touched.add(k);
|
|
1868
|
+
}
|
|
1869
|
+
if (full || cache2.nextExpiry <= now) resync(rows2, cache2);
|
|
1870
|
+
else for (const k of touched) syncKey(rows2, cache2, k, now);
|
|
1871
|
+
const encoding = headers["upstash-encoding"];
|
|
1872
|
+
const base64 = typeof encoding === "string" && encoding.toLowerCase() === "base64";
|
|
1873
|
+
const results = replies.map((r) => upstashReply(r, base64));
|
|
1874
|
+
const wrote = args.some((c) => WRITE_COMMANDS.has(c[0].toLowerCase()));
|
|
1875
|
+
const record3 = { commands: args.map((c) => c[0].toUpperCase()), keys: args.map((c) => c[1] === void 0 ? null : fromBytes(c[1])) };
|
|
1876
|
+
if (single) {
|
|
1877
|
+
const result = results[0];
|
|
1878
|
+
return { status: "error" in result ? 400 : 200, body: result, collection: UPSTASH_KEYS, operation: wrote ? "write" : "read", record: record3 };
|
|
1879
|
+
}
|
|
1880
|
+
return { status: 200, body: results, collection: UPSTASH_KEYS, operation: wrote ? "write" : "read", record: record3 };
|
|
1881
|
+
}
|
|
1882
|
+
var UPSTASH_KEYS, WRITE_COMMANDS, REJECTED, toBytes, fromBytes, caches, GLOBAL_WRITES, consistent;
|
|
1883
|
+
var init_upstash_redis_twin = __esm({
|
|
1884
|
+
"src/runtime/upstash-redis-twin.ts"() {
|
|
1885
|
+
"use strict";
|
|
1886
|
+
init_redis();
|
|
1887
|
+
init_resp();
|
|
1888
|
+
UPSTASH_KEYS = "/keys";
|
|
1889
|
+
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(" "));
|
|
1890
|
+
REJECTED = /* @__PURE__ */ new Set(["eval", "evalsha", "eval_ro", "evalsha_ro", "script", "subscribe", "psubscribe", "blpop", "brpop", "blmove", "monitor", "multi", "exec", "watch"]);
|
|
1891
|
+
toBytes = (v) => Buffer.from(v, "utf8").toString("latin1");
|
|
1892
|
+
fromBytes = (v) => Buffer.from(v, "latin1").toString("utf8");
|
|
1893
|
+
caches = /* @__PURE__ */ new WeakMap();
|
|
1894
|
+
GLOBAL_WRITES = /* @__PURE__ */ new Set(["flushdb", "flushall"]);
|
|
1895
|
+
consistent = (rows2, cache2) => rows2.length === cache2.mirror.length && rows2.every((r, i) => r === cache2.mirror[i]);
|
|
1896
|
+
}
|
|
1897
|
+
});
|
|
1898
|
+
|
|
581
1899
|
// src/runtime/gmail-mime.ts
|
|
582
1900
|
function parseGmailRaw(raw) {
|
|
583
1901
|
if (!/^[A-Za-z0-9_-]+={0,2}$/.test(raw)) return { error: "raw must be a base64url MIME message", unsupported: false };
|
|
@@ -599,12 +1917,192 @@ function parseGmailRaw(raw) {
|
|
|
599
1917
|
if (!header3("to")) return { error: "MIME To header is required", unsupported: false };
|
|
600
1918
|
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 };
|
|
601
1919
|
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 };
|
|
602
|
-
const
|
|
603
|
-
return { headers, text, encodedBody: Buffer.from(
|
|
1920
|
+
const text2 = mime.slice(boundary + 4);
|
|
1921
|
+
return { headers, text: text2, encodedBody: Buffer.from(text2).toString("base64url"), bytes: bytes.length };
|
|
1922
|
+
}
|
|
1923
|
+
function decodeEncodedWords(value) {
|
|
1924
|
+
let failure;
|
|
1925
|
+
const decoded = value.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=(\s+(?==\?))?/g, (_all, charset, kind, text2) => {
|
|
1926
|
+
if (!/^(utf-8|us-ascii)$/i.test(charset)) {
|
|
1927
|
+
failure ??= mimeError(`Encoded header charset ${charset} is outside the verified subset`, true);
|
|
1928
|
+
return "";
|
|
1929
|
+
}
|
|
1930
|
+
if (kind.toUpperCase() === "B") return Buffer.from(text2, "base64").toString("utf8");
|
|
1931
|
+
return Buffer.from(text2.replace(/_/g, " ").replace(/=([0-9A-Fa-f]{2})/g, (_m, hex) => String.fromCharCode(parseInt(hex, 16))), "latin1").toString("utf8");
|
|
1932
|
+
});
|
|
1933
|
+
return failure ?? decoded;
|
|
1934
|
+
}
|
|
1935
|
+
function parseHeaderBlock(block) {
|
|
1936
|
+
const lines = block.split(/\r?\n/);
|
|
1937
|
+
const unfolded = [];
|
|
1938
|
+
for (const line of lines) {
|
|
1939
|
+
if (/^[ \t]/.test(line)) {
|
|
1940
|
+
if (!unfolded.length) return mimeError("MIME header block starts with a continuation line", false);
|
|
1941
|
+
unfolded[unfolded.length - 1] += " " + line.trim();
|
|
1942
|
+
} else if (line) unfolded.push(line);
|
|
1943
|
+
}
|
|
1944
|
+
if (unfolded.length > 200) return mimeError("More than 200 MIME headers", false);
|
|
1945
|
+
const headers = [];
|
|
1946
|
+
for (const line of unfolded) {
|
|
1947
|
+
const match = /^([!-9;-~]+):[ \t]*(.*)$/.exec(line);
|
|
1948
|
+
if (!match || match[2].length > 8192 || /[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(match[2])) return mimeError("Invalid MIME header", false);
|
|
1949
|
+
const value = decodeEncodedWords(match[2]);
|
|
1950
|
+
if (typeof value !== "string") return value;
|
|
1951
|
+
headers.push({ name: match[1], value });
|
|
1952
|
+
}
|
|
1953
|
+
return headers;
|
|
1954
|
+
}
|
|
1955
|
+
function contentType(headers) {
|
|
1956
|
+
const value = headerValue(headers, "content-type") ?? "text/plain; charset=us-ascii";
|
|
1957
|
+
const [type, ...rest] = value.split(";");
|
|
1958
|
+
const params = {};
|
|
1959
|
+
for (const part of rest) {
|
|
1960
|
+
const m = /^\s*([A-Za-z0-9_-]+)\s*=\s*(?:"([^"]*)"|([^\s;]+))\s*$/.exec(part);
|
|
1961
|
+
if (m) params[m[1].toLowerCase()] = m[2] ?? m[3];
|
|
1962
|
+
}
|
|
1963
|
+
return { mimeType: type.trim().toLowerCase(), params };
|
|
604
1964
|
}
|
|
1965
|
+
function decodeBody(body, headers) {
|
|
1966
|
+
const encoding = (headerValue(headers, "content-transfer-encoding") ?? "7bit").trim().toLowerCase();
|
|
1967
|
+
if (["7bit", "8bit", "binary"].includes(encoding)) return Buffer.from(body, "utf8");
|
|
1968
|
+
if (encoding === "quoted-printable") {
|
|
1969
|
+
const bytes = [];
|
|
1970
|
+
const text2 = body.replace(/=\r?\n/g, "");
|
|
1971
|
+
for (let i = 0; i < text2.length; i++) {
|
|
1972
|
+
if (text2[i] === "=" && /^[0-9A-Fa-f]{2}$/.test(text2.slice(i + 1, i + 3))) {
|
|
1973
|
+
bytes.push(parseInt(text2.slice(i + 1, i + 3), 16));
|
|
1974
|
+
i += 2;
|
|
1975
|
+
} else bytes.push(...Buffer.from(text2[i], "utf8"));
|
|
1976
|
+
}
|
|
1977
|
+
return Buffer.from(bytes);
|
|
1978
|
+
}
|
|
1979
|
+
if (encoding === "base64") {
|
|
1980
|
+
const compact = body.replace(/\s+/g, "");
|
|
1981
|
+
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(compact)) return mimeError("Invalid base64 MIME body", false);
|
|
1982
|
+
return Buffer.from(compact, "base64");
|
|
1983
|
+
}
|
|
1984
|
+
return mimeError(`Content-Transfer-Encoding ${encoding} is outside the verified subset`, true);
|
|
1985
|
+
}
|
|
1986
|
+
function textPart(partId, headers, body) {
|
|
1987
|
+
const { mimeType, params } = contentType(headers);
|
|
1988
|
+
if (mimeType !== "text/plain" && mimeType !== "text/html") return mimeError(`MIME part ${mimeType} is outside the verified subset`, true);
|
|
1989
|
+
if (params.charset && !/^(utf-8|us-ascii)$/i.test(params.charset)) return mimeError(`Charset ${params.charset} is outside the verified subset`, true);
|
|
1990
|
+
const decoded = decodeBody(body, headers);
|
|
1991
|
+
if (!Buffer.isBuffer(decoded)) return decoded;
|
|
1992
|
+
if (Buffer.from(decoded.toString("utf8")).compare(decoded) !== 0) return mimeError("MIME text part is not valid UTF-8", true);
|
|
1993
|
+
return { partId, mimeType, filename: "", headers, body: { size: decoded.length, data: decoded.toString("base64url") } };
|
|
1994
|
+
}
|
|
1995
|
+
function parseGmailDraftRaw(raw) {
|
|
1996
|
+
if (!/^[A-Za-z0-9_-]+={0,2}$/.test(raw)) return mimeError("raw must be a base64url MIME message", false);
|
|
1997
|
+
const bytes = Buffer.from(raw, "base64url");
|
|
1998
|
+
if (bytes.toString("base64url") !== raw.replace(/=+$/, "")) return mimeError("raw must be canonical base64url", false);
|
|
1999
|
+
if (bytes.length > 1024 * 1024) return mimeError("MIME message larger than 1 MiB", false);
|
|
2000
|
+
const mime = bytes.toString("utf8");
|
|
2001
|
+
if (Buffer.from(mime).compare(bytes) !== 0) return mimeError("Only UTF-8 MIME messages are supported", true);
|
|
2002
|
+
const top = splitHead(mime);
|
|
2003
|
+
if (!top) return mimeError("MIME headers and body need a blank-line separator", false);
|
|
2004
|
+
const headers = parseHeaderBlock(top.head);
|
|
2005
|
+
if (!Array.isArray(headers)) return headers;
|
|
2006
|
+
const { mimeType, params } = contentType(headers);
|
|
2007
|
+
let payload;
|
|
2008
|
+
if (mimeType === "multipart/alternative") {
|
|
2009
|
+
if (!params.boundary) return mimeError("multipart/alternative needs a boundary", false);
|
|
2010
|
+
const sections = top.body.split(new RegExp(`(?:^|\\r?\\n)--${params.boundary.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`));
|
|
2011
|
+
const closing = sections.findIndex((s) => s.startsWith("--"));
|
|
2012
|
+
if (closing < 0) return mimeError("multipart/alternative has no closing boundary", false);
|
|
2013
|
+
const parts = [];
|
|
2014
|
+
for (const section of sections.slice(1, closing)) {
|
|
2015
|
+
const split = splitHead(section.replace(/^[ \t]*\r?\n/, ""));
|
|
2016
|
+
if (!split) return mimeError("MIME part headers and body need a blank-line separator", false);
|
|
2017
|
+
const partHeaders = parseHeaderBlock(split.head);
|
|
2018
|
+
if (!Array.isArray(partHeaders)) return partHeaders;
|
|
2019
|
+
const part = textPart(String(parts.length), partHeaders, split.body);
|
|
2020
|
+
if ("error" in part) return part;
|
|
2021
|
+
parts.push(part);
|
|
2022
|
+
}
|
|
2023
|
+
if (!parts.length || parts.length > 10) return mimeError("multipart/alternative needs 1 to 10 parts", false);
|
|
2024
|
+
payload = { partId: "", mimeType, filename: "", headers, body: { size: 0 }, parts };
|
|
2025
|
+
} else if (mimeType.startsWith("multipart/")) {
|
|
2026
|
+
return mimeError(`${mimeType} (attachments or nested parts) is outside the verified subset`, true);
|
|
2027
|
+
} else {
|
|
2028
|
+
const part = textPart("", headers, top.body);
|
|
2029
|
+
if ("error" in part) return part;
|
|
2030
|
+
payload = part;
|
|
2031
|
+
}
|
|
2032
|
+
const text2 = partText(payload, "text/plain") ?? partText(payload, "text/html")?.replace(/<[^>]*>/g, " ") ?? "";
|
|
2033
|
+
return { headers, payload, snippet: text2.replace(/\s+/g, " ").trim().slice(0, 200), bytes: bytes.length };
|
|
2034
|
+
}
|
|
2035
|
+
function headerAddresses(value) {
|
|
2036
|
+
return (value?.match(/[^\s<>,;:"()]+@[^\s<>,;:"()]+/g) ?? []).map((a) => a.toLowerCase());
|
|
2037
|
+
}
|
|
2038
|
+
function parseGmailBatch(raw, contentTypeHeader) {
|
|
2039
|
+
const boundary = /boundary=(?:"([^"]+)"|([^\s;]+))/i.exec(contentTypeHeader ?? "");
|
|
2040
|
+
if (!boundary) return mimeError("Batch Content-Type needs a boundary", false);
|
|
2041
|
+
const marker = `--${boundary[1] ?? boundary[2]}`;
|
|
2042
|
+
const sections = raw.split(marker);
|
|
2043
|
+
const closing = sections.findIndex((s, i) => i > 0 && s.startsWith("--"));
|
|
2044
|
+
if (closing < 0) return mimeError("Batch body has no closing boundary", false);
|
|
2045
|
+
const requests = [];
|
|
2046
|
+
for (const section of sections.slice(1, closing)) {
|
|
2047
|
+
const outer = splitHead(section.replace(/^[ \t]*\r?\n/, ""));
|
|
2048
|
+
if (!outer) return mimeError("Batch part needs headers and a request", false);
|
|
2049
|
+
const outerHeaders = parseHeaderBlock(outer.head);
|
|
2050
|
+
if (!Array.isArray(outerHeaders)) return outerHeaders;
|
|
2051
|
+
if (outerHeaders.some((h) => /[\x00-\x08\x0a-\x1f\x7f]/.test(h.value))) return mimeError("Invalid batch part header", false);
|
|
2052
|
+
if (contentType(outerHeaders).mimeType !== "application/http") return mimeError("Batch parts must be application/http", false);
|
|
2053
|
+
const lines = outer.body.split(/\r?\n/);
|
|
2054
|
+
const line = /^([A-Z]+) (\S+)(?: HTTP\/1\.1)?$/.exec(lines[0]?.trim() ?? "");
|
|
2055
|
+
if (!line) return mimeError("Invalid batch request line", false);
|
|
2056
|
+
const rest = lines.slice(1).join("\n");
|
|
2057
|
+
const innerBody = splitHead(rest)?.body ?? "";
|
|
2058
|
+
if (innerBody.trim()) return mimeError("Batch requests with bodies are outside the verified subset", true);
|
|
2059
|
+
const url = new URL(line[2], "http://batch.invalid");
|
|
2060
|
+
requests.push({ contentId: headerValue(outerHeaders, "content-id"), method: line[1], path: url.pathname, query: Object.fromEntries(url.searchParams) });
|
|
2061
|
+
}
|
|
2062
|
+
if (!requests.length || requests.length > 100) return mimeError("Batch needs 1 to 100 requests", false);
|
|
2063
|
+
return requests;
|
|
2064
|
+
}
|
|
2065
|
+
function parseGmailUpload(raw, contentTypeHeader) {
|
|
2066
|
+
const boundary = /boundary=(?:"([^"]+)"|([^\s;]+))/i.exec(contentTypeHeader ?? "");
|
|
2067
|
+
if (!/^multipart\/related\b/i.test(contentTypeHeader ?? "") || !boundary) return mimeError("Upload Content-Type must be multipart/related with a boundary", false);
|
|
2068
|
+
const marker = `--${boundary[1] ?? boundary[2]}`;
|
|
2069
|
+
const sections = raw.split(marker);
|
|
2070
|
+
const closing = sections.findIndex((s, i) => i > 0 && s.startsWith("--"));
|
|
2071
|
+
if (closing !== 3) return mimeError("Upload body must have exactly a metadata part and a message part", false);
|
|
2072
|
+
const parts = [];
|
|
2073
|
+
for (const section of sections.slice(1, closing)) {
|
|
2074
|
+
const split = splitHead(section.replace(/^[ \t]*\r?\n/, ""));
|
|
2075
|
+
if (!split) return mimeError("Upload part needs headers and a body", false);
|
|
2076
|
+
const headers = parseHeaderBlock(split.head);
|
|
2077
|
+
if (!Array.isArray(headers)) return headers;
|
|
2078
|
+
const encoding = headerValue(headers, "content-transfer-encoding")?.toLowerCase();
|
|
2079
|
+
if (encoding && !["7bit", "8bit", "binary"].includes(encoding)) return mimeError(`Upload part encoding ${encoding} is outside the verified subset`, true);
|
|
2080
|
+
parts.push({ type: contentType(headers).mimeType, body: split.body.replace(/\r?\n$/, "") });
|
|
2081
|
+
}
|
|
2082
|
+
const [meta, message] = parts;
|
|
2083
|
+
if (meta.type !== "application/json") return mimeError("First upload part must be application/json metadata", false);
|
|
2084
|
+
if (message.type !== "message/rfc822") return mimeError(`Upload media type ${message.type} is outside the verified subset`, true);
|
|
2085
|
+
let metadata;
|
|
2086
|
+
try {
|
|
2087
|
+
metadata = meta.body.trim() ? JSON.parse(meta.body) : {};
|
|
2088
|
+
} catch {
|
|
2089
|
+
return mimeError("Upload metadata must be JSON", false);
|
|
2090
|
+
}
|
|
2091
|
+
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return mimeError("Upload metadata must be a JSON object", false);
|
|
2092
|
+
if (!message.body.trim()) return mimeError("Upload message is empty", false);
|
|
2093
|
+
return { metadata, raw: Buffer.from(message.body, "utf8").toString("base64url") };
|
|
2094
|
+
}
|
|
2095
|
+
var mimeError, headerValue, splitHead, partText;
|
|
605
2096
|
var init_gmail_mime = __esm({
|
|
606
2097
|
"src/runtime/gmail-mime.ts"() {
|
|
607
2098
|
"use strict";
|
|
2099
|
+
mimeError = (error, unsupported2) => ({ error, unsupported: unsupported2 });
|
|
2100
|
+
headerValue = (headers, name) => headers.find((h) => h.name.toLowerCase() === name)?.value;
|
|
2101
|
+
splitHead = (text2) => {
|
|
2102
|
+
const m = /\r?\n\r?\n/.exec(text2);
|
|
2103
|
+
return m ? { head: text2.slice(0, m.index), body: text2.slice(m.index + m[0].length) } : void 0;
|
|
2104
|
+
};
|
|
2105
|
+
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);
|
|
608
2106
|
}
|
|
609
2107
|
});
|
|
610
2108
|
|
|
@@ -853,9 +2351,9 @@ function notionOperation(method, path, params, headers, data, sequence) {
|
|
|
853
2351
|
if (!page && !block) return notionError("/blocks", 404, "object_not_found", "Could not find block with ID.");
|
|
854
2352
|
const parent = page ? { type: "page_id", page_id: page.id } : { type: "block_id", block_id: block.id };
|
|
855
2353
|
const createdBlocks = params.children.map((child, index) => {
|
|
856
|
-
const
|
|
857
|
-
rows(data, "/blocks").push(
|
|
858
|
-
return
|
|
2354
|
+
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) };
|
|
2355
|
+
rows(data, "/blocks").push(record3);
|
|
2356
|
+
return record3;
|
|
859
2357
|
});
|
|
860
2358
|
return write(200, "/blocks", { object: "list", results: structuredClone(createdBlocks), has_more: false, next_cursor: null, type: "block", block: {} }, createdBlocks[createdBlocks.length - 1]);
|
|
861
2359
|
}
|
|
@@ -908,18 +2406,18 @@ function hubspotOperation(method, path, params, _headers, data, sequence) {
|
|
|
908
2406
|
}
|
|
909
2407
|
if (method !== "POST") return void 0;
|
|
910
2408
|
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 ${object4}`, category: "VALIDATION_ERROR" });
|
|
911
|
-
const
|
|
912
|
-
rows(data, collection).push(
|
|
913
|
-
return created(collection, hubspotEnvelope(
|
|
2409
|
+
const record4 = { id: uniqueId(rows(data, collection), 501 + sequence), properties: structuredClone(properties), createdAt: iso(), updatedAt: iso() };
|
|
2410
|
+
rows(data, collection).push(record4);
|
|
2411
|
+
return created(collection, hubspotEnvelope(record4), record4);
|
|
914
2412
|
}
|
|
915
|
-
const
|
|
916
|
-
if (!
|
|
917
|
-
if (method === "GET") return ok(collection, hubspotEnvelope(
|
|
2413
|
+
const record3 = rows(data, collection).find((r) => r.id === id);
|
|
2414
|
+
if (!record3) return { status: 404, body: { status: "error", message: `Object not found: ${object4} with id ${id}`, category: "OBJECT_NOT_FOUND" }, collection };
|
|
2415
|
+
if (method === "GET") return ok(collection, hubspotEnvelope(record3));
|
|
918
2416
|
if (method === "PATCH") {
|
|
919
2417
|
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" });
|
|
920
|
-
Object.assign(
|
|
921
|
-
|
|
922
|
-
return write(200, collection, hubspotEnvelope(
|
|
2418
|
+
Object.assign(record3.properties, structuredClone(properties));
|
|
2419
|
+
record3.updatedAt = iso();
|
|
2420
|
+
return write(200, collection, hubspotEnvelope(record3), record3);
|
|
923
2421
|
}
|
|
924
2422
|
return void 0;
|
|
925
2423
|
}
|
|
@@ -931,7 +2429,7 @@ function shopifyOperation(method, path, params, _headers, data, sequence) {
|
|
|
931
2429
|
const wrap = resource === "products" ? "product" : resource === "orders" ? "order" : "customer";
|
|
932
2430
|
const rowsIn2 = rows(data, collection);
|
|
933
2431
|
const notFoundShopify = () => notFound(collection, { errors: "Not Found" });
|
|
934
|
-
const enriched = (
|
|
2432
|
+
const enriched = (record4) => ({ ...structuredClone(record4), created_at: record4.created_at ?? iso(), updated_at: iso() });
|
|
935
2433
|
if (!id) {
|
|
936
2434
|
if (method === "GET") {
|
|
937
2435
|
if (Object.keys(params).some((k) => !["limit", "since_id"].includes(k))) return void 0;
|
|
@@ -954,25 +2452,25 @@ function shopifyOperation(method, path, params, _headers, data, sequence) {
|
|
|
954
2452
|
}
|
|
955
2453
|
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];
|
|
956
2454
|
if (Object.keys(body).some((k) => !allowed.includes(k))) return void 0;
|
|
957
|
-
const
|
|
958
|
-
if (resource === "products") Object.assign(
|
|
959
|
-
if (resource === "orders") Object.assign(
|
|
960
|
-
if (resource === "customers") Object.assign(
|
|
961
|
-
rowsIn2.push(
|
|
962
|
-
return created(collection, { [wrap]: enriched(
|
|
963
|
-
}
|
|
964
|
-
const
|
|
965
|
-
if (!
|
|
966
|
-
if (method === "GET") return ok(collection, { [wrap]: enriched(
|
|
2455
|
+
const record4 = { id: uniqueId(rowsIn2, { products: 632910392, orders: 450789469, customers: 207119551 }[resource] + sequence), created_at: iso(), updated_at: iso() };
|
|
2456
|
+
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: [] });
|
|
2457
|
+
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 });
|
|
2458
|
+
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 });
|
|
2459
|
+
rowsIn2.push(record4);
|
|
2460
|
+
return created(collection, { [wrap]: enriched(record4) }, record4);
|
|
2461
|
+
}
|
|
2462
|
+
const record3 = rowsIn2.find((r) => String(r.id) === id);
|
|
2463
|
+
if (!record3) return notFoundShopify();
|
|
2464
|
+
if (method === "GET") return ok(collection, { [wrap]: enriched(record3) });
|
|
967
2465
|
if (method === "PUT") {
|
|
968
2466
|
if (Object.keys(params).some((k) => k !== wrap) || !isObject(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
|
|
969
2467
|
const body = params[wrap];
|
|
970
2468
|
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];
|
|
971
2469
|
if (Object.keys(body).some((k) => !allowed.includes(k))) return void 0;
|
|
972
|
-
for (const [k, v] of Object.entries(body))
|
|
973
|
-
if (resource === "products" && body.title !== void 0)
|
|
974
|
-
|
|
975
|
-
return write(200, collection, { [wrap]: enriched(
|
|
2470
|
+
for (const [k, v] of Object.entries(body)) record3[k] = v;
|
|
2471
|
+
if (resource === "products" && body.title !== void 0) record3.handle = shopifySlug(String(body.title));
|
|
2472
|
+
record3.updated_at = iso();
|
|
2473
|
+
return write(200, collection, { [wrap]: enriched(record3) }, record3);
|
|
976
2474
|
}
|
|
977
2475
|
return void 0;
|
|
978
2476
|
}
|
|
@@ -1043,27 +2541,300 @@ function datadogOperation(method, path, params, _headers, data, sequence) {
|
|
|
1043
2541
|
}
|
|
1044
2542
|
return void 0;
|
|
1045
2543
|
}
|
|
1046
|
-
function
|
|
1047
|
-
const
|
|
2544
|
+
function gmailQueryMatcher(q) {
|
|
2545
|
+
const clauses = q.trim().split(/\s+OR\s+/);
|
|
2546
|
+
const parsed = [];
|
|
2547
|
+
for (const clause of clauses) {
|
|
2548
|
+
const terms = clause.trim().split(/\s+/).map((token) => /^(from|to):([^\s()"]+@[^\s()"]+)$/i.exec(token));
|
|
2549
|
+
if (!terms.length || terms.some((t) => !t)) return void 0;
|
|
2550
|
+
parsed.push(terms.map((t) => ({ field: t[1].toLowerCase(), address: t[2].toLowerCase() })));
|
|
2551
|
+
}
|
|
2552
|
+
return (message) => parsed.some((terms) => terms.every((t) => headerAddresses(gmailHeader(message, t.field)).includes(t.address)));
|
|
2553
|
+
}
|
|
2554
|
+
function gmailBatch(params, headers, data, sequence, raw) {
|
|
2555
|
+
if (raw === void 0 || Object.keys(params).length) return void 0;
|
|
2556
|
+
const contentType2 = headers["content-type"];
|
|
2557
|
+
const requests = parseGmailBatch(raw, typeof contentType2 === "string" ? contentType2 : void 0);
|
|
2558
|
+
if ("error" in requests) return requests.unsupported ? void 0 : googleError(GMAIL_MESSAGES, 400, requests.error);
|
|
2559
|
+
const responses = [];
|
|
2560
|
+
for (const request of requests) {
|
|
2561
|
+
if (request.method !== "GET" || !/^\/gmail\/v1\/users\/me\/(messages|threads)\/[^/]+$/.test(request.path)) return void 0;
|
|
2562
|
+
const result = gmailOperation("GET", request.path, request.query, {}, data, sequence);
|
|
2563
|
+
if (!result) return void 0;
|
|
2564
|
+
responses.push({ contentId: request.contentId, status: result.status, body: result.body });
|
|
2565
|
+
}
|
|
2566
|
+
const boundary = `batch_agenttwin_${sequence}`;
|
|
2567
|
+
const reason = { 200: "OK", 400: "Bad Request", 404: "Not Found" };
|
|
2568
|
+
const body = responses.map((r, i) => `--${boundary}\r
|
|
2569
|
+
Content-Type: application/http\r
|
|
2570
|
+
Content-ID: response-${(r.contentId ?? `item${i + 1}`).replace(/^<|>$/g, "")}\r
|
|
2571
|
+
\r
|
|
2572
|
+
HTTP/1.1 ${r.status} ${reason[r.status] ?? "Error"}\r
|
|
2573
|
+
Content-Type: application/json; charset=UTF-8\r
|
|
2574
|
+
\r
|
|
2575
|
+
${JSON.stringify(r.body)}\r
|
|
2576
|
+
`).join("") + `--${boundary}--\r
|
|
2577
|
+
`;
|
|
2578
|
+
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}` } };
|
|
2579
|
+
}
|
|
2580
|
+
function gmailPublish(data, labelIds, sequence) {
|
|
2581
|
+
const watch = rowsIn(data, GMAIL_WATCH)?.[0];
|
|
2582
|
+
if (!watch) return [];
|
|
2583
|
+
const watched = watch.labelIds ?? [];
|
|
2584
|
+
const matches2 = !watched.length || (watch.labelFilterBehavior === "exclude" ? !labelIds.some((l) => watched.includes(l)) : labelIds.some((l) => watched.includes(l)));
|
|
2585
|
+
if (!matches2) return [];
|
|
2586
|
+
const primary = rowsIn(data, GMAIL_SEND_AS)?.find((r) => r.isPrimary === true);
|
|
2587
|
+
const historyId = gmailHistoryId(rowsIn(data, GMAIL_MESSAGES));
|
|
2588
|
+
const deliveries = [];
|
|
2589
|
+
(rowsIn(data, PUBSUB_SUBSCRIPTIONS) ?? []).filter((sub) => sub.topic === watch.topicName).forEach((sub, i) => {
|
|
2590
|
+
const messageId = `pubsub_at_${sequence}_${i + 1}`, publishTime = new Date(twinNowMs(17e11)).toISOString();
|
|
2591
|
+
const encoded = Buffer.from(JSON.stringify({ emailAddress: primary?.sendAsEmail ?? null, historyId: Number(historyId) })).toString("base64");
|
|
2592
|
+
const row = { messageId, subscription: sub.name, topic: sub.topic, data: encoded, emailAddress: primary?.sendAsEmail ?? null, historyId, publishTime, pushEndpoint: sub.pushEndpoint, delivery: "pending" };
|
|
2593
|
+
rowsIn(data, PUBSUB_MESSAGES).push(row);
|
|
2594
|
+
if (!primary) {
|
|
2595
|
+
row.delivery = "skipped: the mailbox has no primary sendAs address";
|
|
2596
|
+
return;
|
|
2597
|
+
}
|
|
2598
|
+
deliveries.push({ url: String(sub.pushEndpoint), row, body: { message: { data: encoded, messageId, message_id: messageId, publishTime, publish_time: publishTime, attributes: {} }, subscription: sub.name } });
|
|
2599
|
+
});
|
|
2600
|
+
return deliveries;
|
|
2601
|
+
}
|
|
2602
|
+
function gmailStoreDraft(data, mime, threadId, sequence, replaceIndex) {
|
|
2603
|
+
const messages = rowsIn(data, GMAIL_MESSAGES), drafts = rowsIn(data, GMAIL_DRAFTS);
|
|
2604
|
+
const existing = replaceIndex === void 0 ? void 0 : drafts[replaceIndex];
|
|
2605
|
+
const messageId = `gmail_draft_msg_at_${sequence}`, draftId = existing ? String(existing.id) : `r_at_${sequence}`;
|
|
2606
|
+
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) };
|
|
2607
|
+
if (existing) {
|
|
2608
|
+
const old = messages.findIndex((m) => m.id === existing.message.id);
|
|
2609
|
+
if (old >= 0) messages.splice(old, 1);
|
|
2610
|
+
}
|
|
2611
|
+
messages.push(message);
|
|
2612
|
+
const value = (name) => mime.headers.find((h) => h.name.toLowerCase() === name)?.value ?? null;
|
|
2613
|
+
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 } : {} };
|
|
2614
|
+
if (existing) drafts.splice(replaceIndex, 1, draft);
|
|
2615
|
+
else drafts.push(draft);
|
|
2616
|
+
return write(200, GMAIL_DRAFTS, { id: draftId, message: { id: messageId, threadId: message.threadId, labelIds: ["DRAFT"] } }, draft);
|
|
2617
|
+
}
|
|
2618
|
+
function gmailDraftWrite(data, raw, threadIdInput, sequence, index) {
|
|
2619
|
+
const draftFail = (status, message) => googleError(GMAIL_DRAFTS, status, message);
|
|
2620
|
+
if (typeof raw !== "string" || !raw) return draftFail(400, "message.raw must be a base64url MIME string.");
|
|
2621
|
+
if (threadIdInput !== void 0 && typeof threadIdInput !== "string") return draftFail(400, "message.threadId must be a string.");
|
|
2622
|
+
let threadId = threadIdInput;
|
|
2623
|
+
if (index !== void 0) {
|
|
2624
|
+
const current = rowsIn(data, GMAIL_DRAFTS)[index].threadId;
|
|
2625
|
+
if (threadId !== void 0 && threadId !== current) return void 0;
|
|
2626
|
+
threadId = current;
|
|
2627
|
+
} else if (threadId !== void 0 && !gmailThreadMessages(data, threadId).length) return draftFail(404, "Requested entity was not found.");
|
|
2628
|
+
const mime = parseGmailDraftRaw(raw);
|
|
2629
|
+
if ("error" in mime) return mime.unsupported ? void 0 : draftFail(400, mime.error);
|
|
2630
|
+
return gmailStoreDraft(data, mime, threadId, sequence, index);
|
|
2631
|
+
}
|
|
2632
|
+
function gmailOperation(method, path, params, headers, data, sequence, raw) {
|
|
2633
|
+
const MESSAGES = GMAIL_MESSAGES, LABELS = "/gmail/v1/users/me/labels";
|
|
1048
2634
|
const fail = (status, message) => googleError(MESSAGES, status, message);
|
|
2635
|
+
if (path === "/batch/gmail/v1") return method === "POST" ? gmailBatch(params, headers, data, sequence, raw) : void 0;
|
|
2636
|
+
const uploadMatch = /^\/upload\/gmail\/v1\/users\/me\/drafts(?:\/([^/]+))?$/.exec(path);
|
|
2637
|
+
if (uploadMatch) {
|
|
2638
|
+
const id = uploadMatch[1] === void 0 ? void 0 : decodeURIComponent(uploadMatch[1]);
|
|
2639
|
+
if ((id === void 0 ? method !== "POST" : method !== "PUT") || raw === void 0 || Object.keys(params).some((k) => k !== "uploadType") || params.uploadType !== "multipart") return void 0;
|
|
2640
|
+
const ctype = headers["content-type"];
|
|
2641
|
+
const upload = parseGmailUpload(raw, typeof ctype === "string" ? ctype : void 0);
|
|
2642
|
+
if ("error" in upload) return upload.unsupported ? void 0 : googleError(GMAIL_DRAFTS, 400, upload.error);
|
|
2643
|
+
if (Object.keys(upload.metadata).some((k) => !["id", "message"].includes(k))) return void 0;
|
|
2644
|
+
const meta = upload.metadata.message === void 0 ? {} : upload.metadata.message;
|
|
2645
|
+
if (!meta || typeof meta !== "object" || Array.isArray(meta)) return googleError(GMAIL_DRAFTS, 400, "message must be an object.");
|
|
2646
|
+
if (Object.keys(meta).some((k) => k !== "threadId")) return void 0;
|
|
2647
|
+
let index;
|
|
2648
|
+
if (id !== void 0) {
|
|
2649
|
+
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.");
|
|
2650
|
+
index = rowsIn(data, GMAIL_DRAFTS).findIndex((d) => d.id === id);
|
|
2651
|
+
if (index < 0) return googleError(GMAIL_DRAFTS, 404, "Requested entity was not found.");
|
|
2652
|
+
} else if (upload.metadata.id !== void 0) return void 0;
|
|
2653
|
+
const threadId = meta.threadId;
|
|
2654
|
+
return gmailDraftWrite(data, upload.raw, threadId === null ? void 0 : threadId, sequence, index);
|
|
2655
|
+
}
|
|
2656
|
+
if (path === GMAIL_THREADS) {
|
|
2657
|
+
if (method !== "GET" || Object.keys(params).some((k) => !["q", "maxResults", "labelIds"].includes(k))) return void 0;
|
|
2658
|
+
if (params.q !== void 0 && typeof params.q !== "string") return googleError(GMAIL_THREADS, 400, "q must be a string.");
|
|
2659
|
+
const matcher = params.q === void 0 || params.q === "" ? () => true : gmailQueryMatcher(params.q);
|
|
2660
|
+
if (!matcher) return void 0;
|
|
2661
|
+
const max = params.maxResults === void 0 ? 100 : Number(params.maxResults);
|
|
2662
|
+
if (!Number.isInteger(max) || max < 1 || max > 500) return googleError(GMAIL_THREADS, 400, "maxResults must be an integer from 1 to 500.");
|
|
2663
|
+
const labels = params.labelIds === void 0 ? [] : Array.isArray(params.labelIds) ? params.labelIds.map(String) : [String(params.labelIds)];
|
|
2664
|
+
const latest = /* @__PURE__ */ new Map();
|
|
2665
|
+
for (const message of rowsIn(data, MESSAGES)) {
|
|
2666
|
+
const ids = Array.isArray(message.labelIds) ? message.labelIds : [];
|
|
2667
|
+
if (ids.includes("SPAM") || ids.includes("TRASH") || !labels.every((l) => ids.includes(l)) || !matcher(message)) continue;
|
|
2668
|
+
const thread = String(message.threadId ?? message.id);
|
|
2669
|
+
if (!latest.has(thread) || gmailDate(message) > gmailDate(latest.get(thread))) latest.set(thread, message);
|
|
2670
|
+
}
|
|
2671
|
+
const threads = [...latest.entries()].sort((a, b) => gmailDate(b[1]) - gmailDate(a[1])).slice(0, max).map(([id]) => {
|
|
2672
|
+
const messages = gmailThreadMessages(data, id);
|
|
2673
|
+
return { id, snippet: messages.at(-1)?.snippet ?? "", historyId: gmailHistoryId(messages) };
|
|
2674
|
+
});
|
|
2675
|
+
return ok(GMAIL_THREADS, threads.length ? { threads, resultSizeEstimate: threads.length } : { resultSizeEstimate: 0 });
|
|
2676
|
+
}
|
|
2677
|
+
const threadMatch = /^\/gmail\/v1\/users\/me\/threads\/([^/]+)$/.exec(path);
|
|
2678
|
+
if (threadMatch) {
|
|
2679
|
+
if (method !== "GET" || Object.keys(params).some((k) => k !== "format") || params.format !== void 0 && params.format !== "full") return void 0;
|
|
2680
|
+
const messages = gmailThreadMessages(data, decodeURIComponent(threadMatch[1]));
|
|
2681
|
+
if (!messages.length) return googleError(GMAIL_THREADS, 404, "Requested entity was not found.");
|
|
2682
|
+
return ok(GMAIL_THREADS, { id: decodeURIComponent(threadMatch[1]), historyId: gmailHistoryId(messages), messages: structuredClone(messages) });
|
|
2683
|
+
}
|
|
2684
|
+
if (path === "/gmail/v1/users/me/history") {
|
|
2685
|
+
if (method !== "GET" || Object.keys(params).some((k) => !["startHistoryId", "historyTypes", "maxResults"].includes(k))) return void 0;
|
|
2686
|
+
if (params.historyTypes !== void 0 && !["messageAdded", "labelAdded", "labelRemoved"].includes(String(params.historyTypes))) return void 0;
|
|
2687
|
+
if (typeof params.startHistoryId !== "string" || !/^\d{1,20}$/.test(params.startHistoryId)) return googleError(MESSAGES, 400, "startHistoryId is required.");
|
|
2688
|
+
const max = params.maxResults === void 0 ? 100 : Number(params.maxResults);
|
|
2689
|
+
if (!Number.isInteger(max) || max < 1 || max > 500) return googleError(MESSAGES, 400, "maxResults must be an integer from 1 to 500.");
|
|
2690
|
+
const start = BigInt(params.startHistoryId);
|
|
2691
|
+
const all = rowsIn(data, MESSAGES);
|
|
2692
|
+
const added = all.filter((m) => BigInt(String(m.historyId ?? 0)) > start).sort((a, b) => BigInt(String(a.historyId)) < BigInt(String(b.historyId)) ? -1 : 1);
|
|
2693
|
+
if (added.length > max) return void 0;
|
|
2694
|
+
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 ?? []) } }] }));
|
|
2695
|
+
const latest = gmailHistoryId(all);
|
|
2696
|
+
return ok(MESSAGES, { ...history.length ? { history } : {}, historyId: BigInt(latest) > start ? latest : params.startHistoryId });
|
|
2697
|
+
}
|
|
2698
|
+
if (path === GMAIL_SEND_AS) {
|
|
2699
|
+
if (method !== "GET" || Object.keys(params).length) return void 0;
|
|
2700
|
+
return ok(GMAIL_SEND_AS, { sendAs: rowsIn(data, GMAIL_SEND_AS).map((row) => structuredClone(row)) });
|
|
2701
|
+
}
|
|
2702
|
+
if (path === GMAIL_WATCH) {
|
|
2703
|
+
if (method !== "POST" || Object.keys(params).some((k) => !["topicName", "labelIds", "labelFilterBehavior", "labelFilterAction"].includes(k))) return void 0;
|
|
2704
|
+
if (typeof params.topicName !== "string" || !/^projects\/[^/]+\/topics\/[^/]+$/.test(params.topicName)) return googleError(GMAIL_WATCH, 400, "Invalid topicName: expected projects/<project>/topics/<topic>.");
|
|
2705
|
+
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.");
|
|
2706
|
+
const behavior = params.labelFilterBehavior ?? params.labelFilterAction;
|
|
2707
|
+
if (behavior !== void 0 && !["include", "exclude"].includes(String(behavior))) return googleError(GMAIL_WATCH, 400, "Invalid labelFilterBehavior.");
|
|
2708
|
+
const known2 = gmailLabelKnown(data);
|
|
2709
|
+
const labelIds = params.labelIds ?? [];
|
|
2710
|
+
if (labelIds.some((l) => !known2(l))) return googleError(GMAIL_WATCH, 400, "Invalid label in labelIds.");
|
|
2711
|
+
const historyId = gmailHistoryId(rowsIn(data, GMAIL_MESSAGES));
|
|
2712
|
+
const expiration = String(twinNowMs(17e11) + 7 * 24 * 60 * 60 * 1e3);
|
|
2713
|
+
const watch = { topicName: params.topicName, labelIds, labelFilterBehavior: behavior ?? "include", historyId, expiration };
|
|
2714
|
+
rowsIn(data, GMAIL_WATCH).splice(0, Infinity, watch);
|
|
2715
|
+
return write(200, GMAIL_WATCH, { historyId, expiration }, watch);
|
|
2716
|
+
}
|
|
2717
|
+
if (path === "/gmail/v1/users/me/stop") {
|
|
2718
|
+
if (method !== "POST" || Object.keys(params).length) return void 0;
|
|
2719
|
+
const watches = rowsIn(data, GMAIL_WATCH), removed = watches.splice(0, Infinity);
|
|
2720
|
+
return { status: 204, body: null, collection: GMAIL_WATCH, record: { stopped: removed.length }, operation: "write" };
|
|
2721
|
+
}
|
|
2722
|
+
if (path === `${GMAIL_DRAFTS}/send`) {
|
|
2723
|
+
if (method !== "POST" || Object.keys(params).some((k) => !["id", "message"].includes(k))) return void 0;
|
|
2724
|
+
const sendFail = (status, message2) => googleError(GMAIL_DRAFTS, status, message2);
|
|
2725
|
+
if (typeof params.id !== "string" || !params.id) return sendFail(400, "Draft id is required.");
|
|
2726
|
+
const drafts = rowsIn(data, GMAIL_DRAFTS), index = drafts.findIndex((d) => d.id === params.id);
|
|
2727
|
+
if (index < 0) return sendFail(404, "Requested entity was not found.");
|
|
2728
|
+
const messages = rowsIn(data, MESSAGES), draft = drafts[index];
|
|
2729
|
+
const message = messages.find((m) => m.id === draft.message.id);
|
|
2730
|
+
if (!message) return sendFail(404, "Requested entity was not found.");
|
|
2731
|
+
let update;
|
|
2732
|
+
if (params.message !== void 0) {
|
|
2733
|
+
if (!params.message || typeof params.message !== "object" || Array.isArray(params.message)) return sendFail(400, "message must be an object.");
|
|
2734
|
+
const fields = params.message;
|
|
2735
|
+
if (Object.keys(fields).some((k) => !["raw", "threadId"].includes(k))) return void 0;
|
|
2736
|
+
if (fields.threadId !== void 0 && fields.threadId !== message.threadId) return void 0;
|
|
2737
|
+
if (fields.raw !== void 0) {
|
|
2738
|
+
if (typeof fields.raw !== "string" || !fields.raw) return sendFail(400, "message.raw must be a base64url MIME string.");
|
|
2739
|
+
const mime = parseGmailDraftRaw(fields.raw);
|
|
2740
|
+
if ("error" in mime) return mime.unsupported ? void 0 : sendFail(400, mime.error);
|
|
2741
|
+
update = { payload: mime.payload, snippet: mime.snippet, bytes: mime.bytes };
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
2744
|
+
const payload = update?.payload ?? message.payload;
|
|
2745
|
+
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.");
|
|
2746
|
+
drafts.splice(index, 1);
|
|
2747
|
+
Object.assign(message, update ? { payload: update.payload, snippet: update.snippet, sizeEstimate: update.bytes } : {}, { labelIds: ["SENT"], internalDate: String(twinNowMs(17e11)), historyId: String(17e8 + sequence) });
|
|
2748
|
+
return withPush(write(200, MESSAGES, { id: message.id, threadId: message.threadId, labelIds: ["SENT"] }, { ...structuredClone(message), sentFromDraft: draft.id }), gmailPublish(data, ["SENT"], sequence));
|
|
2749
|
+
}
|
|
2750
|
+
const draftMatch = /^\/gmail\/v1\/users\/me\/drafts\/([^/]+)$/.exec(path);
|
|
2751
|
+
if (draftMatch) {
|
|
2752
|
+
const id = decodeURIComponent(draftMatch[1]);
|
|
2753
|
+
const drafts = rowsIn(data, GMAIL_DRAFTS), index = drafts.findIndex((d) => d.id === id);
|
|
2754
|
+
if (method === "GET") {
|
|
2755
|
+
if (Object.keys(params).some((k) => k !== "format") || params.format !== void 0 && params.format !== "full") return void 0;
|
|
2756
|
+
if (index < 0) return googleError(GMAIL_DRAFTS, 404, "Requested entity was not found.");
|
|
2757
|
+
const draft = drafts[index], message = rowsIn(data, MESSAGES).find((m) => m.id === draft.message.id);
|
|
2758
|
+
return ok(GMAIL_DRAFTS, { id, message: structuredClone(message ?? draft.message) });
|
|
2759
|
+
}
|
|
2760
|
+
if (method === "PUT") {
|
|
2761
|
+
if (Object.keys(params).some((k) => !["id", "message"].includes(k))) return void 0;
|
|
2762
|
+
if (index < 0) return googleError(GMAIL_DRAFTS, 404, "Requested entity was not found.");
|
|
2763
|
+
if (params.id !== void 0 && params.id !== id) return googleError(GMAIL_DRAFTS, 400, "Draft id in the body does not match the URL.");
|
|
2764
|
+
const input = params.message;
|
|
2765
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return googleError(GMAIL_DRAFTS, 400, "Draft message is required.");
|
|
2766
|
+
const fields = input;
|
|
2767
|
+
if (Object.keys(fields).some((k) => !["raw", "threadId"].includes(k))) return void 0;
|
|
2768
|
+
return gmailDraftWrite(data, fields.raw, fields.threadId, sequence, index);
|
|
2769
|
+
}
|
|
2770
|
+
if (method === "DELETE") {
|
|
2771
|
+
if (Object.keys(params).length) return void 0;
|
|
2772
|
+
if (index < 0) return googleError(GMAIL_DRAFTS, 404, "Requested entity was not found.");
|
|
2773
|
+
const [removed] = drafts.splice(index, 1);
|
|
2774
|
+
const messages = rowsIn(data, MESSAGES), messageIndex = messages.findIndex((m) => m.id === removed.message.id);
|
|
2775
|
+
if (messageIndex >= 0) messages.splice(messageIndex, 1);
|
|
2776
|
+
return { status: 204, body: null, collection: GMAIL_DRAFTS, record: { id, deleted: true, threadId: removed.threadId ?? null }, operation: "write" };
|
|
2777
|
+
}
|
|
2778
|
+
return void 0;
|
|
2779
|
+
}
|
|
2780
|
+
if (path === GMAIL_DRAFTS && method === "GET") {
|
|
2781
|
+
if (Object.keys(params).some((k) => k !== "maxResults")) return void 0;
|
|
2782
|
+
const max = params.maxResults === void 0 ? 100 : Number(params.maxResults);
|
|
2783
|
+
if (!Number.isInteger(max) || max < 1 || max > 500) return googleError(GMAIL_DRAFTS, 400, "maxResults must be an integer from 1 to 500.");
|
|
2784
|
+
const drafts = rowsIn(data, GMAIL_DRAFTS).slice(-max).reverse().map((d) => {
|
|
2785
|
+
const m = d.message;
|
|
2786
|
+
return { id: d.id, message: { id: m.id, threadId: m.threadId } };
|
|
2787
|
+
});
|
|
2788
|
+
return ok(GMAIL_DRAFTS, drafts.length ? { drafts, resultSizeEstimate: drafts.length } : { resultSizeEstimate: 0 });
|
|
2789
|
+
}
|
|
2790
|
+
if (path === GMAIL_DRAFTS) {
|
|
2791
|
+
if (method !== "POST" || Object.keys(params).some((k) => k !== "message")) return void 0;
|
|
2792
|
+
const input = params.message;
|
|
2793
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return googleError(GMAIL_DRAFTS, 400, "Draft message is required.");
|
|
2794
|
+
const fields = input;
|
|
2795
|
+
if (Object.keys(fields).some((k) => !["raw", "threadId"].includes(k))) return void 0;
|
|
2796
|
+
return gmailDraftWrite(data, fields.raw, fields.threadId, sequence);
|
|
2797
|
+
}
|
|
1049
2798
|
if (path === `${MESSAGES}/send`) {
|
|
1050
2799
|
if (method !== "POST") return void 0;
|
|
1051
2800
|
if (Object.keys(params).some((k) => !["raw", "to", "subject", "text", "threadId"].includes(k))) return void 0;
|
|
1052
|
-
const
|
|
1053
|
-
if (params.raw !== void 0 &&
|
|
1054
|
-
if (params.text !== void 0 &&
|
|
1055
|
-
if (!
|
|
1056
|
-
if (params.text !== void 0 &&
|
|
2801
|
+
const text2 = str(params.text), raw2 = str(params.raw);
|
|
2802
|
+
if (params.raw !== void 0 && raw2 === void 0) return fail(400, "raw must be a string.");
|
|
2803
|
+
if (params.text !== void 0 && text2 === void 0) return fail(400, "text must be a string.");
|
|
2804
|
+
if (!text2 && !raw2) return fail(400, "Message body is required: provide `text` or a `raw` MIME string.");
|
|
2805
|
+
if (params.text !== void 0 && text2 === "") return fail(400, "Message text must not be empty.");
|
|
1057
2806
|
if (params.to !== void 0 && str(params.to) === void 0) return fail(400, "to must be a string.");
|
|
1058
2807
|
if (params.subject !== void 0 && str(params.subject) === void 0) return fail(400, "subject must be a string.");
|
|
1059
2808
|
if (params.threadId !== void 0 && str(params.threadId) === void 0) return fail(400, "threadId must be a string.");
|
|
1060
|
-
if (
|
|
1061
|
-
const mime =
|
|
2809
|
+
if (raw2 && text2 !== void 0) return fail(400, "Provide raw or text, not both.");
|
|
2810
|
+
const mime = raw2 ? parseGmailRaw(raw2) : void 0;
|
|
1062
2811
|
if (mime && "error" in mime) return mime.unsupported ? void 0 : fail(400, mime.error);
|
|
1063
|
-
const body = mime?.text ??
|
|
2812
|
+
const body = mime?.text ?? text2 ?? "";
|
|
1064
2813
|
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) };
|
|
1065
2814
|
rowsIn(data, MESSAGES).push(message);
|
|
1066
|
-
return write(200, MESSAGES, structuredClone(message), message);
|
|
2815
|
+
return withPush(write(200, MESSAGES, structuredClone(message), message), gmailPublish(data, ["SENT"], sequence));
|
|
2816
|
+
}
|
|
2817
|
+
if (path === MESSAGES && method === "POST") {
|
|
2818
|
+
if (Object.keys(params).some((k) => !["raw", "labelIds", "threadId", "internalDateSource"].includes(k))) return void 0;
|
|
2819
|
+
if (typeof params.raw !== "string" || !params.raw) return fail(400, "raw must be a base64url MIME string.");
|
|
2820
|
+
if (params.threadId !== void 0 && (typeof params.threadId !== "string" || !gmailThreadMessages(data, params.threadId).length)) return fail(404, "Requested entity was not found.");
|
|
2821
|
+
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.");
|
|
2822
|
+
const known2 = gmailLabelKnown(data);
|
|
2823
|
+
const labelIds = params.labelIds ?? [];
|
|
2824
|
+
if (labelIds.some((l) => !known2(l))) return fail(400, "Invalid label in labelIds.");
|
|
2825
|
+
if (params.internalDateSource !== void 0 && !["receivedTime", "dateHeader"].includes(String(params.internalDateSource))) return fail(400, "Invalid internalDateSource.");
|
|
2826
|
+
const mime = parseGmailDraftRaw(params.raw);
|
|
2827
|
+
if ("error" in mime) return mime.unsupported ? void 0 : fail(400, mime.error);
|
|
2828
|
+
let internalDate = twinNowMs(17e11);
|
|
2829
|
+
if (params.internalDateSource === "dateHeader") {
|
|
2830
|
+
const date = Date.parse(mime.headers.find((h) => h.name.toLowerCase() === "date")?.value ?? "");
|
|
2831
|
+
if (!Number.isFinite(date)) return fail(400, "internalDateSource dateHeader needs a valid Date header.");
|
|
2832
|
+
internalDate = date;
|
|
2833
|
+
}
|
|
2834
|
+
const id = `gmail_insert_at_${sequence}`;
|
|
2835
|
+
const message = { id, threadId: params.threadId ?? id, labelIds, snippet: mime.snippet, payload: mime.payload, sizeEstimate: mime.bytes, internalDate: String(internalDate), historyId: String(17e8 + sequence) };
|
|
2836
|
+
rowsIn(data, MESSAGES).push(message);
|
|
2837
|
+
return withPush(write(200, MESSAGES, { id, threadId: message.threadId, labelIds }, message), gmailPublish(data, labelIds, sequence));
|
|
1067
2838
|
}
|
|
1068
2839
|
if (path === MESSAGES) {
|
|
1069
2840
|
if (method !== "GET") return void 0;
|
|
@@ -1352,9 +3123,9 @@ function twilioOperation(method, path, params, _headers, data, sequence) {
|
|
|
1352
3123
|
if (missing.length) return fail(400, missing.length === allowed.length ? "21211" : "21606", `No parameter provided for ${allowed.filter((k) => missing.includes(k)).join(", ")}`);
|
|
1353
3124
|
const prefix = resource === "Messages" ? "SM" : "CA";
|
|
1354
3125
|
const sid = `${prefix}${sha(`${prefix.toLowerCase()}:${sequence}:${accountSid}`).slice(0, 32)}`;
|
|
1355
|
-
const
|
|
1356
|
-
records.push(
|
|
1357
|
-
return created(collection, structuredClone(
|
|
3126
|
+
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` };
|
|
3127
|
+
records.push(record3);
|
|
3128
|
+
return created(collection, structuredClone(record3), record3);
|
|
1358
3129
|
}
|
|
1359
3130
|
if (method === "GET") {
|
|
1360
3131
|
if (Object.keys(params).some((k) => !["To", "From"].includes(k))) return void 0;
|
|
@@ -1416,7 +3187,7 @@ function zendeskOperation(method, path, params, _headers, data, sequence) {
|
|
|
1416
3187
|
function restUnsupportedBody(adapter) {
|
|
1417
3188
|
return UNSUPPORTED_BODIES[adapter];
|
|
1418
3189
|
}
|
|
1419
|
-
var EPOCH, iso, sha, detUuid, rows, notFound, badRequest, ok, created, write, isObject, str, pagination, uniqueId, boundedInt, notionPropValue, notionPage, notionError, hubspotEnvelope, SHOPIFY_VERSION, shopifySlug, googleError, rowsIn, JIRA_TRANSITIONS, discordError, ZENDESK_STATUSES, UNSUPPORTED_BODIES, REST_ADAPTERS, REST_ADAPTER_NAMES;
|
|
3190
|
+
var EPOCH, iso, sha, detUuid, rows, notFound, badRequest, ok, created, write, isObject, str, pagination, uniqueId, boundedInt, notionPropValue, notionPage, notionError, hubspotEnvelope, SHOPIFY_VERSION, shopifySlug, googleError, rowsIn, GMAIL_MESSAGES, GMAIL_THREADS, GMAIL_DRAFTS, GMAIL_SEND_AS, GMAIL_WATCH, PUBSUB_SUBSCRIPTIONS, PUBSUB_MESSAGES, gmailHeader, gmailDate, gmailThreadMessages, GMAIL_SYSTEM_LABELS, gmailLabelKnown, gmailHistoryId, withPush, JIRA_TRANSITIONS, discordError, ZENDESK_STATUSES, UNSUPPORTED_BODIES, REST_ADAPTERS, REST_ADAPTER_NAMES;
|
|
1420
3191
|
var init_rest_adapters = __esm({
|
|
1421
3192
|
"src/runtime/rest-adapters.ts"() {
|
|
1422
3193
|
"use strict";
|
|
@@ -1424,6 +3195,7 @@ var init_rest_adapters = __esm({
|
|
|
1424
3195
|
init_llm_adapter();
|
|
1425
3196
|
init_composio_twin();
|
|
1426
3197
|
init_google_oauth_twin();
|
|
3198
|
+
init_upstash_redis_twin();
|
|
1427
3199
|
init_gmail_mime();
|
|
1428
3200
|
EPOCH = 17e8;
|
|
1429
3201
|
iso = (epoch = EPOCH) => new Date(twinNowMs(epoch * 1e3)).toISOString();
|
|
@@ -1439,8 +3211,8 @@ var init_rest_adapters = __esm({
|
|
|
1439
3211
|
notFound = (collection, body) => ({ status: 404, body, collection });
|
|
1440
3212
|
badRequest = (collection, body) => ({ status: 400, body, collection });
|
|
1441
3213
|
ok = (collection, body, operation = "read") => ({ status: 200, body, collection, operation });
|
|
1442
|
-
created = (collection, body,
|
|
1443
|
-
write = (status, collection, body,
|
|
3214
|
+
created = (collection, body, record3) => ({ status: 201, body, collection, record: structuredClone(record3), operation: "write" });
|
|
3215
|
+
write = (status, collection, body, record3) => ({ status, body, collection, record: structuredClone(record3), operation: "write" });
|
|
1444
3216
|
isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
1445
3217
|
str = (v) => typeof v === "string" ? v : void 0;
|
|
1446
3218
|
pagination = (params, limitDefault, limitMax) => {
|
|
@@ -1468,11 +3240,28 @@ var init_rest_adapters = __esm({
|
|
|
1468
3240
|
};
|
|
1469
3241
|
notionPage = (id, parent, properties, archived = false) => ({ object: "page", id, created_time: iso(), last_edited_time: iso(), created_by: null, last_edited_by: null, cover: null, icon: null, parent, archived, properties, url: null });
|
|
1470
3242
|
notionError = (collection, status, code, message) => ({ status, body: { object: "error", status, code, message }, collection });
|
|
1471
|
-
hubspotEnvelope = (
|
|
3243
|
+
hubspotEnvelope = (record3) => ({ id: record3.id, properties: structuredClone(record3.properties), createdAt: record3.createdAt, updatedAt: record3.updatedAt, archived: false });
|
|
1472
3244
|
SHOPIFY_VERSION = "2024-01";
|
|
1473
3245
|
shopifySlug = (value) => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
1474
3246
|
googleError = (collection, status, message) => ({ status, body: { error: { code: status, message, status: status === 404 ? "NOT_FOUND" : "INVALID_ARGUMENT" } }, collection });
|
|
1475
3247
|
rowsIn = (data, collection) => data[collection];
|
|
3248
|
+
GMAIL_MESSAGES = "/gmail/v1/users/me/messages";
|
|
3249
|
+
GMAIL_THREADS = "/gmail/v1/users/me/threads";
|
|
3250
|
+
GMAIL_DRAFTS = "/gmail/v1/users/me/drafts";
|
|
3251
|
+
GMAIL_SEND_AS = "/gmail/v1/users/me/settings/sendAs";
|
|
3252
|
+
GMAIL_WATCH = "/gmail/v1/users/me/watch";
|
|
3253
|
+
PUBSUB_SUBSCRIPTIONS = "/pubsub/subscriptions";
|
|
3254
|
+
PUBSUB_MESSAGES = "/pubsub/messages";
|
|
3255
|
+
gmailHeader = (message, name) => (message.payload?.headers ?? []).find((h) => h.name.toLowerCase() === name)?.value;
|
|
3256
|
+
gmailDate = (message) => Number(message.internalDate ?? 0);
|
|
3257
|
+
gmailThreadMessages = (data, threadId) => rowsIn(data, GMAIL_MESSAGES).filter((m) => m.threadId === threadId).sort((a, b) => gmailDate(a) - gmailDate(b));
|
|
3258
|
+
GMAIL_SYSTEM_LABELS = /* @__PURE__ */ new Set(["INBOX", "SPAM", "TRASH", "UNREAD", "STARRED", "IMPORTANT", "SENT", "DRAFT", "CATEGORY_PERSONAL", "CATEGORY_SOCIAL", "CATEGORY_PROMOTIONS", "CATEGORY_UPDATES", "CATEGORY_FORUMS"]);
|
|
3259
|
+
gmailLabelKnown = (data) => {
|
|
3260
|
+
const seeded = new Set(rowsIn(data, "/gmail/v1/users/me/labels").map((l) => l.id));
|
|
3261
|
+
return (id) => GMAIL_SYSTEM_LABELS.has(id) || seeded.has(id);
|
|
3262
|
+
};
|
|
3263
|
+
gmailHistoryId = (messages) => messages.reduce((max, m) => BigInt(String(m.historyId ?? 0)) > BigInt(max) ? String(m.historyId) : max, "0");
|
|
3264
|
+
withPush = (result, deliveries) => deliveries.length ? { ...result, deliveries } : result;
|
|
1476
3265
|
JIRA_TRANSITIONS = { "11": "To Do", "21": "In Progress", "31": "Done" };
|
|
1477
3266
|
discordError = (collection, code, message) => ({ status: code === 10003 || code === 10004 ? 404 : 400, body: { message, code }, collection });
|
|
1478
3267
|
ZENDESK_STATUSES = ["new", "open", "pending", "solved", "closed"];
|
|
@@ -1493,7 +3282,8 @@ var init_rest_adapters = __esm({
|
|
|
1493
3282
|
"google-oauth": { error: "unsupported_operation", error_description: "Outside the AgentTwin Google OAuth refresh subset", forwardedToProduction: false },
|
|
1494
3283
|
openai: { error: { type: "invalid_request_error", code: "unsupported_operation", message: "Outside the AgentTwin scripted OpenAI subset, or no scripted response is left" }, forwardedToProduction: false },
|
|
1495
3284
|
anthropic: { type: "error", error: { type: "invalid_request_error", message: "Outside the AgentTwin scripted Anthropic subset, or no scripted response is left" }, forwardedToProduction: false },
|
|
1496
|
-
zendesk: { error: "UnsupportedOperation", description: "Outside the verified AgentTwin Zendesk twin subset", forwardedToProduction: false }
|
|
3285
|
+
zendesk: { error: "UnsupportedOperation", description: "Outside the verified AgentTwin Zendesk twin subset", forwardedToProduction: false },
|
|
3286
|
+
"upstash-redis": { error: "ERR outside the verified AgentTwin Upstash Redis twin subset", forwardedToProduction: false }
|
|
1497
3287
|
};
|
|
1498
3288
|
REST_ADAPTERS = {
|
|
1499
3289
|
openai: openaiOperation,
|
|
@@ -1512,7 +3302,8 @@ var init_rest_adapters = __esm({
|
|
|
1512
3302
|
twilio: twilioOperation,
|
|
1513
3303
|
zendesk: zendeskOperation,
|
|
1514
3304
|
"google-oauth": googleOAuthOperation,
|
|
1515
|
-
composio: composioOperation
|
|
3305
|
+
composio: composioOperation,
|
|
3306
|
+
"upstash-redis": upstashRedisOperation
|
|
1516
3307
|
};
|
|
1517
3308
|
REST_ADAPTER_NAMES = Object.keys(REST_ADAPTERS);
|
|
1518
3309
|
}
|
|
@@ -1522,10 +3313,10 @@ var init_rest_adapters = __esm({
|
|
|
1522
3313
|
import { createHash as createHash3, randomBytes } from "crypto";
|
|
1523
3314
|
function normalizeSeed(seed) {
|
|
1524
3315
|
if (seed === void 0 || seed.trim() === "") return randomBytes(16).toString("hex");
|
|
1525
|
-
const
|
|
1526
|
-
if (!/^[a-f0-9]+$/.test(
|
|
1527
|
-
if (
|
|
1528
|
-
return createHash3("sha256").update(
|
|
3316
|
+
const text2 = normalizeHex(seed);
|
|
3317
|
+
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)}`);
|
|
3318
|
+
if (text2.length === 32) return text2;
|
|
3319
|
+
return createHash3("sha256").update(text2).digest("hex").slice(0, 32);
|
|
1529
3320
|
}
|
|
1530
3321
|
function faultOrdinals(selection, seed) {
|
|
1531
3322
|
const count = selection.type === "timeout-after-write" ? 1 : selection.count ?? 1;
|
|
@@ -1858,9 +3649,9 @@ function withParents(row, resource, op2, params) {
|
|
|
1858
3649
|
}
|
|
1859
3650
|
return out;
|
|
1860
3651
|
}
|
|
1861
|
-
function shape(op2, resource,
|
|
3652
|
+
function shape(op2, resource, record3, stream, sequence, params = {}) {
|
|
1862
3653
|
const r = op2.response;
|
|
1863
|
-
const out = withParents(
|
|
3654
|
+
const out = withParents(record3, resource, op2, params);
|
|
1864
3655
|
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;
|
|
1865
3656
|
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)));
|
|
1866
3657
|
if (!holder) return out;
|
|
@@ -1975,19 +3766,19 @@ function handleRest(twin, req, data, ctx) {
|
|
|
1975
3766
|
}
|
|
1976
3767
|
if (op2.kind === "create" || op2.kind === "upsert" && findRow(scoped, resource, id) < 0) {
|
|
1977
3768
|
if (rows2.length >= 1e4) return fail(429, "capacity", "Twin collection is full");
|
|
1978
|
-
const
|
|
1979
|
-
overlay(
|
|
3769
|
+
const record3 = materialize(resource.schema ?? op2.response, "create", stream, ctx.sequence) ?? {};
|
|
3770
|
+
overlay(record3, body, resource.schema, true);
|
|
1980
3771
|
const supplied = Object.keys(body).find((k) => normName(k) === normName(resource.idField));
|
|
1981
|
-
if (id !== void 0)
|
|
1982
|
-
else if (!supplied)
|
|
1983
|
-
else if (findRow(scoped, resource, String(
|
|
3772
|
+
if (id !== void 0) record3[resource.idField] = id;
|
|
3773
|
+
else if (!supplied) record3[resource.idField] = newId(resource, rows2, stream);
|
|
3774
|
+
else if (findRow(scoped, resource, String(record3[resource.idField])) >= 0) return fail(409, "conflict", `${resource.name} ${record3[resource.idField]} already exists`);
|
|
1984
3775
|
for (const p of op2.parentParams ?? []) {
|
|
1985
3776
|
const field = Object.keys(resource.schema?.properties ?? {}).find((k) => normName(k) === normName(p));
|
|
1986
|
-
if (field &&
|
|
1987
|
-
else if (!field)
|
|
3777
|
+
if (field && record3[field] === void 0) record3[field] = params[p];
|
|
3778
|
+
else if (!field) record3[parentKey(p)] = params[p];
|
|
1988
3779
|
}
|
|
1989
|
-
rows2.push(
|
|
1990
|
-
return { status: op2.kind === "upsert" ? op2.status || 200 : op2.status, body: shape(op2, resource,
|
|
3780
|
+
rows2.push(record3);
|
|
3781
|
+
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) };
|
|
1991
3782
|
}
|
|
1992
3783
|
const index = rows2.findIndex((r) => String(r[resource.idField]) === id && inScope(r, resource, params, op2));
|
|
1993
3784
|
if (index < 0) return { ...fail(404, "not_found", `No such ${singular(resource.name)}: ${id}`), operation: "read" };
|
|
@@ -2088,8 +3879,8 @@ function generatedAdapter(adapter) {
|
|
|
2088
3879
|
const m = matchOperation(twin, method, path);
|
|
2089
3880
|
return m ? m.op.resource : void 0;
|
|
2090
3881
|
})() : void 0,
|
|
2091
|
-
bodyMode: (
|
|
2092
|
-
const t = (
|
|
3882
|
+
bodyMode: (contentType2) => {
|
|
3883
|
+
const t = (contentType2 ?? "").toLowerCase();
|
|
2093
3884
|
return /json/.test(t) ? "json" : /x-www-form-urlencoded/.test(t) ? "form" : twin.protocol === "graphql" ? "json" : t || twin.protocol.startsWith("aws-rest") ? "raw" : "json";
|
|
2094
3885
|
}
|
|
2095
3886
|
};
|
|
@@ -2112,25 +3903,25 @@ var init_adapters = __esm({
|
|
|
2112
3903
|
|
|
2113
3904
|
// src/runtime/packs.ts
|
|
2114
3905
|
import { existsSync, readFileSync } from "fs";
|
|
2115
|
-
import { dirname, join as
|
|
3906
|
+
import { dirname, join as join4, resolve as resolve2 } from "path";
|
|
2116
3907
|
import { fileURLToPath, pathToFileURL } from "url";
|
|
2117
3908
|
function packsDir() {
|
|
2118
3909
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
2119
|
-
const candidates = [process.env.AGENTTWIN_TWINS_DIR,
|
|
2120
|
-
return candidates.find((dir) => !!dir && existsSync(
|
|
3910
|
+
const candidates = [process.env.AGENTTWIN_TWINS_DIR, join4(here, "twins"), join4(here, "../twins"), resolve2(here, "../../../twins/dist")];
|
|
3911
|
+
return candidates.find((dir) => !!dir && existsSync(join4(dir, "catalog.json")));
|
|
2121
3912
|
}
|
|
2122
3913
|
function packCatalog() {
|
|
2123
3914
|
if (cached !== void 0) return cached;
|
|
2124
3915
|
const dir = packsDir();
|
|
2125
|
-
cached = dir ? JSON.parse(readFileSync(
|
|
3916
|
+
cached = dir ? JSON.parse(readFileSync(join4(dir, "catalog.json"), "utf8")) : null;
|
|
2126
3917
|
return cached;
|
|
2127
3918
|
}
|
|
2128
3919
|
function loadPack(name) {
|
|
2129
|
-
const
|
|
2130
|
-
if (!
|
|
3920
|
+
const record3 = packRecord(name);
|
|
3921
|
+
if (!record3) throw new Error(`No twin pack named ${name}`);
|
|
2131
3922
|
let factory = loaded.get(name);
|
|
2132
3923
|
if (!factory) {
|
|
2133
|
-
const file =
|
|
3924
|
+
const file = join4(packsDir(), "packs", name, "index.mjs");
|
|
2134
3925
|
factory = import(pathToFileURL(file).href).then((mod) => {
|
|
2135
3926
|
if (typeof mod.createTwinFetch !== "function") throw new Error(`Twin pack ${name} exports no createTwinFetch`);
|
|
2136
3927
|
return mod.createTwinFetch;
|
|
@@ -2155,10 +3946,10 @@ var init_packs = __esm({
|
|
|
2155
3946
|
|
|
2156
3947
|
// src/runtime/enterprise-twins.ts
|
|
2157
3948
|
import { createHash as createHash4 } from "crypto";
|
|
2158
|
-
function eqFilter(expression,
|
|
3949
|
+
function eqFilter(expression, quote3) {
|
|
2159
3950
|
const parts = expression.split(/\s+and\s+/i), tests = [];
|
|
2160
3951
|
for (const part of parts) {
|
|
2161
|
-
const m = new RegExp(`^\\s*([\\w.]+)\\s+eq\\s+(?:${
|
|
3952
|
+
const m = new RegExp(`^\\s*([\\w.]+)\\s+eq\\s+(?:${quote3}([^${quote3}]*)${quote3}|(true|false|-?\\d+(?:\\.\\d+)?|null))\\s*$`, "i").exec(part);
|
|
2162
3953
|
if (!m) return null;
|
|
2163
3954
|
const value = m[2] !== void 0 ? m[2] : m[3] === "null" ? null : m[3] === "true" ? true : m[3] === "false" ? false : Number(m[3]);
|
|
2164
3955
|
tests.push((r) => {
|
|
@@ -2216,7 +4007,7 @@ var init_enterprise_twins = __esm({
|
|
|
2216
4007
|
scalar = (v) => v === null || ["string", "number", "boolean"].includes(typeof v);
|
|
2217
4008
|
flat = (v) => Object.values(v).every(scalar);
|
|
2218
4009
|
read = (collection, body, status = 200, headers) => ({ status, body, collection, operation: "read", ...headers ? { headers } : {} });
|
|
2219
|
-
write2 = (collection,
|
|
4010
|
+
write2 = (collection, record3, body, status = 200, headers) => ({ status, body, collection, record: structuredClone(record3), operation: "write", ...headers ? { headers } : {} });
|
|
2220
4011
|
table = (data, collection) => data[collection] ??= [];
|
|
2221
4012
|
limitOf = (value, fallback, max) => {
|
|
2222
4013
|
if (value === void 0) return fallback;
|
|
@@ -2262,22 +4053,22 @@ var init_enterprise_twins = __esm({
|
|
|
2262
4053
|
const missing = spec.required.filter((f) => body[f] === void 0 || body[f] === null || body[f] === "");
|
|
2263
4054
|
if (missing.length) return { ...sfError(400, "REQUIRED_FIELD_MISSING", `Required fields are missing: [${missing.join(", ")}]`, missing), collection };
|
|
2264
4055
|
const id = (spec.prefix + hash(`salesforce:${object4}:${sequence}:${rows2.length}`).slice(0, 12)).toUpperCase().replace(/^00Q/i, "00Q") + "AAA";
|
|
2265
|
-
const
|
|
2266
|
-
rows2.push(
|
|
2267
|
-
return write2(collection,
|
|
4056
|
+
const record4 = { Id: id, ...body, CreatedDate: iso2(sequence), LastModifiedDate: iso2(sequence), IsDeleted: false };
|
|
4057
|
+
rows2.push(record4);
|
|
4058
|
+
return write2(collection, record4, { id, success: true, errors: [] }, 201);
|
|
2268
4059
|
}
|
|
2269
4060
|
if (!s[2]) return;
|
|
2270
|
-
const
|
|
2271
|
-
if (!
|
|
2272
|
-
if (method === "GET") return read(collection, sfView(object4, version,
|
|
4061
|
+
const record3 = rows2.find((r) => r.Id === s[2] || String(r.Id).slice(0, 15) === s[2].slice(0, 15));
|
|
4062
|
+
if (!record3) return { ...sfError(404, "NOT_FOUND", "The requested resource does not exist"), collection };
|
|
4063
|
+
if (method === "GET") return read(collection, sfView(object4, version, record3));
|
|
2273
4064
|
if (method === "PATCH") {
|
|
2274
4065
|
if (!flat(body) || "Id" in body) return;
|
|
2275
|
-
Object.assign(
|
|
2276
|
-
return write2(collection,
|
|
4066
|
+
Object.assign(record3, body, { LastModifiedDate: iso2(sequence) });
|
|
4067
|
+
return write2(collection, record3, null, 204);
|
|
2277
4068
|
}
|
|
2278
4069
|
if (method === "DELETE") {
|
|
2279
|
-
rows2.splice(rows2.indexOf(
|
|
2280
|
-
return write2(collection, { ...
|
|
4070
|
+
rows2.splice(rows2.indexOf(record3), 1);
|
|
4071
|
+
return write2(collection, { ...record3, IsDeleted: true }, null, 204);
|
|
2281
4072
|
}
|
|
2282
4073
|
};
|
|
2283
4074
|
SN_TABLES = { incident: "INC", change_request: "CHG", problem: "PRB", sc_request: "REQ", sys_user: null };
|
|
@@ -2306,7 +4097,7 @@ var init_enterprise_twins = __esm({
|
|
|
2306
4097
|
if (!sysId && method === "POST") {
|
|
2307
4098
|
if (!flat(body) || "sys_id" in body) return;
|
|
2308
4099
|
const prefix = SN_TABLES[name];
|
|
2309
|
-
const
|
|
4100
|
+
const record4 = {
|
|
2310
4101
|
sys_id: hash(`servicenow:${name}:${sequence}:${rows2.length}`).slice(0, 32),
|
|
2311
4102
|
...prefix ? { number: `${prefix}${String(nextNumber(rows2, "number", 10001)).padStart(7, "0")}` } : {},
|
|
2312
4103
|
...name === "incident" ? { state: "1", impact: "3", urgency: "3", priority: "5" } : {},
|
|
@@ -2315,21 +4106,21 @@ var init_enterprise_twins = __esm({
|
|
|
2315
4106
|
sys_updated_on: snTime(sequence),
|
|
2316
4107
|
sys_mod_count: "0"
|
|
2317
4108
|
};
|
|
2318
|
-
rows2.push(
|
|
2319
|
-
return write2(collection,
|
|
4109
|
+
rows2.push(record4);
|
|
4110
|
+
return write2(collection, record4, { result: record4 }, 201);
|
|
2320
4111
|
}
|
|
2321
4112
|
if (!sysId) return;
|
|
2322
|
-
const
|
|
2323
|
-
if (!
|
|
2324
|
-
if (method === "GET") return read(collection, { result:
|
|
4113
|
+
const record3 = rows2.find((r) => r.sys_id === sysId);
|
|
4114
|
+
if (!record3) return { ...snError(404, "No Record found", "Record doesn't exist or ACL restricts the record retrieval"), collection };
|
|
4115
|
+
if (method === "GET") return read(collection, { result: record3 });
|
|
2325
4116
|
if (method === "PATCH" || method === "PUT") {
|
|
2326
4117
|
if (!flat(body) || "sys_id" in body || "number" in body) return;
|
|
2327
|
-
Object.assign(
|
|
2328
|
-
return write2(collection,
|
|
4118
|
+
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) });
|
|
4119
|
+
return write2(collection, record3, { result: record3 });
|
|
2329
4120
|
}
|
|
2330
4121
|
if (method === "DELETE") {
|
|
2331
|
-
rows2.splice(rows2.indexOf(
|
|
2332
|
-
return write2(collection,
|
|
4122
|
+
rows2.splice(rows2.indexOf(record3), 1);
|
|
4123
|
+
return write2(collection, record3, null, 204);
|
|
2333
4124
|
}
|
|
2334
4125
|
};
|
|
2335
4126
|
wdError = (status, error, errors = []) => ({ status, body: { error, errors } });
|
|
@@ -2358,7 +4149,7 @@ var init_enterprise_twins = __esm({
|
|
|
2358
4149
|
const taken = new Set(requests.filter((r) => r.worker?.id === workerId && r.status !== "Canceled").flatMap((r) => r.days.map((d) => d.date)));
|
|
2359
4150
|
const clash = days.find((d) => taken.has(d.date));
|
|
2360
4151
|
if (clash) return { ...wdError(400, "Validation error", [{ error: `Time off has already been requested for ${clash.date}.`, field: "days" }]), collection: "/timeOffRequests" };
|
|
2361
|
-
const
|
|
4152
|
+
const record3 = {
|
|
2362
4153
|
id: hash(`workday:timeoff:${sequence}:${requests.length}`).slice(0, 32),
|
|
2363
4154
|
descriptor: `Time Off Request: ${worker.descriptor}`,
|
|
2364
4155
|
worker: { id: workerId, descriptor: worker.descriptor },
|
|
@@ -2367,8 +4158,8 @@ var init_enterprise_twins = __esm({
|
|
|
2367
4158
|
businessProcessParameters: { overallStatus: "In Progress", comment: isObject2(body.businessProcessParameters) ? body.businessProcessParameters.comment ?? null : null },
|
|
2368
4159
|
createdOn: iso2(sequence)
|
|
2369
4160
|
};
|
|
2370
|
-
requests.push(
|
|
2371
|
-
return write2("/timeOffRequests",
|
|
4161
|
+
requests.push(record3);
|
|
4162
|
+
return write2("/timeOffRequests", record3, record3, 201);
|
|
2372
4163
|
}
|
|
2373
4164
|
};
|
|
2374
4165
|
SAP_SETS = { A_BusinessPartner: { service: "API_BUSINESS_PARTNER", key: "BusinessPartner" }, A_SalesOrder: { service: "API_SALES_ORDER_SRV", key: "SalesOrder" } };
|
|
@@ -2381,8 +4172,8 @@ var init_enterprise_twins = __esm({
|
|
|
2381
4172
|
if (method === "GET") {
|
|
2382
4173
|
const issued = header2(headers, "x-csrf-token")?.toLowerCase() === "fetch" ? { "x-csrf-token": csrf } : void 0;
|
|
2383
4174
|
if (key2) {
|
|
2384
|
-
const
|
|
2385
|
-
return
|
|
4175
|
+
const record4 = rows2.find((r) => r[SAP_SETS[set].key] === key2);
|
|
4176
|
+
return record4 ? read(collection, { d: sapView(set, record4) }, 200, issued) : { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection };
|
|
2386
4177
|
}
|
|
2387
4178
|
const where = query.$filter ? eqFilter(query.$filter, "'") : () => true;
|
|
2388
4179
|
const top = limitOf(query.$top, 1e3, 5e3), skip = Number(query.$skip ?? 0);
|
|
@@ -2393,16 +4184,16 @@ var init_enterprise_twins = __esm({
|
|
|
2393
4184
|
if (method === "POST" && !key2) {
|
|
2394
4185
|
if (set === "A_BusinessPartner") {
|
|
2395
4186
|
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 };
|
|
2396
|
-
const
|
|
2397
|
-
rows2.push(
|
|
2398
|
-
return write2(collection,
|
|
4187
|
+
const record5 = { BusinessPartner: String(nextNumber(rows2, "BusinessPartner", 10000001)), ...body, CreationDate: `/Date(${twinNowMs((EPOCH2 + sequence) * 1e3)})/`, BusinessPartnerIsBlocked: false };
|
|
4188
|
+
rows2.push(record5);
|
|
4189
|
+
return write2(collection, record5, { d: sapView(set, record5) }, 201);
|
|
2399
4190
|
}
|
|
2400
4191
|
const items = isObject2(body.to_Item) && Array.isArray(body.to_Item.results) ? body.to_Item.results : null;
|
|
2401
4192
|
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 };
|
|
2402
4193
|
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 };
|
|
2403
4194
|
const total = items.reduce((sum, i) => sum + Number(i.NetAmount ?? 0), 0);
|
|
2404
4195
|
const { to_Item: _items, ...header_ } = body;
|
|
2405
|
-
const
|
|
4196
|
+
const record4 = {
|
|
2406
4197
|
SalesOrder: String(nextNumber(rows2, "SalesOrder", 1)).padStart(10, "0"),
|
|
2407
4198
|
...header_,
|
|
2408
4199
|
TransactionCurrency: body.TransactionCurrency ?? "USD",
|
|
@@ -2411,15 +4202,15 @@ var init_enterprise_twins = __esm({
|
|
|
2411
4202
|
CreationDate: `/Date(${twinNowMs((EPOCH2 + sequence) * 1e3)})/`,
|
|
2412
4203
|
to_Item: { results: items.map((i, n) => ({ SalesOrderItem: String((n + 1) * 10), ...i })) }
|
|
2413
4204
|
};
|
|
2414
|
-
rows2.push(
|
|
2415
|
-
return write2(collection,
|
|
4205
|
+
rows2.push(record4);
|
|
4206
|
+
return write2(collection, record4, { d: sapView(set, record4) }, 201);
|
|
2416
4207
|
}
|
|
2417
|
-
const
|
|
2418
|
-
if (!
|
|
4208
|
+
const record3 = key2 ? rows2.find((r) => r[SAP_SETS[set].key] === key2) : void 0;
|
|
4209
|
+
if (!record3) return key2 ? { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection } : void 0;
|
|
2419
4210
|
if (method === "PATCH" || method === "MERGE") {
|
|
2420
4211
|
if (!flat(body) || SAP_SETS[set].key in body) return;
|
|
2421
|
-
Object.assign(
|
|
2422
|
-
return write2(collection,
|
|
4212
|
+
Object.assign(record3, body);
|
|
4213
|
+
return write2(collection, record3, null, 204);
|
|
2423
4214
|
}
|
|
2424
4215
|
};
|
|
2425
4216
|
graphError = (status, code, message, sequence) => ({ status, body: { error: { code, message, innerError: { date: iso2(sequence), "request-id": hash(`graph:${sequence}:${code}`).slice(0, 36) } } } });
|
|
@@ -2450,7 +4241,7 @@ var init_enterprise_twins = __esm({
|
|
|
2450
4241
|
if (!isObject2(body.body) || typeof body.body.content !== "string" || !body.body.content.trim()) return { ...graphError(400, "BadRequest", "Missing body content", sequence), collection: "/messages" };
|
|
2451
4242
|
if (body.body.contentType !== void 0 && !["text", "html"].includes(body.body.contentType)) return;
|
|
2452
4243
|
if (parentId && !messages.some((r) => scope(r) && r.id === parentId)) return { ...graphError(404, "NotFound", "Resource not found", sequence), collection: "/messages" };
|
|
2453
|
-
const
|
|
4244
|
+
const record3 = {
|
|
2454
4245
|
id: String(twinNowMs((EPOCH2 + sequence) * 1e3) + messages.length),
|
|
2455
4246
|
replyToId: parentId ?? null,
|
|
2456
4247
|
messageType: "message",
|
|
@@ -2464,8 +4255,8 @@ var init_enterprise_twins = __esm({
|
|
|
2464
4255
|
attachments: [],
|
|
2465
4256
|
mentions: []
|
|
2466
4257
|
};
|
|
2467
|
-
messages.push(
|
|
2468
|
-
return write2("/messages",
|
|
4258
|
+
messages.push(record3);
|
|
4259
|
+
return write2("/messages", record3, record3, 201);
|
|
2469
4260
|
};
|
|
2470
4261
|
address = (r) => isObject2(r) && isObject2(r.emailAddress) && typeof r.emailAddress.address === "string" && /^[^@\s]+@[^@\s]+$/.test(r.emailAddress.address);
|
|
2471
4262
|
outlook = (method, path, body, query, _headers, data, sequence) => {
|
|
@@ -2473,7 +4264,7 @@ var init_enterprise_twins = __esm({
|
|
|
2473
4264
|
if (!m) return;
|
|
2474
4265
|
const messages = table(data, "/messages"), [, route, folder, id, reply] = m;
|
|
2475
4266
|
const store = (message, parentFolderId) => {
|
|
2476
|
-
const
|
|
4267
|
+
const record4 = {
|
|
2477
4268
|
id: Buffer.from(hash(`outlook:${sequence}:${messages.length}`).slice(0, 30)).toString("base64url"),
|
|
2478
4269
|
createdDateTime: iso2(sequence),
|
|
2479
4270
|
sentDateTime: iso2(sequence),
|
|
@@ -2489,8 +4280,8 @@ var init_enterprise_twins = __esm({
|
|
|
2489
4280
|
parentFolderId,
|
|
2490
4281
|
conversationId: message.conversationId ?? graphId(`conv:${sequence}`)
|
|
2491
4282
|
};
|
|
2492
|
-
messages.push(
|
|
2493
|
-
return
|
|
4283
|
+
messages.push(record4);
|
|
4284
|
+
return record4;
|
|
2494
4285
|
};
|
|
2495
4286
|
if (route === "sendMail" && method === "POST") {
|
|
2496
4287
|
const message = body.message;
|
|
@@ -2504,17 +4295,17 @@ var init_enterprise_twins = __esm({
|
|
|
2504
4295
|
const page = graphPage(messages.filter((r) => !folder || r.parentFolderId === folder), query);
|
|
2505
4296
|
return page ? read("/messages", { value: page }) : void 0;
|
|
2506
4297
|
}
|
|
2507
|
-
const
|
|
2508
|
-
if (!
|
|
2509
|
-
if (!reply && method === "GET") return read("/messages",
|
|
4298
|
+
const record3 = id ? messages.find((r) => r.id === id) : void 0;
|
|
4299
|
+
if (!record3) return id ? { ...graphError(404, "ErrorItemNotFound", "The specified object was not found in the store.", sequence), collection: "/messages" } : void 0;
|
|
4300
|
+
if (!reply && method === "GET") return read("/messages", record3);
|
|
2510
4301
|
if (!reply && method === "PATCH") {
|
|
2511
4302
|
if (Object.keys(body).some((k) => !["isRead", "categories", "importance", "flag"].includes(k))) return;
|
|
2512
|
-
Object.assign(
|
|
2513
|
-
return write2("/messages",
|
|
4303
|
+
Object.assign(record3, body);
|
|
4304
|
+
return write2("/messages", record3, record3);
|
|
2514
4305
|
}
|
|
2515
4306
|
if (reply && method === "POST") {
|
|
2516
|
-
const to =
|
|
2517
|
-
return write2("/messages", store({ subject: `RE: ${
|
|
4307
|
+
const to = record3.parentFolderId === "sentitems" ? record3.toRecipients : [record3.from];
|
|
4308
|
+
return write2("/messages", store({ subject: `RE: ${record3.subject}`, body: { contentType: "text", content: String(body.comment ?? "") }, toRecipients: to, conversationId: record3.conversationId }, "sentitems"), null, 202);
|
|
2518
4309
|
}
|
|
2519
4310
|
};
|
|
2520
4311
|
entra = (method, path, body, query, _headers, data, sequence) => {
|
|
@@ -2534,9 +4325,9 @@ var init_enterprise_twins = __esm({
|
|
|
2534
4325
|
if (users.some((u) => String(u.userPrincipalName).toLowerCase() === String(body.userPrincipalName).toLowerCase()))
|
|
2535
4326
|
return { ...graphError(400, "Request_BadRequest", "Another object with the same value for property userPrincipalName already exists.", sequence), collection: "/users" };
|
|
2536
4327
|
const { passwordProfile: _secret, ...profile } = body;
|
|
2537
|
-
const
|
|
2538
|
-
users.push(
|
|
2539
|
-
return write2("/users",
|
|
4328
|
+
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) };
|
|
4329
|
+
users.push(record3);
|
|
4330
|
+
return write2("/users", record3, record3, 201);
|
|
2540
4331
|
}
|
|
2541
4332
|
if (kind === "groups" && !key2 && method === "GET") {
|
|
2542
4333
|
const page = graphPage(groups2, query);
|
|
@@ -2609,9 +4400,9 @@ var init_enterprise_twins = __esm({
|
|
|
2609
4400
|
if (users.some((u) => String(u.profile?.login).toLowerCase() === String(profile.login).toLowerCase()))
|
|
2610
4401
|
return { ...oktaError(400, "E0000001", "Api validation failed: login", ["login: An object with this field already exists in the current organization"]), collection: "/users" };
|
|
2611
4402
|
const active = query.activate !== "false";
|
|
2612
|
-
const
|
|
2613
|
-
users.push(
|
|
2614
|
-
return write2("/users",
|
|
4403
|
+
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 } };
|
|
4404
|
+
users.push(record3);
|
|
4405
|
+
return write2("/users", record3, record3);
|
|
2615
4406
|
}
|
|
2616
4407
|
if (kind === "groups" && !key2 && method === "GET") {
|
|
2617
4408
|
const q = query.q?.toLowerCase();
|
|
@@ -2680,9 +4471,9 @@ var init_enterprise_twins = __esm({
|
|
|
2680
4471
|
const page2 = pages.find((p) => p.id === String(body.pageId) && p.status !== "trashed");
|
|
2681
4472
|
if (!page2) return { ...cfError(404, "NOT_FOUND", "Page not found"), collection: "/comments" };
|
|
2682
4473
|
if (!storage(body.body)) return { ...cfError(400, "INVALID_REQUEST_PARAMETER", "Comment body must use the storage representation"), collection: "/comments" };
|
|
2683
|
-
const
|
|
2684
|
-
comments.push(
|
|
2685
|
-
return write2("/comments",
|
|
4474
|
+
const record3 = { id: nextId2(), pageId: page2.id, status: "current", title: `Re: ${page2.title}`, version: { number: 1, createdAt: iso2(sequence) }, body: body.body };
|
|
4475
|
+
comments.push(record3);
|
|
4476
|
+
return write2("/comments", record3, record3);
|
|
2686
4477
|
}
|
|
2687
4478
|
if (kind !== "pages") return;
|
|
2688
4479
|
if (!id && method === "GET") {
|
|
@@ -2696,9 +4487,9 @@ var init_enterprise_twins = __esm({
|
|
|
2696
4487
|
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" };
|
|
2697
4488
|
if (pages.some((p) => p.spaceId === String(body.spaceId) && p.title === body.title && p.status !== "trashed"))
|
|
2698
4489
|
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" };
|
|
2699
|
-
const
|
|
2700
|
-
pages.push(
|
|
2701
|
-
return write2("/pages",
|
|
4490
|
+
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 };
|
|
4491
|
+
pages.push(record3);
|
|
4492
|
+
return write2("/pages", record3, view2(record3));
|
|
2702
4493
|
}
|
|
2703
4494
|
const page = pages.find((p) => p.id === id && p.status !== "trashed");
|
|
2704
4495
|
if (!page) return { ...cfError(404, "NOT_FOUND", "Page not found"), collection: "/pages" };
|
|
@@ -2730,9 +4521,9 @@ var init_enterprise_twins = __esm({
|
|
|
2730
4521
|
while (files.some((f) => f.siteId === siteId && f.name === `${body.name} ${n}`)) n++;
|
|
2731
4522
|
name = `${body.name} ${n}`;
|
|
2732
4523
|
}
|
|
2733
|
-
const
|
|
2734
|
-
files.push(
|
|
2735
|
-
return write2("/driveItems",
|
|
4524
|
+
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)}` };
|
|
4525
|
+
files.push(record3);
|
|
4526
|
+
return write2("/driveItems", record3, record3, 201);
|
|
2736
4527
|
}
|
|
2737
4528
|
if (!listKey) return method === "GET" ? read("/lists", { value: lists.filter((l) => l.siteId === siteId) }) : void 0;
|
|
2738
4529
|
const list2 = lists.find((l) => l.siteId === siteId && (l.id === listKey || l.displayName === decodeURIComponent(listKey)));
|
|
@@ -2749,9 +4540,9 @@ var init_enterprise_twins = __esm({
|
|
|
2749
4540
|
if (!itemId && method === "POST") {
|
|
2750
4541
|
if (!isObject2(body.fields) || !flat(body.fields)) return { ...graphError(400, "invalidRequest", "Invalid request: fields are required.", sequence), collection: "/listItems" };
|
|
2751
4542
|
const id = String(nextNumber(own, "id", 1));
|
|
2752
|
-
const
|
|
2753
|
-
items.push(
|
|
2754
|
-
return write2("/listItems",
|
|
4543
|
+
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 } };
|
|
4544
|
+
items.push(record3);
|
|
4545
|
+
return write2("/listItems", record3, view2(record3, true), 201);
|
|
2755
4546
|
}
|
|
2756
4547
|
const item = own.find((i) => i.id === itemId);
|
|
2757
4548
|
if (!item) return { ...graphError(404, "itemNotFound", "The resource could not be found.", sequence), collection: "/listItems" };
|
|
@@ -2806,9 +4597,9 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
|
|
|
2806
4597
|
message: "Statement executed successfully.",
|
|
2807
4598
|
createdOn: twinNowMs((EPOCH2 + sequence) * 1e3)
|
|
2808
4599
|
});
|
|
2809
|
-
const remember = (collection, res, operation,
|
|
4600
|
+
const remember = (collection, res, operation, record3) => {
|
|
2810
4601
|
log.push({ statementHandle: handle, statement, result: res, createdOn: iso2(sequence) });
|
|
2811
|
-
return operation === "read" ? read(collection, res) : write2(collection,
|
|
4602
|
+
return operation === "read" ? read(collection, res) : write2(collection, record3 ?? { statement }, res);
|
|
2812
4603
|
};
|
|
2813
4604
|
let s;
|
|
2814
4605
|
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)) {
|
|
@@ -2899,31 +4690,31 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
|
|
|
2899
4690
|
total = lines.reduce((sum, l) => sum + Number(l.quantity) * Number(l.rate ?? 0), 0);
|
|
2900
4691
|
}
|
|
2901
4692
|
const newId2 = String(nextNumber(rows2, "id", 1001));
|
|
2902
|
-
const
|
|
2903
|
-
rows2.push(
|
|
2904
|
-
return write2(collection,
|
|
4693
|
+
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) };
|
|
4694
|
+
rows2.push(record4);
|
|
4695
|
+
return write2(collection, record4, null, 204, { location: `/services/rest/record/v1/${type}/${newId2}` });
|
|
2905
4696
|
}
|
|
2906
|
-
const
|
|
2907
|
-
if (!
|
|
2908
|
-
if (method === "GET") return read(collection, { links: nsLink(type,
|
|
4697
|
+
const record3 = id ? rows2.find((r) => r.id === id) : void 0;
|
|
4698
|
+
if (!record3) return { ...nsError(404, "Record Not Found", "The record instance does not exist. Provide a valid record instance ID.", "NONEXISTENT_ID"), collection };
|
|
4699
|
+
if (method === "GET") return read(collection, { links: nsLink(type, record3.id), ...record3 });
|
|
2909
4700
|
if (method === "PATCH") {
|
|
2910
4701
|
if ("id" in body) return;
|
|
2911
|
-
Object.assign(
|
|
2912
|
-
return write2(collection,
|
|
4702
|
+
Object.assign(record3, body, { lastModifiedDate: iso2(sequence) });
|
|
4703
|
+
return write2(collection, record3, null, 204);
|
|
2913
4704
|
}
|
|
2914
4705
|
if (method === "DELETE") {
|
|
2915
|
-
rows2.splice(rows2.indexOf(
|
|
2916
|
-
return write2(collection,
|
|
4706
|
+
rows2.splice(rows2.indexOf(record3), 1);
|
|
4707
|
+
return write2(collection, record3, null, 204);
|
|
2917
4708
|
}
|
|
2918
4709
|
};
|
|
2919
4710
|
pdError = (status, message, code, errors = []) => ({ status, body: { error: { message, code, errors } } });
|
|
2920
4711
|
pdId = (seed) => "P" + hash(seed).replace(/[^A-Z0-9]/gi, "").toUpperCase().slice(0, 6);
|
|
2921
4712
|
pagerduty = (method, path, body, query, headers, data, sequence) => {
|
|
2922
4713
|
const services = table(data, "/services"), incidents = table(data, "/incidents"), notes = table(data, "/notes"), events = table(data, "/events");
|
|
2923
|
-
const
|
|
4714
|
+
const open2 = (serviceId, key2) => incidents.find((i) => i.service.id === serviceId && i.incident_key === key2 && i.status !== "resolved");
|
|
2924
4715
|
const create = (service, title, urgency, key2, details) => {
|
|
2925
4716
|
const id2 = pdId(`pd:incident:${sequence}:${incidents.length}`);
|
|
2926
|
-
const
|
|
4717
|
+
const record3 = {
|
|
2927
4718
|
id: id2,
|
|
2928
4719
|
type: "incident",
|
|
2929
4720
|
summary: `[#${incidents.length + 1}] ${title}`,
|
|
@@ -2938,8 +4729,8 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
|
|
|
2938
4729
|
html_url: `https://contoso.pagerduty.test/incidents/${id2}`,
|
|
2939
4730
|
...details === void 0 ? {} : { body: { type: "incident_body", details } }
|
|
2940
4731
|
};
|
|
2941
|
-
incidents.push(
|
|
2942
|
-
return
|
|
4732
|
+
incidents.push(record3);
|
|
4733
|
+
return record3;
|
|
2943
4734
|
};
|
|
2944
4735
|
if (path === "/v2/enqueue" && method === "POST") {
|
|
2945
4736
|
const service = services.find((s) => s.integration_key && s.integration_key === body.routing_key);
|
|
@@ -2950,7 +4741,7 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
|
|
|
2950
4741
|
return { status: 400, collection: "/events", body: { status: "invalid event", message: "Event object is invalid", errors: ["'payload.summary', 'payload.source' and 'payload.severity' are required"] } };
|
|
2951
4742
|
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"] } };
|
|
2952
4743
|
const key2 = String(body.dedup_key ?? hash(`pd:dedup:${sequence}`).slice(0, 32));
|
|
2953
|
-
const existing =
|
|
4744
|
+
const existing = open2(service.id, key2);
|
|
2954
4745
|
if (action === "trigger" && !existing) create(service, payload.summary, payload.severity === "critical" || payload.severity === "error" ? "high" : "low", key2, payload.custom_details);
|
|
2955
4746
|
if (action !== "trigger" && existing) Object.assign(existing, { status: action === "acknowledge" ? "acknowledged" : "resolved", updated_at: iso2(sequence) });
|
|
2956
4747
|
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) };
|
|
@@ -2975,9 +4766,9 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
|
|
|
2975
4766
|
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" };
|
|
2976
4767
|
const service = services.find((s) => s.id === input.service.id);
|
|
2977
4768
|
if (!service) return { ...pdError(400, "Invalid Input Provided", 2001, ["Service not found"]), collection: "/incidents" };
|
|
2978
|
-
if (input.incident_key &&
|
|
2979
|
-
const
|
|
2980
|
-
return write2("/incidents",
|
|
4769
|
+
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" };
|
|
4770
|
+
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);
|
|
4771
|
+
return write2("/incidents", record3, { incident: record3 }, 201);
|
|
2981
4772
|
}
|
|
2982
4773
|
const incident = incidents.find((i) => i.id === id);
|
|
2983
4774
|
if (!incident) return { ...pdError(404, "Not Found", 2100), collection: "/incidents" };
|
|
@@ -3132,6 +4923,7 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
|
|
|
3132
4923
|
});
|
|
3133
4924
|
|
|
3134
4925
|
// src/runtime/spec.ts
|
|
4926
|
+
import { isAbsolute } from "path";
|
|
3135
4927
|
function parseWorld(value) {
|
|
3136
4928
|
const invalid = (message) => {
|
|
3137
4929
|
throw new Error(`Invalid world: ${message}`);
|
|
@@ -3153,7 +4945,7 @@ function parseWorld(value) {
|
|
|
3153
4945
|
if (!object2(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid("service names must be unique lowercase identifiers");
|
|
3154
4946
|
const item = service;
|
|
3155
4947
|
if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
|
|
3156
|
-
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");
|
|
4948
|
+
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");
|
|
3157
4949
|
const paths = /* @__PURE__ */ new Set();
|
|
3158
4950
|
for (const entry of item.collections) {
|
|
3159
4951
|
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");
|
|
@@ -3187,6 +4979,8 @@ function parseWorld(value) {
|
|
|
3187
4979
|
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");
|
|
3188
4980
|
if (v.postgres !== void 0) {
|
|
3189
4981
|
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");
|
|
4982
|
+
const extensions = v.postgres.extensions;
|
|
4983
|
+
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(", ")}`);
|
|
3190
4984
|
const clock = v.postgres.clock;
|
|
3191
4985
|
if (clock !== void 0 && !validPostgresClock(clock)) invalid("postgres.clock requires only now, a canonical UTC timestamp such as 2026-01-01T00:00:00.000Z");
|
|
3192
4986
|
for (const a of v.postgres.assertions) {
|
|
@@ -3282,7 +5076,40 @@ function parseWorld(value) {
|
|
|
3282
5076
|
}
|
|
3283
5077
|
}
|
|
3284
5078
|
}
|
|
3285
|
-
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");
|
|
5079
|
+
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");
|
|
5080
|
+
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");
|
|
5081
|
+
if (v.env !== void 0) {
|
|
5082
|
+
if (!object2(v.env) || Object.keys(v.env).length > 200) invalid("env must be an object of at most 200 string variables");
|
|
5083
|
+
for (const [key2, value2] of Object.entries(v.env)) {
|
|
5084
|
+
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");
|
|
5085
|
+
if (RESERVED_ENV.test(key2)) invalid(`env cannot set ${key2}: AgentTwin sets it for the run`);
|
|
5086
|
+
}
|
|
5087
|
+
}
|
|
5088
|
+
if (v.server !== void 0) {
|
|
5089
|
+
const server = v.server;
|
|
5090
|
+
if (!object2(server) || Object.keys(server).some((k) => !["baseUrl", "readyPath", "readyTimeoutSeconds", "steps"].includes(k))) invalid("server needs baseUrl, optional readyPath and readyTimeoutSeconds, and steps");
|
|
5091
|
+
let u;
|
|
5092
|
+
try {
|
|
5093
|
+
u = new URL(String(server.baseUrl));
|
|
5094
|
+
} catch {
|
|
5095
|
+
u = void 0;
|
|
5096
|
+
}
|
|
5097
|
+
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>");
|
|
5098
|
+
if (server.readyPath !== void 0 && !isServerPath(server.readyPath)) invalid("server readyPath must start with a single / and contain no backslash or control characters");
|
|
5099
|
+
if (server.readyTimeoutSeconds !== void 0 && (!Number.isInteger(server.readyTimeoutSeconds) || Number(server.readyTimeoutSeconds) < 1 || Number(server.readyTimeoutSeconds) > 240)) invalid("server readyTimeoutSeconds must be 1\u2013240");
|
|
5100
|
+
if (!Array.isArray(server.steps) || !server.steps.length || server.steps.length > 50) invalid("server needs 1\u201350 steps");
|
|
5101
|
+
for (const raw of server.steps) {
|
|
5102
|
+
const step = raw;
|
|
5103
|
+
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");
|
|
5104
|
+
if (typeof step.target !== "string" || step.target !== "app" && !services.has(step.target)) invalid('server step target must be "app" or a service name');
|
|
5105
|
+
if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(String(step.method))) invalid("server step method must be GET, POST, PUT, PATCH or DELETE");
|
|
5106
|
+
if (!isServerPath(step.path)) invalid("server step path must start with a single / and contain no backslash or control characters");
|
|
5107
|
+
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");
|
|
5108
|
+
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");
|
|
5109
|
+
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");
|
|
5110
|
+
}
|
|
5111
|
+
if (v.browser !== void 0) invalid("use either browser or server, not both");
|
|
5112
|
+
}
|
|
3286
5113
|
if (v.fetchRoutes !== void 0) {
|
|
3287
5114
|
if (!Array.isArray(v.fetchRoutes) || !v.fetchRoutes.length || v.fetchRoutes.length > 10) invalid("fetchRoutes needs 1\u201310 explicit origin/service mappings");
|
|
3288
5115
|
const origins = /* @__PURE__ */ new Set();
|
|
@@ -3299,16 +5126,17 @@ function parseWorld(value) {
|
|
|
3299
5126
|
origins.add(mapping.origin);
|
|
3300
5127
|
}
|
|
3301
5128
|
}
|
|
3302
|
-
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"];
|
|
5129
|
+
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"];
|
|
3303
5130
|
if (Object.keys(v).some((k) => !keys.includes(k))) invalid("unknown world field");
|
|
3304
5131
|
return v;
|
|
3305
5132
|
}
|
|
3306
|
-
var RUNTIMES, ADAPTER_OPTIONAL_COLLECTIONS, ADAPTER_COLLECTIONS, FAULT_TYPES, PROPERTY_KINDS, object2, namePattern, inRangeInt;
|
|
5133
|
+
var RUNTIMES, ADAPTER_OPTIONAL_COLLECTIONS, ADAPTER_COLLECTIONS, FAULT_TYPES, PROPERTY_KINDS, RESERVED_ENV, isServerPath, object2, namePattern, inRangeInt;
|
|
3307
5134
|
var init_spec = __esm({
|
|
3308
5135
|
"src/runtime/spec.ts"() {
|
|
3309
5136
|
"use strict";
|
|
3310
5137
|
init_twin_clock();
|
|
3311
5138
|
init_postgres_clock();
|
|
5139
|
+
init_types();
|
|
3312
5140
|
init_adapters();
|
|
3313
5141
|
init_packs();
|
|
3314
5142
|
init_application_clock();
|
|
@@ -3316,6 +5144,7 @@ var init_spec = __esm({
|
|
|
3316
5144
|
RUNTIMES = /^(?:\/[\w./-]+\/)?(?:node|python[0-9.]*|uv|poetry|pipenv|go|ruby|bundle|deno|bun|curl)$/;
|
|
3317
5145
|
ADAPTER_OPTIONAL_COLLECTIONS = {
|
|
3318
5146
|
stripe: ["/v1/charges", "/v1/refunds", "/v1/events"],
|
|
5147
|
+
gmail: ["/gmail/v1/users/me/drafts", "/gmail/v1/users/me/settings/sendAs", "/gmail/v1/users/me/watch", "/pubsub/subscriptions", "/pubsub/messages"],
|
|
3319
5148
|
...ENTERPRISE_OPTIONAL_COLLECTIONS
|
|
3320
5149
|
};
|
|
3321
5150
|
ADAPTER_COLLECTIONS = {
|
|
@@ -3337,12 +5166,15 @@ var init_spec = __esm({
|
|
|
3337
5166
|
twilio: ["/2010-04-01/Messages", "/2010-04-01/Calls"],
|
|
3338
5167
|
composio: ["/connected_accounts", "/tools", "/messages"],
|
|
3339
5168
|
"google-oauth": ["/clients", "/grants", "/tokens"],
|
|
5169
|
+
"upstash-redis": ["/keys"],
|
|
3340
5170
|
zendesk: ["/api/v2/tickets", "/api/v2/users", "/api/v2/organizations"],
|
|
3341
5171
|
// Enterprise twins: any subset of their optional collections; Snowflake tables are free-form.
|
|
3342
5172
|
...Object.fromEntries(ENTERPRISE_ADAPTERS.filter((a) => !FREEFORM_COLLECTION_ADAPTERS.includes(a)).map((a) => [a, []]))
|
|
3343
5173
|
};
|
|
3344
5174
|
FAULT_TYPES = ["timeout-after-write", "blackhole", "server-error", "duplicate-write", "slow-response"];
|
|
3345
5175
|
PROPERTY_KINDS = ["unique-per-act", "no-loss", "effect-count"];
|
|
5176
|
+
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;
|
|
5177
|
+
isServerPath = (path) => typeof path === "string" && path.length <= 4096 && path.startsWith("/") && !path.startsWith("//") && !path.includes("\\") && !/[\u0000-\u001f\u007f]/.test(path);
|
|
3346
5178
|
object2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
3347
5179
|
namePattern = /^[a-z][a-z0-9_]{0,39}$/;
|
|
3348
5180
|
inRangeInt = (x, min, max) => Number.isInteger(x) && Number(x) >= min && Number(x) <= max;
|
|
@@ -3351,7 +5183,7 @@ var init_spec = __esm({
|
|
|
3351
5183
|
|
|
3352
5184
|
// src/runtime/pack-log.ts
|
|
3353
5185
|
import { closeSync, existsSync as existsSync2, openSync, readdirSync, readSync, statSync } from "fs";
|
|
3354
|
-
import { join as
|
|
5186
|
+
import { join as join5 } from "path";
|
|
3355
5187
|
function packCollection(type, requestPath) {
|
|
3356
5188
|
const segments = requestPath.split("/").filter(Boolean);
|
|
3357
5189
|
const at = segments.findIndex((s) => s === type || singular2(s) === type || s.replace(/-/g, "_") === type || singular2(s.replace(/-/g, "_")) === type);
|
|
@@ -3391,7 +5223,7 @@ var init_pack_log = __esm({
|
|
|
3391
5223
|
partial = /* @__PURE__ */ new Map();
|
|
3392
5224
|
files() {
|
|
3393
5225
|
if (!existsSync2(this.root)) return [];
|
|
3394
|
-
return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) =>
|
|
5226
|
+
return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join5(this.root, f)).sort();
|
|
3395
5227
|
}
|
|
3396
5228
|
drain() {
|
|
3397
5229
|
const out = [];
|
|
@@ -3405,8 +5237,8 @@ var init_pack_log = __esm({
|
|
|
3405
5237
|
closeSync(fd);
|
|
3406
5238
|
}
|
|
3407
5239
|
this.offsets.set(file, size);
|
|
3408
|
-
const
|
|
3409
|
-
const lines =
|
|
5240
|
+
const text2 = (this.partial.get(file) ?? "") + buffer.toString("utf8");
|
|
5241
|
+
const lines = text2.split("\n");
|
|
3410
5242
|
this.partial.set(file, lines.pop() ?? "");
|
|
3411
5243
|
for (const line of lines) if (line.trim()) try {
|
|
3412
5244
|
out.push(JSON.parse(line));
|
|
@@ -3423,13 +5255,13 @@ var init_pack_log = __esm({
|
|
|
3423
5255
|
});
|
|
3424
5256
|
|
|
3425
5257
|
// src/runtime/http-world.ts
|
|
3426
|
-
import { createServer } from "http";
|
|
5258
|
+
import { createServer as createServer3 } from "http";
|
|
3427
5259
|
import { isDeepStrictEqual } from "util";
|
|
3428
5260
|
import { createHash as createHash5 } from "crypto";
|
|
3429
5261
|
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
3430
|
-
import { mkdir, mkdtemp as
|
|
3431
|
-
import { tmpdir as
|
|
3432
|
-
import { join as
|
|
5262
|
+
import { mkdir, mkdtemp as mkdtemp3, rm as rm3, writeFile as writeFile2 } from "fs/promises";
|
|
5263
|
+
import { tmpdir as tmpdir3 } from "os";
|
|
5264
|
+
import { join as join6 } from "path";
|
|
3433
5265
|
var idempotencyKeyDigest, HttpWorld;
|
|
3434
5266
|
var init_http_world = __esm({
|
|
3435
5267
|
"src/runtime/http-world.ts"() {
|
|
@@ -3470,10 +5302,46 @@ var init_http_world = __esm({
|
|
|
3470
5302
|
epoch = 0;
|
|
3471
5303
|
replayKeys = /* @__PURE__ */ new Map();
|
|
3472
5304
|
sourceContext = new AsyncLocalStorage2();
|
|
3473
|
-
record(service, operation, path, detail,
|
|
5305
|
+
record(service, operation, path, detail, record3) {
|
|
3474
5306
|
if (this.events.length >= 5e4) return;
|
|
3475
5307
|
const source = this.sourceContext.getStore();
|
|
3476
|
-
this.events.push({ sequence: this.events.length + 1, service, operation, path, detail, ...
|
|
5308
|
+
this.events.push({ sequence: this.events.length + 1, service, operation, path, detail, ...record3 ? { record: structuredClone(record3) } : {}, ...source ? { source } : {} });
|
|
5309
|
+
}
|
|
5310
|
+
/**
|
|
5311
|
+
* Delivers twin-initiated pushes (Gmail watch → Pub/Sub push subscription) to the application under test, once
|
|
5312
|
+
* each, after the triggering response. Only loopback http endpoints are allowed, so a push can never leave the
|
|
5313
|
+
* machine; the outcome is written to the push row and recorded as a `push` event.
|
|
5314
|
+
*/
|
|
5315
|
+
push(service, deliveries, epoch) {
|
|
5316
|
+
for (const delivery of deliveries) {
|
|
5317
|
+
const timer = setTimeout(async () => {
|
|
5318
|
+
this.timers.delete(timer);
|
|
5319
|
+
if (epoch !== this.epoch) return;
|
|
5320
|
+
let target;
|
|
5321
|
+
try {
|
|
5322
|
+
target = new URL(delivery.url);
|
|
5323
|
+
} catch {
|
|
5324
|
+
target = void 0;
|
|
5325
|
+
}
|
|
5326
|
+
if (!target || target.protocol !== "http:" || !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || target.username || target.password) {
|
|
5327
|
+
delivery.row.delivery = "rejected: pushEndpoint must be a loopback http URL";
|
|
5328
|
+
this.record(service, "push", "/pubsub/messages", `push rejected: ${String(delivery.row.messageId)} endpoint is not loopback http`);
|
|
5329
|
+
return;
|
|
5330
|
+
}
|
|
5331
|
+
try {
|
|
5332
|
+
const response = await fetch(target, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(delivery.body), redirect: "error", signal: AbortSignal.timeout(6e4) });
|
|
5333
|
+
await response.arrayBuffer().catch(() => void 0);
|
|
5334
|
+
if (epoch !== this.epoch) return;
|
|
5335
|
+
delivery.row.delivery = response.status;
|
|
5336
|
+
this.record(service, "push", "/pubsub/messages", `push ${String(delivery.row.messageId)} delivered: HTTP ${response.status}`, { messageId: delivery.row.messageId, status: response.status });
|
|
5337
|
+
} catch (error) {
|
|
5338
|
+
if (epoch !== this.epoch) return;
|
|
5339
|
+
delivery.row.delivery = `failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
5340
|
+
this.record(service, "push", "/pubsub/messages", `push ${String(delivery.row.messageId)} failed`);
|
|
5341
|
+
}
|
|
5342
|
+
}, 25);
|
|
5343
|
+
this.timers.add(timer);
|
|
5344
|
+
}
|
|
3477
5345
|
}
|
|
3478
5346
|
/** Tags the event just recorded with the request's idempotency key digest. */
|
|
3479
5347
|
keyed(key2) {
|
|
@@ -3527,7 +5395,7 @@ var init_http_world = __esm({
|
|
|
3527
5395
|
this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server2.address().port}`, token };
|
|
3528
5396
|
continue;
|
|
3529
5397
|
}
|
|
3530
|
-
const server =
|
|
5398
|
+
const server = createServer3((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
|
|
3531
5399
|
const epoch = this.epoch;
|
|
3532
5400
|
const send = (code, body, headers = {}) => {
|
|
3533
5401
|
if (!res.destroyed) {
|
|
@@ -3649,33 +5517,43 @@ var init_http_world = __esm({
|
|
|
3649
5517
|
}
|
|
3650
5518
|
chunks.push(Buffer.from(chunk));
|
|
3651
5519
|
}
|
|
3652
|
-
const
|
|
5520
|
+
const text2 = Buffer.concat(chunks).toString("utf8");
|
|
3653
5521
|
let parsed;
|
|
3654
5522
|
const mode = generated?.bodyMode(req.headers["content-type"]);
|
|
3655
|
-
if ((enterprise || generated) && !
|
|
5523
|
+
if ((enterprise || generated) && !text2.trim()) parsed = {};
|
|
3656
5524
|
else if (mode === "form") {
|
|
3657
|
-
const form = new URLSearchParams(
|
|
5525
|
+
const form = new URLSearchParams(text2);
|
|
3658
5526
|
parsed = {};
|
|
3659
5527
|
for (const key3 of new Set(form.keys())) {
|
|
3660
5528
|
const all = form.getAll(key3);
|
|
3661
5529
|
parsed[key3] = all.length > 1 ? all : all[0];
|
|
3662
5530
|
}
|
|
3663
5531
|
} else if (mode === "raw") {
|
|
3664
|
-
rawBody =
|
|
5532
|
+
rawBody = text2;
|
|
3665
5533
|
parsed = {};
|
|
3666
|
-
} else if (service.adapter === "
|
|
5534
|
+
} else if (service.adapter === "gmail" && /^multipart\/mixed\b/i.test(String(req.headers["content-type"] ?? ""))) {
|
|
5535
|
+
rawBody = text2;
|
|
5536
|
+
parsed = {};
|
|
5537
|
+
} else if (service.adapter === "gmail" && /^multipart\/related\b/i.test(String(req.headers["content-type"] ?? ""))) {
|
|
5538
|
+
rawBody = text2;
|
|
5539
|
+
parsed = Object.fromEntries(url.searchParams);
|
|
5540
|
+
} else if (service.adapter === "upstash-redis") {
|
|
5541
|
+
rawBody = text2;
|
|
5542
|
+
parsed = {};
|
|
5543
|
+
} else if (service.adapter === "gmail" && !text2.trim()) parsed = {};
|
|
5544
|
+
else if (service.adapter === "google-oauth") {
|
|
3667
5545
|
if (req.headers["content-type"]?.split(";")[0].trim().toLowerCase() !== "application/x-www-form-urlencoded") {
|
|
3668
5546
|
respond(400, { error: "invalid_request" });
|
|
3669
5547
|
return;
|
|
3670
5548
|
}
|
|
3671
|
-
const form = new URLSearchParams(
|
|
5549
|
+
const form = new URLSearchParams(text2);
|
|
3672
5550
|
if ([...form.keys()].some((key3) => form.getAll(key3).length !== 1)) {
|
|
3673
5551
|
respond(400, { error: "invalid_request" });
|
|
3674
5552
|
return;
|
|
3675
5553
|
}
|
|
3676
5554
|
parsed = Object.fromEntries(form);
|
|
3677
5555
|
} else try {
|
|
3678
|
-
parsed = (slack || service.adapter === "stripe" || service.adapter === "twilio") && req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(
|
|
5556
|
+
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);
|
|
3679
5557
|
} catch {
|
|
3680
5558
|
respond(400, { error: "expected_json_object" });
|
|
3681
5559
|
return;
|
|
@@ -3708,7 +5586,7 @@ var init_http_world = __esm({
|
|
|
3708
5586
|
return;
|
|
3709
5587
|
}
|
|
3710
5588
|
const query = Object.fromEntries(url.searchParams);
|
|
3711
|
-
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);
|
|
5589
|
+
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);
|
|
3712
5590
|
const headers = (r) => "headers" in r ? r.headers : void 0;
|
|
3713
5591
|
const result = invoke(this.events.length + 1);
|
|
3714
5592
|
if (!result) {
|
|
@@ -3723,15 +5601,19 @@ var init_http_world = __esm({
|
|
|
3723
5601
|
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) } : {} });
|
|
3724
5602
|
const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result.operation === "write" && !key3 && matchesFault(result.collection);
|
|
3725
5603
|
const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
|
|
5604
|
+
const pushes = (r) => "deliveries" in r ? [...r.deliveries ?? []] : [];
|
|
5605
|
+
const deliveries = pushes(result);
|
|
3726
5606
|
if (duplicate2) {
|
|
3727
5607
|
const second = invoke(this.events.length + 1);
|
|
3728
5608
|
if (second?.operation === "write") {
|
|
5609
|
+
deliveries.push(...pushes(second));
|
|
3729
5610
|
this.record(service.name, second.operation, second.collection, path, "record" in second ? second.record : second.body);
|
|
3730
5611
|
this.faultActions++;
|
|
3731
5612
|
this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${result.collection})`);
|
|
3732
5613
|
} else if (second) {
|
|
3733
5614
|
this.record(service.name, "fault", fault.path, `duplicate-write: second delivery replaced by ${second.operation ?? "failure"}`);
|
|
3734
5615
|
respond(second.status, second.body, headers(second));
|
|
5616
|
+
if (deliveries.length) this.push(service.name, deliveries, epoch);
|
|
3735
5617
|
return;
|
|
3736
5618
|
}
|
|
3737
5619
|
}
|
|
@@ -3746,6 +5628,7 @@ var init_http_world = __esm({
|
|
|
3746
5628
|
}, fault.delayMs);
|
|
3747
5629
|
this.timers.add(timer);
|
|
3748
5630
|
} else respondSlowly(result.collection, result.operation ?? "request", result.status, result.body, headers(result));
|
|
5631
|
+
if (deliveries.length) this.push(service.name, deliveries, epoch);
|
|
3749
5632
|
return;
|
|
3750
5633
|
}
|
|
3751
5634
|
if (slack) {
|
|
@@ -3847,9 +5730,9 @@ var init_http_world = __esm({
|
|
|
3847
5730
|
}
|
|
3848
5731
|
})));
|
|
3849
5732
|
server.requestTimeout = 1e4;
|
|
3850
|
-
await new Promise((
|
|
5733
|
+
await new Promise((resolve8, reject) => {
|
|
3851
5734
|
server.once("error", reject);
|
|
3852
|
-
server.listen(0, "127.0.0.1",
|
|
5735
|
+
server.listen(0, "127.0.0.1", resolve8);
|
|
3853
5736
|
});
|
|
3854
5737
|
this.servers.push(server);
|
|
3855
5738
|
this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server.address().port}`, token };
|
|
@@ -3867,26 +5750,26 @@ var init_http_world = __esm({
|
|
|
3867
5750
|
async startPack(service, token, faultOrdinalsFor, faultKey, data, latencyMs) {
|
|
3868
5751
|
const name = service.adapter.slice(PACK_PREFIX.length), meta = packRecord(name);
|
|
3869
5752
|
if (this.twinClock && packCatalog()?.engine[meta.generation]?.clockSupport !== "async-context-v1") throw new Error("Twin packs need rebuilding for per-run clock support");
|
|
3870
|
-
const root = await
|
|
5753
|
+
const root = await mkdtemp3(join6(tmpdir3(), `agenttwin-pack-${name}-`));
|
|
3871
5754
|
this.packRoots.push(root);
|
|
3872
5755
|
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" : "";
|
|
3873
|
-
const writeSeedLog = async (dir,
|
|
3874
|
-
if (!
|
|
3875
|
-
await mkdir(
|
|
3876
|
-
await writeFile2(
|
|
5756
|
+
const writeSeedLog = async (dir, text2) => {
|
|
5757
|
+
if (!text2) return;
|
|
5758
|
+
await mkdir(join6(dir, ".volter/world", meta.logService), { recursive: true });
|
|
5759
|
+
await writeFile2(join6(dir, ".volter/world", meta.logService, "actions.jsonl"), text2);
|
|
3877
5760
|
};
|
|
3878
5761
|
let tenant = {}, credential;
|
|
3879
5762
|
if (meta.logService && meta.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account)) {
|
|
3880
|
-
const probe = await
|
|
5763
|
+
const probe = await mkdtemp3(join6(tmpdir3(), `agenttwin-pack-${name}-probe-`));
|
|
3881
5764
|
try {
|
|
3882
5765
|
await writeSeedLog(probe, worldSeed);
|
|
3883
5766
|
const scratch = await (await loadPack(name))({ root: probe });
|
|
3884
5767
|
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();
|
|
3885
|
-
const probed = new PackActionTail(
|
|
5768
|
+
const probed = new PackActionTail(join6(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
|
|
3886
5769
|
tenant = tenantFields(probed);
|
|
3887
5770
|
credential = credentialAction(probed);
|
|
3888
5771
|
} finally {
|
|
3889
|
-
await
|
|
5772
|
+
await rm3(probe, { recursive: true, force: true });
|
|
3890
5773
|
}
|
|
3891
5774
|
}
|
|
3892
5775
|
const account = credential && service.account ? JSON.stringify({ ...credential, id: `${credential.id ?? "credential"}:preset`, fields: { ...credential.fields, ...service.account } }) + "\n" : "";
|
|
@@ -3894,7 +5777,7 @@ var init_http_world = __esm({
|
|
|
3894
5777
|
await writeSeedLog(root, seeded);
|
|
3895
5778
|
const twin = await (await loadPack(name))({ root });
|
|
3896
5779
|
const baseHost = meta.hosts[0]?.host ?? `${name}.twin.test`;
|
|
3897
|
-
const log = new PackActionTail(
|
|
5780
|
+
const log = new PackActionTail(join6(root, ".volter"));
|
|
3898
5781
|
let issued = {};
|
|
3899
5782
|
if (meta.credentialDoor) {
|
|
3900
5783
|
const r = await twin(new Request(`https://${baseHost}${meta.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta.credentialDoor.body ?? {}) }));
|
|
@@ -3951,7 +5834,7 @@ var init_http_world = __esm({
|
|
|
3951
5834
|
chain = run3.then(() => void 0, () => void 0);
|
|
3952
5835
|
return run3;
|
|
3953
5836
|
};
|
|
3954
|
-
const server =
|
|
5837
|
+
const server = createServer3((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
|
|
3955
5838
|
const epoch = this.epoch;
|
|
3956
5839
|
const send = (status, headers, body) => {
|
|
3957
5840
|
if (!res.destroyed) {
|
|
@@ -4087,9 +5970,9 @@ var init_http_world = __esm({
|
|
|
4087
5970
|
}
|
|
4088
5971
|
})));
|
|
4089
5972
|
server.requestTimeout = 1e4;
|
|
4090
|
-
await new Promise((
|
|
5973
|
+
await new Promise((resolve8, reject) => {
|
|
4091
5974
|
server.once("error", reject);
|
|
4092
|
-
server.listen(0, "127.0.0.1",
|
|
5975
|
+
server.listen(0, "127.0.0.1", resolve8);
|
|
4093
5976
|
});
|
|
4094
5977
|
return server;
|
|
4095
5978
|
}
|
|
@@ -4129,32 +6012,32 @@ var init_http_world = __esm({
|
|
|
4129
6012
|
this.epoch++;
|
|
4130
6013
|
for (const timer of this.timers) clearTimeout(timer);
|
|
4131
6014
|
this.timers.clear();
|
|
4132
|
-
await Promise.all(this.servers.map((server) => new Promise((
|
|
4133
|
-
server.close(() =>
|
|
6015
|
+
await Promise.all(this.servers.map((server) => new Promise((resolve8) => {
|
|
6016
|
+
server.close(() => resolve8());
|
|
4134
6017
|
server.closeAllConnections();
|
|
4135
6018
|
})));
|
|
4136
6019
|
this.servers.length = 0;
|
|
4137
|
-
await Promise.all(this.packRoots.splice(0).map((root) =>
|
|
6020
|
+
await Promise.all(this.packRoots.splice(0).map((root) => rm3(root, { recursive: true, force: true })));
|
|
4138
6021
|
}
|
|
4139
6022
|
};
|
|
4140
6023
|
}
|
|
4141
6024
|
});
|
|
4142
6025
|
|
|
4143
6026
|
// src/runtime/application-process.ts
|
|
4144
|
-
import { execFile } from "child_process";
|
|
4145
|
-
import { promisify } from "util";
|
|
6027
|
+
import { execFile as execFile2 } from "child_process";
|
|
6028
|
+
import { promisify as promisify2 } from "util";
|
|
4146
6029
|
import { win32 } from "path";
|
|
4147
6030
|
async function processes() {
|
|
4148
6031
|
if (process.platform === "win32") {
|
|
4149
6032
|
const shell = win32.join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
4150
6033
|
const script = "$ErrorActionPreference='Stop'; @(Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -gt 1 -and $_.CreationDate } | ForEach-Object { @{pid=[int]$_.ProcessId;parent=[int]$_.ParentProcessId;born=$_.CreationDate.ToUniversalTime().ToString('o');state='running'} }) | ConvertTo-Json -Compress";
|
|
4151
|
-
const { stdout: stdout2 } = await
|
|
6034
|
+
const { stdout: stdout2 } = await exec2(shell, ["-NoProfile", "-NonInteractive", "-Command", script], { timeout: 1e3, windowsHide: true, maxBuffer: 4 * 1024 * 1024 });
|
|
4152
6035
|
const data = JSON.parse(stdout2.trim() || "[]");
|
|
4153
6036
|
const rows2 = Array.isArray(data) ? data : [data];
|
|
4154
6037
|
if (!rows2.every((r) => Number.isSafeInteger(r.pid) && Number.isSafeInteger(r.parent) && typeof r.born === "string")) throw Error("Invalid process evidence");
|
|
4155
6038
|
return rows2;
|
|
4156
6039
|
}
|
|
4157
|
-
const { stdout } = await
|
|
6040
|
+
const { stdout } = await exec2("ps", ["-axo", "pid=,ppid=,stat=,lstart="], { timeout: 1e3, maxBuffer: 4 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } });
|
|
4158
6041
|
return stdout.trim().split("\n").filter(Boolean).map((line) => {
|
|
4159
6042
|
const [pid, parent, state, ...born] = line.trim().split(/\s+/);
|
|
4160
6043
|
return { pid: Number(pid), parent: Number(parent), state, born: born.join(" ") };
|
|
@@ -4165,15 +6048,15 @@ function manageApplication(child) {
|
|
|
4165
6048
|
let scan = Promise.resolve();
|
|
4166
6049
|
let scanError;
|
|
4167
6050
|
let stopPromise;
|
|
4168
|
-
const exited = new Promise((
|
|
4169
|
-
child.once("exit",
|
|
6051
|
+
const exited = new Promise((resolve8, reject) => {
|
|
6052
|
+
child.once("exit", resolve8);
|
|
4170
6053
|
child.once("error", reject);
|
|
4171
6054
|
});
|
|
4172
6055
|
void exited.catch(() => {
|
|
4173
6056
|
});
|
|
4174
|
-
const closed = new Promise((
|
|
4175
|
-
child.once("close", () =>
|
|
4176
|
-
child.once("error", () =>
|
|
6057
|
+
const closed = new Promise((resolve8) => {
|
|
6058
|
+
child.once("close", () => resolve8());
|
|
6059
|
+
child.once("error", () => resolve8());
|
|
4177
6060
|
});
|
|
4178
6061
|
async function capture() {
|
|
4179
6062
|
const rows2 = await processes();
|
|
@@ -4221,7 +6104,7 @@ function manageApplication(child) {
|
|
|
4221
6104
|
if (process.platform === "win32" && targets.length) {
|
|
4222
6105
|
const exe = win32.join(process.env.SystemRoot || "C:\\Windows", "System32", "taskkill.exe");
|
|
4223
6106
|
try {
|
|
4224
|
-
await
|
|
6107
|
+
await exec2(exe, [...targets.flatMap((t) => ["/PID", String(t.pid)]), "/T", "/F"], { timeout: 1e3, windowsHide: true });
|
|
4225
6108
|
} catch {
|
|
4226
6109
|
}
|
|
4227
6110
|
} else {
|
|
@@ -4268,22 +6151,22 @@ function manageApplication(child) {
|
|
|
4268
6151
|
}
|
|
4269
6152
|
} };
|
|
4270
6153
|
}
|
|
4271
|
-
var
|
|
6154
|
+
var exec2, CLEANUP_MS;
|
|
4272
6155
|
var init_application_process = __esm({
|
|
4273
6156
|
"src/runtime/application-process.ts"() {
|
|
4274
6157
|
"use strict";
|
|
4275
|
-
|
|
6158
|
+
exec2 = promisify2(execFile2);
|
|
4276
6159
|
CLEANUP_MS = 5e3;
|
|
4277
6160
|
}
|
|
4278
6161
|
});
|
|
4279
6162
|
|
|
4280
6163
|
// src/runtime/browser-process-windows.ts
|
|
4281
|
-
import { randomUUID } from "crypto";
|
|
4282
|
-
import { execFile as
|
|
4283
|
-
import { promisify as
|
|
6164
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
6165
|
+
import { execFile as execFile3 } from "child_process";
|
|
6166
|
+
import { promisify as promisify3 } from "util";
|
|
4284
6167
|
import { win32 as win322 } from "path";
|
|
4285
6168
|
function windowsBrowserProcess(executable, commands = run) {
|
|
4286
|
-
const marker = "--agenttwin-browser-owner=" +
|
|
6169
|
+
const marker = "--agenttwin-browser-owner=" + randomUUID2();
|
|
4287
6170
|
const system = process.env.SystemRoot || process.env.SYSTEMROOT || "C:\\Windows";
|
|
4288
6171
|
const powershell = win322.join(system, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
4289
6172
|
const taskkill = win322.join(system, "System32", "taskkill.exe");
|
|
@@ -4333,33 +6216,33 @@ function windowsBrowserProcess(executable, commands = run) {
|
|
|
4333
6216
|
}
|
|
4334
6217
|
};
|
|
4335
6218
|
}
|
|
4336
|
-
var
|
|
6219
|
+
var exec3, run;
|
|
4337
6220
|
var init_browser_process_windows = __esm({
|
|
4338
6221
|
"src/runtime/browser-process-windows.ts"() {
|
|
4339
6222
|
"use strict";
|
|
4340
|
-
|
|
4341
|
-
run = (file, args) =>
|
|
6223
|
+
exec3 = promisify3(execFile3);
|
|
6224
|
+
run = (file, args) => exec3(file, args, { windowsHide: true, timeout: 2e3, maxBuffer: 4 * 1024 * 1024 });
|
|
4342
6225
|
}
|
|
4343
6226
|
});
|
|
4344
6227
|
|
|
4345
6228
|
// src/runtime/browser-process.ts
|
|
4346
|
-
import { mkdtemp as
|
|
4347
|
-
import { tmpdir as
|
|
4348
|
-
import { join as
|
|
4349
|
-
import { execFile as
|
|
4350
|
-
import { promisify as
|
|
6229
|
+
import { mkdtemp as mkdtemp4, writeFile as writeFile3, readFile, rm as rm4 } from "fs/promises";
|
|
6230
|
+
import { tmpdir as tmpdir4 } from "os";
|
|
6231
|
+
import { join as join7 } from "path";
|
|
6232
|
+
import { execFile as execFile4 } from "child_process";
|
|
6233
|
+
import { promisify as promisify4 } from "util";
|
|
4351
6234
|
async function ownBrowserProcess(executable) {
|
|
4352
6235
|
if (process.platform === "win32") return withCleanup(windowsBrowserProcess(executable), async () => {
|
|
4353
6236
|
});
|
|
4354
|
-
const root = await
|
|
4355
|
-
const pidFile =
|
|
6237
|
+
const root = await mkdtemp4(join7(tmpdir4(), "agenttwin-browser-owner-"));
|
|
6238
|
+
const pidFile = join7(root, "pid"), launcher = join7(root, "launch");
|
|
4356
6239
|
await writeFile3(launcher, `#!/bin/sh
|
|
4357
6240
|
echo $$ > ${quote(pidFile)}
|
|
4358
6241
|
exec ${quote(executable)} "$@"
|
|
4359
6242
|
`, { mode: 448 });
|
|
4360
6243
|
let group;
|
|
4361
6244
|
async function processes2() {
|
|
4362
|
-
const { stdout } = await
|
|
6245
|
+
const { stdout } = await exec4("ps", ["-axo", "pid=,pgid=,stat="], { timeout: 2e3, maxBuffer: 4 * 1024 * 1024 });
|
|
4363
6246
|
return stdout.trim().split("\n").map((line) => {
|
|
4364
6247
|
const [pid, pgid, state] = line.trim().split(/\s+/);
|
|
4365
6248
|
return { pid: Number(pid), pgid: Number(pgid), state };
|
|
@@ -4369,7 +6252,7 @@ exec ${quote(executable)} "$@"
|
|
|
4369
6252
|
if (group) return group;
|
|
4370
6253
|
let pid;
|
|
4371
6254
|
try {
|
|
4372
|
-
pid = Number((await
|
|
6255
|
+
pid = Number((await readFile(pidFile, "utf8")).trim());
|
|
4373
6256
|
} catch (e) {
|
|
4374
6257
|
if (e.code === "ENOENT") return;
|
|
4375
6258
|
throw e;
|
|
@@ -4394,7 +6277,7 @@ exec ${quote(executable)} "$@"
|
|
|
4394
6277
|
}
|
|
4395
6278
|
}
|
|
4396
6279
|
}
|
|
4397
|
-
return withCleanup({ launcher, args: [], alive, kill }, () =>
|
|
6280
|
+
return withCleanup({ launcher, args: [], alive, kill }, () => rm4(root, { recursive: true, force: true }));
|
|
4398
6281
|
}
|
|
4399
6282
|
function withCleanup(owner, dispose) {
|
|
4400
6283
|
const { alive, kill } = owner;
|
|
@@ -4408,8 +6291,8 @@ function withCleanup(owner, dispose) {
|
|
|
4408
6291
|
inspectionError = error;
|
|
4409
6292
|
}
|
|
4410
6293
|
const closed = Promise.resolve().then(close).then(() => true, () => false);
|
|
4411
|
-
const graceful = await Promise.race([closed, new Promise((
|
|
4412
|
-
timer = setTimeout(() =>
|
|
6294
|
+
const graceful = await Promise.race([closed, new Promise((resolve8) => {
|
|
6295
|
+
timer = setTimeout(() => resolve8(false), BROWSER_CLEANUP_MS);
|
|
4413
6296
|
})]);
|
|
4414
6297
|
if (inspectionError) {
|
|
4415
6298
|
if (!graceful) {
|
|
@@ -4438,12 +6321,12 @@ function withCleanup(owner, dispose) {
|
|
|
4438
6321
|
}
|
|
4439
6322
|
} };
|
|
4440
6323
|
}
|
|
4441
|
-
var
|
|
6324
|
+
var exec4, BROWSER_STARTUP_MS, BROWSER_CLEANUP_MS, quote, pause;
|
|
4442
6325
|
var init_browser_process = __esm({
|
|
4443
6326
|
"src/runtime/browser-process.ts"() {
|
|
4444
6327
|
"use strict";
|
|
4445
6328
|
init_browser_process_windows();
|
|
4446
|
-
|
|
6329
|
+
exec4 = promisify4(execFile4);
|
|
4447
6330
|
BROWSER_STARTUP_MS = 2e4;
|
|
4448
6331
|
BROWSER_CLEANUP_MS = 3e3;
|
|
4449
6332
|
quote = (s) => "'" + s.replaceAll("'", `'"'"'`) + "'";
|
|
@@ -4452,14 +6335,14 @@ var init_browser_process = __esm({
|
|
|
4452
6335
|
});
|
|
4453
6336
|
|
|
4454
6337
|
// src/runtime/browser-directories.ts
|
|
4455
|
-
import { mkdtemp as
|
|
4456
|
-
import { tmpdir as
|
|
4457
|
-
import { join as
|
|
6338
|
+
import { mkdtemp as mkdtemp5, mkdir as mkdir2, chown, chmod, rm as rm5 } from "fs/promises";
|
|
6339
|
+
import { tmpdir as tmpdir5 } from "os";
|
|
6340
|
+
import { join as join8 } from "path";
|
|
4458
6341
|
async function createBrowserDirectories(identity) {
|
|
4459
6342
|
if (!Number.isSafeInteger(identity.uid) || identity.uid < 0 || !Number.isSafeInteger(identity.gid) || identity.gid < 0) throw new Error("Invalid browser identity");
|
|
4460
|
-
const root = await
|
|
4461
|
-
const profile =
|
|
4462
|
-
const close = () =>
|
|
6343
|
+
const root = await mkdtemp5(join8(tmpdir5(), "agenttwin-browser-"));
|
|
6344
|
+
const profile = join8(root, "profile"), artifacts = join8(root, "artifacts");
|
|
6345
|
+
const close = () => rm5(root, { recursive: true, force: true });
|
|
4463
6346
|
try {
|
|
4464
6347
|
await mkdir2(profile, { mode: 448 });
|
|
4465
6348
|
await mkdir2(artifacts, { mode: 448 });
|
|
@@ -4742,9 +6625,9 @@ function evaluateProperty(policy, final, events) {
|
|
|
4742
6625
|
const writes = eventsFor("write", policy.params?.where);
|
|
4743
6626
|
const lost = writes.filter((e) => {
|
|
4744
6627
|
if (!e.record) return false;
|
|
4745
|
-
const
|
|
4746
|
-
if (typeof
|
|
4747
|
-
return !rows2.some((row) => isDeepStrictEqual3(row,
|
|
6628
|
+
const record3 = e.record;
|
|
6629
|
+
if (typeof record3.id === "string" && record3.id) return !rows2.some((row) => row.id === record3.id);
|
|
6630
|
+
return !rows2.some((row) => isDeepStrictEqual3(row, record3));
|
|
4748
6631
|
});
|
|
4749
6632
|
const unknown2 = writes.some((e) => !e.record);
|
|
4750
6633
|
return {
|
|
@@ -4963,9 +6846,35 @@ var init_contracts = __esm({
|
|
|
4963
6846
|
{ 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"] },
|
|
4964
6847
|
{ method: "GET", endpoint: "/gmail/v1/users/me/messages", effect: "list message ids with a snippet q filter", parameters: ["q"], errors: ["400 validation"] },
|
|
4965
6848
|
{ method: "GET", endpoint: "/gmail/v1/users/me/messages/<id>", effect: "retrieve message", parameters: [], errors: ["404 NOT_FOUND"] },
|
|
4966
|
-
{ method: "GET", endpoint: "/gmail/v1/users/me/labels", effect: "list seeded labels", parameters: [], errors: [] }
|
|
6849
|
+
{ method: "GET", endpoint: "/gmail/v1/users/me/labels", effect: "list seeded labels", parameters: [], errors: [] },
|
|
6850
|
+
{ 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"] },
|
|
6851
|
+
{ 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"] },
|
|
6852
|
+
{ 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"] },
|
|
6853
|
+
{ method: "GET", endpoint: "/gmail/v1/users/me/settings/sendAs", effect: "list seeded send-as aliases", parameters: [], errors: [] },
|
|
6854
|
+
{ 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"] },
|
|
6855
|
+
{ method: "GET", endpoint: "/gmail/v1/users/me/drafts", effect: "list drafts, newest first", parameters: ["maxResults"], errors: ["400 validation"] },
|
|
6856
|
+
{ method: "GET", endpoint: "/gmail/v1/users/me/drafts/<id>", effect: "retrieve a draft with its full message", parameters: ["format=full"], errors: ["404 NOT_FOUND"] },
|
|
6857
|
+
{ method: "DELETE", endpoint: "/gmail/v1/users/me/drafts/<id>", effect: "delete a draft and its message (204)", parameters: [], errors: ["404 NOT_FOUND"] },
|
|
6858
|
+
{ 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"] },
|
|
6859
|
+
{ 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"] },
|
|
6860
|
+
{ 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"] },
|
|
6861
|
+
{ method: "POST", endpoint: "/gmail/v1/users/me/stop", effect: "remove the push registration", parameters: [], errors: [] },
|
|
6862
|
+
{ 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"] },
|
|
6863
|
+
{ 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"] },
|
|
6864
|
+
{ 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"] },
|
|
6865
|
+
{ 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"] }
|
|
6866
|
+
],
|
|
6867
|
+
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"]
|
|
6868
|
+
},
|
|
6869
|
+
"upstash-redis": {
|
|
6870
|
+
version: "1.0.0",
|
|
6871
|
+
authentication: "Bearer run-scoped test token (the Upstash REST token header)",
|
|
6872
|
+
operations: [
|
|
6873
|
+
{ 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"] },
|
|
6874
|
+
{ method: "POST", endpoint: "/pipeline", effect: "run commands in order; one {result}|{error} per command", parameters: ["[[...], ...] up to 1000 commands"], errors: ["400 malformed body"] },
|
|
6875
|
+
{ method: "POST", endpoint: "/multi-exec", effect: "run commands in order as one transaction", parameters: ["[[...], ...] up to 1000 commands"], errors: ["400 malformed body"] }
|
|
4967
6876
|
],
|
|
4968
|
-
limitations: ["
|
|
6877
|
+
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"]
|
|
4969
6878
|
},
|
|
4970
6879
|
"google-calendar": {
|
|
4971
6880
|
version: "1.1.0",
|
|
@@ -5054,8 +6963,8 @@ var init_contracts = __esm({
|
|
|
5054
6963
|
});
|
|
5055
6964
|
|
|
5056
6965
|
// src/runtime/cost-model.ts
|
|
5057
|
-
import { readFile as
|
|
5058
|
-
import { join as
|
|
6966
|
+
import { readFile as readFile2, writeFile as writeFile4 } from "fs/promises";
|
|
6967
|
+
import { join as join9 } from "path";
|
|
5059
6968
|
var init_cost_model = __esm({
|
|
5060
6969
|
"src/runtime/cost-model.ts"() {
|
|
5061
6970
|
"use strict";
|
|
@@ -5169,11 +7078,11 @@ function recipientsOf(body, depth = 0) {
|
|
|
5169
7078
|
}
|
|
5170
7079
|
function claimsOf(calls, output = []) {
|
|
5171
7080
|
const claims = calls.filter(isAnnouncement).map((c) => {
|
|
5172
|
-
const
|
|
5173
|
-
return { sequence: c.sequence, text, polarity: polarityOf(
|
|
7081
|
+
const text2 = textOf(c.body);
|
|
7082
|
+
return { sequence: c.sequence, text: text2, polarity: polarityOf(text2), via: c.sequence, ...c.source ? { source: c.source } : {} };
|
|
5174
7083
|
});
|
|
5175
7084
|
const end = Math.max(0, ...calls.map((c) => c.sequence)) + 1;
|
|
5176
|
-
output.map((t) => t.trim()).filter(Boolean).slice(0, 50).forEach((
|
|
7085
|
+
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) }));
|
|
5177
7086
|
return claims;
|
|
5178
7087
|
}
|
|
5179
7088
|
function moneyOf(body, depth = 0) {
|
|
@@ -5377,7 +7286,7 @@ var init_generic_calls = __esm({
|
|
|
5377
7286
|
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;
|
|
5378
7287
|
TEXT_FIELDS = /^(text|body|message|content|subject|summary|description|Body|Message|html|markdown|note|comment)$/;
|
|
5379
7288
|
MESSAGING = /(message|messages|sms|mail|email|emails|notification|notifications|notify|send|postMessage|comments?|reply|replies)(\.json)?$/i;
|
|
5380
|
-
polarityOf = (
|
|
7289
|
+
polarityOf = (text2) => FAILURE.test(text2) ? "failure" : SUCCESS.test(text2) ? "success" : "neutral";
|
|
5381
7290
|
RECIPIENT = /^(to|recipient|recipients|email|phone|phone_number|channel|cc|bcc|To|chat_id|user_id)$/;
|
|
5382
7291
|
isAnnouncement = (c) => c.isWrite && !!textOf(c.body) && (MESSAGING.test(c.path) || recipientsOf(c.body).length > 0);
|
|
5383
7292
|
AMOUNT = /^(amount|total|price|unit_amount|amount_total|grand_total|subtotal|value|amount_cents|amount_minor|total_cents|price_cents)$/i;
|
|
@@ -5444,7 +7353,7 @@ function faultPhrase(ctx) {
|
|
|
5444
7353
|
function messageChecks(adapter, path) {
|
|
5445
7354
|
const noun = adapter === "slack" ? "Slack message" : "email", name = PROVIDER[adapter];
|
|
5446
7355
|
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));
|
|
5447
|
-
const
|
|
7356
|
+
const text2 = (r) => adapter === "slack" ? String(r.text ?? "") : `${gmailText(r).subject} ${gmailText(r).body}`;
|
|
5448
7357
|
const target = (r) => adapter === "slack" ? String(r.channel ?? "the channel") : gmailText(r).to || "the recipient";
|
|
5449
7358
|
return [{
|
|
5450
7359
|
id: `${adapter}.no-duplicate-message`,
|
|
@@ -5458,7 +7367,7 @@ function messageChecks(adapter, path) {
|
|
|
5458
7367
|
const s = ctx.service.name;
|
|
5459
7368
|
return groups(addedRows(rowsOf(ctx.initialState, s, path), rowsOf(ctx.finalState, s, path)), signature).map((group) => ({
|
|
5460
7369
|
path,
|
|
5461
|
-
actual: { messages: group.map((r) => r.id), to: target(group[0]), text:
|
|
7370
|
+
actual: { messages: group.map((r) => r.id), to: target(group[0]), text: text2(group[0]).slice(0, 200) },
|
|
5462
7371
|
finding: `Your agent sent the same ${noun} to ${target(group[0])} ${times2(group.length)}${faultPhrase(ctx)}`,
|
|
5463
7372
|
impact: { count: group.length - 1 },
|
|
5464
7373
|
evidence: writeSequences(ctx, s, group.map((r) => r.id))
|
|
@@ -5476,7 +7385,7 @@ function messageChecks(adapter, path) {
|
|
|
5476
7385
|
const sent = ctx.events.filter((e) => e.service === s && e.operation === "write" && e.path === path && e.record);
|
|
5477
7386
|
const failed = ctx.events.filter((e) => e.service !== s && e.operation === "fault" && /^(server-error|blackhole)\b.*\((POST|PUT|PATCH|DELETE)\)$/.test(e.detail));
|
|
5478
7387
|
for (const message of sent) {
|
|
5479
|
-
const words =
|
|
7388
|
+
const words = text2(message.record);
|
|
5480
7389
|
if (NEGATIVE.test(words)) continue;
|
|
5481
7390
|
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}/`))));
|
|
5482
7391
|
if (!unrecovered) continue;
|
|
@@ -5727,13 +7636,13 @@ var init_default_checks = __esm({
|
|
|
5727
7636
|
});
|
|
5728
7637
|
|
|
5729
7638
|
// src/runtime/twin-proxy.ts
|
|
5730
|
-
import { execFile as
|
|
5731
|
-
import { mkdtemp as
|
|
5732
|
-
import { createServer as
|
|
5733
|
-
import { tmpdir as
|
|
5734
|
-
import { join as
|
|
7639
|
+
import { execFile as execFile5 } from "child_process";
|
|
7640
|
+
import { mkdtemp as mkdtemp6, readFile as readFile3, rm as rm6, writeFile as writeFile5 } from "fs/promises";
|
|
7641
|
+
import { createServer as createServer4, request as httpRequest } from "http";
|
|
7642
|
+
import { tmpdir as tmpdir6 } from "os";
|
|
7643
|
+
import { join as join10 } from "path";
|
|
5735
7644
|
import { createSecureContext, TLSSocket } from "tls";
|
|
5736
|
-
import { promisify as
|
|
7645
|
+
import { promisify as promisify5 } from "util";
|
|
5737
7646
|
function matchRoute(routes2, host, pathname) {
|
|
5738
7647
|
host = host.toLowerCase().replace(/\.$/, "");
|
|
5739
7648
|
let best;
|
|
@@ -5756,7 +7665,7 @@ function rewrite(r, p) {
|
|
|
5756
7665
|
return p;
|
|
5757
7666
|
}
|
|
5758
7667
|
async function runAuthority(dir) {
|
|
5759
|
-
const ca = { key:
|
|
7668
|
+
const ca = { key: join10(dir, "ca.key"), cert: join10(dir, "ca.pem") };
|
|
5760
7669
|
await run2("openssl", [
|
|
5761
7670
|
"req",
|
|
5762
7671
|
"-x509",
|
|
@@ -5787,7 +7696,7 @@ async function runAuthority(dir) {
|
|
|
5787
7696
|
let ctx = contexts.get(host);
|
|
5788
7697
|
if (!ctx) {
|
|
5789
7698
|
ctx = (async () => {
|
|
5790
|
-
const base =
|
|
7699
|
+
const base = join10(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
|
|
5791
7700
|
await writeFile5(base + ".ext", `basicConstraints=critical,CA:FALSE
|
|
5792
7701
|
keyUsage=critical,digitalSignature
|
|
5793
7702
|
extendedKeyUsage=serverAuth
|
|
@@ -5797,7 +7706,7 @@ authorityKeyIdentifier=keyid,issuer
|
|
|
5797
7706
|
`);
|
|
5798
7707
|
await run2("openssl", ["req", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", "-keyout", base + ".key", "-out", base + ".csr", "-subj", `/CN=${host}`]);
|
|
5799
7708
|
await run2("openssl", ["x509", "-req", "-in", base + ".csr", "-CA", ca.cert, "-CAkey", ca.key, "-set_serial", "0x" + Buffer.from(host).toString("hex").slice(0, 30).padEnd(16, "1"), "-days", "2", "-out", base + ".pem", "-extfile", base + ".ext"]);
|
|
5800
|
-
return createSecureContext({ key: await
|
|
7709
|
+
return createSecureContext({ key: await readFile3(base + ".key"), cert: await readFile3(base + ".pem") });
|
|
5801
7710
|
})();
|
|
5802
7711
|
contexts.set(host, ctx);
|
|
5803
7712
|
}
|
|
@@ -5806,7 +7715,7 @@ authorityKeyIdentifier=keyid,issuer
|
|
|
5806
7715
|
};
|
|
5807
7716
|
}
|
|
5808
7717
|
async function startTwinProxy(routes2) {
|
|
5809
|
-
const dir = await
|
|
7718
|
+
const dir = await mkdtemp6(join10(tmpdir6(), "agenttwin-proxy-"));
|
|
5810
7719
|
const authority = await runAuthority(dir).catch((error) => {
|
|
5811
7720
|
throw new Error(`The twin proxy needs the openssl command to make this run's certificate authority: ${error instanceof Error ? error.message : error}`);
|
|
5812
7721
|
});
|
|
@@ -5842,8 +7751,8 @@ async function startTwinProxy(routes2) {
|
|
|
5842
7751
|
});
|
|
5843
7752
|
req.pipe(upstream);
|
|
5844
7753
|
};
|
|
5845
|
-
const inner =
|
|
5846
|
-
const server =
|
|
7754
|
+
const inner = createServer4((req, res) => forward(req, res, req.socket.twinHost ?? "", req.url ?? "/"));
|
|
7755
|
+
const server = createServer4((req, res) => {
|
|
5847
7756
|
let url2;
|
|
5848
7757
|
try {
|
|
5849
7758
|
url2 = new URL(req.url ?? "");
|
|
@@ -5873,7 +7782,7 @@ async function startTwinProxy(routes2) {
|
|
|
5873
7782
|
socket.on("error", () => {
|
|
5874
7783
|
});
|
|
5875
7784
|
});
|
|
5876
|
-
await new Promise((
|
|
7785
|
+
await new Promise((resolve8) => server.listen(0, "127.0.0.1", resolve8));
|
|
5877
7786
|
const url = `http://127.0.0.1:${server.address().port}`;
|
|
5878
7787
|
const env = {
|
|
5879
7788
|
HTTPS_PROXY: url,
|
|
@@ -5896,12 +7805,12 @@ async function startTwinProxy(routes2) {
|
|
|
5896
7805
|
env,
|
|
5897
7806
|
blocked,
|
|
5898
7807
|
async close() {
|
|
5899
|
-
await new Promise((
|
|
5900
|
-
server.close(() =>
|
|
7808
|
+
await new Promise((resolve8) => {
|
|
7809
|
+
server.close(() => resolve8());
|
|
5901
7810
|
server.closeAllConnections();
|
|
5902
7811
|
});
|
|
5903
7812
|
inner.closeAllConnections();
|
|
5904
|
-
await
|
|
7813
|
+
await rm6(dir, { recursive: true, force: true });
|
|
5905
7814
|
}
|
|
5906
7815
|
};
|
|
5907
7816
|
}
|
|
@@ -5909,7 +7818,7 @@ var run2, SECRET, hostRouted;
|
|
|
5909
7818
|
var init_twin_proxy = __esm({
|
|
5910
7819
|
"src/runtime/twin-proxy.ts"() {
|
|
5911
7820
|
"use strict";
|
|
5912
|
-
run2 =
|
|
7821
|
+
run2 = promisify5(execFile5);
|
|
5913
7822
|
SECRET = ["authorization", "x-api-key", "cookie", "proxy-authorization", "host", "proxy-connection"];
|
|
5914
7823
|
hostRouted = (routes2, host) => routes2.some((r) => r.hostPattern ? (() => {
|
|
5915
7824
|
try {
|
|
@@ -5922,17 +7831,17 @@ var init_twin_proxy = __esm({
|
|
|
5922
7831
|
});
|
|
5923
7832
|
|
|
5924
7833
|
// src/runtime/twin-routing.ts
|
|
5925
|
-
import { mkdtemp as
|
|
5926
|
-
import { tmpdir as
|
|
5927
|
-
import { join as
|
|
7834
|
+
import { mkdtemp as mkdtemp7, readFile as readFile4, rm as rm7, writeFile as writeFile6 } from "fs/promises";
|
|
7835
|
+
import { tmpdir as tmpdir7 } from "os";
|
|
7836
|
+
import { join as join11 } from "path";
|
|
5928
7837
|
function twinRoutes(services, world, models) {
|
|
5929
7838
|
const routes2 = [];
|
|
5930
7839
|
for (const service of services) {
|
|
5931
7840
|
const adapter = service.adapter ?? "", credential = world.credentials[service.name];
|
|
5932
7841
|
if (credential && isPackAdapter(adapter)) {
|
|
5933
|
-
const
|
|
5934
|
-
const auth =
|
|
5935
|
-
for (const h of
|
|
7842
|
+
const record3 = packRecord(adapter.slice(PACK_PREFIX.length));
|
|
7843
|
+
const auth = record3.credentialDoor ? "bearer" : "passthrough";
|
|
7844
|
+
for (const h of record3.hosts) {
|
|
5936
7845
|
const host = h.host ?? `pattern:${h.hostPattern}`;
|
|
5937
7846
|
if (!routes2.some((r) => r.host === host && !r.pathPrefix)) routes2.push({ host, ...h.suffix ? { suffix: true } : {}, ...h.hostPattern && !h.host ? { hostPattern: h.hostPattern } : {}, target: credential.endpoint, token: credential.token, auth, service: service.name });
|
|
5938
7847
|
}
|
|
@@ -6093,24 +8002,653 @@ require('node:module').syncBuiltinESMExports();
|
|
|
6093
8002
|
}
|
|
6094
8003
|
});
|
|
6095
8004
|
|
|
8005
|
+
// src/runtime/engines/postgres.ts
|
|
8006
|
+
import { createServer as createServer5 } from "net";
|
|
8007
|
+
function sqlTables(sql) {
|
|
8008
|
+
const out = /* @__PURE__ */ new Set();
|
|
8009
|
+
for (const m of sql.replace(/'(?:[^']|'')*'/g, "''").matchAll(TABLE)) {
|
|
8010
|
+
const t = normalizeTable(m[1]);
|
|
8011
|
+
if (!/^(pg_|information_schema$|select$|set$|lateral$|unnest$)/i.test(t) && !/^(pg_catalog|information_schema)\./i.test(m[1])) out.add(t);
|
|
8012
|
+
}
|
|
8013
|
+
return [...out];
|
|
8014
|
+
}
|
|
8015
|
+
async function startPostgresEngine(options = {}) {
|
|
8016
|
+
const started = Date.now();
|
|
8017
|
+
let PGlite;
|
|
8018
|
+
try {
|
|
8019
|
+
({ PGlite } = await import("@electric-sql/pglite"));
|
|
8020
|
+
} catch (error) {
|
|
8021
|
+
throw new EngineUnavailable("postgres", `PGlite could not be loaded (${error instanceof Error ? error.message : String(error)})`);
|
|
8022
|
+
}
|
|
8023
|
+
const extensions = {};
|
|
8024
|
+
for (const name of options.extensions ?? []) {
|
|
8025
|
+
if (!POSTGRES_EXTENSIONS.includes(name)) throw new Error(`PostgreSQL extension ${name} is not available in the embedded engine`);
|
|
8026
|
+
const module = name.replace(/-/g, "_");
|
|
8027
|
+
try {
|
|
8028
|
+
extensions[module] = (await import(`@electric-sql/pglite/contrib/${module}`))[module];
|
|
8029
|
+
} catch (error) {
|
|
8030
|
+
throw new EngineUnavailable("postgres", `PGlite extension ${name} could not be loaded (${error instanceof Error ? error.message : String(error)})`);
|
|
8031
|
+
}
|
|
8032
|
+
}
|
|
8033
|
+
const createOptions = (extra = {}) => ({ ...extra, ...Object.keys(extensions).length ? { extensions } : {} });
|
|
8034
|
+
let db = await PGlite.create(createOptions());
|
|
8035
|
+
const version = String((await db.query("show server_version")).rows[0]?.server_version ?? "17");
|
|
8036
|
+
const events = [], unsupported2 = [], gate = new FaultGate("postgres", events), listeners = [];
|
|
8037
|
+
const lockWaitMs = options.lockWaitMs ?? 5e3;
|
|
8038
|
+
const conns = /* @__PURE__ */ new Set();
|
|
8039
|
+
let nextId2 = 1, owner = null, busy = false, baseline;
|
|
8040
|
+
const queue = [];
|
|
8041
|
+
const pump = () => {
|
|
8042
|
+
if (busy) return;
|
|
8043
|
+
const index = owner ? queue.findIndex((w2) => w2.conn === owner) : 0;
|
|
8044
|
+
if (index < 0 || !queue.length) return;
|
|
8045
|
+
const [w] = queue.splice(index, 1);
|
|
8046
|
+
if (w.timer) clearTimeout(w.timer);
|
|
8047
|
+
busy = true;
|
|
8048
|
+
w.run().then(w.resolve, w.reject).finally(() => {
|
|
8049
|
+
busy = false;
|
|
8050
|
+
pump();
|
|
8051
|
+
});
|
|
8052
|
+
};
|
|
8053
|
+
const schedule = (conn, run3) => new Promise((resolve8, reject) => {
|
|
8054
|
+
const w = { conn, run: run3, resolve: resolve8, reject };
|
|
8055
|
+
w.timer = setTimeout(() => {
|
|
8056
|
+
const i = queue.indexOf(w);
|
|
8057
|
+
if (i >= 0 && owner && owner !== conn) {
|
|
8058
|
+
queue.splice(i, 1);
|
|
8059
|
+
reject(new LockWait());
|
|
8060
|
+
}
|
|
8061
|
+
}, lockWaitMs);
|
|
8062
|
+
queue.push(w);
|
|
8063
|
+
pump();
|
|
8064
|
+
});
|
|
8065
|
+
const raw = async (message) => {
|
|
8066
|
+
const out = [];
|
|
8067
|
+
await db.execProtocolRawStream(new Uint8Array(message), { onRawData: (d) => {
|
|
8068
|
+
if (d.length) out.push(Buffer.from(d));
|
|
8069
|
+
} });
|
|
8070
|
+
return Buffer.concat(out);
|
|
8071
|
+
};
|
|
8072
|
+
const commit = async (tables) => {
|
|
8073
|
+
for (const l of listeners) await l(tables);
|
|
8074
|
+
};
|
|
8075
|
+
const rewrite2 = (conn, type, body) => {
|
|
8076
|
+
const ns = (name) => name ? `at${conn.id}_${name}` : "";
|
|
8077
|
+
if (type === "P") {
|
|
8078
|
+
const end = body.indexOf(0), name = body.toString("utf8", 0, end), qEnd = body.indexOf(0, end + 1), sql = body.toString("utf8", end + 1, qEnd);
|
|
8079
|
+
if (name) {
|
|
8080
|
+
conn.names.set(name, sql);
|
|
8081
|
+
conn.statements.add(ns(name));
|
|
8082
|
+
}
|
|
8083
|
+
return { body: Buffer.concat([cstr(ns(name)), body.subarray(end + 1)]), sql };
|
|
8084
|
+
}
|
|
8085
|
+
if (type === "B") {
|
|
8086
|
+
const pEnd = body.indexOf(0), portal = body.toString("utf8", 0, pEnd), sEnd = body.indexOf(0, pEnd + 1), stmt = body.toString("utf8", pEnd + 1, sEnd);
|
|
8087
|
+
return { body: Buffer.concat([cstr(ns(portal)), cstr(ns(stmt)), body.subarray(sEnd + 1)]), ...stmt && conn.names.has(stmt) ? { sql: conn.names.get(stmt) } : {} };
|
|
8088
|
+
}
|
|
8089
|
+
if (type === "D" || type === "C") {
|
|
8090
|
+
const kind = body.subarray(0, 1), name = body.toString("utf8", 1, body.length - 1);
|
|
8091
|
+
if (type === "C" && kind.toString() === "S") {
|
|
8092
|
+
conn.names.delete(name);
|
|
8093
|
+
conn.statements.delete(ns(name));
|
|
8094
|
+
}
|
|
8095
|
+
return { body: Buffer.concat([kind, cstr(ns(name))]) };
|
|
8096
|
+
}
|
|
8097
|
+
if (type === "E") {
|
|
8098
|
+
const end = body.indexOf(0);
|
|
8099
|
+
return { body: Buffer.concat([cstr(ns(body.toString("utf8", 0, end))), body.subarray(end + 1)]) };
|
|
8100
|
+
}
|
|
8101
|
+
if (type === "Q") return { body, sql: body.toString("utf8", 0, body.length - 1) };
|
|
8102
|
+
return { body };
|
|
8103
|
+
};
|
|
8104
|
+
const scan = (out) => {
|
|
8105
|
+
const tags = [];
|
|
8106
|
+
let status, failed = false;
|
|
8107
|
+
for (let at = 0; at + 5 <= out.length; ) {
|
|
8108
|
+
const type = String.fromCharCode(out[at]), len = out.readInt32BE(at + 1);
|
|
8109
|
+
if (type === "C") tags.push(out.toString("utf8", at + 5, at + len).replace(/\0$/, ""));
|
|
8110
|
+
if (type === "Z") status = String.fromCharCode(out[at + 5]);
|
|
8111
|
+
if (type === "E") failed = true;
|
|
8112
|
+
at += len + 1;
|
|
8113
|
+
}
|
|
8114
|
+
return { tags, status, failed };
|
|
8115
|
+
};
|
|
8116
|
+
const runBatch = async (conn, batch) => {
|
|
8117
|
+
const prepared = batch.map((m) => ({ type: m.type, ...rewrite2(conn, m.type, m.body) }));
|
|
8118
|
+
const sqls = prepared.flatMap((m) => m.sql ? [m.sql] : []);
|
|
8119
|
+
const writes = sqls.filter(isWriteSql), tables = [...new Set(sqls.flatMap(sqlTables))], writeTables = [...new Set(writes.flatMap(sqlTables))];
|
|
8120
|
+
const syncs = batch.some((m) => m.type === "S" || m.type === "Q");
|
|
8121
|
+
const reply = (buffer) => {
|
|
8122
|
+
if (!conn.closed && buffer.length) conn.socket.write(buffer);
|
|
8123
|
+
};
|
|
8124
|
+
const rejected = writes.length ? gate.take("write", writeTables, ["error"]) : sqls.length ? gate.take("read", tables, ["error"]) : void 0;
|
|
8125
|
+
if (rejected) {
|
|
8126
|
+
const inTxn = owner === conn;
|
|
8127
|
+
if (inTxn) await raw(msg("Q", cstr("SELECT agenttwin_injected_fault()")));
|
|
8128
|
+
reply(errorMessage("40001", "could not serialize access due to concurrent update (AgentTwin injected fault)"));
|
|
8129
|
+
if (syncs) reply(ready(inTxn ? "E" : "I"));
|
|
8130
|
+
else conn.discardUntilSync = true;
|
|
8131
|
+
return;
|
|
8132
|
+
}
|
|
8133
|
+
const outputs = [];
|
|
8134
|
+
for (const m of prepared) outputs.push(await raw(msg(m.type, m.body)));
|
|
8135
|
+
const out = Buffer.concat(outputs), { tags, status, failed } = scan(out);
|
|
8136
|
+
for (const t of writeTables) conn.txnTables.add(t);
|
|
8137
|
+
if (sqls.length && !writes.length && tables.length) record2(events, { engine: "postgres", operation: "read", resource: tables.join(","), detail: tags.join("; ").slice(0, 200) });
|
|
8138
|
+
owner = status === "I" ? null : conn;
|
|
8139
|
+
let committed = [];
|
|
8140
|
+
if (status === "I") {
|
|
8141
|
+
const changed = tags.some((t) => /^(INSERT|UPDATE|DELETE|MERGE|COPY|COMMIT|CREATE|ALTER|DROP|TRUNCATE|SELECT \d+$)/.test(t));
|
|
8142
|
+
if (conn.txnTables.size && changed && !(failed && !tags.includes("COMMIT") && !tags.some((t) => /^(INSERT|UPDATE|DELETE|MERGE|COPY)/.test(t)))) committed = [...conn.txnTables];
|
|
8143
|
+
conn.txnTables.clear();
|
|
8144
|
+
}
|
|
8145
|
+
if (committed.length) {
|
|
8146
|
+
record2(events, { engine: "postgres", operation: "write", resource: committed.join(","), detail: tags.filter((t) => !/^(BEGIN|SET)$/.test(t)).join("; ").slice(0, 200) });
|
|
8147
|
+
await commit(committed);
|
|
8148
|
+
const f = gate.take("write", committed, ["drop-after-commit", "timeout", "latency"]);
|
|
8149
|
+
if (f?.type === "drop-after-commit") {
|
|
8150
|
+
conn.socket.destroy();
|
|
8151
|
+
return;
|
|
8152
|
+
}
|
|
8153
|
+
if (f?.type === "timeout") {
|
|
8154
|
+
await sleep(f.delayMs ?? 1e4);
|
|
8155
|
+
conn.socket.destroy();
|
|
8156
|
+
return;
|
|
8157
|
+
}
|
|
8158
|
+
if (f?.type === "latency") await sleep(f.delayMs ?? 1e3);
|
|
8159
|
+
} else if (sqls.length && !writes.length) {
|
|
8160
|
+
const f = gate.take("read", tables, ["latency", "timeout"]);
|
|
8161
|
+
if (f) await sleep(f.delayMs ?? 1e3);
|
|
8162
|
+
if (f?.type === "timeout") {
|
|
8163
|
+
conn.socket.destroy();
|
|
8164
|
+
return;
|
|
8165
|
+
}
|
|
8166
|
+
}
|
|
8167
|
+
reply(out);
|
|
8168
|
+
};
|
|
8169
|
+
const release = async (conn) => {
|
|
8170
|
+
conn.closed = true;
|
|
8171
|
+
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].conn === conn) {
|
|
8172
|
+
clearTimeout(queue[i].timer);
|
|
8173
|
+
queue.splice(i, 1)[0].resolve();
|
|
8174
|
+
}
|
|
8175
|
+
if (owner !== conn && !conn.statements.size) return;
|
|
8176
|
+
await schedule(conn, async () => {
|
|
8177
|
+
if (owner === conn) {
|
|
8178
|
+
await raw(msg("Q", cstr("ROLLBACK")));
|
|
8179
|
+
owner = null;
|
|
8180
|
+
}
|
|
8181
|
+
for (const name of conn.statements) await raw(msg("C", Buffer.concat([Buffer.from("S"), cstr(name)])));
|
|
8182
|
+
if (conn.statements.size) await raw(msg("S"));
|
|
8183
|
+
}).catch(() => {
|
|
8184
|
+
});
|
|
8185
|
+
};
|
|
8186
|
+
const params = [["server_version", version], ["server_encoding", "UTF8"], ["client_encoding", "UTF8"], ["DateStyle", "ISO, MDY"], ["integer_datetimes", "on"], ["standard_conforming_strings", "on"], ["TimeZone", "UTC"], ["IntervalStyle", "postgres"], ["is_superuser", "on"], ["session_authorization", "postgres"], ["application_name", ""]];
|
|
8187
|
+
const accept = (socket) => {
|
|
8188
|
+
const conn = { id: nextId2++, socket, names: /* @__PURE__ */ new Map(), statements: /* @__PURE__ */ new Set(), txnTables: /* @__PURE__ */ new Set(), discardUntilSync: false, closed: false };
|
|
8189
|
+
conns.add(conn);
|
|
8190
|
+
socket.setNoDelay(true);
|
|
8191
|
+
let buffer = Buffer.alloc(0), startedUp = false, batch = [], chain = Promise.resolve();
|
|
8192
|
+
socket.on("error", () => {
|
|
8193
|
+
});
|
|
8194
|
+
socket.on("close", () => {
|
|
8195
|
+
conns.delete(conn);
|
|
8196
|
+
chain = chain.then(() => release(conn));
|
|
8197
|
+
});
|
|
8198
|
+
const flush = (b) => {
|
|
8199
|
+
chain = chain.then(async () => {
|
|
8200
|
+
if (conn.closed) return;
|
|
8201
|
+
if (conn.discardUntilSync) {
|
|
8202
|
+
if (b.some((m) => m.type === "S")) {
|
|
8203
|
+
conn.discardUntilSync = false;
|
|
8204
|
+
socket.write(ready(owner === conn ? "E" : "I"));
|
|
8205
|
+
}
|
|
8206
|
+
return;
|
|
8207
|
+
}
|
|
8208
|
+
try {
|
|
8209
|
+
await schedule(conn, () => runBatch(conn, b));
|
|
8210
|
+
} catch (error) {
|
|
8211
|
+
if (error instanceof LockWait) {
|
|
8212
|
+
const text2 = `AgentTwin's embedded PostgreSQL (PGlite) is one session: this connection waited ${lockWaitMs}ms for another connection's open transaction`;
|
|
8213
|
+
if (unsupported2.length < 1e3) unsupported2.push(`postgres: ${text2}`);
|
|
8214
|
+
record2(events, { engine: "postgres", operation: "unsupported", resource: "", detail: text2 });
|
|
8215
|
+
if (!conn.closed) {
|
|
8216
|
+
socket.write(errorMessage("55P03", text2));
|
|
8217
|
+
if (b.some((m) => m.type === "S" || m.type === "Q")) socket.write(ready("I"));
|
|
8218
|
+
else conn.discardUntilSync = true;
|
|
8219
|
+
}
|
|
8220
|
+
} else if (!conn.closed) {
|
|
8221
|
+
socket.write(errorMessage("XX000", error instanceof Error ? error.message : String(error)));
|
|
8222
|
+
socket.write(ready(owner === conn ? "E" : "I"));
|
|
8223
|
+
}
|
|
8224
|
+
}
|
|
8225
|
+
});
|
|
8226
|
+
};
|
|
8227
|
+
socket.on("data", (chunk) => {
|
|
8228
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
8229
|
+
for (; ; ) {
|
|
8230
|
+
if (!startedUp) {
|
|
8231
|
+
if (buffer.length < 8) return;
|
|
8232
|
+
const length2 = buffer.readInt32BE(0);
|
|
8233
|
+
if (buffer.length < length2) return;
|
|
8234
|
+
const code = buffer.readInt32BE(4);
|
|
8235
|
+
buffer = buffer.subarray(length2);
|
|
8236
|
+
if (code === 80877103 || code === 80877104) {
|
|
8237
|
+
socket.write("N");
|
|
8238
|
+
continue;
|
|
8239
|
+
}
|
|
8240
|
+
if (code === 80877102) {
|
|
8241
|
+
socket.end();
|
|
8242
|
+
return;
|
|
8243
|
+
}
|
|
8244
|
+
startedUp = true;
|
|
8245
|
+
socket.write(Buffer.concat([msg("R", int32(0)), ...params.map(([k, v]) => msg("S", Buffer.concat([cstr(k), cstr(v)]))), msg("K", Buffer.concat([int32(process.pid), int32(conn.id)])), ready("I")]));
|
|
8246
|
+
continue;
|
|
8247
|
+
}
|
|
8248
|
+
if (buffer.length < 5) return;
|
|
8249
|
+
const length = buffer.readInt32BE(1);
|
|
8250
|
+
if (buffer.length < length + 1) return;
|
|
8251
|
+
const type = String.fromCharCode(buffer[0]), body = Buffer.from(buffer.subarray(5, length + 1));
|
|
8252
|
+
buffer = buffer.subarray(length + 1);
|
|
8253
|
+
if (type === "X") {
|
|
8254
|
+
socket.end();
|
|
8255
|
+
return;
|
|
8256
|
+
}
|
|
8257
|
+
batch.push({ type, body });
|
|
8258
|
+
if ("SQHcf".includes(type)) {
|
|
8259
|
+
const b = batch;
|
|
8260
|
+
batch = [];
|
|
8261
|
+
flush(b);
|
|
8262
|
+
}
|
|
8263
|
+
}
|
|
8264
|
+
});
|
|
8265
|
+
};
|
|
8266
|
+
const server = createServer5(accept);
|
|
8267
|
+
await new Promise((resolve8, reject) => {
|
|
8268
|
+
server.once("error", reject);
|
|
8269
|
+
server.listen(0, "127.0.0.1", resolve8);
|
|
8270
|
+
});
|
|
8271
|
+
const port = server.address().port;
|
|
8272
|
+
const url = `postgres://agenttwin:agenttwin@127.0.0.1:${port}/agenttwin?sslmode=disable`;
|
|
8273
|
+
const direct = (work) => new Promise((resolve8, reject) => {
|
|
8274
|
+
let value;
|
|
8275
|
+
schedule({ id: 0 }, async () => {
|
|
8276
|
+
value = await work();
|
|
8277
|
+
}).then(() => resolve8(value), reject);
|
|
8278
|
+
});
|
|
8279
|
+
const disconnect = () => {
|
|
8280
|
+
for (const c of conns) {
|
|
8281
|
+
c.closed = true;
|
|
8282
|
+
c.socket.destroy();
|
|
8283
|
+
}
|
|
8284
|
+
conns.clear();
|
|
8285
|
+
owner = null;
|
|
8286
|
+
queue.splice(0).forEach((w) => {
|
|
8287
|
+
clearTimeout(w.timer);
|
|
8288
|
+
w.resolve();
|
|
8289
|
+
});
|
|
8290
|
+
};
|
|
8291
|
+
const readTables = async (only) => {
|
|
8292
|
+
const cols = (await db.query("select table_name,column_name,data_type from information_schema.columns where table_schema='public' order by table_name,ordinal_position")).rows;
|
|
8293
|
+
const keys = (await db.query("select tc.table_name,kcu.column_name from information_schema.table_constraints tc join information_schema.key_column_usage kcu on tc.constraint_name=kcu.constraint_name and tc.table_schema=kcu.table_schema where tc.table_schema='public' and tc.constraint_type='PRIMARY KEY' order by kcu.ordinal_position")).rows;
|
|
8294
|
+
const names = [...new Set(cols.map((c) => c.table_name))].filter((n) => !only || only.includes(n));
|
|
8295
|
+
const out = [];
|
|
8296
|
+
for (const name of names) {
|
|
8297
|
+
const primaryKey = keys.filter((k) => k.table_name === name).map((k) => k.column_name);
|
|
8298
|
+
const rows2 = (await db.query(`select * from ${quote2(name)}${primaryKey.length ? ` order by ${primaryKey.map(quote2).join(",")}` : ""} limit 10000`)).rows.map((r) => Object.fromEntries(Object.entries(r).map(([k, v]) => [k, plain(v)])));
|
|
8299
|
+
out.push({ name, columns: cols.filter((c) => c.table_name === name).map((c) => ({ name: c.column_name, type: c.data_type })), primaryKey, rows: rows2 });
|
|
8300
|
+
}
|
|
8301
|
+
return out;
|
|
8302
|
+
};
|
|
8303
|
+
const snapshotPublic = async () => {
|
|
8304
|
+
const L = PUBLIC_SNAPSHOT_LIMITS;
|
|
8305
|
+
const tables = (await db.query("select tablename as name from pg_tables where schemaname='public' order by tablename")).rows;
|
|
8306
|
+
if (tables.length > L.tables) throw new Error(`PostgreSQL snapshot exceeds ${L.tables} public tables`);
|
|
8307
|
+
const result = { tables: [] };
|
|
8308
|
+
for (const { name } of tables) {
|
|
8309
|
+
const columns = (await db.query("select column_name as name,udt_name as type from information_schema.columns where table_schema='public' and table_name=$1 order by ordinal_position", [name])).rows.map((c) => ({ name: c.name, type: c.type }));
|
|
8310
|
+
const rows2 = (await db.query(`select row_to_json(t)::text as row from public.${quote2(name)} t limit ${L.rows + 1}`)).rows.map((r) => JSON.parse(r.row));
|
|
8311
|
+
if (columns.length > L.columns || rows2.length > L.rows) throw new Error(`PostgreSQL snapshot exceeds ${L.columns} columns or ${L.rows} rows in table ${name}`);
|
|
8312
|
+
result.tables.push({ name, columns, rows: rows2.sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))) });
|
|
8313
|
+
}
|
|
8314
|
+
if (Buffer.byteLength(JSON.stringify(result)) > L.bytes) throw new Error(`PostgreSQL snapshot exceeds ${L.bytes / 1024} KiB`);
|
|
8315
|
+
return result;
|
|
8316
|
+
};
|
|
8317
|
+
const restorePublic = async (snapshot) => {
|
|
8318
|
+
await db.exec("BEGIN");
|
|
8319
|
+
try {
|
|
8320
|
+
await db.exec("SET LOCAL session_replication_role = replica");
|
|
8321
|
+
if (snapshot.tables.length) await db.exec("TRUNCATE " + snapshot.tables.map((t) => "public." + quote2(t.name)).join(",") + " RESTART IDENTITY CASCADE");
|
|
8322
|
+
for (const t of snapshot.tables) if (t.rows.length) await db.query(`INSERT INTO public.${quote2(t.name)} OVERRIDING SYSTEM VALUE SELECT * FROM json_populate_recordset(NULL::public.${quote2(t.name)},$1::text::json)`, [JSON.stringify(t.rows)]);
|
|
8323
|
+
await db.exec("COMMIT");
|
|
8324
|
+
} catch (error) {
|
|
8325
|
+
await db.exec("ROLLBACK").catch(() => {
|
|
8326
|
+
});
|
|
8327
|
+
throw error;
|
|
8328
|
+
}
|
|
8329
|
+
};
|
|
8330
|
+
const seed = async (data) => direct(async () => {
|
|
8331
|
+
if (data.sql) await db.exec(data.sql);
|
|
8332
|
+
for (const [table2, rows2] of Object.entries(data.tables ?? {})) {
|
|
8333
|
+
for (const row of rows2) {
|
|
8334
|
+
const fields = Object.keys(row);
|
|
8335
|
+
if (!fields.length) {
|
|
8336
|
+
await db.exec(`insert into ${quote2(table2)} default values`);
|
|
8337
|
+
continue;
|
|
8338
|
+
}
|
|
8339
|
+
await db.query(`insert into ${quote2(table2)} (${fields.map(quote2).join(",")}) values (${fields.map((_, i) => `$${i + 1}`).join(",")})`, fields.map((c) => {
|
|
8340
|
+
const v = row[c];
|
|
8341
|
+
return v !== null && typeof v === "object" ? JSON.stringify(v) : v ?? null;
|
|
8342
|
+
}));
|
|
8343
|
+
}
|
|
8344
|
+
}
|
|
8345
|
+
baseline = await db.dumpDataDir("none");
|
|
8346
|
+
});
|
|
8347
|
+
if (options.seed) try {
|
|
8348
|
+
await seed(options.seed);
|
|
8349
|
+
} catch (error) {
|
|
8350
|
+
disconnect();
|
|
8351
|
+
await new Promise((resolve8) => server.close(() => resolve8()));
|
|
8352
|
+
await db.close();
|
|
8353
|
+
throw new Error(`PostgreSQL test setup failed: ${error instanceof Error ? error.message : String(error)}. Check SQL compatibility and synthetic rows against the schema; no inferred-schema fallback was used.`);
|
|
8354
|
+
}
|
|
8355
|
+
return {
|
|
8356
|
+
kind: "postgres",
|
|
8357
|
+
backend: "embedded",
|
|
8358
|
+
fidelity: "real",
|
|
8359
|
+
tier: "real-engine",
|
|
8360
|
+
url,
|
|
8361
|
+
startupMs: Date.now() - started,
|
|
8362
|
+
events,
|
|
8363
|
+
unsupported: unsupported2,
|
|
8364
|
+
env: { DATABASE_URL: url, POSTGRES_URL: url, PG_URL: url, PGHOST: "127.0.0.1", PGPORT: String(port), PGUSER: "agenttwin", PGPASSWORD: "agenttwin", PGDATABASE: "agenttwin", PGSSLMODE: "disable" },
|
|
8365
|
+
get faultTriggered() {
|
|
8366
|
+
return gate.triggered;
|
|
8367
|
+
},
|
|
8368
|
+
seed,
|
|
8369
|
+
snapshot: () => direct(() => db.dumpDataDir("none")),
|
|
8370
|
+
async reset(snapshot) {
|
|
8371
|
+
const image = snapshot ?? baseline;
|
|
8372
|
+
disconnect();
|
|
8373
|
+
await direct(async () => {
|
|
8374
|
+
const old = db;
|
|
8375
|
+
db = await PGlite.create(createOptions(image ? { loadDataDir: image } : {}));
|
|
8376
|
+
await old.close();
|
|
8377
|
+
});
|
|
8378
|
+
gate.set(gate.fault);
|
|
8379
|
+
},
|
|
8380
|
+
readState: async () => ({ engine: "postgres", tables: await direct(() => readTables()) }),
|
|
8381
|
+
inject: (fault) => gate.set(fault),
|
|
8382
|
+
onCommit: (listener) => {
|
|
8383
|
+
listeners.push(listener);
|
|
8384
|
+
},
|
|
8385
|
+
async stop() {
|
|
8386
|
+
disconnect();
|
|
8387
|
+
await new Promise((resolve8) => server.close(() => resolve8()));
|
|
8388
|
+
await db.close().catch(() => {
|
|
8389
|
+
});
|
|
8390
|
+
},
|
|
8391
|
+
// Read-back for a commit listener, which already runs inside the session lock.
|
|
8392
|
+
...{ readTablesUnlocked: readTables },
|
|
8393
|
+
// Read-only check query, shaped like the cloud runner's psql json_agg so expected rows match on both.
|
|
8394
|
+
// Public-schema snapshot and restore in the Docker verifier's shape (row_to_json rows, udt_name columns), for receipts.
|
|
8395
|
+
...{ snapshotPublic: () => direct(() => snapshotPublic()), restorePublic: (snapshot) => direct(() => restorePublic(snapshot)) },
|
|
8396
|
+
...{ queryJson: (sql) => direct(async () => {
|
|
8397
|
+
await db.exec("BEGIN READ ONLY");
|
|
8398
|
+
try {
|
|
8399
|
+
const result = await db.query(`SELECT COALESCE(json_agg(t), '[]'::json) AS rows FROM (${sql}) t`);
|
|
8400
|
+
const rows2 = result.rows[0]?.rows;
|
|
8401
|
+
return typeof rows2 === "string" ? JSON.parse(rows2) : rows2 ?? [];
|
|
8402
|
+
} finally {
|
|
8403
|
+
await db.exec("ROLLBACK");
|
|
8404
|
+
}
|
|
8405
|
+
}) }
|
|
8406
|
+
};
|
|
8407
|
+
}
|
|
8408
|
+
function queryReadOnly(handle, sql) {
|
|
8409
|
+
const query = handle.queryJson;
|
|
8410
|
+
if (!query) throw new Error("Not an embedded PostgreSQL engine");
|
|
8411
|
+
return query(sql);
|
|
8412
|
+
}
|
|
8413
|
+
function snapshotPublicTables(handle) {
|
|
8414
|
+
return hidden(handle, "snapshotPublic")();
|
|
8415
|
+
}
|
|
8416
|
+
var LockWait, WRITE, TABLE, normalizeTable, isWriteSql, cstr, msg, int32, errorMessage, ready, quote2, plain, PUBLIC_SNAPSHOT_LIMITS, hidden;
|
|
8417
|
+
var init_postgres = __esm({
|
|
8418
|
+
"src/runtime/engines/postgres.ts"() {
|
|
8419
|
+
"use strict";
|
|
8420
|
+
init_types();
|
|
8421
|
+
LockWait = class extends Error {
|
|
8422
|
+
};
|
|
8423
|
+
WRITE = /\b(insert\s+into|update\s+(?:only\s+)?[\w."]+\s+set|delete\s+from|merge\s+into|truncate|create\s+(?:unique\s+)?(?:table|index|view|sequence|type|schema|function|extension)|alter\s+table|drop\s+(?:table|index|view|sequence|type|schema)|copy\s+[\w."]+(?:\s*\([^)]*\))?\s+from)\b/i;
|
|
8424
|
+
TABLE = /(?:insert\s+into|(?<!do\s)update(?:\s+only)?|delete\s+from|merge\s+into|truncate(?:\s+table)?|from|join|copy|alter\s+table|create\s+table(?:\s+if\s+not\s+exists)?)\s+((?:"[^"]+"|[A-Za-z_][\w$]*)(?:\.(?:"[^"]+"|[A-Za-z_][\w$]*))?)/gi;
|
|
8425
|
+
normalizeTable = (name) => {
|
|
8426
|
+
const parts = name.split(".");
|
|
8427
|
+
const last = parts.at(-1);
|
|
8428
|
+
return last.startsWith('"') ? last.slice(1, -1) : last.toLowerCase();
|
|
8429
|
+
};
|
|
8430
|
+
isWriteSql = (sql) => WRITE.test(sql.replace(/'(?:[^']|'')*'/g, "''"));
|
|
8431
|
+
cstr = (text2) => Buffer.from(text2 + "\0", "utf8");
|
|
8432
|
+
msg = (type, body = Buffer.alloc(0)) => {
|
|
8433
|
+
const head = Buffer.alloc(5);
|
|
8434
|
+
head.write(type, 0, "latin1");
|
|
8435
|
+
head.writeInt32BE(body.length + 4, 1);
|
|
8436
|
+
return Buffer.concat([head, body]);
|
|
8437
|
+
};
|
|
8438
|
+
int32 = (n) => {
|
|
8439
|
+
const b = Buffer.alloc(4);
|
|
8440
|
+
b.writeInt32BE(n);
|
|
8441
|
+
return b;
|
|
8442
|
+
};
|
|
8443
|
+
errorMessage = (code, message) => msg("E", Buffer.concat([cstr("SERROR"), cstr("VERROR"), cstr("C" + code), cstr("M" + message), Buffer.from([0])]));
|
|
8444
|
+
ready = (status) => msg("Z", Buffer.from(status));
|
|
8445
|
+
quote2 = (name) => '"' + name.replaceAll('"', '""') + '"';
|
|
8446
|
+
plain = (v) => v instanceof Date ? v.toISOString() : typeof v === "bigint" ? Number.isSafeInteger(Number(v)) ? Number(v) : v.toString() : v instanceof Uint8Array ? Buffer.from(v).toString("base64") : v;
|
|
8447
|
+
PUBLIC_SNAPSHOT_LIMITS = { tables: 200, columns: 100, rows: 1e3, bytes: 512 * 1024 };
|
|
8448
|
+
hidden = (handle, name) => {
|
|
8449
|
+
const fn = handle[name];
|
|
8450
|
+
if (typeof fn !== "function") throw new Error("Not an embedded PostgreSQL engine");
|
|
8451
|
+
return fn;
|
|
8452
|
+
};
|
|
8453
|
+
}
|
|
8454
|
+
});
|
|
8455
|
+
|
|
8456
|
+
// src/runtime/local-engines.ts
|
|
8457
|
+
import { readFile as readFile5 } from "fs/promises";
|
|
8458
|
+
import { join as join12 } from "path";
|
|
8459
|
+
async function evaluatePostgresAssertions(postgres2, assertions) {
|
|
8460
|
+
const results = [];
|
|
8461
|
+
for (const assertion of assertions) {
|
|
8462
|
+
let actual;
|
|
8463
|
+
try {
|
|
8464
|
+
actual = await queryReadOnly(postgres2, assertion.query);
|
|
8465
|
+
} catch (error) {
|
|
8466
|
+
actual = { error: error instanceof Error ? error.message : String(error) };
|
|
8467
|
+
}
|
|
8468
|
+
results.push({ service: "postgres", query: assertion.query, expected: assertion.equals, actual, passed: JSON.stringify(actual) === JSON.stringify(assertion.equals) });
|
|
8469
|
+
}
|
|
8470
|
+
return results;
|
|
8471
|
+
}
|
|
8472
|
+
async function startLocalEngines(app, spec) {
|
|
8473
|
+
const started = [];
|
|
8474
|
+
const stop = async () => {
|
|
8475
|
+
await Promise.all(started.splice(0).map((e) => e.stop().catch(() => {
|
|
8476
|
+
})));
|
|
8477
|
+
};
|
|
8478
|
+
let postgres2, redis, initialTables;
|
|
8479
|
+
try {
|
|
8480
|
+
if (spec.postgres) {
|
|
8481
|
+
postgres2 = await startPostgresEngine({ extensions: spec.postgres.extensions });
|
|
8482
|
+
started.push(postgres2);
|
|
8483
|
+
if (spec.postgres.seedFile) {
|
|
8484
|
+
const sql = await readFile5(join12(app, spec.postgres.seedFile), "utf8");
|
|
8485
|
+
try {
|
|
8486
|
+
await postgres2.seed({ sql });
|
|
8487
|
+
} catch (error) {
|
|
8488
|
+
throw new Error(`PostgreSQL seedFile ${spec.postgres.seedFile} failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
8489
|
+
}
|
|
8490
|
+
}
|
|
8491
|
+
initialTables = await snapshotPublicTables(postgres2).catch(() => void 0);
|
|
8492
|
+
}
|
|
8493
|
+
if (spec.redis) {
|
|
8494
|
+
redis = await startRedisEngine({ prefer: "binary" }).catch((error) => {
|
|
8495
|
+
if (error instanceof EngineUnavailable) return startRedisEngine({ prefer: "in-process" });
|
|
8496
|
+
throw error;
|
|
8497
|
+
});
|
|
8498
|
+
started.push(redis);
|
|
8499
|
+
}
|
|
8500
|
+
} catch (error) {
|
|
8501
|
+
await stop();
|
|
8502
|
+
throw error;
|
|
8503
|
+
}
|
|
8504
|
+
return {
|
|
8505
|
+
env: { ...postgres2?.env ?? {}, ...redis?.env ?? {} },
|
|
8506
|
+
async evaluate() {
|
|
8507
|
+
const results = spec.postgres ? await evaluatePostgresAssertions(postgres2, spec.postgres.assertions) : [];
|
|
8508
|
+
if (spec.redis) {
|
|
8509
|
+
const state = await redis.readState();
|
|
8510
|
+
const keys = "keys" in state ? state.keys : [];
|
|
8511
|
+
for (const assertion of spec.redis.assertions) {
|
|
8512
|
+
const entry = keys.find((k) => k.key === assertion.key);
|
|
8513
|
+
const actual = entry === void 0 ? null : entry.type === "string" ? String(entry.value) : { error: `WRONGTYPE ${entry.type}` };
|
|
8514
|
+
results.push({ service: "redis", key: assertion.key, expected: assertion.equals, actual, passed: actual === assertion.equals });
|
|
8515
|
+
}
|
|
8516
|
+
}
|
|
8517
|
+
return results;
|
|
8518
|
+
},
|
|
8519
|
+
async databaseEvidence() {
|
|
8520
|
+
if (!postgres2 || !initialTables) return void 0;
|
|
8521
|
+
const final = await snapshotPublicTables(postgres2).catch(() => void 0);
|
|
8522
|
+
return final && { engine: "embedded-postgres", extensions: [...spec.postgres?.extensions ?? []], initial: initialTables, final };
|
|
8523
|
+
},
|
|
8524
|
+
unsupported: () => started.flatMap((e) => e.unsupported.map((u) => `${e.kind}: ${u}`)),
|
|
8525
|
+
stop
|
|
8526
|
+
};
|
|
8527
|
+
}
|
|
8528
|
+
var init_local_engines = __esm({
|
|
8529
|
+
"src/runtime/local-engines.ts"() {
|
|
8530
|
+
"use strict";
|
|
8531
|
+
init_postgres();
|
|
8532
|
+
init_redis();
|
|
8533
|
+
init_types();
|
|
8534
|
+
}
|
|
8535
|
+
});
|
|
8536
|
+
|
|
8537
|
+
// src/runtime/server-steps.ts
|
|
8538
|
+
function stepUrl(base, path) {
|
|
8539
|
+
if (!isServerPath(path)) throw new Error(`Path ${JSON.stringify(path)} must start with a single / and contain no backslash or control characters`);
|
|
8540
|
+
const root = new URL(base), prefix = root.pathname.replace(/\/+$/, "");
|
|
8541
|
+
const url = new URL(root.origin + prefix + path);
|
|
8542
|
+
if (url.origin !== root.origin || prefix && url.pathname !== prefix && !url.pathname.startsWith(prefix + "/")) throw new Error(`Path ${JSON.stringify(path)} leaves ${root.origin}${prefix}`);
|
|
8543
|
+
return url.href;
|
|
8544
|
+
}
|
|
8545
|
+
async function runServerSteps(spec, world, signal, onReady = () => {
|
|
8546
|
+
}) {
|
|
8547
|
+
const recipe = spec.server, started = Date.now();
|
|
8548
|
+
const evidence = { ready: false, readyMs: 0, steps: [], passed: false };
|
|
8549
|
+
const ready2 = stepUrl(recipe.baseUrl, recipe.readyPath ?? "/");
|
|
8550
|
+
const deadline = started + (recipe.readyTimeoutSeconds ?? 60) * 1e3;
|
|
8551
|
+
const secrets = Object.values(world.credentials).map((c) => c.token);
|
|
8552
|
+
const redact = (text2) => secrets.reduce((out, token) => out.split(token).join("[test-token]"), text2);
|
|
8553
|
+
for (; ; ) {
|
|
8554
|
+
signal.throwIfAborted();
|
|
8555
|
+
try {
|
|
8556
|
+
const response = await fetch(ready2, { redirect: "manual", signal: AbortSignal.any([signal, AbortSignal.timeout(2e3)]) });
|
|
8557
|
+
await response.arrayBuffer().catch(() => void 0);
|
|
8558
|
+
if (response.status < 500) break;
|
|
8559
|
+
} catch (error) {
|
|
8560
|
+
if (signal.aborted) throw error;
|
|
8561
|
+
}
|
|
8562
|
+
if (Date.now() >= deadline) {
|
|
8563
|
+
evidence.readyMs = Date.now() - started;
|
|
8564
|
+
evidence.error = `Server did not answer ${recipe.readyPath ?? "/"} within ${recipe.readyTimeoutSeconds ?? 60}s`;
|
|
8565
|
+
return evidence;
|
|
8566
|
+
}
|
|
8567
|
+
await sleep2(250, signal);
|
|
8568
|
+
}
|
|
8569
|
+
evidence.ready = true;
|
|
8570
|
+
evidence.readyMs = Date.now() - started;
|
|
8571
|
+
onReady();
|
|
8572
|
+
for (const step of recipe.steps) {
|
|
8573
|
+
signal.throwIfAborted();
|
|
8574
|
+
const credential = step.target === "app" ? void 0 : world.credentials[step.target];
|
|
8575
|
+
const base = credential ? credential.endpoint : recipe.baseUrl;
|
|
8576
|
+
const headers = new Headers(step.headers ?? {});
|
|
8577
|
+
if (credential) headers.set("authorization", "Bearer " + credential.token);
|
|
8578
|
+
let body;
|
|
8579
|
+
if (step.body !== void 0) {
|
|
8580
|
+
body = typeof step.body === "string" ? step.body : JSON.stringify(step.body);
|
|
8581
|
+
if (!headers.has("content-type") && typeof step.body !== "string") headers.set("content-type", "application/json");
|
|
8582
|
+
}
|
|
8583
|
+
const record3 = { target: step.target, method: step.method, path: step.path, passed: false };
|
|
8584
|
+
evidence.steps.push(record3);
|
|
8585
|
+
try {
|
|
8586
|
+
const url = stepUrl(base, step.path);
|
|
8587
|
+
const response = await fetch(url, { method: step.method, headers, body, redirect: "manual", signal: AbortSignal.any([signal, AbortSignal.timeout(Math.min(spec.timeoutSeconds * 1e3, 12e4))]) });
|
|
8588
|
+
const text2 = await response.text().catch(() => "");
|
|
8589
|
+
record3.status = response.status;
|
|
8590
|
+
record3.passed = step.expectStatus !== void 0 ? response.status === step.expectStatus : response.status < 400;
|
|
8591
|
+
if (!record3.passed) {
|
|
8592
|
+
record3.responseExcerpt = redact(text2.slice(0, 500));
|
|
8593
|
+
evidence.error = `${step.method} ${step.path} on ${step.target} returned ${response.status}${step.expectStatus !== void 0 ? `, expected ${step.expectStatus}` : ""}`;
|
|
8594
|
+
return evidence;
|
|
8595
|
+
}
|
|
8596
|
+
} catch (error) {
|
|
8597
|
+
if (signal.aborted) throw error;
|
|
8598
|
+
record3.error = error instanceof Error ? error.message : String(error);
|
|
8599
|
+
evidence.error = `${step.method} ${step.path} on ${step.target} failed: ${record3.error}`;
|
|
8600
|
+
return evidence;
|
|
8601
|
+
}
|
|
8602
|
+
}
|
|
8603
|
+
evidence.passed = true;
|
|
8604
|
+
return evidence;
|
|
8605
|
+
}
|
|
8606
|
+
var sleep2;
|
|
8607
|
+
var init_server_steps = __esm({
|
|
8608
|
+
"src/runtime/server-steps.ts"() {
|
|
8609
|
+
"use strict";
|
|
8610
|
+
init_spec();
|
|
8611
|
+
sleep2 = (ms, signal) => new Promise((resolve8, reject) => {
|
|
8612
|
+
const timer = setTimeout(resolve8, ms);
|
|
8613
|
+
signal?.addEventListener("abort", () => {
|
|
8614
|
+
clearTimeout(timer);
|
|
8615
|
+
reject(signal.reason ?? new Error("aborted"));
|
|
8616
|
+
}, { once: true });
|
|
8617
|
+
});
|
|
8618
|
+
}
|
|
8619
|
+
});
|
|
8620
|
+
|
|
6096
8621
|
// src/runtime/local.ts
|
|
6097
|
-
import { spawn } from "child_process";
|
|
6098
|
-
|
|
8622
|
+
import { spawn as spawn2 } from "child_process";
|
|
8623
|
+
import { realpath as realpath2 } from "fs/promises";
|
|
8624
|
+
import { dirname as dirname2, resolve as resolve3 } from "path";
|
|
8625
|
+
async function sourceRoot(app, spec) {
|
|
8626
|
+
const real = await realpath2(app);
|
|
8627
|
+
if (!spec.directory) return real;
|
|
8628
|
+
for (let candidate = real; ; candidate = dirname2(candidate)) {
|
|
8629
|
+
if (await realpath2(resolve3(candidate, spec.directory)).then((p) => p === real, () => false)) return candidate;
|
|
8630
|
+
if (dirname2(candidate) === candidate) return real;
|
|
8631
|
+
}
|
|
8632
|
+
}
|
|
8633
|
+
async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {}, filesDir = app) {
|
|
6099
8634
|
if (spec.applicationClock && !/(^|\/)node(\.exe)?$/.test(spec.command[0])) throw new Error("applicationClock requires a Node application");
|
|
6100
|
-
if (spec.postgres || spec.redis) throw new Error("This world needs PostgreSQL or Redis. Use --runtime hosted or --runtime e2b, or prepare a workflow using HTTP twins only. No local containers are started.");
|
|
6101
8635
|
signal?.throwIfAborted();
|
|
6102
8636
|
const world = existingWorld ?? new HttpWorld(spec, seed), started = Date.now();
|
|
8637
|
+
let engines;
|
|
6103
8638
|
try {
|
|
6104
8639
|
const credentials = existingWorld ? world.credentials : await world.start();
|
|
6105
8640
|
const initialState = world.snapshot();
|
|
6106
|
-
const env = { ...Object.assign({}, ...Object.values(world.packEnv)), ...extraEnv, PATH: process.env.PATH ?? ""
|
|
8641
|
+
const env = { ...Object.assign({}, ...Object.values(world.packEnv)), ...extraEnv, NODE_ENV: "test", ...spec.env ?? {}, PATH: process.env.PATH ?? "" };
|
|
6107
8642
|
for (const [name, c] of Object.entries(credentials)) {
|
|
6108
8643
|
env[`AGENTTWIN_${name.toUpperCase()}_URL`] = c.endpoint;
|
|
6109
8644
|
env[`AGENTTWIN_${name.toUpperCase()}_TOKEN`] = c.token;
|
|
6110
8645
|
}
|
|
8646
|
+
engines = await startLocalEngines(filesDir, spec);
|
|
8647
|
+
Object.assign(env, engines.env);
|
|
6111
8648
|
let stdout = "", stderr = "", timedOut = false;
|
|
6112
|
-
const hook = await createRequestSourceHook(app, spec, credentials);
|
|
6113
8649
|
const node = /(^|\/)node(\.exe)?$/.test(spec.command[0]);
|
|
8650
|
+
const hook = await createRequestSourceHook(await sourceRoot(app, spec), spec, credentials);
|
|
8651
|
+
if (node) env.NODE_OPTIONS = [extraEnv.NODE_OPTIONS, `--require ${JSON.stringify(hook.path)}`].filter(Boolean).join(" ");
|
|
6114
8652
|
let proxy;
|
|
6115
8653
|
if (!node) {
|
|
6116
8654
|
const configured = extraEnv.AGENTTWIN_ROUTES ? JSON.parse(extraEnv.AGENTTWIN_ROUTES).routes : void 0;
|
|
@@ -6118,7 +8656,7 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
|
|
|
6118
8656
|
Object.assign(env, proxy.env, { HOME: process.env.HOME ?? "", LANG: process.env.LANG ?? "C.UTF-8", PYTHONUNBUFFERED: "1", PYTHONDONTWRITEBYTECODE: "1" });
|
|
6119
8657
|
if (process.env.VIRTUAL_ENV) env.VIRTUAL_ENV = process.env.VIRTUAL_ENV;
|
|
6120
8658
|
}
|
|
6121
|
-
const child = node ?
|
|
8659
|
+
const child = node ? spawn2(process.execPath, ["--require", hook.path, ...spec.command.slice(1)], { cwd: app, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32" }) : spawn2(spec.command[0], spec.command.slice(1), { cwd: app, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32" });
|
|
6122
8660
|
child.stdout.on("data", (b) => {
|
|
6123
8661
|
stdout = (stdout + b.toString()).slice(-65536);
|
|
6124
8662
|
});
|
|
@@ -6141,19 +8679,27 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
|
|
|
6141
8679
|
executionAbort.abort(new Error("Test deadline exceeded"));
|
|
6142
8680
|
kill();
|
|
6143
8681
|
};
|
|
6144
|
-
let timer = setTimeout(expire, spec.timeoutSeconds * 1e3 + (spec.browser ? BROWSER_STARTUP_MS + BROWSER_CLEANUP_MS : 0));
|
|
8682
|
+
let timer = setTimeout(expire, spec.timeoutSeconds * 1e3 + (spec.browser ? BROWSER_STARTUP_MS + BROWSER_CLEANUP_MS : 0) + (spec.server ? (spec.server.readyTimeoutSeconds ?? 60) * 1e3 : 0));
|
|
6145
8683
|
const browserReady = () => {
|
|
6146
8684
|
clearTimeout(timer);
|
|
6147
8685
|
timer = setTimeout(expire, spec.timeoutSeconds * 1e3 + BROWSER_CLEANUP_MS);
|
|
6148
8686
|
};
|
|
6149
8687
|
let work;
|
|
6150
8688
|
const completion = managed.exited;
|
|
8689
|
+
let server;
|
|
6151
8690
|
let browser, background, executionError;
|
|
6152
8691
|
let exitCode;
|
|
6153
8692
|
let blockedFetches = [];
|
|
6154
8693
|
try {
|
|
6155
|
-
if (spec.browser || spec.background) {
|
|
8694
|
+
if (spec.browser || spec.background || spec.server) {
|
|
6156
8695
|
work = (async () => {
|
|
8696
|
+
if (spec.server) {
|
|
8697
|
+
server = await runServerSteps(spec, world, executionAbort.signal, browserReady);
|
|
8698
|
+
if (!server.passed) {
|
|
8699
|
+
executionError = server.error;
|
|
8700
|
+
return 1;
|
|
8701
|
+
}
|
|
8702
|
+
}
|
|
6157
8703
|
if (spec.browser) {
|
|
6158
8704
|
try {
|
|
6159
8705
|
browser = await browserExecution(spec, world, executionAbort.signal, void 0, browserReady);
|
|
@@ -6167,7 +8713,7 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
|
|
|
6167
8713
|
return 0;
|
|
6168
8714
|
})();
|
|
6169
8715
|
exitCode = await Promise.race([work, completion.then((code) => {
|
|
6170
|
-
if (!spec.browser && code === 0) return work;
|
|
8716
|
+
if (!spec.browser && !spec.server && code === 0) return work;
|
|
6171
8717
|
throw new Error(timedOut ? "Test deadline exceeded" : `Application exited before browser/background completion (${code})`);
|
|
6172
8718
|
})]);
|
|
6173
8719
|
} else exitCode = await completion;
|
|
@@ -6211,11 +8757,15 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
|
|
|
6211
8757
|
const assertions = world.assertions();
|
|
6212
8758
|
const evaluation = evaluateState(spec, initialState, world.state, world.events);
|
|
6213
8759
|
const defaultChecks = runDefaultChecks({ spec, initialState, finalState: world.state, events: world.events, fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null });
|
|
6214
|
-
const
|
|
6215
|
-
|
|
8760
|
+
const infrastructureAssertions = await engines.evaluate();
|
|
8761
|
+
const embeddedDatabase = await engines.databaseEvidence();
|
|
8762
|
+
const unsupported2 = [...world.unsupported, ...engines.unsupported()];
|
|
8763
|
+
const status = blockedFetches.length || unsupported2.length || spec.fault && !world.faultTriggered ? "incomplete" : timedOut || server && !server.ready || exitCode !== 0 && !(server && !server.passed) ? "error" : server?.passed === false || background?.passed === false || browser?.passed === false ? "failed" : evaluation.outcome === "passed" && defaultChecks.every((c) => c.passed) && infrastructureAssertions.every((a) => a.passed) ? "passed" : "failed";
|
|
8764
|
+
return { schema: "agenttwin/run-v1", name: spec.name, workflowId: spec.workflowId, status, applicationClock: applicationClockEvidence(spec.applicationClock), twinClock: twinClockEvidence(world.twinClock), browser, ...server ? { server } : {}, background, executionError, application: { command: spec.command, exitCode, timedOut, stdout, stderr }, assertions, evaluation, defaultChecks, contracts: operationMatrix(spec), scenario: spec.scenario, infrastructureAssertions, ...embeddedDatabase ? { embeddedDatabase } : {}, fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null, seed: world.seed, reproducibility: spec.applicationClock ? "Explicit Date clock fixed; timers, performance clocks and scheduling remain real. Twin randomness uses the recorded seed." : "Seed " + world.seed + " deterministically drives twin-side fault scheduling, latency jitter and test credentials. The seed does not control the application's own randomness, wall-clock behavior or threading; compare runs only over twin events and final state.", initialState, finalState: world.snapshot(), events: structuredClone(world.events), blockedFetches, unsupported: unsupported2, durationMs: Date.now() - started, coverage: "CLI Node execution with fresh in-process HTTP collections and advertised provider subsets. Optional Chromium browser steps and bounded collection-state background completion. Not a VM or network/filesystem isolation boundary. No production environment variables inherited; reviewed code can still access the host filesystem and network.", isolation: { kind: "process", productionCredentialsInherited: false, network: "host network; not isolated", rootFilesystem: "host-accessible; explicit files staged in temporary directory" } };
|
|
6216
8765
|
} finally {
|
|
6217
8766
|
if (existingWorld) world.quiesce();
|
|
6218
8767
|
else await world.close();
|
|
8768
|
+
await engines?.stop();
|
|
6219
8769
|
}
|
|
6220
8770
|
}
|
|
6221
8771
|
var init_local = __esm({
|
|
@@ -6233,13 +8783,15 @@ var init_local = __esm({
|
|
|
6233
8783
|
init_default_checks();
|
|
6234
8784
|
init_twin_proxy();
|
|
6235
8785
|
init_twin_routing();
|
|
8786
|
+
init_local_engines();
|
|
8787
|
+
init_server_steps();
|
|
6236
8788
|
}
|
|
6237
8789
|
});
|
|
6238
8790
|
|
|
6239
8791
|
// src/runtime/scenarios.ts
|
|
6240
8792
|
import { createHash as createHash7 } from "crypto";
|
|
6241
8793
|
import { mkdir as mkdir3, readFile as readFile6, readdir, writeFile as writeFile7 } from "fs/promises";
|
|
6242
|
-
import { join as
|
|
8794
|
+
import { join as join13 } from "path";
|
|
6243
8795
|
import { isDeepStrictEqual as isDeepStrictEqual4 } from "util";
|
|
6244
8796
|
function parseScenario(value) {
|
|
6245
8797
|
const fail = (detail) => {
|
|
@@ -6278,7 +8830,7 @@ function reference(ref) {
|
|
|
6278
8830
|
}
|
|
6279
8831
|
async function loadScenario(cwd, ref) {
|
|
6280
8832
|
const { id, version } = reference(ref);
|
|
6281
|
-
const path =
|
|
8833
|
+
const path = join13(cwd, ".agenttwin/scenarios", id, `${version}.json`);
|
|
6282
8834
|
const bytes = await readFile6(path);
|
|
6283
8835
|
if (bytes.length > 2 * 1024 * 1024) throw new Error("Scenario exceeds 2 MiB");
|
|
6284
8836
|
const scenario = parseScenario(JSON.parse(bytes.toString()));
|
|
@@ -6329,8 +8881,8 @@ var init_exit = __esm({
|
|
|
6329
8881
|
});
|
|
6330
8882
|
|
|
6331
8883
|
// src/runtime/stage-worker.ts
|
|
6332
|
-
import { copyFile, rm as
|
|
6333
|
-
import { basename, dirname as
|
|
8884
|
+
import { copyFile, rm as rm8 } from "fs/promises";
|
|
8885
|
+
import { basename, dirname as dirname3, join as join14 } from "path";
|
|
6334
8886
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
6335
8887
|
var init_stage_worker = __esm({
|
|
6336
8888
|
"src/runtime/stage-worker.ts"() {
|
|
@@ -6348,8 +8900,8 @@ var init_offline = __esm({
|
|
|
6348
8900
|
|
|
6349
8901
|
// src/runtime/credentials.ts
|
|
6350
8902
|
import { homedir } from "os";
|
|
6351
|
-
import { join as
|
|
6352
|
-
import { readFile as readFile7, mkdir as mkdir4, writeFile as writeFile8, chmod as chmod2, rm as
|
|
8903
|
+
import { join as join15 } from "path";
|
|
8904
|
+
import { readFile as readFile7, mkdir as mkdir4, writeFile as writeFile8, chmod as chmod2, rm as rm9 } from "fs/promises";
|
|
6353
8905
|
var init_credentials = __esm({
|
|
6354
8906
|
"src/runtime/credentials.ts"() {
|
|
6355
8907
|
"use strict";
|
|
@@ -6358,7 +8910,7 @@ var init_credentials = __esm({
|
|
|
6358
8910
|
|
|
6359
8911
|
// src/runtime/remote.ts
|
|
6360
8912
|
import { readFile as readFile8 } from "fs/promises";
|
|
6361
|
-
import { join as
|
|
8913
|
+
import { join as join16 } from "path";
|
|
6362
8914
|
var init_remote = __esm({
|
|
6363
8915
|
"src/runtime/remote.ts"() {
|
|
6364
8916
|
"use strict";
|
|
@@ -6369,29 +8921,29 @@ var init_remote = __esm({
|
|
|
6369
8921
|
});
|
|
6370
8922
|
|
|
6371
8923
|
// src/runtime/docker-engine.ts
|
|
6372
|
-
import { execFile as
|
|
6373
|
-
import { promisify as
|
|
6374
|
-
var
|
|
8924
|
+
import { execFile as execFile6 } from "child_process";
|
|
8925
|
+
import { promisify as promisify6 } from "util";
|
|
8926
|
+
var exec5;
|
|
6375
8927
|
var init_docker_engine = __esm({
|
|
6376
8928
|
"src/runtime/docker-engine.ts"() {
|
|
6377
8929
|
"use strict";
|
|
6378
|
-
|
|
8930
|
+
exec5 = promisify6(execFile6);
|
|
6379
8931
|
}
|
|
6380
8932
|
});
|
|
6381
8933
|
|
|
6382
8934
|
// src/runtime/docker-postgres.ts
|
|
6383
8935
|
import postgres from "postgres";
|
|
6384
|
-
import { execFile as
|
|
6385
|
-
import { promisify as
|
|
6386
|
-
import { randomBytes as randomBytes2, randomUUID as
|
|
8936
|
+
import { execFile as execFile7, spawn as spawn3 } from "child_process";
|
|
8937
|
+
import { promisify as promisify7, isDeepStrictEqual as isDeepStrictEqual5 } from "util";
|
|
8938
|
+
import { randomBytes as randomBytes2, randomUUID as randomUUID3 } from "crypto";
|
|
6387
8939
|
import { Duplex } from "stream";
|
|
6388
|
-
var
|
|
8940
|
+
var exec6;
|
|
6389
8941
|
var init_docker_postgres = __esm({
|
|
6390
8942
|
"src/runtime/docker-postgres.ts"() {
|
|
6391
8943
|
"use strict";
|
|
6392
8944
|
init_docker_engine();
|
|
6393
8945
|
init_postgres_clock();
|
|
6394
|
-
|
|
8946
|
+
exec6 = promisify7(execFile7);
|
|
6395
8947
|
}
|
|
6396
8948
|
});
|
|
6397
8949
|
|
|
@@ -6405,13 +8957,13 @@ var init_stdio_fetch = __esm({
|
|
|
6405
8957
|
});
|
|
6406
8958
|
|
|
6407
8959
|
// src/runtime/docker.ts
|
|
6408
|
-
import { execFile as
|
|
6409
|
-
import { promisify as
|
|
6410
|
-
import { chmod as chmod3, copyFile as copyFile2, mkdir as mkdir5, mkdtemp as
|
|
6411
|
-
import { tmpdir as
|
|
6412
|
-
import { join as
|
|
6413
|
-
import { randomUUID as
|
|
6414
|
-
var
|
|
8960
|
+
import { execFile as execFile8, spawn as spawn4 } from "child_process";
|
|
8961
|
+
import { promisify as promisify8 } from "util";
|
|
8962
|
+
import { chmod as chmod3, copyFile as copyFile2, mkdir as mkdir5, mkdtemp as mkdtemp8, readFile as readFile9, rm as rm10, writeFile as writeFile9 } from "fs/promises";
|
|
8963
|
+
import { tmpdir as tmpdir8 } from "os";
|
|
8964
|
+
import { join as join17 } from "path";
|
|
8965
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
8966
|
+
var exec7;
|
|
6415
8967
|
var init_docker = __esm({
|
|
6416
8968
|
"src/runtime/docker.ts"() {
|
|
6417
8969
|
"use strict";
|
|
@@ -6426,16 +8978,16 @@ var init_docker = __esm({
|
|
|
6426
8978
|
init_application_clock();
|
|
6427
8979
|
init_docker_engine();
|
|
6428
8980
|
init_docker_engine();
|
|
6429
|
-
|
|
8981
|
+
exec7 = promisify8(execFile8);
|
|
6430
8982
|
}
|
|
6431
8983
|
});
|
|
6432
8984
|
|
|
6433
8985
|
// src/runtime/git.ts
|
|
6434
|
-
import { execFile as
|
|
6435
|
-
import { promisify as
|
|
8986
|
+
import { execFile as execFile9 } from "child_process";
|
|
8987
|
+
import { promisify as promisify9 } from "util";
|
|
6436
8988
|
async function captureGit(cwd, previousHead) {
|
|
6437
|
-
const
|
|
6438
|
-
const git = async (...args) => (await
|
|
8989
|
+
const exec8 = promisify9(execFile9);
|
|
8990
|
+
const git = async (...args) => (await exec8("git", args, { cwd, timeout: 5e3, maxBuffer: 1024 * 1024 })).stdout.trim();
|
|
6439
8991
|
try {
|
|
6440
8992
|
const head = await git("rev-parse", "HEAD");
|
|
6441
8993
|
const [branch, total, status, history] = await Promise.all([git("branch", "--show-current"), git("rev-list", "--count", "HEAD"), git("status", "--porcelain", "--untracked-files=no"), git("log", "--since=14 days ago", "-100", "--format=%H %cI")]);
|
|
@@ -6463,7 +9015,7 @@ var init_git = __esm({
|
|
|
6463
9015
|
|
|
6464
9016
|
// src/runtime/hosted-packs.ts
|
|
6465
9017
|
import { readFile as readFile10, readdir as readdir2 } from "fs/promises";
|
|
6466
|
-
import { join as
|
|
9018
|
+
import { join as join18 } from "path";
|
|
6467
9019
|
var init_hosted_packs = __esm({
|
|
6468
9020
|
"src/runtime/hosted-packs.ts"() {
|
|
6469
9021
|
"use strict";
|
|
@@ -6476,7 +9028,7 @@ import { createRequire } from "module";
|
|
|
6476
9028
|
import { readFile as readFile11 } from "fs/promises";
|
|
6477
9029
|
import { randomBytes as randomBytes3 } from "crypto";
|
|
6478
9030
|
import { homedir as homedir2 } from "os";
|
|
6479
|
-
import { join as
|
|
9031
|
+
import { join as join19 } from "path";
|
|
6480
9032
|
var init_e2b = __esm({
|
|
6481
9033
|
"src/runtime/e2b.ts"() {
|
|
6482
9034
|
"use strict";
|
|
@@ -6490,7 +9042,7 @@ var init_e2b = __esm({
|
|
|
6490
9042
|
// src/runtime/matrix.ts
|
|
6491
9043
|
import { createHash as createHash8 } from "crypto";
|
|
6492
9044
|
import { mkdir as mkdir6, readFile as readFile12, writeFile as writeFile10 } from "fs/promises";
|
|
6493
|
-
import { join as
|
|
9045
|
+
import { join as join20, relative, resolve as resolve4 } from "path";
|
|
6494
9046
|
var init_matrix = __esm({
|
|
6495
9047
|
"src/runtime/matrix.ts"() {
|
|
6496
9048
|
"use strict";
|
|
@@ -6502,8 +9054,8 @@ var init_matrix = __esm({
|
|
|
6502
9054
|
|
|
6503
9055
|
// src/runtime/source-build.ts
|
|
6504
9056
|
import { createHash as createHash9 } from "crypto";
|
|
6505
|
-
import { lstat, readFile as readFile13, realpath as
|
|
6506
|
-
import { isAbsolute, join as
|
|
9057
|
+
import { lstat, readFile as readFile13, realpath as realpath3 } from "fs/promises";
|
|
9058
|
+
import { isAbsolute as isAbsolute2, join as join21, relative as relative2, resolve as resolve5, sep } from "path";
|
|
6507
9059
|
import { isDeepStrictEqual as isDeepStrictEqual6 } from "util";
|
|
6508
9060
|
var init_source_build = __esm({
|
|
6509
9061
|
"src/runtime/source-build.ts"() {
|
|
@@ -6513,24 +9065,24 @@ var init_source_build = __esm({
|
|
|
6513
9065
|
});
|
|
6514
9066
|
|
|
6515
9067
|
// src/commands/run.ts
|
|
6516
|
-
import { mkdtemp as
|
|
6517
|
-
import { tmpdir as
|
|
6518
|
-
import { basename as basename2, dirname as
|
|
6519
|
-
import { createHash as createHash10, randomUUID as
|
|
9068
|
+
import { mkdtemp as mkdtemp9, mkdir as mkdir7, readFile as readFile14, writeFile as writeFile11, realpath as realpath4, lstat as lstat2, rm as rm11 } from "fs/promises";
|
|
9069
|
+
import { tmpdir as tmpdir9 } from "os";
|
|
9070
|
+
import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join22, relative as relative3, resolve as resolve6, sep as sep2 } from "path";
|
|
9071
|
+
import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
|
|
6520
9072
|
async function stageApplication(root, files, destination) {
|
|
6521
|
-
const canonicalRoot = await
|
|
9073
|
+
const canonicalRoot = await realpath4(root);
|
|
6522
9074
|
const digests = {};
|
|
6523
9075
|
let bytes = 0;
|
|
6524
9076
|
for (const file of files) {
|
|
6525
|
-
if (
|
|
6526
|
-
const source = await
|
|
9077
|
+
if (isAbsolute3(file) || file.includes("\\") || file.split("/").some((p) => p === ".." || /^(\.env.*|\.git|\.ssh|\.aws|\.azure|\.config|\.npmrc|\.netrc|credentials.*)$/i.test(p)) || /\.(pem|key|p12|pfx)$/i.test(file)) throw new CliError(`Unsafe application file: ${file}`, { code: EXIT.USAGE });
|
|
9078
|
+
const source = await realpath4(resolve6(canonicalRoot, file));
|
|
6527
9079
|
const rel = relative3(canonicalRoot, source);
|
|
6528
|
-
if (rel.startsWith(`..${sep2}`) || rel === ".." ||
|
|
9080
|
+
if (rel.startsWith(`..${sep2}`) || rel === ".." || isAbsolute3(rel) || source !== resolve6(canonicalRoot, file) || !(await lstat2(source)).isFile()) throw new CliError(`Files must be regular files within the project, without symlinks: ${file}`, { code: EXIT.USAGE });
|
|
6529
9081
|
const contents = await readFile14(source);
|
|
6530
9082
|
bytes += contents.length;
|
|
6531
9083
|
if (bytes > 20 * 1024 * 1024) throw new CliError("Application files exceed 20 MiB; supply a smaller built bundle", { code: EXIT.USAGE });
|
|
6532
|
-
const target =
|
|
6533
|
-
await mkdir7(
|
|
9084
|
+
const target = join22(destination, file);
|
|
9085
|
+
await mkdir7(dirname4(target), { recursive: true });
|
|
6534
9086
|
await writeFile11(target, contents, { mode: 420 });
|
|
6535
9087
|
digests[file] = createHash10("sha256").update(contents).digest("hex");
|
|
6536
9088
|
}
|
|
@@ -6564,13 +9116,13 @@ init_scenarios();
|
|
|
6564
9116
|
init_contracts();
|
|
6565
9117
|
init_run();
|
|
6566
9118
|
init_git();
|
|
6567
|
-
import { createServer as
|
|
6568
|
-
import { randomBytes as randomBytes4, randomUUID as
|
|
6569
|
-
import { mkdir as mkdir8, mkdtemp as
|
|
6570
|
-
import { dirname as
|
|
6571
|
-
import { tmpdir as
|
|
9119
|
+
import { createServer as createServer6 } from "http";
|
|
9120
|
+
import { randomBytes as randomBytes4, randomUUID as randomUUID6, createHash as createHash11 } from "crypto";
|
|
9121
|
+
import { mkdir as mkdir8, mkdtemp as mkdtemp10, readFile as readFile15, readdir as readdir3, rename, rm as rm12, writeFile as writeFile12 } from "fs/promises";
|
|
9122
|
+
import { dirname as dirname5, join as join23, resolve as resolve7, relative as relative4, sep as sep3 } from "path";
|
|
9123
|
+
import { tmpdir as tmpdir10 } from "os";
|
|
6572
9124
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
6573
|
-
import { spawn as
|
|
9125
|
+
import { spawn as spawn5 } from "child_process";
|
|
6574
9126
|
var uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
6575
9127
|
var hash2 = (spec) => createHash11("sha256").update(JSON.stringify(spec)).digest("hex");
|
|
6576
9128
|
function duration(value) {
|
|
@@ -6578,15 +9130,15 @@ function duration(value) {
|
|
|
6578
9130
|
return value;
|
|
6579
9131
|
}
|
|
6580
9132
|
async function persist(directory2, session) {
|
|
6581
|
-
const temporary =
|
|
9133
|
+
const temporary = join23(directory2, `${randomUUID6()}.tmp`);
|
|
6582
9134
|
await writeFile12(temporary, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
|
|
6583
|
-
await rename(temporary,
|
|
9135
|
+
await rename(temporary, join23(directory2, "session.json"));
|
|
6584
9136
|
}
|
|
6585
9137
|
var view = ({ controlToken: _token, cwd: _cwd, file: _file, controlUrl: _control, ...session }) => session;
|
|
6586
9138
|
async function serveWorldSession(directory2) {
|
|
6587
|
-
const session = JSON.parse(await readFile15(
|
|
9139
|
+
const session = JSON.parse(await readFile15(join23(directory2, "session.json"), "utf8"));
|
|
6588
9140
|
if (session.status !== "provisioning" || !uuid.test(session.id)) throw new Error("Session is not awaiting provisioning");
|
|
6589
|
-
const spec = parseWorld(JSON.parse(await readFile15(
|
|
9141
|
+
const spec = parseWorld(JSON.parse(await readFile15(join23(directory2, "world.json"), "utf8")));
|
|
6590
9142
|
const world = new HttpWorld(spec);
|
|
6591
9143
|
let control;
|
|
6592
9144
|
let timer;
|
|
@@ -6611,8 +9163,8 @@ async function serveWorldSession(directory2) {
|
|
|
6611
9163
|
session.status = status;
|
|
6612
9164
|
session.credentials = void 0;
|
|
6613
9165
|
await world.close();
|
|
6614
|
-
if (control) await new Promise((
|
|
6615
|
-
control.close(() =>
|
|
9166
|
+
if (control) await new Promise((resolve8) => {
|
|
9167
|
+
control.close(() => resolve8());
|
|
6616
9168
|
control.closeAllConnections();
|
|
6617
9169
|
});
|
|
6618
9170
|
await save();
|
|
@@ -6627,7 +9179,7 @@ async function serveWorldSession(directory2) {
|
|
|
6627
9179
|
};
|
|
6628
9180
|
try {
|
|
6629
9181
|
session.credentials = await world.start();
|
|
6630
|
-
control =
|
|
9182
|
+
control = createServer6(async (req, res) => {
|
|
6631
9183
|
const reply = (status, value) => {
|
|
6632
9184
|
if (!res.destroyed) {
|
|
6633
9185
|
res.writeHead(status, { "content-type": "application/json" });
|
|
@@ -6689,7 +9241,7 @@ async function serveWorldSession(directory2) {
|
|
|
6689
9241
|
let current = parseWorld(JSON.parse(await readFile15(session.file, "utf8")));
|
|
6690
9242
|
if (session.scenario) current = applyScenario(current, await loadScenario(session.cwd, session.scenario));
|
|
6691
9243
|
if (hash2(current) !== hash2(spec)) throw new Error("World specification or scenario changed; provision a new world. Source patches are allowed.");
|
|
6692
|
-
const stage = await
|
|
9244
|
+
const stage = await mkdtemp10(join23(tmpdir10(), "agenttwin-session-run-"));
|
|
6693
9245
|
active = new AbortController();
|
|
6694
9246
|
let result;
|
|
6695
9247
|
try {
|
|
@@ -6697,28 +9249,28 @@ async function serveWorldSession(directory2) {
|
|
|
6697
9249
|
session.status = "running";
|
|
6698
9250
|
await save();
|
|
6699
9251
|
active.signal.throwIfAborted();
|
|
6700
|
-
const sourceDigests = await stageApplication(
|
|
9252
|
+
const sourceDigests = await stageApplication(dirname5(session.file), spec.files, stage);
|
|
6701
9253
|
active.signal.throwIfAborted();
|
|
6702
9254
|
world.reset();
|
|
6703
9255
|
const report = await executeLocal(stage, spec, active.signal, world);
|
|
6704
9256
|
if (stopping) throw new Error("World expired during execution");
|
|
6705
|
-
const runId =
|
|
9257
|
+
const runId = randomUUID6();
|
|
6706
9258
|
let project = "local-workspace";
|
|
6707
9259
|
try {
|
|
6708
|
-
project = JSON.parse(await readFile15(
|
|
9260
|
+
project = JSON.parse(await readFile15(join23(session.cwd, ".agenttwin/inventory.json"), "utf8")).name ?? project;
|
|
6709
9261
|
} catch {
|
|
6710
9262
|
}
|
|
6711
|
-
const receipt = { ...report, sourceDirectory: relative4(session.cwd,
|
|
6712
|
-
const out =
|
|
9263
|
+
const receipt = { ...report, sourceDirectory: relative4(session.cwd, dirname5(session.file)).split(sep3).join("/"), runId, worldId: session.id, runtime: "local", project, git: await captureGit(session.cwd), createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: hash2(spec), provenance: "CLI-reported execution; not independently attested" };
|
|
9264
|
+
const out = join23(session.cwd, ".agenttwin/runs", runId);
|
|
6713
9265
|
await mkdir8(out, { recursive: true, mode: 448 });
|
|
6714
|
-
const evidencePath =
|
|
9266
|
+
const evidencePath = join23(out, "run.json");
|
|
6715
9267
|
await writeFile12(evidencePath, JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
|
|
6716
|
-
await writeFile12(
|
|
9268
|
+
await writeFile12(join23(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
|
|
6717
9269
|
session.lastRunId = runId;
|
|
6718
9270
|
result = { ...receipt, evidencePath };
|
|
6719
9271
|
} finally {
|
|
6720
9272
|
active = void 0;
|
|
6721
|
-
await
|
|
9273
|
+
await rm12(stage, { recursive: true, force: true });
|
|
6722
9274
|
if (!stopping) {
|
|
6723
9275
|
session.status = "ready";
|
|
6724
9276
|
await save();
|
|
@@ -6732,11 +9284,11 @@ async function serveWorldSession(directory2) {
|
|
|
6732
9284
|
}
|
|
6733
9285
|
});
|
|
6734
9286
|
control.requestTimeout = 1e4;
|
|
6735
|
-
await new Promise((
|
|
9287
|
+
await new Promise((resolve8, reject) => {
|
|
6736
9288
|
control.once("error", reject);
|
|
6737
|
-
control.listen(0, "127.0.0.1",
|
|
9289
|
+
control.listen(0, "127.0.0.1", resolve8);
|
|
6738
9290
|
});
|
|
6739
|
-
const latest = JSON.parse(await readFile15(
|
|
9291
|
+
const latest = JSON.parse(await readFile15(join23(directory2, "session.json"), "utf8"));
|
|
6740
9292
|
if (latest.status !== "provisioning") throw new Error("Provisioning was abandoned");
|
|
6741
9293
|
session.controlUrl = `http://127.0.0.1:${control.address().port}`;
|
|
6742
9294
|
if (stopping) throw new Error("World expired during provisioning");
|