@circuitwall/jarela 1.3.0 → 1.4.1
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/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/build-manifest.json +3 -3
- package/.next/standalone/.next/prerender-manifest.json +3 -3
- package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_global-error.html +1 -1
- package/.next/standalone/.next/server/app/_global-error.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_not-found.html +2 -2
- package/.next/standalone/.next/server/app/_not-found.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
- package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js +10 -1
- package/.next/standalone/.next/server/app/api/v1/builtin-tools/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/dashboard/currency/route.js +10 -5
- package/.next/standalone/.next/server/app/api/v1/dashboard/currency/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/page-capture/route.js +37 -3
- package/.next/standalone/.next/server/app/api/v1/page-capture/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/providers/[provider]/probe/route.js +9 -1
- package/.next/standalone/.next/server/app/api/v1/providers/[provider]/probe/route.js.map +1 -1
- package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js +33 -8
- package/.next/standalone/.next/server/app/api/v1/threads/[thread_id]/run/route.js.map +1 -1
- package/.next/standalone/.next/server/app/page.js +73 -204
- package/.next/standalone/.next/server/app/page.js.map +1 -1
- package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/setup/page.js +1 -1
- package/.next/standalone/.next/server/app/setup/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/setup/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/chunks/1718.js +159 -0
- package/.next/standalone/.next/server/chunks/1718.js.map +1 -0
- package/.next/standalone/.next/server/chunks/2082.js +6 -3
- package/.next/standalone/.next/server/chunks/2082.js.map +1 -1
- package/.next/standalone/.next/server/chunks/210.js +28 -0
- package/.next/standalone/.next/server/chunks/210.js.map +1 -1
- package/.next/standalone/.next/server/chunks/423.js +6 -3
- package/.next/standalone/.next/server/chunks/423.js.map +1 -1
- package/.next/standalone/.next/server/chunks/4631.js +37 -5
- package/.next/standalone/.next/server/chunks/4631.js.map +1 -1
- package/.next/standalone/.next/server/chunks/8167.js +255 -204
- package/.next/standalone/.next/server/chunks/8167.js.map +1 -1
- package/.next/standalone/.next/server/chunks/8866.js +38 -5
- package/.next/standalone/.next/server/chunks/8866.js.map +1 -1
- package/.next/standalone/.next/server/chunks/9032.js +8 -0
- package/.next/standalone/.next/server/chunks/9032.js.map +1 -1
- package/.next/standalone/.next/server/chunks/{7883.js → 9557.js} +15 -3
- package/.next/standalone/.next/server/chunks/9557.js.map +1 -0
- package/.next/standalone/.next/server/middleware-build-manifest.js +3 -3
- package/.next/standalone/.next/server/middleware.js +6 -3
- package/.next/standalone/.next/server/pages/404.html +2 -2
- package/.next/standalone/.next/server/pages/500.html +1 -1
- package/.next/standalone/.next/server/proxy.js.map +1 -1
- package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
- package/.next/standalone/.next/static/chunks/{2351-68d8987bbe17ba2d.js → 2351-1ab119fb3b48f4c9.js} +258 -205
- package/.next/standalone/.next/static/chunks/2351-1ab119fb3b48f4c9.js.map +1 -0
- package/.next/standalone/.next/static/chunks/{9209-0d46118e502f8bf5.js → 4097-64691f9110cf167c.js} +14 -2
- package/.next/standalone/.next/static/chunks/4097-64691f9110cf167c.js.map +1 -0
- package/.next/standalone/.next/static/chunks/app/{page-2ab710949b62a638.js → page-145150e0468544e7.js} +74 -205
- package/.next/standalone/.next/static/chunks/app/page-145150e0468544e7.js.map +1 -0
- package/.next/standalone/.next/static/chunks/app/setup/{page-9a465b5fa755b3c3.js → page-a1463a9ace439ff7.js} +2 -2
- package/.next/standalone/.next/static/chunks/app/setup/{page-9a465b5fa755b3c3.js.map → page-a1463a9ace439ff7.js.map} +1 -1
- package/.next/standalone/.next/static/chunks/{webpack-ff5627013a5e3842.js → webpack-f4ac5c5f92cfd1c1.js} +13 -1
- package/.next/standalone/.next/static/chunks/webpack-f4ac5c5f92cfd1c1.js.map +1 -0
- package/.next/standalone/package.json +2 -1
- package/CHANGELOG.md +84 -0
- package/README.md +51 -26
- package/api/client.ts +10 -9
- package/app/api/v1/dashboard/currency/route.ts +7 -2
- package/app/api/v1/providers/[provider]/probe/route.ts +12 -1
- package/app/api/v1/threads/[thread_id]/run/route.ts +22 -8
- package/components/chat/InputBar.tsx +10 -1
- package/components/layout/AppShell.tsx +53 -17
- package/components/setup/PinKeypad.tsx +238 -0
- package/components/setup/ScreenLock.tsx +8 -173
- package/components/setup/UnlockScreen.tsx +25 -192
- package/lib/api/page-capture.test.ts +58 -0
- package/lib/api/page-capture.ts +31 -1
- package/lib/documents/remote/github.ts +16 -2
- package/lib/documents/remote/mail.ts +11 -2
- package/lib/lifecycle/shutdown.ts +9 -0
- package/lib/providers/github-copilot-auth.ts +2 -0
- package/lib/providers/github-copilot.ts +1 -0
- package/lib/tools/async-results.ts +11 -0
- package/package.json +2 -1
- package/scripts/install-to-system.ps1 +2 -2
- package/scripts/installed-launcher.ps1 +81 -17
- package/.next/standalone/.next/server/chunks/7883.js.map +0 -1
- package/.next/standalone/.next/static/chunks/2351-68d8987bbe17ba2d.js.map +0 -1
- package/.next/standalone/.next/static/chunks/9209-0d46118e502f8bf5.js.map +0 -1
- package/.next/standalone/.next/static/chunks/app/page-2ab710949b62a638.js.map +0 -1
- package/.next/standalone/.next/static/chunks/webpack-ff5627013a5e3842.js.map +0 -1
- /package/.next/standalone/.next/static/{ZKy7LJ3KXj2TIyKOg_fBH → WQdcnm9NyqpeNc0Z8_woo}/_buildManifest.js +0 -0
- /package/.next/standalone/.next/static/{ZKy7LJ3KXj2TIyKOg_fBH → WQdcnm9NyqpeNc0Z8_woo}/_ssgManifest.js +0 -0
|
@@ -309,10 +309,13 @@ async function POST(req, { params }) {
|
|
|
309
309
|
await iter.return?.();
|
|
310
310
|
} catch {}
|
|
311
311
|
};
|
|
312
|
+
let timer = null;
|
|
312
313
|
try {
|
|
313
314
|
await Promise.race([
|
|
314
315
|
probe(),
|
|
315
|
-
new Promise((_, reject)=>
|
|
316
|
+
new Promise((_, reject)=>{
|
|
317
|
+
timer = setTimeout(()=>reject(new Error(`probe timed out after ${PROBE_TIMEOUT_MS}ms`)), PROBE_TIMEOUT_MS);
|
|
318
|
+
})
|
|
316
319
|
]);
|
|
317
320
|
return server.NextResponse.json({
|
|
318
321
|
ok: true
|
|
@@ -323,6 +326,11 @@ async function POST(req, { params }) {
|
|
|
323
326
|
ok: false,
|
|
324
327
|
error: msg
|
|
325
328
|
});
|
|
329
|
+
} finally{
|
|
330
|
+
// Without this, the 15s timer keeps firing after probe() wins the
|
|
331
|
+
// race and the route returns — leaking an unhandled rejection per
|
|
332
|
+
// probe (which then trips the global handler).
|
|
333
|
+
if (timer) clearTimeout(timer);
|
|
326
334
|
}
|
|
327
335
|
}
|
|
328
336
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"../app/api/v1/providers/[provider]/probe/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;CAQC,GAEuD;AACV;AAC6B;AACG;AAK9E,MAAMM,mBAAmB;AAElB,eAAeC,KAAKC,GAAgB,EAAE,EAAEC,MAAM,EAAU;IAC7D,MAAM,EAAEC,UAAUC,YAAY,EAAE,GAAG,MAAMF;IACzC,MAAMG,OAAO,MAAMJ,IAAIK,IAAI,GAAGC,KAAK,CAAC,IAAO,EAAC;IAM5C,IAAI,CAACF,KAAKG,QAAQ,EAAE;QAClB,OAAOf,mBAAYA,CAACa,IAAI,CAAC;YAAEG,IAAI;YAAOC,OAAO;QAAoB,GAAG;YAAEC,QAAQ;QAAI;IACpF;IAEA,gDAAgD;IAChD,qEAAqE;IACrE,+DAA+D;IAC/D,yCAAyC;IACzC,uEAAuE;IACvE,mEAAmE;IACnE,IAAIC,iBAAiC,CAAC;IACtC,IAAIP,KAAKQ,aAAa,EAAE;QACtB,MAAMC,OAAOjB,qCAAaA,CAACQ,KAAKQ,aAAa;QAC7C,IAAIC,MAAMF,iBAA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G,OAAO,GAAGF,OAAOD;QACpD,OAAOxB,mBAAYA,CAACa,IAAI,CAAC;YAAEG,IAAI;YAAOC,OAAO2B;QAAI;IACnD;AACF;;;AC9E+F;AACvC;AACqB;AACkB;AACvB;AACgB;AACT;AACK;AACmC;AACjD;AACO;AACf;AACsC;AACzB;AACM;AACC;AAChB;AACyC;AAC3G;AACA;AACA;AACA,wBAAwB,mCAAmB;AAC3C;AACA,cAAc,oBAAS;AACvB;AACA;AACA;AACA;AACA,KAAK;AACL,aAAa,OAAoC,IAAI,CAAE;AACvD,wBAAwB,MAAuC;AAC/D;AACA;AACA;AACA,cAAc,qBAAQ;AACtB;AACA;AACA;AACA;AACA,OAAO,MAAsD,GAAG,CAE3D,CAAC;AACN,CAAC;AACD;AACA;AACA;AACA,QAAQ,sDAAsD;AAC9D;AACA,WAAW,0BAAW;AACtB;AACA;AACA,KAAK;AACL;AAC0F;AACnF;AACP;AACA,QAAQ,+BAAc;AACtB;AACA;AACA,QAAQ,+BAAc;AACtB;AACA;AACA;AACA;AACA;AACA,QAAQ,KAAqB,EAAE,EAE1B,CAAC;AACN;AACA;AACA;AACA,+BAA+B,KAAwC;AACvE;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6NAA6N;AACzO,8BAA8B,+BAAgB;AAC9C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,2CAAe;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,6CAAqB;AAC7B;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,mBAAmB,0BAAS;AAC5B;AACA;AACA,kCAAkC,+BAAc;AAChD,6BAA6B,+BAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,4BAA4B,oBAAe;AAC3C,4BAA4B,qBAAgB;AAC5C,oBAAoB,+BAAkB,kCAAkC,uCAAsB;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iEAAiE,wBAAc;AAC/E,+DAA+D,yCAAyC;AACxG;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,EAAE,MAAM;AACpD;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,uCAAuC,QAAQ,EAAE,QAAQ;AACzD;AACA,aAAa;AACb;AACA;AACA;AACA,+CAA+C,oBAAoB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,uCAAyB;AACjE;AACA,oCAAoC,oCAAsB;AAC1D;AACA;AACA;AACA;AACA,sJAAsJ,4BAAc;AACpK,0IAA0I,4BAAc;AACxJ;AACA;AACA;AACA,sCAAsC,8BAAe;AACrD;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,8BAA8B,qCAAY;AAC1C;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,oCAAmB;AACjE;AACA;AACA,6BAA6B;AAC7B,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,oBAAS;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,qIAAqI,8BAAe;AACpJ;AACA,2GAA2G,iHAAiH;AAC5N;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yCAA2B;AACvD;AACA,+BAA+B,oCAAsB;AACrD;AACA;AACA;AACA;AACA,6CAA6C,uCAAqB;AAClE;AACA,kBAAkB,qCAAY;AAC9B;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,6EAA6E,wBAAc;AAC3F,iCAAiC,QAAQ,EAAE,QAAQ;AACnD,0BAA0B,qBAAQ;AAClC;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA,MAAM;AACN,6BAA6B,2CAAe;AAC5C;AACA;AACA;AACA;AACA;AACA,kCAAkC,oCAAmB;AACrD;AACA;AACA,iBAAiB;AACjB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA,cAAc,qCAAY;AAC1B;AACA,SAAS;AACT;AACA;AACA;;AAEA;;;;;;;;AC7WA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA","sources":["webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/router/utils/app-paths\"","webpack://@circuitwall/jarela/external node-commonjs \"node:process\"","webpack://@circuitwall/jarela/external commonjs2 \"url\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/after-task-async-storage.external.js\"","webpack://@circuitwall/jarela/external commonjs \"undici\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-page.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:async_hooks\"","webpack://@circuitwall/jarela/external commonjs2 \"stream\"","webpack://@circuitwall/jarela/external commonjs2 \"util\"","webpack://@circuitwall/jarela/external commonjs2 \"fs\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-async-storage.external.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:child_process\"","webpack://@circuitwall/jarela/external commonjs2 \"path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:http\"","webpack://@circuitwall/jarela/external node-commonjs \"node:https\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-route.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:os\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs/promises\"","webpack://@circuitwall/jarela/external commonjs2 \"crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"https\"","webpack://@circuitwall/jarela/external node-commonjs \"node:stream\"","webpack://@circuitwall/jarela/external node-commonjs \"node:util\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-unit-async-storage.external.js\"","webpack://@circuitwall/jarela/./app/api/v1/providers/[provider]/probe/route.ts","webpack://@circuitwall/jarela/?0ab9","webpack://@circuitwall/jarela/external node-commonjs \"node:fs\"","webpack://@circuitwall/jarela/external node-commonjs \"node:worker_threads\"","webpack://@circuitwall/jarela/external node-commonjs \"node:path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"buffer\"","webpack://@circuitwall/jarela/external node-commonjs \"node:sqlite\"","webpack://@circuitwall/jarela/external commonjs2 \"http\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/no-fallback-error.external\"","webpack://@circuitwall/jarela/external commonjs2 \"events\""],"sourcesContent":["module.exports = require(\"next/dist/shared/lib/router/utils/app-paths\");","module.exports = require(\"node:process\");","module.exports = require(\"url\");","module.exports = require(\"next/dist/server/app-render/after-task-async-storage.external.js\");","module.exports = require(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","module.exports = require(\"node:async_hooks\");","module.exports = require(\"stream\");","module.exports = require(\"util\");","module.exports = require(\"fs\");","module.exports = require(\"next/dist/server/app-render/work-async-storage.external.js\");","module.exports = require(\"node:child_process\");","module.exports = require(\"path\");","module.exports = require(\"node:http\");","module.exports = require(\"node:https\");","module.exports = require(\"next/dist/compiled/next-server/app-route.runtime.prod.js\");","module.exports = require(\"node:os\");","module.exports = require(\"node:fs/promises\");","module.exports = require(\"crypto\");","module.exports = require(\"https\");","module.exports = require(\"node:stream\");","module.exports = require(\"node:util\");","module.exports = require(\"next/dist/server/app-render/work-unit-async-storage.external.js\");","/**\n * @public — `POST /api/v1/providers/[provider]/probe`\n *\n * Sends a 1-token \"ping\" chat to confirm the provider/model_id/params\n * combination actually responds. Used by the Model editor's \"Test\n * connection\" button and as a pre-save guard so embedding-only or\n * unauthorized models surface immediately instead of failing later\n * when an agent tries to use them.\n */\n\nimport { NextRequest, NextResponse } from \"next/server\";\nimport { getProvider } from \"@/lib/providers\";\nimport { getModelConfig, getModelParams } from \"@/lib/stores/model-config\";\nimport { getCredential, getCredentialParams } from \"@/lib/stores/credentials\";\nimport type { ProviderParams } from \"@/lib/providers/types\";\n\ntype Params = { params: Promise<{ provider: string }> };\n\nconst PROBE_TIMEOUT_MS = 15_000;\n\nexport async function POST(req: NextRequest, { params }: Params) {\n const { provider: providerName } = await params;\n const body = await req.json().catch(() => ({})) as {\n model_id?: string;\n params?: ProviderParams;\n name?: string; // optional: hydrate params from saved model_config\n credential_id?: string; // optional: hydrate api_key from saved credential\n };\n if (!body.model_id) {\n return NextResponse.json({ ok: false, error: \"model_id required\" }, { status: 400 });\n }\n\n // Layer params in lowest-to-highest precedence:\n // 1. saved credential (api_key / base_url / extra_headers / OAuth)\n // 2. saved model_config inline params (non-secret overrides)\n // 3. body.params (form-time overrides)\n // This lets the editor \"Test connection\" before save while still using\n // a stored credential's secret without surfacing it to the client.\n let providerParams: ProviderParams = {};\n if (body.credential_id) {\n const cred = getCredential(body.credential_id);\n if (cred) providerParams = { ...providerParams, ...getCredentialParams(cred) };\n }\n if (body.name) {\n const cfg = getModelConfig(body.name);\n if (cfg) providerParams = { ...providerParams, ...getModelParams(cfg) };\n }\n providerParams = { ...providerParams, ...(body.params ?? {}) };\n\n let provider;\n try {\n provider = getProvider(providerName);\n } catch (e) {\n return NextResponse.json({ ok: false, error: String(e instanceof Error ? e.message : e) }, { status: 200 });\n }\n\n const probe = async () => {\n const { stream } = await provider.chat(\n body.model_id!,\n [{ role: \"user\", content: \"ping\" }],\n { ...providerParams, max_tokens: 1 },\n );\n // Pull just the first chunk to confirm the stream opened.\n const iter = stream[Symbol.asyncIterator]();\n await iter.next();\n try { await (iter as { return?: () => Promise<unknown> }).return?.(); } catch { /* best-effort */ }\n };\n\n try {\n await Promise.race([\n probe(),\n new Promise((_, reject) => setTimeout(() => reject(new Error(`probe timed out after ${PROBE_TIMEOUT_MS}ms`)), PROBE_TIMEOUT_MS)),\n ]);\n return NextResponse.json({ ok: true });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return NextResponse.json({ ok: false, error: msg });\n }\n}\n","import { AppRouteRouteModule } from \"next/dist/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/server/lib/patch-fetch\";\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from \"next/dist/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/server/lib/trace/tracer\";\nimport { setManifestsSingleton } from \"next/dist/server/app-render/manifests-singleton\";\nimport { normalizeAppPath } from \"next/dist/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/lib/constants\";\nimport { NoFallbackError } from \"next/dist/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/server/response-cache\";\nimport * as userland from \"/home/runner/work/jarela/jarela/app/api/v1/providers/[provider]/probe/route.ts\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"standalone\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/v1/providers/[provider]/probe/route\",\n pathname: \"/api/v1/providers/[provider]/probe\",\n filename: \"route\",\n bundlePath: \"app/api/v1/providers/[provider]/probe/route\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"/home/runner/work/jarela/jarela/app/api/v1/providers/[provider]/probe/route.ts\",\n nextConfigOutput,\n // The static import is used for initialization (methods, dynamic, etc.).\n userland: userland,\n // In Turbopack dev mode, also provide a getter that calls require() on every\n // request. This re-reads from devModuleCache so HMR updates are picked up,\n // and the async wrapper unwraps async-module Promises (ESM-only\n // serverExternalPackages) automatically.\n ...process.env.TURBOPACK && process.env.__NEXT_DEV_SERVER ? {\n getUserland: ()=>import(\"/home/runner/work/jarela/jarela/app/api/v1/providers/[provider]/probe/route.ts\")\n } : {}\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta);\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint());\n }\n let srcPage = \"/api/v1/providers/[provider]/probe/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, deploymentId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId,\n deploymentId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","module.exports = require(\"node:fs\");","module.exports = require(\"node:worker_threads\");","module.exports = require(\"node:path\");","module.exports = require(\"node:crypto\");","module.exports = require(\"buffer\");","module.exports = require(\"node:sqlite\");","module.exports = require(\"http\");","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","module.exports = require(\"events\");"],"names":["NextResponse","getProvider","getModelConfig","getModelParams","getCredential","getCredentialParams","PROBE_TIMEOUT_MS","POST","req","params","provider","providerName","body","json","catch","model_id","ok","error","status","providerParams","credential_id","cred","name","cfg","e","String","Error","message","probe","stream","chat","role","content","max_tokens","iter","Symbol","asyncIterator","next","return","Promise","race","_","reject","setTimeout","msg"],"sourceRoot":"","ignoreList":[0,3,5,10,15,22,32]}
|
|
1
|
+
{"version":3,"file":"../app/api/v1/providers/[provider]/probe/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACAA;;;;;;;;CAQC,GAEuD;AACV;AAC6B;AACG;AAK9E,MAAMM,mBAAmB;AAElB,eAAeC,KAAKC,GAAgB,EAAE,EAAEC,MAAM,EAAU;IAC7D,MAAM,EAAEC,UAAUC,YAAY,EAAE,GAAG,MAAMF;IACzC,MAAMG,OAAO,MAAMJ,IAAIK,IAAI,GAAGC,KAAK,CAAC,IAAO,EAAC;IAM5C,IAAI,CAACF,KAAKG,QAAQ,EAAE;QAClB,OAAOf,mBAAYA,CAACa,IAAI,CAAC;YAAEG,IAAI;YAAOC,OAAO;QAAoB,GAAG;YAAEC,QAAQ;QAAI;IACpF;IAEA,gDAAgD;IAChD,qEAAqE;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BAA0B,2CAAe;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,6CAAqB;AAC7B;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,mBAAmB,0BAAS;AAC5B;AACA;AACA,kCAAkC,+BAAc;AAChD,6BAA6B,+BAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,4BAA4B,oBAAe;AAC3C,4BAA4B,qBAAgB;AAC5C,oBAAoB,+BAAkB,kCAAkC,uCAAsB;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iEAAiE,wBAAc;AAC/E,+DAA+D,yCAAyC;AACxG;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,EAAE,MAAM;AACpD;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,uCAAuC,QAAQ,EAAE,QAAQ;AACzD;AACA,aAAa;AACb;AACA;AACA;AACA,+CAA+C,oBAAoB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,uCAAyB;AACjE;AACA,oCAAoC,oCAAsB;AAC1D;AACA;AACA;AACA;AACA,sJAAsJ,4BAAc;AACpK,0IAA0I,4BAAc;AACxJ;AACA;AACA;AACA,sCAAsC,8BAAe;AACrD;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,8BAA8B,qCAAY;AAC1C;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,oCAAmB;AACjE;AACA;AACA,6BAA6B;AAC7B,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,oBAAS;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,qIAAqI,8BAAe;AACpJ;AACA,2GAA2G,iHAAiH;AAC5N;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yCAA2B;AACvD;AACA,+BAA+B,oCAAsB;AACrD;AACA;AACA;AACA;AACA,6CAA6C,uCAAqB;AAClE;AACA,kBAAkB,qCAAY;AAC9B;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,6EAA6E,wBAAc;AAC3F,iCAAiC,QAAQ,EAAE,QAAQ;AACnD,0BAA0B,qBAAQ;AAClC;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA,MAAM;AACN,6BAA6B,2CAAe;AAC5C;AACA;AACA;AACA;AACA;AACA,kCAAkC,oCAAmB;AACrD;AACA;AACA,iBAAiB;AACjB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA,cAAc,qCAAY;AAC1B;AACA,SAAS;AACT;AACA;AACA;;AAEA;;;;;;;;AC7WA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA","sources":["webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/router/utils/app-paths\"","webpack://@circuitwall/jarela/external node-commonjs \"node:process\"","webpack://@circuitwall/jarela/external commonjs2 \"url\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/after-task-async-storage.external.js\"","webpack://@circuitwall/jarela/external commonjs \"undici\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-page.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:async_hooks\"","webpack://@circuitwall/jarela/external commonjs2 \"stream\"","webpack://@circuitwall/jarela/external commonjs2 \"util\"","webpack://@circuitwall/jarela/external commonjs2 \"fs\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-async-storage.external.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:child_process\"","webpack://@circuitwall/jarela/external commonjs2 \"path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:http\"","webpack://@circuitwall/jarela/external node-commonjs \"node:https\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-route.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:os\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs/promises\"","webpack://@circuitwall/jarela/external commonjs2 \"crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"https\"","webpack://@circuitwall/jarela/external node-commonjs \"node:stream\"","webpack://@circuitwall/jarela/external node-commonjs \"node:util\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-unit-async-storage.external.js\"","webpack://@circuitwall/jarela/./app/api/v1/providers/[provider]/probe/route.ts","webpack://@circuitwall/jarela/?0ab9","webpack://@circuitwall/jarela/external node-commonjs \"node:fs\"","webpack://@circuitwall/jarela/external node-commonjs \"node:worker_threads\"","webpack://@circuitwall/jarela/external node-commonjs \"node:path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"buffer\"","webpack://@circuitwall/jarela/external node-commonjs \"node:sqlite\"","webpack://@circuitwall/jarela/external commonjs2 \"http\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/no-fallback-error.external\"","webpack://@circuitwall/jarela/external commonjs2 \"events\""],"sourcesContent":["module.exports = require(\"next/dist/shared/lib/router/utils/app-paths\");","module.exports = require(\"node:process\");","module.exports = require(\"url\");","module.exports = require(\"next/dist/server/app-render/after-task-async-storage.external.js\");","module.exports = require(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","module.exports = require(\"node:async_hooks\");","module.exports = require(\"stream\");","module.exports = require(\"util\");","module.exports = require(\"fs\");","module.exports = require(\"next/dist/server/app-render/work-async-storage.external.js\");","module.exports = require(\"node:child_process\");","module.exports = require(\"path\");","module.exports = require(\"node:http\");","module.exports = require(\"node:https\");","module.exports = require(\"next/dist/compiled/next-server/app-route.runtime.prod.js\");","module.exports = require(\"node:os\");","module.exports = require(\"node:fs/promises\");","module.exports = require(\"crypto\");","module.exports = require(\"https\");","module.exports = require(\"node:stream\");","module.exports = require(\"node:util\");","module.exports = require(\"next/dist/server/app-render/work-unit-async-storage.external.js\");","/**\n * @public — `POST /api/v1/providers/[provider]/probe`\n *\n * Sends a 1-token \"ping\" chat to confirm the provider/model_id/params\n * combination actually responds. Used by the Model editor's \"Test\n * connection\" button and as a pre-save guard so embedding-only or\n * unauthorized models surface immediately instead of failing later\n * when an agent tries to use them.\n */\n\nimport { NextRequest, NextResponse } from \"next/server\";\nimport { getProvider } from \"@/lib/providers\";\nimport { getModelConfig, getModelParams } from \"@/lib/stores/model-config\";\nimport { getCredential, getCredentialParams } from \"@/lib/stores/credentials\";\nimport type { ProviderParams } from \"@/lib/providers/types\";\n\ntype Params = { params: Promise<{ provider: string }> };\n\nconst PROBE_TIMEOUT_MS = 15_000;\n\nexport async function POST(req: NextRequest, { params }: Params) {\n const { provider: providerName } = await params;\n const body = await req.json().catch(() => ({})) as {\n model_id?: string;\n params?: ProviderParams;\n name?: string; // optional: hydrate params from saved model_config\n credential_id?: string; // optional: hydrate api_key from saved credential\n };\n if (!body.model_id) {\n return NextResponse.json({ ok: false, error: \"model_id required\" }, { status: 400 });\n }\n\n // Layer params in lowest-to-highest precedence:\n // 1. saved credential (api_key / base_url / extra_headers / OAuth)\n // 2. saved model_config inline params (non-secret overrides)\n // 3. body.params (form-time overrides)\n // This lets the editor \"Test connection\" before save while still using\n // a stored credential's secret without surfacing it to the client.\n let providerParams: ProviderParams = {};\n if (body.credential_id) {\n const cred = getCredential(body.credential_id);\n if (cred) providerParams = { ...providerParams, ...getCredentialParams(cred) };\n }\n if (body.name) {\n const cfg = getModelConfig(body.name);\n if (cfg) providerParams = { ...providerParams, ...getModelParams(cfg) };\n }\n providerParams = { ...providerParams, ...(body.params ?? {}) };\n\n let provider;\n try {\n provider = getProvider(providerName);\n } catch (e) {\n return NextResponse.json({ ok: false, error: String(e instanceof Error ? e.message : e) }, { status: 200 });\n }\n\n const probe = async () => {\n const { stream } = await provider.chat(\n body.model_id!,\n [{ role: \"user\", content: \"ping\" }],\n { ...providerParams, max_tokens: 1 },\n );\n // Pull just the first chunk to confirm the stream opened.\n const iter = stream[Symbol.asyncIterator]();\n await iter.next();\n try { await (iter as { return?: () => Promise<unknown> }).return?.(); } catch { /* best-effort */ }\n };\n\n let timer: ReturnType<typeof setTimeout> | null = null;\n try {\n await Promise.race([\n probe(),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`probe timed out after ${PROBE_TIMEOUT_MS}ms`)),\n PROBE_TIMEOUT_MS,\n );\n }),\n ]);\n return NextResponse.json({ ok: true });\n } catch (e) {\n const msg = e instanceof Error ? e.message : String(e);\n return NextResponse.json({ ok: false, error: msg });\n } finally {\n // Without this, the 15s timer keeps firing after probe() wins the\n // race and the route returns — leaking an unhandled rejection per\n // probe (which then trips the global handler).\n if (timer) clearTimeout(timer);\n }\n}\n","import { AppRouteRouteModule } from \"next/dist/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/server/lib/patch-fetch\";\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from \"next/dist/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/server/lib/trace/tracer\";\nimport { setManifestsSingleton } from \"next/dist/server/app-render/manifests-singleton\";\nimport { normalizeAppPath } from \"next/dist/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/lib/constants\";\nimport { NoFallbackError } from \"next/dist/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/server/response-cache\";\nimport * as userland from \"/home/runner/work/jarela/jarela/app/api/v1/providers/[provider]/probe/route.ts\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"standalone\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/v1/providers/[provider]/probe/route\",\n pathname: \"/api/v1/providers/[provider]/probe\",\n filename: \"route\",\n bundlePath: \"app/api/v1/providers/[provider]/probe/route\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"/home/runner/work/jarela/jarela/app/api/v1/providers/[provider]/probe/route.ts\",\n nextConfigOutput,\n // The static import is used for initialization (methods, dynamic, etc.).\n userland: userland,\n // In Turbopack dev mode, also provide a getter that calls require() on every\n // request. This re-reads from devModuleCache so HMR updates are picked up,\n // and the async wrapper unwraps async-module Promises (ESM-only\n // serverExternalPackages) automatically.\n ...process.env.TURBOPACK && process.env.__NEXT_DEV_SERVER ? {\n getUserland: ()=>import(\"/home/runner/work/jarela/jarela/app/api/v1/providers/[provider]/probe/route.ts\")\n } : {}\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta);\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint());\n }\n let srcPage = \"/api/v1/providers/[provider]/probe/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, deploymentId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId,\n deploymentId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n","module.exports = require(\"node:fs\");","module.exports = require(\"node:worker_threads\");","module.exports = require(\"node:path\");","module.exports = require(\"node:crypto\");","module.exports = require(\"buffer\");","module.exports = require(\"node:sqlite\");","module.exports = require(\"http\");","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","module.exports = require(\"events\");"],"names":["NextResponse","getProvider","getModelConfig","getModelParams","getCredential","getCredentialParams","PROBE_TIMEOUT_MS","POST","req","params","provider","providerName","body","json","catch","model_id","ok","error","status","providerParams","credential_id","cred","name","cfg","e","String","Error","message","probe","stream","chat","role","content","max_tokens","iter","Symbol","asyncIterator","next","return","timer","Promise","race","_","reject","setTimeout","msg","clearTimeout"],"sourceRoot":"","ignoreList":[0,3,5,10,15,22,32]}
|
|
@@ -682,9 +682,16 @@ async function DELETE(_req, { params }) {
|
|
|
682
682
|
});
|
|
683
683
|
}
|
|
684
684
|
function attachStream(thread_id, stream_options) {
|
|
685
|
+
// Captured by both start() and cancel() so the cancel branch can tear
|
|
686
|
+
// down the poll timer + subscription when the client disconnects.
|
|
687
|
+
// Without this, navigating away from a long-running thread leaks an
|
|
688
|
+
// event subscriber + 2Hz setInterval per visit until the run finishes
|
|
689
|
+
// (or forever if it doesn't).
|
|
690
|
+
let poll = null;
|
|
691
|
+
let unsubscribe = null;
|
|
692
|
+
let clientGone = false;
|
|
685
693
|
const stream = new ReadableStream({
|
|
686
694
|
start (controller) {
|
|
687
|
-
let clientGone = false;
|
|
688
695
|
const safeEnqueue = (chunk)=>{
|
|
689
696
|
if (clientGone) return;
|
|
690
697
|
try {
|
|
@@ -700,13 +707,14 @@ function attachStream(thread_id, stream_options) {
|
|
|
700
707
|
...ev.data
|
|
701
708
|
}));
|
|
702
709
|
};
|
|
703
|
-
const
|
|
704
|
-
|
|
710
|
+
const sub = (0,run_registry/* subscribe */.B1)(thread_id, onEvent);
|
|
711
|
+
unsubscribe = sub.unsubscribe;
|
|
712
|
+
if (!sub.run) {
|
|
705
713
|
controller.close();
|
|
706
714
|
return;
|
|
707
715
|
}
|
|
708
716
|
// If run already terminal, close after replay.
|
|
709
|
-
if (run.status !== "running") {
|
|
717
|
+
if (sub.run.status !== "running") {
|
|
710
718
|
try {
|
|
711
719
|
controller.close();
|
|
712
720
|
} catch {}
|
|
@@ -715,11 +723,17 @@ function attachStream(thread_id, stream_options) {
|
|
|
715
723
|
// When the run finishes (status changes), close our response. We
|
|
716
724
|
// poll lightly because the run might finish due to other subscribers'
|
|
717
725
|
// signals; simpler than wiring a second listener channel.
|
|
718
|
-
|
|
726
|
+
poll = setInterval(()=>{
|
|
719
727
|
const r = (0,run_registry/* getRun */.Mh)(thread_id);
|
|
720
728
|
if (!r || r.status !== "running") {
|
|
721
|
-
|
|
722
|
-
|
|
729
|
+
if (poll) {
|
|
730
|
+
clearInterval(poll);
|
|
731
|
+
poll = null;
|
|
732
|
+
}
|
|
733
|
+
if (unsubscribe) {
|
|
734
|
+
unsubscribe();
|
|
735
|
+
unsubscribe = null;
|
|
736
|
+
}
|
|
723
737
|
if (!clientGone) {
|
|
724
738
|
try {
|
|
725
739
|
controller.close();
|
|
@@ -730,7 +744,18 @@ function attachStream(thread_id, stream_options) {
|
|
|
730
744
|
poll.unref?.();
|
|
731
745
|
},
|
|
732
746
|
cancel () {
|
|
733
|
-
|
|
747
|
+
// Client navigated away — agent run keeps going in registry, but
|
|
748
|
+
// tear down OUR poll + subscription so we don't leak a timer +
|
|
749
|
+
// subscriber per disconnect.
|
|
750
|
+
clientGone = true;
|
|
751
|
+
if (poll) {
|
|
752
|
+
clearInterval(poll);
|
|
753
|
+
poll = null;
|
|
754
|
+
}
|
|
755
|
+
if (unsubscribe) {
|
|
756
|
+
unsubscribe();
|
|
757
|
+
unsubscribe = null;
|
|
758
|
+
}
|
|
734
759
|
}
|
|
735
760
|
});
|
|
736
761
|
return (0,sse/* sseResponse */.t)(stream);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"../app/api/v1/threads/[thread_id]/run/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAa;AACb,IAAI,KAAmC,EAAE,EAExC,CAAC;AACF,QAAQ,KAAqC,EAAE,EAc1C,CAAC;AACN,YAAY,KAAsC,EAAE,EAM3C,CAAC;AACV,gBAAgB,KAAqB,EAAE,EAE1B,CAAC;AACd,gBAAgB,2CAAoF;AACpG;AACA;AACA;AACA;;AAEA;;;;;;;ACnCA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;;;;ACAA,yEAAyE;AACzE,yEAAyE;AACzE,yEAAyE;AACzE,oDAAoD;AAW7C,SAASA,YACdC,MAAsB,EACtBC,OAA2B,CAAC,CAAC;IAE7B,MAAM,EAAEC,wBAAwB,IAAI,EAAE,GAAGD;IACzC,MAAME,UAAkC;QACtC,gBAAgB;QAChB,iBAAiB;QACjBC,YAAY;IACd;IACA,IAAIF,uBAAuBC,OAAO,CAAC,oBAAoB,GAAG;IAC1D,OAAO,IAAIE,SAASL,QAAQ;QAAEG;IAAQ;AACxC;;;;;;;;AC1BA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA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A;AACA;AACA,+BAA+B,KAAwC;AACvE;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6NAA6N;AACzO,8BAA8B,+BAAgB;AAC9C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,2CAAe;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,6CAAqB;AAC7B;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,mBAAmB,0BAAS;AAC5B;AACA;AACA,kCAAkC,+BAAc;AAChD,6BAA6B,+BAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,4BAA4B,oBAAe;AAC3C,4BAA4B,qBAAgB;AAC5C,oBAAoB,+BAAkB,kCAAkC,uCAAsB;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iEAAiE,wBAAc;AAC/E,+DAA+D,yCAAyC;AACxG;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,EAAE,MAAM;AACpD;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,uCAAuC,QAAQ,EAAE,QAAQ;AACzD;AACA,aAAa;AACb;AACA;AACA;AACA,+CAA+C,oBAAoB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,uCAAyB;AACjE;AACA,oCAAoC,oCAAsB;AAC1D;AACA;AACA;AACA;AACA,sJAAsJ,4BAAc;AACpK,0IAA0I,4BAAc;AACxJ;AACA;AACA;AACA,sCAAsC,8BAAe;AACrD;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,8BAA8B,qCAAY;AAC1C;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,oCAAmB;AACjE;AACA;AACA,6BAA6B;AAC7B,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,oBAAS;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,qIAAqI,8BAAe;AACpJ;AACA,2GAA2G,iHAAiH;AAC5N;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yCAA2B;AACvD;AACA,+BAA+B,oCAAsB;AACrD;AACA;AACA;AACA;AACA,6CAA6C,uCAAqB;AAClE;AACA,kBAAkB,qCAAY;AAC9B;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,6EAA6E,wBAAc;AAC3F,iCAAiC,QAAQ,EAAE,QAAQ;AACnD,0BAA0B,qBAAQ;AAClC;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA,MAAM;AACN,6BAA6B,2CAAe;AAC5C;AACA;AACA;AACA;AACA;AACA,kCAAkC,oCAAmB;AACrD;AACA;AACA,iBAAiB;AACjB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA,cAAc,qCAAY;AAC1B;AACA,SAAS;AACT;AACA;AACA;;AAEA","sources":["webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/router/utils/app-paths\"","webpack://@circuitwall/jarela/external node-commonjs \"node:process\"","webpack://@circuitwall/jarela/external commonjs2 \"url\"","webpack://@circuitwall/jarela/external commonjs \"undici\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-page.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:async_hooks\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/route-modules/app-route/module.compiled.js","webpack://@circuitwall/jarela/external commonjs2 \"stream\"","webpack://@circuitwall/jarela/external commonjs2 \"util\"","webpack://@circuitwall/jarela/external commonjs2 \"fs\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-async-storage.external.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:child_process\"","webpack://@circuitwall/jarela/external commonjs2 \"path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:http\"","webpack://@circuitwall/jarela/external node-commonjs \"node:dns\"","webpack://@circuitwall/jarela/external node-commonjs \"node:https\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-route.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:os\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs/promises\"","webpack://@circuitwall/jarela/./lib/api/sse.ts","webpack://@circuitwall/jarela/external commonjs2 \"crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"https\"","webpack://@circuitwall/jarela/external node-commonjs \"node:stream\"","webpack://@circuitwall/jarela/external node-commonjs \"node:util\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-unit-async-storage.external.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs\"","webpack://@circuitwall/jarela/external node-commonjs \"node:worker_threads\"","webpack://@circuitwall/jarela/external node-commonjs \"node:path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:net\"","webpack://@circuitwall/jarela/external node-commonjs \"node:crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"buffer\"","webpack://@circuitwall/jarela/external commonjs2 \"fs/promises\"","webpack://@circuitwall/jarela/external node-commonjs \"node:sqlite\"","webpack://@circuitwall/jarela/external commonjs2 \"http\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/no-fallback-error.external\"","webpack://@circuitwall/jarela/external module \"@langchain/mcp-adapters\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/send-response.js","webpack://@circuitwall/jarela/external commonjs2 \"events\"","webpack://@circuitwall/jarela/./app/api/v1/threads/[thread_id]/run/route.ts","webpack://@circuitwall/jarela/?07f6"],"sourcesContent":["module.exports = require(\"next/dist/shared/lib/router/utils/app-paths\");","module.exports = require(\"node:process\");","module.exports = require(\"url\");","module.exports = require(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","module.exports = require(\"node:async_hooks\");","\"use strict\";\nif (process.env.NEXT_RUNTIME === 'edge') {\n module.exports = require('next/dist/server/route-modules/app-route/module.js');\n} else {\n if (process.env.__NEXT_EXPERIMENTAL_REACT) {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.prod.js');\n }\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.prod.js');\n }\n }\n }\n}\n\n//# sourceMappingURL=module.compiled.js.map","module.exports = require(\"stream\");","module.exports = require(\"util\");","module.exports = require(\"fs\");","module.exports = require(\"next/dist/server/app-render/work-async-storage.external.js\");","module.exports = require(\"node:child_process\");","module.exports = require(\"path\");","module.exports = require(\"node:http\");","module.exports = require(\"node:dns\");","module.exports = require(\"node:https\");","module.exports = require(\"next/dist/compiled/next-server/app-route.runtime.prod.js\");","module.exports = require(\"node:os\");","module.exports = require(\"node:fs/promises\");","// Shared response builder for Server-Sent Event streams. Centralises the\n// content-type / cache-control / connection / proxy-buffering headers so\n// every SSE endpoint behaves identically through nginx, tailscale-serve,\n// and Cloudflare. See ADR-0009 for the proxy story.\n\nexport interface SseResponseOptions {\n /**\n * Set `X-Accel-Buffering: no`. Required when intermediate proxies\n * (nginx, tailscale-serve) might coalesce small chunks and break SSE\n * framing. Default: true.\n */\n disableProxyBuffering?: boolean;\n}\n\nexport function sseResponse(\n stream: ReadableStream,\n opts: SseResponseOptions = {},\n): Response {\n const { disableProxyBuffering = true } = opts;\n const headers: Record<string, string> = {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n };\n if (disableProxyBuffering) headers[\"X-Accel-Buffering\"] = \"no\";\n return new Response(stream, { headers });\n}\n","module.exports = require(\"crypto\");","module.exports = require(\"https\");","module.exports = require(\"node:stream\");","module.exports = require(\"node:util\");","module.exports = require(\"next/dist/server/app-render/work-unit-async-storage.external.js\");","module.exports = require(\"node:fs\");","module.exports = require(\"node:worker_threads\");","module.exports = require(\"node:path\");","module.exports = require(\"node:net\");","module.exports = require(\"node:crypto\");","module.exports = require(\"buffer\");","module.exports = require(\"fs/promises\");","module.exports = require(\"node:sqlite\");","module.exports = require(\"http\");","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","module.exports = import(\"@langchain/mcp-adapters\");;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"sendResponse\", {\n enumerable: true,\n get: function() {\n return sendResponse;\n }\n});\nconst _helpers = require(\"./base-http/helpers\");\nconst _pipereadable = require(\"./pipe-readable\");\nconst _utils = require(\"./web/utils\");\nasync function sendResponse(req, res, response, waitUntil) {\n if (// The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextResponse)(res)) {\n var // Copy over the response headers.\n _response_headers;\n // Copy over the response status.\n res.statusCode = response.status;\n res.statusMessage = response.statusText;\n // TODO: this is not spec-compliant behavior and we should not restrict\n // headers that are allowed to appear many times.\n //\n // See:\n // https://github.com/vercel/next.js/pull/70127\n const headersWithMultipleValuesAllowed = [\n // can add more headers to this list if needed\n 'set-cookie',\n 'www-authenticate',\n 'proxy-authenticate',\n 'vary'\n ];\n (_response_headers = response.headers) == null ? void 0 : _response_headers.forEach((value, name)=>{\n // `x-middleware-set-cookie` is an internal header not needed for the response\n if (name.toLowerCase() === 'x-middleware-set-cookie') {\n return;\n }\n // The append handling is special cased for `set-cookie`.\n if (name.toLowerCase() === 'set-cookie') {\n // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n for (const cookie of (0, _utils.splitCookiesString)(value)){\n res.appendHeader(name, cookie);\n }\n } else {\n // only append the header if it is either not present in the outbound response\n // or if the header supports multiple values\n const isHeaderPresent = typeof res.getHeader(name) !== 'undefined';\n if (headersWithMultipleValuesAllowed.includes(name.toLowerCase()) || !isHeaderPresent) {\n res.appendHeader(name, value);\n }\n }\n });\n /**\n * The response can't be directly piped to the underlying response. The\n * following is duplicated from the edge runtime handler.\n *\n * See packages/next/server/next-server.ts\n */ const { originalResponse } = res;\n // A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD\n if (response.body && req.method !== 'HEAD') {\n await (0, _pipereadable.pipeToNodeResponse)(response.body, originalResponse, waitUntil);\n } else {\n originalResponse.end();\n }\n }\n}\n\n//# sourceMappingURL=send-response.js.map","module.exports = require(\"events\");","/**\n * @public — `POST /api/v1/threads/[thread_id]/run` (submit run),\n * `GET /api/v1/threads/[thread_id]/run` (subscribe via SSE)\n *\n * Agent execution endpoint. Submit a run, then stream tokens, tool\n * calls, and final state. The split-and-subscribe shape lets reconnects\n * pick up an in-flight stream. See `docs/api.md`.\n */\n\nimport { NextRequest } from \"next/server\";\nimport type { StreamOptions, StreamChunk } from \"@/lib/agents/base\";\nimport type { ContentPart } from \"@/lib/tools/types\";\nimport {\n prepareThreadRun,\n persistAssistantMessage,\n withInterruptMarker,\n RunThreadError,\n snapshotThreadModelConfigName,\n shouldEmitChunk,\n} from \"@/lib/agents/run-thread\";\nimport { broadcast, finishRun, startRun, subscribe, abortRun, getRun } from \"@/lib/agents/run-registry\";\nimport { enqueueThreadRun, QueueFullError } from \"@/lib/agents/run-queue\";\nimport { collectStream } from \"@/lib/agents/stream-collector\";\nimport { getThread } from \"@/lib/stores/threads\";\nimport { publish as publishNotification } from \"@/lib/notifications/bus\";\nimport { sseResponse } from \"@/lib/api/sse\";\nimport { resolveTurnProfile } from \"@/lib/agents/turn-profile\";\n\ntype Params = { params: Promise<{ thread_id: string }> };\n\nconst enc = new TextEncoder();\nconst sse = (obj: Record<string, unknown>) => enc.encode(`data: ${JSON.stringify(obj)}\\n\\n`);\n\n// POST is the *command* half of the run lifecycle (ADR-0008). It accepts the\n// new user message, registers a run in the in-memory registry, kicks the\n// agent loop off in a detached async task, and returns 202 immediately. The\n// caller must follow up with a GET on this same path (as an `EventSource`)\n// to subscribe to the chunk stream — see GET below.\n//\n// Splitting submit from subscribe gives us a single reliable streaming\n// primitive across all browsers (EventSource is the only WebKit-native\n// streaming API that survives iOS Safari + Tailscale HTTP/2 proxies). It\n// also collapses what was previously a WS sidecar + SSE-over-POST +\n// SSE-GET-reattach trio into one transport.\nexport async function POST(req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const { message, attachments, stream_options, hot_since } = (await req.json()) as {\n message: string;\n attachments?: ContentPart[];\n stream_options?: StreamOptions;\n // ADR-0042 — explicit context boundary the chat picked. ISO timestamp,\n // null to clear the pin, omitted to leave whatever's already persisted\n // on the thread.\n hot_since?: string | null;\n };\n\n // Per-thread FIFO queue (lib/agents/run-queue.ts). Every entry point\n // that drives an agent on a thread goes through this — HTTP POST,\n // scheduler, watcher, trigger, bridge — so concurrent fires on the same\n // thread_id serialise instead of racing the LangGraph checkpoint store.\n // If the queue is already at the soft cap, reject with 503 so the\n // caller can back off rather than pin yet more work in memory.\n const thread = getThread(thread_id);\n const pinnedModelConfigName = snapshotThreadModelConfigName(thread_id);\n let position: number;\n try {\n ({ position } = enqueueThreadRun(thread_id, \"user\", async () => {\n // startRun is called once it's our turn so the registry only ever\n // holds one active entry per thread at a time. Subscribers that\n // attach via GET before our turn comes will see no run yet and the\n // SSE handler emits a synthetic done — the client reopens the\n // EventSource and picks up the stream once we're running.\n const active = startRun(thread_id, thread?.agent_id ?? null);\n let prepared;\n try {\n prepared = await prepareThreadRun({\n thread_id,\n message,\n options: stream_options,\n attachments,\n signal: active.abort.signal,\n hot_since,\n context_profile: resolveTurnProfile(\"user\"),\n _pinned_model_config_name: pinnedModelConfigName,\n });\n } catch (err) {\n // Prep failure (unknown agent, model misconfig, …). With queueing\n // the HTTP request has already returned 202, so the error has to\n // surface as an SSE chunk to any attached subscriber. There may\n // be no subscriber if the GET hasn't connected yet — the chunk\n // is buffered on the ActiveRun for the next attach.\n const message_ = err instanceof RunThreadError ? err.message : String(err);\n const code = err instanceof RunThreadError ? err.code : \"run_prepare_error\";\n broadcast(active, { type: \"error\", data: { message: message_, code } });\n finishRun(active, \"error\");\n return;\n }\n\n // Drive the agent to completion regardless of client connection. Events\n // go to the registry; the GET subscriber (and any reattaching clients)\n // receive them via subscribe().\n //\n // CRITICAL: finishRun() MUST run no matter what — if it doesn't, the\n // run is pinned as \"running\" forever and the TTL eviction (scheduled\n // inside finishRun()) never fires, so a leaked entry never self-heals.\n // Wrap the whole body in try/finally.\n let terminal: \"done\" | \"error\" = \"error\";\n let assistantContent = \"\";\n try {\n const collected = await collectStream(prepared.stream as AsyncIterable<StreamChunk>, {\n onChunk: (chunk) => broadcast(active, chunk),\n });\n assistantContent = collected.assistantContent;\n terminal = collected.terminal;\n // If the stream threw mid-iteration, collectStream returns terminal=\"error\"\n // but no `error` chunk was broadcast — surface one to subscribers. Skip\n // when the run was deliberately aborted: llm.ts already emitted an\n // `error{code:\"aborted\"}` chunk for that path and re-broadcasting as\n // `stream_error` would mask the intent.\n if (collected.terminal === \"error\" && collected.errorMessage && !collected.aborted) {\n broadcast(active, {\n type: \"error\",\n data: { message: collected.errorMessage, code: \"stream_error\" },\n });\n }\n try {\n // On a user abort (Stop / steer), append the interrupt footer so\n // the partial reply is never silently dropped and the next agent\n // turn sees a clear marker explaining the cut. withInterruptMarker\n // returns the bare marker when the partial is empty, which forces\n // persistAssistantMessage past its skip-empty guard so the thread\n // always has a row recording what happened.\n const contentToPersist = collected.aborted\n ? withInterruptMarker(collected.assistantContent)\n : collected.assistantContent;\n persistAssistantMessage(thread_id, contentToPersist, collected.usedTools, collected.toolEvents, null, collected.usage ?? null, prepared.context_snapshot ?? null, prepared.source_manifest ?? null);\n } catch (persistErr) {\n terminal = \"error\";\n broadcast(active, {\n type: \"error\",\n data: { message: `persist failed: ${(persistErr as Error).message}`, code: \"persist_error\" },\n });\n }\n } catch (err) {\n terminal = \"error\";\n broadcast(active, {\n type: \"error\",\n data: { message: (err as Error).message ?? String(err), code: \"run_crashed\" },\n });\n } finally {\n finishRun(active, terminal);\n publishNotification({\n type: \"run_completed\",\n thread_id,\n agent_id: thread?.agent_id ?? null,\n status: terminal,\n preview: assistantContent.replace(/\\s+/g, \" \").trim().slice(0, 120),\n ts: Date.now(),\n });\n }\n }));\n } catch (err) {\n if (err instanceof QueueFullError) {\n return new Response(\n JSON.stringify({ accepted: false, code: \"queue_full\", thread_id, error: err.message }),\n { status: 503, headers: { \"Content-Type\": \"application/json\" } },\n );\n }\n throw err;\n }\n\n return new Response(\n JSON.stringify({ accepted: true, thread_id, queue_position: position }),\n { status: 202, headers: { \"Content-Type\": \"application/json\" } },\n );\n}\n\n// GET is the *query* half of the run lifecycle (ADR-0008). Attaches to an\n// active (or recently-finished, within the registry TTL) run and streams\n// chunks as Server-Sent Events. Always consumed client-side via\n// `EventSource` — never `fetch().body.getReader()`, which is unreliable on\n// iOS Safari for long-lived streaming responses.\n//\n// Emits a single synthetic `done` event and closes when there's no run to\n// attach to (run never existed, or it finished + TTL-evicted before the GET\n// arrived). We deliberately do NOT return 404 here: browsers map a 404 SSE\n// response onto `EventSource.onerror` with no terminal event, which trips\n// EventSource's auto-reconnect logic and leaves the client in a \"stream\n// open but silent\" state — UIs gating on a `done` event hang forever\n// showing the Stop/Reconnecting affordances. A 200 with `data: {\"type\":\n// \"done\"}\\n\\n` makes the iterator drain cleanly on every transport.\n//\n// `show_tools` / `show_thinking` query params let the caller suppress\n// chunk types it doesn't want to render. Defaults: both on. The full\n// `StreamOptions` shape is only meaningful on the POST (tool policy &\n// agent run config are run-wide settings, not per-subscriber filters).\nexport async function GET(req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const showTools = req.nextUrl.searchParams.get(\"show_tools\") !== \"false\";\n const showThinking = req.nextUrl.searchParams.get(\"show_thinking\") !== \"false\";\n const stream_options: StreamOptions = {\n filters: { include_tools: showTools, include_thinking: showThinking },\n };\n\n const run = getRun(thread_id);\n if (!run) {\n const stream = new ReadableStream({\n start(controller) {\n controller.enqueue(sse({ type: \"done\" }));\n controller.close();\n },\n });\n return sseResponse(stream);\n }\n\n return attachStream(thread_id, stream_options);\n}\n\n// DELETE aborts the currently-running agent for this thread. The agent stream\n// loop in llm.ts catches the resulting AbortError and emits a synthetic\n// `error` + `done` event pair so subscribers (and the client's queue-drain\n// hook) finish cleanly.\nexport async function DELETE(_req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const aborted = abortRun(thread_id, \"user_interrupted\");\n return new Response(JSON.stringify({ aborted }), {\n status: aborted ? 200 : 404,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\nfunction attachStream(\n thread_id: string,\n stream_options?: StreamOptions,\n): Response {\n const stream = new ReadableStream({\n start(controller) {\n let clientGone = false;\n const safeEnqueue = (chunk: Uint8Array): void => {\n if (clientGone) return;\n try { controller.enqueue(chunk); } catch { clientGone = true; }\n };\n\n const onEvent = (ev: StreamChunk) => {\n if (!shouldEmitChunk(ev.type, stream_options)) return;\n safeEnqueue(sse({ type: ev.type, ...ev.data }));\n };\n\n const { run, unsubscribe } = subscribe(thread_id, onEvent);\n if (!run) {\n controller.close();\n return;\n }\n\n // If run already terminal, close after replay.\n if (run.status !== \"running\") {\n try { controller.close(); } catch { /* */ }\n return;\n }\n\n // When the run finishes (status changes), close our response. We\n // poll lightly because the run might finish due to other subscribers'\n // signals; simpler than wiring a second listener channel.\n const poll = setInterval(() => {\n const r = getRun(thread_id);\n if (!r || r.status !== \"running\") {\n clearInterval(poll);\n unsubscribe();\n if (!clientGone) {\n try { controller.close(); } catch { /* */ }\n }\n }\n }, 500);\n poll.unref?.();\n },\n cancel() {\n // Client navigated away — agent run keeps going in registry.\n },\n });\n\n return sseResponse(stream);\n}\n","import { AppRouteRouteModule } from \"next/dist/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/server/lib/patch-fetch\";\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from \"next/dist/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/server/lib/trace/tracer\";\nimport { setManifestsSingleton } from \"next/dist/server/app-render/manifests-singleton\";\nimport { normalizeAppPath } from \"next/dist/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/lib/constants\";\nimport { NoFallbackError } from \"next/dist/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/server/response-cache\";\nimport * as userland from \"/home/runner/work/jarela/jarela/app/api/v1/threads/[thread_id]/run/route.ts\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"standalone\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/v1/threads/[thread_id]/run/route\",\n pathname: \"/api/v1/threads/[thread_id]/run\",\n filename: \"route\",\n bundlePath: \"app/api/v1/threads/[thread_id]/run/route\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"/home/runner/work/jarela/jarela/app/api/v1/threads/[thread_id]/run/route.ts\",\n nextConfigOutput,\n // The static import is used for initialization (methods, dynamic, etc.).\n userland: userland,\n // In Turbopack dev mode, also provide a getter that calls require() on every\n // request. This re-reads from devModuleCache so HMR updates are picked up,\n // and the async wrapper unwraps async-module Promises (ESM-only\n // serverExternalPackages) automatically.\n ...process.env.TURBOPACK && process.env.__NEXT_DEV_SERVER ? {\n getUserland: ()=>import(\"/home/runner/work/jarela/jarela/app/api/v1/threads/[thread_id]/run/route.ts\")\n } : {}\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta);\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint());\n }\n let srcPage = \"/api/v1/threads/[thread_id]/run/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, deploymentId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId,\n deploymentId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n"],"names":["sseResponse","stream","opts","disableProxyBuffering","headers","Connection","Response","prepareThreadRun","persistAssistantMessage","withInterruptMarker","RunThreadError","snapshotThreadModelConfigName","shouldEmitChunk","broadcast","finishRun","startRun","subscribe","abortRun","getRun","enqueueThreadRun","QueueFullError","collectStream","getThread","publish","publishNotification","resolveTurnProfile","enc","TextEncoder","sse","obj","encode","JSON","stringify","POST","req","params","thread_id","message","attachments","stream_options","hot_since","json","thread","pinnedModelConfigName","position","active","agent_id","prepared","options","signal","abort","context_profile","_pinned_model_config_name","err","message_","String","code","type","data","terminal","assistantContent","collected","onChunk","chunk","errorMessage","aborted","contentToPersist","usedTools","toolEvents","usage","context_snapshot","source_manifest","persistErr","status","preview","replace","trim","slice","ts","Date","now","accepted","error","queue_position","GET","showTools","nextUrl","searchParams","get","showThinking","filters","include_tools","include_thinking","run","ReadableStream","start","controller","enqueue","close","attachStream","DELETE","_req","clientGone","safeEnqueue","onEvent","ev","unsubscribe","poll","setInterval","r","clearInterval","unref","cancel"],"sourceRoot":"","ignoreList":[0,4,6,10,16,24,34,36]}
|
|
1
|
+
{"version":3,"file":"../app/api/v1/threads/[thread_id]/run/route.js","mappings":";;;;;;;;;;AAAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAa;AACb,IAAI,KAAmC,EAAE,EAExC,CAAC;AACF,QAAQ,KAAqC,EAAE,EAc1C,CAAC;AACN,YAAY,KAAsC,EAAE,EAM3C,CAAC;AACV,gBAAgB,KAAqB,EAAE,EAE1B,CAAC;AACd,gBAAgB,2CAAoF;AACpG;AACA;AACA;AACA;;AAEA;;;;;;;ACnCA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;;ACAA;;;;;;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D;YAC/D,6BAA6B;YAC7BT,aAAa;YACb,IAAIF,MAAM;gBAAES,cAAcT;gBAAOA,OAAO;YAAM;YAC9C,IAAIC,aAAa;gBAAEA;gBAAeA,cAAc;YAAM;QACxD;IACF;IAEA,OAAOvG,0BAAWA,CAACC;AACrB;;;ACvS+F;AACvC;AACqB;AACkB;AACvB;AACgB;AACT;AACK;AACmC;AACjD;AACO;AACf;AACsC;AACzB;AACM;AACC;AAChB;AACsC;AACxG;AACA;AACA;AACA,wBAAwB,mCAAmB;AAC3C;AACA,cAAc,oBAAS;AACvB;AACA;AACA;AACA;AACA,KAAK;AACL,aAAa,OAAoC,IAAI,CAAE;AACvD,wBAAwB,MAAuC;AAC/D;AACA;AACA;AACA,cAAc,qBAAQ;AACtB;AACA;AACA;AACA;AACA,OAAO,MAAsD,GAAG,CAE3D,CAAC;AACN,CAAC;AACD;AACA;AACA;AACA,QAAQ,sDAAsD;AAC9D;AACA,WAAW,0BAAW;AACtB;AACA;AACA,KAAK;AACL;AAC0F;AACnF;AACP;AACA,QAAQ,+BAAc;AACtB;AACA;AACA,QAAQ,+BAAc;AACtB;AACA;AACA;AACA;AACA;AACA,QAAQ,KAAqB,EAAE,EAE1B,CAAC;AACN;AACA;AACA;AACA,+BAA+B,KAAwC;AACvE;AACA;AACA;AACA,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA,YAAY,6NAA6N;AACzO,8BAA8B,+BAAgB;AAC9C;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,0BAA0B,2CAAe;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,QAAQ,6CAAqB;AAC7B;AACA;AACA;AACA,SAAS;AACT;AACA;AACA,mBAAmB,0BAAS;AAC5B;AACA;AACA,kCAAkC,+BAAc;AAChD,6BAA6B,+BAAc;AAC3C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA,SAAS;AACT;AACA;AACA;AACA;AACA;AACA,4BAA4B,oBAAe;AAC3C,4BAA4B,qBAAgB;AAC5C,oBAAoB,+BAAkB,kCAAkC,uCAAsB;AAC9F;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA,iEAAiE,wBAAc;AAC/E,+DAA+D,yCAAyC;AACxG;AACA;AACA;AACA;AACA,oCAAoC,QAAQ,EAAE,MAAM;AACpD;AACA;AACA;AACA;AACA,qBAAqB;AACrB;AACA;AACA;AACA;AACA;AACA;AACA;AACA,kBAAkB;AAClB,uCAAuC,QAAQ,EAAE,QAAQ;AACzD;AACA,aAAa;AACb;AACA;AACA;AACA,+CAA+C,oBAAoB;AACnE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,wCAAwC,uCAAyB;AACjE;AACA,oCAAoC,oCAAsB;AAC1D;AACA;AACA;AACA;AACA,sJAAsJ,4BAAc;AACpK,0IAA0I,4BAAc;AACxJ;AACA;AACA;AACA,sCAAsC,8BAAe;AACrD;AACA;AACA;AACA,6BAA6B;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA,sBAAsB;AACtB;AACA,8BAA8B,qCAAY;AAC1C;AACA;AACA,kBAAkB;AAClB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,8CAA8C,oCAAmB;AACjE;AACA;AACA,6BAA6B;AAC7B,yBAAyB;AACzB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,2BAA2B,oBAAS;AACpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA,qIAAqI,8BAAe;AACpJ;AACA,2GAA2G,iHAAiH;AAC5N;AACA;AACA;AACA,iBAAiB;AACjB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,4BAA4B,yCAA2B;AACvD;AACA,+BAA+B,oCAAsB;AACrD;AACA;AACA;AACA;AACA,6CAA6C,uCAAqB;AAClE;AACA,kBAAkB,qCAAY;AAC9B;AACA;AACA;AACA,aAAa;AACb;AACA;AACA;AACA;AACA;AACA;AACA,UAAU;AACV;AACA,6EAA6E,wBAAc;AAC3F,iCAAiC,QAAQ,EAAE,QAAQ;AACnD,0BAA0B,qBAAQ;AAClC;AACA;AACA;AACA;AACA,iBAAiB;AACjB;AACA,MAAM;AACN,6BAA6B,2CAAe;AAC5C;AACA;AACA;AACA;AACA;AACA,kCAAkC,oCAAmB;AACrD;AACA;AACA,iBAAiB;AACjB,aAAa;AACb;AACA;AACA;AACA;AACA;AACA,cAAc,qCAAY;AAC1B;AACA,SAAS;AACT;AACA;AACA;;AAEA","sources":["webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/router/utils/app-paths\"","webpack://@circuitwall/jarela/external node-commonjs \"node:process\"","webpack://@circuitwall/jarela/external commonjs2 \"url\"","webpack://@circuitwall/jarela/external commonjs \"undici\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-page.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:async_hooks\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/route-modules/app-route/module.compiled.js","webpack://@circuitwall/jarela/external commonjs2 \"stream\"","webpack://@circuitwall/jarela/external commonjs2 \"util\"","webpack://@circuitwall/jarela/external commonjs2 \"fs\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-async-storage.external.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:child_process\"","webpack://@circuitwall/jarela/external commonjs2 \"path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:http\"","webpack://@circuitwall/jarela/external node-commonjs \"node:dns\"","webpack://@circuitwall/jarela/external node-commonjs \"node:https\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/compiled/next-server/app-route.runtime.prod.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:os\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs/promises\"","webpack://@circuitwall/jarela/./lib/api/sse.ts","webpack://@circuitwall/jarela/external commonjs2 \"crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"https\"","webpack://@circuitwall/jarela/external node-commonjs \"node:stream\"","webpack://@circuitwall/jarela/external node-commonjs \"node:util\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/server/app-render/work-unit-async-storage.external.js\"","webpack://@circuitwall/jarela/external node-commonjs \"node:fs\"","webpack://@circuitwall/jarela/external node-commonjs \"node:worker_threads\"","webpack://@circuitwall/jarela/external node-commonjs \"node:path\"","webpack://@circuitwall/jarela/external node-commonjs \"node:net\"","webpack://@circuitwall/jarela/external node-commonjs \"node:crypto\"","webpack://@circuitwall/jarela/external commonjs2 \"buffer\"","webpack://@circuitwall/jarela/external commonjs2 \"fs/promises\"","webpack://@circuitwall/jarela/external node-commonjs \"node:sqlite\"","webpack://@circuitwall/jarela/external commonjs2 \"http\"","webpack://@circuitwall/jarela/external commonjs \"next/dist/shared/lib/no-fallback-error.external\"","webpack://@circuitwall/jarela/external module \"@langchain/mcp-adapters\"","webpack://@circuitwall/jarela/./node_modules/next/dist/server/send-response.js","webpack://@circuitwall/jarela/external commonjs2 \"events\"","webpack://@circuitwall/jarela/./app/api/v1/threads/[thread_id]/run/route.ts","webpack://@circuitwall/jarela/?07f6"],"sourcesContent":["module.exports = require(\"next/dist/shared/lib/router/utils/app-paths\");","module.exports = require(\"node:process\");","module.exports = require(\"url\");","module.exports = require(\"undici\");","module.exports = require(\"next/dist/compiled/next-server/app-page.runtime.prod.js\");","module.exports = require(\"node:async_hooks\");","\"use strict\";\nif (process.env.NEXT_RUNTIME === 'edge') {\n module.exports = require('next/dist/server/route-modules/app-route/module.js');\n} else {\n if (process.env.__NEXT_EXPERIMENTAL_REACT) {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo-experimental.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route-experimental.runtime.prod.js');\n }\n }\n } else {\n if (process.env.NODE_ENV === 'development') {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.dev.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.dev.js');\n }\n } else {\n if (process.env.TURBOPACK) {\n module.exports = require('next/dist/compiled/next-server/app-route-turbo.runtime.prod.js');\n } else {\n module.exports = require('next/dist/compiled/next-server/app-route.runtime.prod.js');\n }\n }\n }\n}\n\n//# sourceMappingURL=module.compiled.js.map","module.exports = require(\"stream\");","module.exports = require(\"util\");","module.exports = require(\"fs\");","module.exports = require(\"next/dist/server/app-render/work-async-storage.external.js\");","module.exports = require(\"node:child_process\");","module.exports = require(\"path\");","module.exports = require(\"node:http\");","module.exports = require(\"node:dns\");","module.exports = require(\"node:https\");","module.exports = require(\"next/dist/compiled/next-server/app-route.runtime.prod.js\");","module.exports = require(\"node:os\");","module.exports = require(\"node:fs/promises\");","// Shared response builder for Server-Sent Event streams. Centralises the\n// content-type / cache-control / connection / proxy-buffering headers so\n// every SSE endpoint behaves identically through nginx, tailscale-serve,\n// and Cloudflare. See ADR-0009 for the proxy story.\n\nexport interface SseResponseOptions {\n /**\n * Set `X-Accel-Buffering: no`. Required when intermediate proxies\n * (nginx, tailscale-serve) might coalesce small chunks and break SSE\n * framing. Default: true.\n */\n disableProxyBuffering?: boolean;\n}\n\nexport function sseResponse(\n stream: ReadableStream,\n opts: SseResponseOptions = {},\n): Response {\n const { disableProxyBuffering = true } = opts;\n const headers: Record<string, string> = {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n };\n if (disableProxyBuffering) headers[\"X-Accel-Buffering\"] = \"no\";\n return new Response(stream, { headers });\n}\n","module.exports = require(\"crypto\");","module.exports = require(\"https\");","module.exports = require(\"node:stream\");","module.exports = require(\"node:util\");","module.exports = require(\"next/dist/server/app-render/work-unit-async-storage.external.js\");","module.exports = require(\"node:fs\");","module.exports = require(\"node:worker_threads\");","module.exports = require(\"node:path\");","module.exports = require(\"node:net\");","module.exports = require(\"node:crypto\");","module.exports = require(\"buffer\");","module.exports = require(\"fs/promises\");","module.exports = require(\"node:sqlite\");","module.exports = require(\"http\");","module.exports = require(\"next/dist/shared/lib/no-fallback-error.external\");","module.exports = import(\"@langchain/mcp-adapters\");;","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"sendResponse\", {\n enumerable: true,\n get: function() {\n return sendResponse;\n }\n});\nconst _helpers = require(\"./base-http/helpers\");\nconst _pipereadable = require(\"./pipe-readable\");\nconst _utils = require(\"./web/utils\");\nasync function sendResponse(req, res, response, waitUntil) {\n if (// The type check here ensures that `req` is correctly typed, and the\n // environment variable check provides dead code elimination.\n process.env.NEXT_RUNTIME !== 'edge' && (0, _helpers.isNodeNextResponse)(res)) {\n var // Copy over the response headers.\n _response_headers;\n // Copy over the response status.\n res.statusCode = response.status;\n res.statusMessage = response.statusText;\n // TODO: this is not spec-compliant behavior and we should not restrict\n // headers that are allowed to appear many times.\n //\n // See:\n // https://github.com/vercel/next.js/pull/70127\n const headersWithMultipleValuesAllowed = [\n // can add more headers to this list if needed\n 'set-cookie',\n 'www-authenticate',\n 'proxy-authenticate',\n 'vary'\n ];\n (_response_headers = response.headers) == null ? void 0 : _response_headers.forEach((value, name)=>{\n // `x-middleware-set-cookie` is an internal header not needed for the response\n if (name.toLowerCase() === 'x-middleware-set-cookie') {\n return;\n }\n // The append handling is special cased for `set-cookie`.\n if (name.toLowerCase() === 'set-cookie') {\n // TODO: (wyattjoh) replace with native response iteration when we can upgrade undici\n for (const cookie of (0, _utils.splitCookiesString)(value)){\n res.appendHeader(name, cookie);\n }\n } else {\n // only append the header if it is either not present in the outbound response\n // or if the header supports multiple values\n const isHeaderPresent = typeof res.getHeader(name) !== 'undefined';\n if (headersWithMultipleValuesAllowed.includes(name.toLowerCase()) || !isHeaderPresent) {\n res.appendHeader(name, value);\n }\n }\n });\n /**\n * The response can't be directly piped to the underlying response. The\n * following is duplicated from the edge runtime handler.\n *\n * See packages/next/server/next-server.ts\n */ const { originalResponse } = res;\n // A response body must not be sent for HEAD requests. See https://httpwg.org/specs/rfc9110.html#HEAD\n if (response.body && req.method !== 'HEAD') {\n await (0, _pipereadable.pipeToNodeResponse)(response.body, originalResponse, waitUntil);\n } else {\n originalResponse.end();\n }\n }\n}\n\n//# sourceMappingURL=send-response.js.map","module.exports = require(\"events\");","/**\n * @public — `POST /api/v1/threads/[thread_id]/run` (submit run),\n * `GET /api/v1/threads/[thread_id]/run` (subscribe via SSE)\n *\n * Agent execution endpoint. Submit a run, then stream tokens, tool\n * calls, and final state. The split-and-subscribe shape lets reconnects\n * pick up an in-flight stream. See `docs/api.md`.\n */\n\nimport { NextRequest } from \"next/server\";\nimport type { StreamOptions, StreamChunk } from \"@/lib/agents/base\";\nimport type { ContentPart } from \"@/lib/tools/types\";\nimport {\n prepareThreadRun,\n persistAssistantMessage,\n withInterruptMarker,\n RunThreadError,\n snapshotThreadModelConfigName,\n shouldEmitChunk,\n} from \"@/lib/agents/run-thread\";\nimport { broadcast, finishRun, startRun, subscribe, abortRun, getRun } from \"@/lib/agents/run-registry\";\nimport { enqueueThreadRun, QueueFullError } from \"@/lib/agents/run-queue\";\nimport { collectStream } from \"@/lib/agents/stream-collector\";\nimport { getThread } from \"@/lib/stores/threads\";\nimport { publish as publishNotification } from \"@/lib/notifications/bus\";\nimport { sseResponse } from \"@/lib/api/sse\";\nimport { resolveTurnProfile } from \"@/lib/agents/turn-profile\";\n\ntype Params = { params: Promise<{ thread_id: string }> };\n\nconst enc = new TextEncoder();\nconst sse = (obj: Record<string, unknown>) => enc.encode(`data: ${JSON.stringify(obj)}\\n\\n`);\n\n// POST is the *command* half of the run lifecycle (ADR-0008). It accepts the\n// new user message, registers a run in the in-memory registry, kicks the\n// agent loop off in a detached async task, and returns 202 immediately. The\n// caller must follow up with a GET on this same path (as an `EventSource`)\n// to subscribe to the chunk stream — see GET below.\n//\n// Splitting submit from subscribe gives us a single reliable streaming\n// primitive across all browsers (EventSource is the only WebKit-native\n// streaming API that survives iOS Safari + Tailscale HTTP/2 proxies). It\n// also collapses what was previously a WS sidecar + SSE-over-POST +\n// SSE-GET-reattach trio into one transport.\nexport async function POST(req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const { message, attachments, stream_options, hot_since } = (await req.json()) as {\n message: string;\n attachments?: ContentPart[];\n stream_options?: StreamOptions;\n // ADR-0042 — explicit context boundary the chat picked. ISO timestamp,\n // null to clear the pin, omitted to leave whatever's already persisted\n // on the thread.\n hot_since?: string | null;\n };\n\n // Per-thread FIFO queue (lib/agents/run-queue.ts). Every entry point\n // that drives an agent on a thread goes through this — HTTP POST,\n // scheduler, watcher, trigger, bridge — so concurrent fires on the same\n // thread_id serialise instead of racing the LangGraph checkpoint store.\n // If the queue is already at the soft cap, reject with 503 so the\n // caller can back off rather than pin yet more work in memory.\n const thread = getThread(thread_id);\n const pinnedModelConfigName = snapshotThreadModelConfigName(thread_id);\n let position: number;\n try {\n ({ position } = enqueueThreadRun(thread_id, \"user\", async () => {\n // startRun is called once it's our turn so the registry only ever\n // holds one active entry per thread at a time. Subscribers that\n // attach via GET before our turn comes will see no run yet and the\n // SSE handler emits a synthetic done — the client reopens the\n // EventSource and picks up the stream once we're running.\n const active = startRun(thread_id, thread?.agent_id ?? null);\n let prepared;\n try {\n prepared = await prepareThreadRun({\n thread_id,\n message,\n options: stream_options,\n attachments,\n signal: active.abort.signal,\n hot_since,\n context_profile: resolveTurnProfile(\"user\"),\n _pinned_model_config_name: pinnedModelConfigName,\n });\n } catch (err) {\n // Prep failure (unknown agent, model misconfig, …). With queueing\n // the HTTP request has already returned 202, so the error has to\n // surface as an SSE chunk to any attached subscriber. There may\n // be no subscriber if the GET hasn't connected yet — the chunk\n // is buffered on the ActiveRun for the next attach.\n const message_ = err instanceof RunThreadError ? err.message : String(err);\n const code = err instanceof RunThreadError ? err.code : \"run_prepare_error\";\n broadcast(active, { type: \"error\", data: { message: message_, code } });\n finishRun(active, \"error\");\n return;\n }\n\n // Drive the agent to completion regardless of client connection. Events\n // go to the registry; the GET subscriber (and any reattaching clients)\n // receive them via subscribe().\n //\n // CRITICAL: finishRun() MUST run no matter what — if it doesn't, the\n // run is pinned as \"running\" forever and the TTL eviction (scheduled\n // inside finishRun()) never fires, so a leaked entry never self-heals.\n // Wrap the whole body in try/finally.\n let terminal: \"done\" | \"error\" = \"error\";\n let assistantContent = \"\";\n try {\n const collected = await collectStream(prepared.stream as AsyncIterable<StreamChunk>, {\n onChunk: (chunk) => broadcast(active, chunk),\n });\n assistantContent = collected.assistantContent;\n terminal = collected.terminal;\n // If the stream threw mid-iteration, collectStream returns terminal=\"error\"\n // but no `error` chunk was broadcast — surface one to subscribers. Skip\n // when the run was deliberately aborted: llm.ts already emitted an\n // `error{code:\"aborted\"}` chunk for that path and re-broadcasting as\n // `stream_error` would mask the intent.\n if (collected.terminal === \"error\" && collected.errorMessage && !collected.aborted) {\n broadcast(active, {\n type: \"error\",\n data: { message: collected.errorMessage, code: \"stream_error\" },\n });\n }\n try {\n // On a user abort (Stop / steer), append the interrupt footer so\n // the partial reply is never silently dropped and the next agent\n // turn sees a clear marker explaining the cut. withInterruptMarker\n // returns the bare marker when the partial is empty, which forces\n // persistAssistantMessage past its skip-empty guard so the thread\n // always has a row recording what happened.\n const contentToPersist = collected.aborted\n ? withInterruptMarker(collected.assistantContent)\n : collected.assistantContent;\n persistAssistantMessage(thread_id, contentToPersist, collected.usedTools, collected.toolEvents, null, collected.usage ?? null, prepared.context_snapshot ?? null, prepared.source_manifest ?? null);\n } catch (persistErr) {\n terminal = \"error\";\n broadcast(active, {\n type: \"error\",\n data: { message: `persist failed: ${(persistErr as Error).message}`, code: \"persist_error\" },\n });\n }\n } catch (err) {\n terminal = \"error\";\n broadcast(active, {\n type: \"error\",\n data: { message: (err as Error).message ?? String(err), code: \"run_crashed\" },\n });\n } finally {\n finishRun(active, terminal);\n publishNotification({\n type: \"run_completed\",\n thread_id,\n agent_id: thread?.agent_id ?? null,\n status: terminal,\n preview: assistantContent.replace(/\\s+/g, \" \").trim().slice(0, 120),\n ts: Date.now(),\n });\n }\n }));\n } catch (err) {\n if (err instanceof QueueFullError) {\n return new Response(\n JSON.stringify({ accepted: false, code: \"queue_full\", thread_id, error: err.message }),\n { status: 503, headers: { \"Content-Type\": \"application/json\" } },\n );\n }\n throw err;\n }\n\n return new Response(\n JSON.stringify({ accepted: true, thread_id, queue_position: position }),\n { status: 202, headers: { \"Content-Type\": \"application/json\" } },\n );\n}\n\n// GET is the *query* half of the run lifecycle (ADR-0008). Attaches to an\n// active (or recently-finished, within the registry TTL) run and streams\n// chunks as Server-Sent Events. Always consumed client-side via\n// `EventSource` — never `fetch().body.getReader()`, which is unreliable on\n// iOS Safari for long-lived streaming responses.\n//\n// Emits a single synthetic `done` event and closes when there's no run to\n// attach to (run never existed, or it finished + TTL-evicted before the GET\n// arrived). We deliberately do NOT return 404 here: browsers map a 404 SSE\n// response onto `EventSource.onerror` with no terminal event, which trips\n// EventSource's auto-reconnect logic and leaves the client in a \"stream\n// open but silent\" state — UIs gating on a `done` event hang forever\n// showing the Stop/Reconnecting affordances. A 200 with `data: {\"type\":\n// \"done\"}\\n\\n` makes the iterator drain cleanly on every transport.\n//\n// `show_tools` / `show_thinking` query params let the caller suppress\n// chunk types it doesn't want to render. Defaults: both on. The full\n// `StreamOptions` shape is only meaningful on the POST (tool policy &\n// agent run config are run-wide settings, not per-subscriber filters).\nexport async function GET(req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const showTools = req.nextUrl.searchParams.get(\"show_tools\") !== \"false\";\n const showThinking = req.nextUrl.searchParams.get(\"show_thinking\") !== \"false\";\n const stream_options: StreamOptions = {\n filters: { include_tools: showTools, include_thinking: showThinking },\n };\n\n const run = getRun(thread_id);\n if (!run) {\n const stream = new ReadableStream({\n start(controller) {\n controller.enqueue(sse({ type: \"done\" }));\n controller.close();\n },\n });\n return sseResponse(stream);\n }\n\n return attachStream(thread_id, stream_options);\n}\n\n// DELETE aborts the currently-running agent for this thread. The agent stream\n// loop in llm.ts catches the resulting AbortError and emits a synthetic\n// `error` + `done` event pair so subscribers (and the client's queue-drain\n// hook) finish cleanly.\nexport async function DELETE(_req: NextRequest, { params }: Params) {\n const { thread_id } = await params;\n const aborted = abortRun(thread_id, \"user_interrupted\");\n return new Response(JSON.stringify({ aborted }), {\n status: aborted ? 200 : 404,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\nfunction attachStream(\n thread_id: string,\n stream_options?: StreamOptions,\n): Response {\n // Captured by both start() and cancel() so the cancel branch can tear\n // down the poll timer + subscription when the client disconnects.\n // Without this, navigating away from a long-running thread leaks an\n // event subscriber + 2Hz setInterval per visit until the run finishes\n // (or forever if it doesn't).\n let poll: ReturnType<typeof setInterval> | null = null;\n let unsubscribe: (() => void) | null = null;\n let clientGone = false;\n\n const stream = new ReadableStream({\n start(controller) {\n const safeEnqueue = (chunk: Uint8Array): void => {\n if (clientGone) return;\n try { controller.enqueue(chunk); } catch { clientGone = true; }\n };\n\n const onEvent = (ev: StreamChunk) => {\n if (!shouldEmitChunk(ev.type, stream_options)) return;\n safeEnqueue(sse({ type: ev.type, ...ev.data }));\n };\n\n const sub = subscribe(thread_id, onEvent);\n unsubscribe = sub.unsubscribe;\n if (!sub.run) {\n controller.close();\n return;\n }\n\n // If run already terminal, close after replay.\n if (sub.run.status !== \"running\") {\n try { controller.close(); } catch { /* */ }\n return;\n }\n\n // When the run finishes (status changes), close our response. We\n // poll lightly because the run might finish due to other subscribers'\n // signals; simpler than wiring a second listener channel.\n poll = setInterval(() => {\n const r = getRun(thread_id);\n if (!r || r.status !== \"running\") {\n if (poll) { clearInterval(poll); poll = null; }\n if (unsubscribe) { unsubscribe(); unsubscribe = null; }\n if (!clientGone) {\n try { controller.close(); } catch { /* */ }\n }\n }\n }, 500);\n poll.unref?.();\n },\n cancel() {\n // Client navigated away — agent run keeps going in registry, but\n // tear down OUR poll + subscription so we don't leak a timer +\n // subscriber per disconnect.\n clientGone = true;\n if (poll) { clearInterval(poll); poll = null; }\n if (unsubscribe) { unsubscribe(); unsubscribe = null; }\n },\n });\n\n return sseResponse(stream);\n}\n","import { AppRouteRouteModule } from \"next/dist/server/route-modules/app-route/module.compiled\";\nimport { RouteKind } from \"next/dist/server/route-kind\";\nimport { patchFetch as _patchFetch } from \"next/dist/server/lib/patch-fetch\";\nimport { addRequestMeta, getRequestMeta, setRequestMeta } from \"next/dist/server/request-meta\";\nimport { getTracer, SpanKind } from \"next/dist/server/lib/trace/tracer\";\nimport { setManifestsSingleton } from \"next/dist/server/app-render/manifests-singleton\";\nimport { normalizeAppPath } from \"next/dist/shared/lib/router/utils/app-paths\";\nimport { NodeNextRequest, NodeNextResponse } from \"next/dist/server/base-http/node\";\nimport { NextRequestAdapter, signalFromNodeResponse } from \"next/dist/server/web/spec-extension/adapters/next-request\";\nimport { BaseServerSpan } from \"next/dist/server/lib/trace/constants\";\nimport { getRevalidateReason } from \"next/dist/server/instrumentation/utils\";\nimport { sendResponse } from \"next/dist/server/send-response\";\nimport { fromNodeOutgoingHttpHeaders, toNodeOutgoingHttpHeaders } from \"next/dist/server/web/utils\";\nimport { getCacheControlHeader } from \"next/dist/server/lib/cache-control\";\nimport { INFINITE_CACHE, NEXT_CACHE_TAGS_HEADER } from \"next/dist/lib/constants\";\nimport { NoFallbackError } from \"next/dist/shared/lib/no-fallback-error.external\";\nimport { CachedRouteKind } from \"next/dist/server/response-cache\";\nimport * as userland from \"/home/runner/work/jarela/jarela/app/api/v1/threads/[thread_id]/run/route.ts\";\n// We inject the nextConfigOutput here so that we can use them in the route\n// module.\nconst nextConfigOutput = \"standalone\"\nconst routeModule = new AppRouteRouteModule({\n definition: {\n kind: RouteKind.APP_ROUTE,\n page: \"/api/v1/threads/[thread_id]/run/route\",\n pathname: \"/api/v1/threads/[thread_id]/run\",\n filename: \"route\",\n bundlePath: \"app/api/v1/threads/[thread_id]/run/route\"\n },\n distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',\n relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',\n resolvedPagePath: \"/home/runner/work/jarela/jarela/app/api/v1/threads/[thread_id]/run/route.ts\",\n nextConfigOutput,\n // The static import is used for initialization (methods, dynamic, etc.).\n userland: userland,\n // In Turbopack dev mode, also provide a getter that calls require() on every\n // request. This re-reads from devModuleCache so HMR updates are picked up,\n // and the async wrapper unwraps async-module Promises (ESM-only\n // serverExternalPackages) automatically.\n ...process.env.TURBOPACK && process.env.__NEXT_DEV_SERVER ? {\n getUserland: ()=>import(\"/home/runner/work/jarela/jarela/app/api/v1/threads/[thread_id]/run/route.ts\")\n } : {}\n});\n// Pull out the exports that we need to expose from the module. This should\n// be eliminated when we've moved the other routes to the new format. These\n// are used to hook into the route.\nconst { workAsyncStorage, workUnitAsyncStorage, serverHooks } = routeModule;\nfunction patchFetch() {\n return _patchFetch({\n workAsyncStorage,\n workUnitAsyncStorage\n });\n}\nexport { routeModule, workAsyncStorage, workUnitAsyncStorage, serverHooks, patchFetch, };\nexport async function handler(req, res, ctx) {\n if (ctx.requestMeta) {\n setRequestMeta(req, ctx.requestMeta);\n }\n if (routeModule.isDev) {\n addRequestMeta(req, 'devRequestTimingInternalsEnd', process.hrtime.bigint());\n }\n let srcPage = \"/api/v1/threads/[thread_id]/run/route\";\n // turbopack doesn't normalize `/index` in the page name\n // so we need to to process dynamic routes properly\n // TODO: fix turbopack providing differing value from webpack\n if (process.env.TURBOPACK) {\n srcPage = srcPage.replace(/\\/index$/, '') || '/';\n } else if (srcPage === '/index') {\n // we always normalize /index specifically\n srcPage = '/';\n }\n const multiZoneDraftMode = process.env.__NEXT_MULTI_ZONE_DRAFT_MODE;\n const prepareResult = await routeModule.prepare(req, res, {\n srcPage,\n multiZoneDraftMode\n });\n if (!prepareResult) {\n res.statusCode = 400;\n res.end('Bad Request');\n ctx.waitUntil == null ? void 0 : ctx.waitUntil.call(ctx, Promise.resolve());\n return null;\n }\n const { buildId, deploymentId, params, nextConfig, parsedUrl, isDraftMode, prerenderManifest, routerServerContext, isOnDemandRevalidate, revalidateOnlyGenerated, resolvedPathname, clientReferenceManifest, serverActionsManifest } = prepareResult;\n const normalizedSrcPage = normalizeAppPath(srcPage);\n let isIsr = Boolean(prerenderManifest.dynamicRoutes[normalizedSrcPage] || prerenderManifest.routes[resolvedPathname]);\n const render404 = async ()=>{\n // TODO: should route-module itself handle rendering the 404\n if (routerServerContext == null ? void 0 : routerServerContext.render404) {\n await routerServerContext.render404(req, res, parsedUrl, false);\n } else {\n res.end('This page could not be found');\n }\n return null;\n };\n if (isIsr && !isDraftMode) {\n const isPrerendered = Boolean(prerenderManifest.routes[resolvedPathname]);\n const prerenderInfo = prerenderManifest.dynamicRoutes[normalizedSrcPage];\n if (prerenderInfo) {\n if (prerenderInfo.fallback === false && !isPrerendered) {\n if (nextConfig.adapterPath) {\n return await render404();\n }\n throw new NoFallbackError();\n }\n }\n }\n let cacheKey = null;\n if (isIsr && !routeModule.isDev && !isDraftMode) {\n cacheKey = resolvedPathname;\n // ensure /index and / is normalized to one key\n cacheKey = cacheKey === '/index' ? '/' : cacheKey;\n }\n const supportsDynamicResponse = // If we're in development, we always support dynamic HTML\n routeModule.isDev === true || // If this is not SSG or does not have static paths, then it supports\n // dynamic HTML.\n !isIsr;\n // This is a revalidation request if the request is for a static\n // page and it is not being resumed from a postponed render and\n // it is not a dynamic RSC request then it is a revalidation\n // request.\n const isStaticGeneration = isIsr && !supportsDynamicResponse;\n // Before rendering (which initializes component tree modules), we have to\n // set the reference manifests to our global store so Server Action's\n // encryption util can access to them at the top level of the page module.\n if (serverActionsManifest && clientReferenceManifest) {\n setManifestsSingleton({\n page: srcPage,\n clientReferenceManifest,\n serverActionsManifest\n });\n }\n const method = req.method || 'GET';\n const tracer = getTracer();\n const activeSpan = tracer.getActiveScopeSpan();\n const isWrappedByNextServer = Boolean(routerServerContext == null ? void 0 : routerServerContext.isWrappedByNextServer);\n const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'));\n const incrementalCache = getRequestMeta(req, 'incrementalCache') || await routeModule.getIncrementalCache(req, nextConfig, prerenderManifest, isMinimalMode);\n incrementalCache == null ? void 0 : incrementalCache.resetRequestCache();\n globalThis.__incrementalCache = incrementalCache;\n const context = {\n params,\n previewProps: prerenderManifest.preview,\n renderOpts: {\n experimental: {\n authInterrupts: Boolean(nextConfig.experimental.authInterrupts)\n },\n cacheComponents: Boolean(nextConfig.cacheComponents),\n supportsDynamicResponse,\n incrementalCache,\n cacheLifeProfiles: nextConfig.cacheLife,\n waitUntil: ctx.waitUntil,\n onClose: (cb)=>{\n res.on('close', cb);\n },\n onAfterTaskError: undefined,\n onInstrumentationRequestError: (error, _request, errorContext, silenceLog)=>routeModule.onRequestError(req, error, errorContext, silenceLog, routerServerContext)\n },\n sharedContext: {\n buildId,\n deploymentId\n }\n };\n const nodeNextReq = new NodeNextRequest(req);\n const nodeNextRes = new NodeNextResponse(res);\n const nextReq = NextRequestAdapter.fromNodeNextRequest(nodeNextReq, signalFromNodeResponse(res));\n try {\n let parentSpan;\n const invokeRouteModule = async (span)=>{\n return routeModule.handle(nextReq, context).finally(()=>{\n if (!span) return;\n span.setAttributes({\n 'http.status_code': res.statusCode,\n 'next.rsc': false\n });\n const rootSpanAttributes = tracer.getRootSpanAttributes();\n // We were unable to get attributes, probably OTEL is not enabled\n if (!rootSpanAttributes) {\n return;\n }\n if (rootSpanAttributes.get('next.span_type') !== BaseServerSpan.handleRequest) {\n console.warn(`Unexpected root span type '${rootSpanAttributes.get('next.span_type')}'. Please report this Next.js issue https://github.com/vercel/next.js`);\n return;\n }\n const route = rootSpanAttributes.get('next.route');\n if (route) {\n const name = `${method} ${route}`;\n span.setAttributes({\n 'next.route': route,\n 'http.route': route,\n 'next.span_name': name\n });\n span.updateName(name);\n // Propagate http.route to the parent span if one exists (e.g.\n // a platform-created HTTP span in adapter deployments).\n if (parentSpan && parentSpan !== span) {\n parentSpan.setAttribute('http.route', route);\n parentSpan.updateName(name);\n }\n } else {\n span.updateName(`${method} ${srcPage}`);\n }\n });\n };\n const handleResponse = async (currentSpan)=>{\n var _cacheEntry_value;\n const responseGenerator = async ({ previousCacheEntry })=>{\n try {\n if (!isMinimalMode && isOnDemandRevalidate && revalidateOnlyGenerated && !previousCacheEntry) {\n res.statusCode = 404;\n // on-demand revalidate always sets this header\n res.setHeader('x-nextjs-cache', 'REVALIDATED');\n res.end('This page could not be found');\n return null;\n }\n const response = await invokeRouteModule(currentSpan);\n req.fetchMetrics = context.renderOpts.fetchMetrics;\n let pendingWaitUntil = context.renderOpts.pendingWaitUntil;\n // Attempt using provided waitUntil if available\n // if it's not we fallback to sendResponse's handling\n if (pendingWaitUntil) {\n if (ctx.waitUntil) {\n ctx.waitUntil(pendingWaitUntil);\n pendingWaitUntil = undefined;\n }\n }\n const cacheTags = context.renderOpts.collectedTags;\n // If the request is for a static response, we can cache it so long\n // as it's not edge.\n if (isIsr) {\n const blob = await response.blob();\n // Copy the headers from the response.\n const headers = toNodeOutgoingHttpHeaders(response.headers);\n if (cacheTags) {\n headers[NEXT_CACHE_TAGS_HEADER] = cacheTags;\n }\n if (!headers['content-type'] && blob.type) {\n headers['content-type'] = blob.type;\n }\n const revalidate = typeof context.renderOpts.collectedRevalidate === 'undefined' || context.renderOpts.collectedRevalidate >= INFINITE_CACHE ? false : context.renderOpts.collectedRevalidate;\n const expire = typeof context.renderOpts.collectedExpire === 'undefined' || context.renderOpts.collectedExpire >= INFINITE_CACHE ? undefined : context.renderOpts.collectedExpire;\n // Create the cache entry for the response.\n const cacheEntry = {\n value: {\n kind: CachedRouteKind.APP_ROUTE,\n status: response.status,\n body: Buffer.from(await blob.arrayBuffer()),\n headers\n },\n cacheControl: {\n revalidate,\n expire\n }\n };\n return cacheEntry;\n } else {\n // send response without caching if not ISR\n await sendResponse(nodeNextReq, nodeNextRes, response, context.renderOpts.pendingWaitUntil);\n return null;\n }\n } catch (err) {\n // if this is a background revalidate we need to report\n // the request error here as it won't be bubbled\n if (previousCacheEntry == null ? void 0 : previousCacheEntry.isStale) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: srcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n throw err;\n }\n };\n const cacheEntry = await routeModule.handleResponse({\n req,\n nextConfig,\n cacheKey,\n routeKind: RouteKind.APP_ROUTE,\n isFallback: false,\n prerenderManifest,\n isRoutePPREnabled: false,\n isOnDemandRevalidate,\n revalidateOnlyGenerated,\n responseGenerator,\n waitUntil: ctx.waitUntil,\n isMinimalMode\n });\n // we don't create a cacheEntry for ISR\n if (!isIsr) {\n return null;\n }\n if ((cacheEntry == null ? void 0 : (_cacheEntry_value = cacheEntry.value) == null ? void 0 : _cacheEntry_value.kind) !== CachedRouteKind.APP_ROUTE) {\n var _cacheEntry_value1;\n throw Object.defineProperty(new Error(`Invariant: app-route received invalid cache entry ${cacheEntry == null ? void 0 : (_cacheEntry_value1 = cacheEntry.value) == null ? void 0 : _cacheEntry_value1.kind}`), \"__NEXT_ERROR_CODE\", {\n value: \"E701\",\n enumerable: false,\n configurable: true\n });\n }\n if (!isMinimalMode) {\n res.setHeader('x-nextjs-cache', isOnDemandRevalidate ? 'REVALIDATED' : cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT');\n }\n // Draft mode should never be cached\n if (isDraftMode) {\n res.setHeader('Cache-Control', 'private, no-cache, no-store, max-age=0, must-revalidate');\n }\n const headers = fromNodeOutgoingHttpHeaders(cacheEntry.value.headers);\n if (!(isMinimalMode && isIsr)) {\n headers.delete(NEXT_CACHE_TAGS_HEADER);\n }\n // If cache control is already set on the response we don't\n // override it to allow users to customize it via next.config\n if (cacheEntry.cacheControl && !res.getHeader('Cache-Control') && !headers.get('Cache-Control')) {\n headers.set('Cache-Control', getCacheControlHeader(cacheEntry.cacheControl));\n }\n await sendResponse(nodeNextReq, nodeNextRes, // @ts-expect-error - Argument of type 'Buffer<ArrayBufferLike>' is not assignable to parameter of type 'BodyInit | null | undefined'.\n new Response(cacheEntry.value.body, {\n headers,\n status: cacheEntry.value.status || 200\n }));\n return null;\n };\n // TODO: activeSpan code path is for when wrapped by\n // next-server can be removed when this is no longer used\n if (isWrappedByNextServer && activeSpan) {\n await handleResponse(activeSpan);\n } else {\n parentSpan = tracer.getActiveScopeSpan();\n await tracer.withPropagatedContext(req.headers, ()=>tracer.trace(BaseServerSpan.handleRequest, {\n spanName: `${method} ${srcPage}`,\n kind: SpanKind.SERVER,\n attributes: {\n 'http.method': method,\n 'http.target': req.url\n }\n }, handleResponse), undefined, !isWrappedByNextServer);\n }\n } catch (err) {\n if (!(err instanceof NoFallbackError)) {\n const silenceLog = false;\n await routeModule.onRequestError(req, err, {\n routerKind: 'App Router',\n routePath: normalizedSrcPage,\n routeType: 'route',\n revalidateReason: getRevalidateReason({\n isStaticGeneration,\n isOnDemandRevalidate\n })\n }, silenceLog, routerServerContext);\n }\n // rethrow so that we can handle serving error page\n // If this is during static generation, throw the error again.\n if (isIsr) throw err;\n // Otherwise, send a 500 response.\n await sendResponse(nodeNextReq, nodeNextRes, new Response(null, {\n status: 500\n }));\n return null;\n }\n}\n\n//# sourceMappingURL=app-route.js.map\n"],"names":["sseResponse","stream","opts","disableProxyBuffering","headers","Connection","Response","prepareThreadRun","persistAssistantMessage","withInterruptMarker","RunThreadError","snapshotThreadModelConfigName","shouldEmitChunk","broadcast","finishRun","startRun","subscribe","abortRun","getRun","enqueueThreadRun","QueueFullError","collectStream","getThread","publish","publishNotification","resolveTurnProfile","enc","TextEncoder","sse","obj","encode","JSON","stringify","POST","req","params","thread_id","message","attachments","stream_options","hot_since","json","thread","pinnedModelConfigName","position","active","agent_id","prepared","options","signal","abort","context_profile","_pinned_model_config_name","err","message_","String","code","type","data","terminal","assistantContent","collected","onChunk","chunk","errorMessage","aborted","contentToPersist","usedTools","toolEvents","usage","context_snapshot","source_manifest","persistErr","status","preview","replace","trim","slice","ts","Date","now","accepted","error","queue_position","GET","showTools","nextUrl","searchParams","get","showThinking","filters","include_tools","include_thinking","run","ReadableStream","start","controller","enqueue","close","attachStream","DELETE","_req","poll","unsubscribe","clientGone","safeEnqueue","onEvent","ev","sub","setInterval","r","clearInterval","unref","cancel"],"sourceRoot":"","ignoreList":[0,4,6,10,16,24,34,36]}
|