@aglyn/plugins-ai 1.0.0-beta.227 → 1.0.0-beta.229
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +17 -17
- package/src/lib/components/ai-brief-dialog.component.js +1 -1
- package/src/lib/components/ai-brief-dialog.component.js.map +1 -1
- package/src/lib/components/ai-describe-automation.component.js +7 -2
- package/src/lib/components/ai-describe-automation.component.js.map +1 -1
- package/src/lib/components/ai-describe-button.component.js +6 -1
- package/src/lib/components/ai-describe-button.component.js.map +1 -1
- package/src/lib/components/ai-describe-page.component.d.ts +1 -1
- package/src/lib/components/ai-describe-page.component.js +1 -1
- package/src/lib/components/ai-describe-page.component.js.map +1 -1
- package/src/lib/components/ai-job-events.d.ts +7 -1
- package/src/lib/components/ai-job-events.js +4 -2
- package/src/lib/components/ai-job-events.js.map +1 -1
- package/src/lib/components/ai-job-site.d.ts +22 -0
- package/src/lib/components/ai-job-site.js +73 -0
- package/src/lib/components/ai-job-site.js.map +1 -0
- package/src/lib/components/ai-jobs-list-page.component.d.ts +23 -0
- package/src/lib/components/ai-jobs-list-page.component.js +314 -0
- package/src/lib/components/ai-jobs-list-page.component.js.map +1 -0
- package/src/lib/components/ai-jobs-page.component.d.ts +7 -0
- package/src/lib/components/ai-jobs-page.component.js +30 -0
- package/src/lib/components/ai-jobs-page.component.js.map +1 -0
- package/src/lib/components/ai-page-brief-dialog.component.d.ts +1 -1
- package/src/lib/components/ai-page-brief-dialog.component.js.map +1 -1
- package/src/lib/components/ai-site-build-page.component.d.ts +31 -3
- package/src/lib/components/ai-site-build-page.component.js +394 -243
- package/src/lib/components/ai-site-build-page.component.js.map +1 -1
- package/src/lib/components/ai-site-start-card.component.d.ts +18 -1
- package/src/lib/components/ai-site-start-card.component.js +27 -15
- package/src/lib/components/ai-site-start-card.component.js.map +1 -1
- package/src/lib/components/assist-jobs-drawer.component.d.ts +11 -0
- package/src/lib/components/assist-jobs-drawer.component.js +37 -1
- package/src/lib/components/assist-jobs-drawer.component.js.map +1 -1
- package/src/lib/components/assist-panel.component.js +9 -4
- package/src/lib/components/assist-panel.component.js.map +1 -1
- package/src/lib/jobs/ai-job-draft-ids.d.ts +6 -0
- package/src/lib/jobs/ai-job-draft-ids.js +9 -0
- package/src/lib/jobs/ai-job-draft-ids.js.map +1 -1
- package/src/lib/jobs/ai-job-drafts.d.ts +7 -0
- package/src/lib/jobs/ai-job-drafts.js +16 -7
- package/src/lib/jobs/ai-job-drafts.js.map +1 -1
- package/src/lib/jobs/ai-job-layout-site-pages.d.ts +70 -0
- package/src/lib/jobs/ai-job-layout-site-pages.js +216 -0
- package/src/lib/jobs/ai-job-layout-site-pages.js.map +1 -0
- package/src/lib/jobs/ai-job-layout-step.d.ts +2 -2
- package/src/lib/jobs/ai-job-layout-step.js +21 -2
- package/src/lib/jobs/ai-job-layout-step.js.map +1 -1
- package/src/lib/jobs/ai-job-page-sections.d.ts +6 -5
- package/src/lib/jobs/ai-job-page-sections.js +3 -3
- package/src/lib/jobs/ai-job-page-sections.js.map +1 -1
- package/src/lib/jobs/ai-job-page-step.d.ts +19 -1
- package/src/lib/jobs/ai-job-page-step.js +50 -8
- package/src/lib/jobs/ai-job-page-step.js.map +1 -1
- package/src/lib/jobs/ai-job-plan-step.js +7 -2
- package/src/lib/jobs/ai-job-plan-step.js.map +1 -1
- package/src/lib/jobs/ai-job-site-step.d.ts +21 -0
- package/src/lib/jobs/ai-job-site-step.js +103 -17
- package/src/lib/jobs/ai-job-site-step.js.map +1 -1
- package/src/lib/jobs/ai-job-text-step.d.ts +7 -1
- package/src/lib/jobs/ai-job-text-step.js.map +1 -1
- package/src/lib/jobs/ai-jobs.d.ts +19 -1
- package/src/lib/jobs/ai-jobs.js +130 -53
- package/src/lib/jobs/ai-jobs.js.map +1 -1
- package/src/lib/jobs/ai-site-publish.d.ts +98 -0
- package/src/lib/jobs/ai-site-publish.js +372 -0
- package/src/lib/jobs/ai-site-publish.js.map +1 -0
- package/src/lib/jobs/fixtures/ai-page-briefs.d.ts +7 -6
- package/src/lib/jobs/fixtures/ai-page-briefs.js +23 -56
- package/src/lib/jobs/fixtures/ai-page-briefs.js.map +1 -1
- package/src/lib/model/ai-job-failure-copy.d.ts +20 -1
- package/src/lib/model/ai-job-failure-copy.js +28 -1
- package/src/lib/model/ai-job-failure-copy.js.map +1 -1
- package/src/lib/model/ai-job-notice.d.ts +6 -1
- package/src/lib/model/ai-job-notice.js +29 -3
- package/src/lib/model/ai-job-notice.js.map +1 -1
- package/src/lib/model/ai-jobs.types.d.ts +34 -0
- package/src/lib/model/ai-jobs.types.js.map +1 -1
- package/src/lib/model/ai-plan-capabilities.d.ts +25 -10
- package/src/lib/model/ai-plan-capabilities.js +15 -2
- package/src/lib/model/ai-plan-capabilities.js.map +1 -1
- package/src/lib/model/ai-site-build-progress.d.ts +25 -1
- package/src/lib/model/ai-site-build-progress.js +129 -15
- package/src/lib/model/ai-site-build-progress.js.map +1 -1
- package/src/lib/model/ai-site-start-seo.d.ts +35 -0
- package/src/lib/model/ai-site-start-seo.js +145 -7
- package/src/lib/model/ai-site-start-seo.js.map +1 -1
- package/src/lib/model/ai-site-start.d.ts +14 -0
- package/src/lib/model/ai-site-start.js +43 -0
- package/src/lib/model/ai-site-start.js.map +1 -1
- package/src/lib/plugin.js +18 -10
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/runtime/ai-doctrine-validators.d.ts +16 -12
- package/src/lib/runtime/ai-doctrine-validators.js +19 -36
- package/src/lib/runtime/ai-doctrine-validators.js.map +1 -1
- package/src/lib/runtime/ai-doctrine.d.ts +6 -0
- package/src/lib/runtime/ai-doctrine.js +6 -2
- package/src/lib/runtime/ai-doctrine.js.map +1 -1
- package/src/lib/runtime/ai-eval-live.d.ts +1 -1
- package/src/lib/runtime/ai-eval-live.js +1 -1
- package/src/lib/runtime/ai-eval-live.js.map +1 -1
- package/src/lib/server/ai-jobs-live-sites.d.ts +26 -0
- package/src/lib/server/ai-jobs-live-sites.js +58 -0
- package/src/lib/server/ai-jobs-live-sites.js.map +1 -0
- package/src/lib/server/ai-jobs-route.js +22 -3
- package/src/lib/server/ai-jobs-route.js.map +1 -1
- package/src/lib/usage/assist-job-refund.d.ts +3 -2
- package/src/lib/usage/assist-job-refund.js +2 -1
- package/src/lib/usage/assist-job-refund.js.map +1 -1
|
@@ -31,6 +31,7 @@ import { AI_JOB_INLINE_BUDGET_MS, aiJobNextStepMinimumMs, aiJobSummary, createAi
|
|
|
31
31
|
import { releaseAssistMessage } from "../usage/assist-usage.js";
|
|
32
32
|
import { aiUsageMeter } from "../usage/ai-usage-meter.js";
|
|
33
33
|
import { aiJobsGate } from "./ai-jobs-gate.js";
|
|
34
|
+
import { withoutErasedSites } from "./ai-jobs-live-sites.js";
|
|
34
35
|
import { AI_JOB_ACTIVE_STATUSES } from "../model/ai-job-activity.js";
|
|
35
36
|
/**
|
|
36
37
|
* AI generation jobs: create and list (AGL-2904).
|
|
@@ -46,7 +47,9 @@ import { AI_JOB_ACTIVE_STATUSES } from "../model/ai-job-activity.js";
|
|
|
46
47
|
* from there.
|
|
47
48
|
*
|
|
48
49
|
* `GET` lists the org's jobs, newest first, through the read gate: the
|
|
49
|
-
* same rungs up to the lockdown verdict, no reservation.
|
|
50
|
+
* same rungs up to the lockdown verdict, no reservation. A job naming a
|
|
51
|
+
* site that no longer exists is left out, so a page can come back shorter
|
|
52
|
+
* than its `limit`.
|
|
50
53
|
*
|
|
51
54
|
* The request must NAME the org it is metered against (AGL-1934). There
|
|
52
55
|
* is no fallback to "the caller's first org".
|
|
@@ -299,14 +302,30 @@ export async function GET(request) {
|
|
|
299
302
|
// console's top-bar indicator and the Assist launcher count.
|
|
300
303
|
const active = rawStatus === 'active';
|
|
301
304
|
const limit = Number((_url_searchParams_get2 = url.searchParams.get('limit')) != null ? _url_searchParams_get2 : '');
|
|
305
|
+
// `hostId` (AGL-3596): one site's jobs, for the site's AI jobs page — a
|
|
306
|
+
// query on the field under the (hostId, createdAt) index, never a filter
|
|
307
|
+
// of a loaded window. An id that is not one is refused rather than ignored,
|
|
308
|
+
// which would answer with every site's jobs.
|
|
309
|
+
const rawHost = url.searchParams.get('hostId');
|
|
310
|
+
if (rawHost !== null && !ID_CHARS.test(rawHost)) {
|
|
311
|
+
return Response.json({
|
|
312
|
+
error: 'hostId is not a site id'
|
|
313
|
+
}, {
|
|
314
|
+
status: 400
|
|
315
|
+
});
|
|
316
|
+
}
|
|
302
317
|
const now = new Date();
|
|
303
|
-
|
|
318
|
+
// A job naming a site that has been deleted is not listed (AGL-3596), so
|
|
319
|
+
// no surface counts or shows work on a site nobody can open.
|
|
320
|
+
const jobs = await withoutErasedSites(gate.firestore, await listAiJobs(gate.firestore, gate.orgId, _extends({}, status ? {
|
|
304
321
|
status
|
|
305
322
|
} : {}, active ? {
|
|
306
323
|
statuses: AI_JOB_ACTIVE_STATUSES
|
|
324
|
+
} : {}, rawHost ? {
|
|
325
|
+
hostId: rawHost
|
|
307
326
|
} : {}, Number.isFinite(limit) && limit > 0 ? {
|
|
308
327
|
limit
|
|
309
|
-
} : {}));
|
|
328
|
+
} : {})));
|
|
310
329
|
return Response.json({
|
|
311
330
|
jobs: jobs.map((job)=>aiJobSummary(job, now)),
|
|
312
331
|
// Whether the workspace spends the Free taste (AGL-3594), so the guided
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-jobs-route.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// lockdown-423: via libs/plugins/ai/src/lib/runtime/ai-gate.ts\n// The POST climbs `aiGateLadder`, whose lockdown rung is the verdict; the\n// GET climbs `ai-jobs-gate.ts`, which carries the same rung.\n\nimport { randomUUID } from 'crypto'\nimport { resolveEffectivePlan } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n AI_JOB_KINDS,\n type AiJobKind,\n type AiJobStatus,\n} from '../model/ai-jobs.types'\n// By their own entry points rather than the barrel (AGL-2903): the specs\n// stub the barrel closed-world, and the ladder, the machine and the runtime\n// are the things under test here, not things to be stubbed away.\nimport { aiGateLadder } from '../runtime/ai-gate'\nimport { aiJobAdmissionRefusal, aiJobSiteRefusal } from '../jobs/ai-job-admission'\nimport { AI_JOB_BRIEF_MAX_CHARS } from '../jobs/ai-job-text-step'\nimport { aiJobAdmittedInputs } from '../jobs/ai-job-auto-confirm'\nimport {\n AI_JOB_INLINE_BUDGET_MS,\n aiJobNextStepMinimumMs,\n aiJobSummary,\n createAiJob,\n listAiJobs,\n runAiJobStep,\n} from '../jobs/ai-jobs'\nimport { releaseAssistMessage } from '../usage/assist-usage'\nimport { aiUsageMeter } from '../usage/ai-usage-meter'\nimport { aiJobsGate } from './ai-jobs-gate'\nimport { AI_JOB_ACTIVE_STATUSES } from '../model/ai-job-activity'\n\n/**\n * AI generation jobs: create and list (AGL-2904).\n *\n * `POST` is a door that spends, so it climbs the whole ladder (AGL-2903) —\n * `aiGenerative`, `release_ai_generative`, the `ai-generate` switch, a\n * per-uid window, and a reservation — and then creates the job and runs\n * its first step INLINE under `AI_JOB_INLINE_BUDGET_MS`. A step that\n * finishes in time answers with the job `done` (or `queued` behind its\n * next step); one that does not is aborted, its reservation handed back,\n * and the job answers `queued` for the beat to resume. Either way the\n * caller gets the job document, and the events route is how it watches\n * from there.\n *\n * `GET` lists the org's jobs, newest first, through the read gate: the\n * same rungs up to the lockdown verdict, no reservation.\n *\n * The request must NAME the org it is metered against (AGL-1934). There\n * is no fallback to \"the caller's first org\".\n */\n\nconst AI_JOBS_RATE_LIMIT = { key: 'ai-jobs', limit: 10, windowMs: 60_000 }\n\n/** Kind-specific inputs, bounded: a runner reads scalars, not a document. */\nconst MAX_INPUTS_JSON_CHARS = 8_000\n\n/** The admitted statuses for the list filter, as the union spells them. */\nconst AI_JOB_STATUSES: readonly AiJobStatus[] = [\n 'queued',\n 'running',\n 'needs_input',\n 'needs_review',\n 'done',\n 'failed',\n 'canceled',\n]\n\nexport interface CreateAiJobBody {\n orgId: string\n hostId: string | null\n kind: AiJobKind\n brief: string\n inputs: Record<string, string | number | boolean>\n /** A catalog model the creator picked (AGL-2942), or `null` for Auto. */\n model: string | null\n}\n\nconst ID_CHARS = /^[A-Za-z0-9_-]{1,100}$/\n\n/** The longest model id a body may carry; the catalog's ids are far shorter. */\nconst MAX_MODEL_CHARS = 100\n\n/** Validate + clamp the request body; a string names what is wrong. */\nexport function parseCreateAiJobBody(payload: unknown): CreateAiJobBody | string {\n const body = (payload ?? {}) as Record<string, unknown>\n const orgId = String(body.orgId ?? '').trim()\n if (!orgId) return 'Open a workspace before using this feature'\n const kind = String(body.kind ?? '')\n if (!(AI_JOB_KINDS as readonly string[]).includes(kind)) {\n return `kind must be one of ${AI_JOB_KINDS.join(', ')}`\n }\n const brief = String(body.brief ?? '').trim()\n if (!brief) return 'Write a brief for the job'\n if (brief.length > AI_JOB_BRIEF_MAX_CHARS) {\n return `Keep the brief under ${AI_JOB_BRIEF_MAX_CHARS.toLocaleString('en-US')} characters`\n }\n const rawHost = body.hostId\n const hostId =\n rawHost === undefined || rawHost === null || rawHost === ''\n ? null\n : typeof rawHost === 'string' && ID_CHARS.test(rawHost)\n ? rawHost\n : undefined\n if (hostId === undefined) return 'hostId is not a site id'\n // A theme is fields on one site's document, so a theme job that names no\n // site has nothing to propose a change to (AGL-2938).\n if (kind === 'theme' && !hostId) return 'Open a site before changing its theme'\n const rawInputs = body.inputs\n const inputs: Record<string, string | number | boolean> = {}\n if (rawInputs !== undefined && rawInputs !== null) {\n if (typeof rawInputs !== 'object' || Array.isArray(rawInputs)) {\n return 'inputs must be an object'\n }\n for (const [key, value] of Object.entries(rawInputs as Record<string, unknown>)) {\n if (\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'boolean'\n ) {\n return `inputs.${key} must be a string, number or boolean`\n }\n inputs[key] = value\n }\n if (JSON.stringify(inputs).length > MAX_INPUTS_JSON_CHARS) {\n return 'inputs are too large'\n }\n }\n const rawModel = typeof body.model === 'string' ? body.model.trim() : ''\n if (rawModel.length > MAX_MODEL_CHARS) return 'model is not a model id'\n // Validated against the plan and the allotment allowlists when each step\n // runs, not here: the allowlists are read inside the step's reservation.\n const model = rawModel && rawModel !== 'auto' ? rawModel : null\n return { orgId, hostId, kind: kind as AiJobKind, brief, inputs, model }\n}\n\nexport async function POST(request: Request): Promise<Response> {\n let payload: unknown\n try {\n payload = await request.json()\n } catch {\n payload = null\n }\n const parsed = parseCreateAiJobBody(payload)\n // The org is parsed BEFORE the ladder so a request that named none is\n // refused with the ladder's 400 rather than a shape error; every other\n // shape fault waits until the caller has proven who they are.\n const orgId = typeof parsed === 'string' ? String((payload as Record<string, unknown> | null)?.orgId ?? '') : parsed.orgId\n // The site rides along for the same reason: a collaborator's `ai.generate`\n // is decided per site (AGL-2927), so the ladder needs it before it can say\n // whether this member may generate here at all.\n const hostId = typeof parsed === 'string' ? null : parsed.hostId\n const gate = await aiGateLadder(\n { request, orgId, hostId },\n {\n feature: 'aiGenerative',\n releaseFlag: 'release_ai_generative',\n lockdownFeature: 'ai-generate',\n permission: 'ai.generate',\n rateLimit: AI_JOBS_RATE_LIMIT,\n },\n )\n if (gate instanceof Response) return gate\n if (typeof parsed === 'string') {\n // Admitted, reserved, and then found to have sent nothing runnable: the\n // reservation goes back, because no token was spent.\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n return Response.json({ error: parsed }, { status: 400 })\n }\n // What only this kind can say about the request (AGL-2909): a site it\n // needs, inputs it reads, an allowance its draft counts against. Asked\n // before the job exists, so a refusal spends nothing.\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>>\n try {\n // A site that switched AI off first (AGL-3028), then the kind's own check.\n refusal =\n (await aiJobSiteRefusal({\n firestore: gate.firestore,\n org: gate.org,\n hostId: parsed.hostId,\n })) ??\n (await aiJobAdmissionRefusal(parsed.kind, {\n firestore: gate.firestore,\n orgId: gate.orgId,\n hostId: parsed.hostId,\n inputs: parsed.inputs,\n org: gate.org,\n uid: gate.uid,\n }))\n } catch (error) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n console.error('ai job admission failed', { orgId: gate.orgId, kind: parsed.kind, error })\n return Response.json({ error: 'The AI job could not be created' }, { status: 500 })\n }\n if (refusal) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n return Response.json({ error: refusal.error }, { status: refusal.status })\n }\n\n const now = new Date()\n let created: Awaited<ReturnType<typeof createAiJob>>\n try {\n // The guided start's own plan confirmation (AGL-3594), kept only for a\n // site job on a site that has published nothing of the owner's yet.\n const inputs = await aiJobAdmittedInputs(gate.firestore, {\n kind: parsed.kind,\n hostId: parsed.hostId,\n inputs: parsed.inputs,\n })\n created = await createAiJob(\n gate.firestore,\n {\n orgId: gate.orgId,\n hostId: parsed.hostId,\n kind: parsed.kind,\n brief: parsed.brief,\n inputs,\n model: parsed.model,\n createdBy: gate.uid,\n createdByEmail: gate.decoded.email ?? null,\n },\n now,\n )\n } catch (error) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n console.error('ai job create failed', { orgId: gate.orgId, error })\n return Response.json({ error: 'The AI job could not be created' }, { status: 500 })\n }\n const jobId = created.$id\n\n // A first step that needs more time than this request has (AGL-2907) is left\n // queued for the beat, which starts it with a budget of its own: a provider\n // call this request's timeout cut off would be billed upstream and metered\n // nowhere. Nothing ran, so the reservation goes back.\n if (aiJobNextStepMinimumMs(created) > AI_JOB_INLINE_BUDGET_MS) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n return Response.json(\n {\n job: aiJobSummary(created, now),\n meter: aiUsageMeter(gate.reservation, { lastCredits: null }),\n },\n { status: 200 },\n )\n }\n\n // The first step, inline, on the reservation the ladder already holds.\n // The runner hands that reservation back itself if the provider is never\n // reached, and re-queues the step when the budget ends first.\n const run = await runAiJobStep(gate.firestore, gate.orgId, jobId, {\n owner: `route:${randomUUID()}`,\n now,\n reservation: gate.reservation,\n org: gate.org,\n signal: AbortSignal.timeout(AI_JOB_INLINE_BUDGET_MS),\n // The caller is on the request, so what the inline step produces is\n // attributed with their address; the beat's steps carry the uid alone.\n actor: { uid: gate.uid, email: gate.decoded.email ?? null },\n // The workspace's AI pause lets staff through, as the ladder above did.\n staff: gate.staff,\n })\n if (run.outcome === 'not-claimable') {\n // A job created a moment ago has a claimable first step; anything else\n // is a fault in the machine, and the reservation must not be stranded.\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n console.error('ai job first step not claimable', { orgId: gate.orgId, jobId })\n return Response.json({ error: 'The AI job could not be started' }, { status: 500 })\n }\n return Response.json(\n {\n job: aiJobSummary(run.job),\n // The usage strip's envelope (AGL-2942): the reservation the ladder\n // took, with what the inline step spent.\n meter: aiUsageMeter(gate.reservation, {\n lastCredits: run.job.creditsSpent > 0 ? run.job.creditsSpent : null,\n }),\n },\n { status: 200 },\n )\n}\n\nexport async function GET(request: Request): Promise<Response> {\n const url = new URL(request.url)\n const gate = await aiJobsGate(request, url.searchParams.get('orgId') ?? '')\n if (gate instanceof Response) return gate\n const rawStatus = url.searchParams.get('status') ?? ''\n const status = (AI_JOB_STATUSES as readonly string[]).includes(rawStatus)\n ? (rawStatus as AiJobStatus)\n : undefined\n // `active` (AGL-3593): every job not yet settled, which is what the\n // console's top-bar indicator and the Assist launcher count.\n const active = rawStatus === 'active'\n const limit = Number(url.searchParams.get('limit') ?? '')\n const now = new Date()\n const jobs = await listAiJobs(gate.firestore, gate.orgId, {\n ...(status ? { status } : {}),\n ...(active ? { statuses: AI_JOB_ACTIVE_STATUSES } : {}),\n ...(Number.isFinite(limit) && limit > 0 ? { limit } : {}),\n })\n return Response.json(\n {\n jobs: jobs.map((job) => aiJobSummary(job, now)),\n // Whether the workspace spends the Free taste (AGL-3594), so the guided\n // start offers the Free page band from the request it already makes.\n freeTaste: resolveEffectivePlan(gate.org as never) === 'free',\n },\n { status: 200, headers: { 'Cache-Control': 'no-store' } },\n )\n}\n\nexport const dynamic = 'force-dynamic'\nexport const maxDuration = 60\n"],"names":["randomUUID","resolveEffectivePlan","AI_JOB_KINDS","aiGateLadder","aiJobAdmissionRefusal","aiJobSiteRefusal","AI_JOB_BRIEF_MAX_CHARS","aiJobAdmittedInputs","AI_JOB_INLINE_BUDGET_MS","aiJobNextStepMinimumMs","aiJobSummary","createAiJob","listAiJobs","runAiJobStep","releaseAssistMessage","aiUsageMeter","aiJobsGate","AI_JOB_ACTIVE_STATUSES","AI_JOBS_RATE_LIMIT","key","limit","windowMs","MAX_INPUTS_JSON_CHARS","AI_JOB_STATUSES","ID_CHARS","MAX_MODEL_CHARS","parseCreateAiJobBody","payload","body","orgId","String","trim","kind","includes","join","brief","length","toLocaleString","rawHost","hostId","undefined","test","rawInputs","inputs","Array","isArray","value","Object","entries","JSON","stringify","rawModel","model","POST","request","gate","json","parsed","feature","releaseFlag","lockdownFeature","permission","rateLimit","Response","firestore","reservation","catch","error","status","refusal","org","uid","console","now","Date","created","createdBy","createdByEmail","decoded","email","jobId","$id","job","meter","lastCredits","run","owner","signal","AbortSignal","timeout","actor","staff","outcome","creditsSpent","GET","url","URL","searchParams","get","rawStatus","active","Number","jobs","statuses","isFinite","map","freeTaste","headers","dynamic","maxDuration"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,+DAA+D;AAC/D,0EAA0E;AAC1E,6DAA6D;AAE7D,SAASA,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E,aACpDuC,SAAS;QAAEA;IAAO,IAAI,CAAC,GACvBgC,SAAS;QAAEG,UAAUtF;IAAuB,IAAI,CAAC,GACjDoF,OAAOG,QAAQ,CAACpF,UAAUA,QAAQ,IAAI;QAAEA;IAAM,IAAI,CAAC;IAEzD,OAAO2C,SAASP,IAAI,CAClB;QACE8C,MAAMA,KAAKG,GAAG,CAAC,CAACvB,MAAQxE,aAAawE,KAAKT;QAC1C,wEAAwE;QACxE,qEAAqE;QACrEiC,WAAWzG,qBAAqBsD,KAAKe,GAAG,MAAe;IACzD,GACA;QAAEF,QAAQ;QAAKuC,SAAS;YAAE,iBAAiB;QAAW;IAAE;AAE5D;AAEA,OAAO,MAAMC,UAAU,gBAAe;AACtC,OAAO,MAAMC,cAAc,GAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/server/ai-jobs-route.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// lockdown-423: via libs/plugins/ai/src/lib/runtime/ai-gate.ts\n// The POST climbs `aiGateLadder`, whose lockdown rung is the verdict; the\n// GET climbs `ai-jobs-gate.ts`, which carries the same rung.\n\nimport { randomUUID } from 'crypto'\nimport { resolveEffectivePlan } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport {\n AI_JOB_KINDS,\n type AiJobKind,\n type AiJobStatus,\n} from '../model/ai-jobs.types'\n// By their own entry points rather than the barrel (AGL-2903): the specs\n// stub the barrel closed-world, and the ladder, the machine and the runtime\n// are the things under test here, not things to be stubbed away.\nimport { aiGateLadder } from '../runtime/ai-gate'\nimport { aiJobAdmissionRefusal, aiJobSiteRefusal } from '../jobs/ai-job-admission'\nimport { AI_JOB_BRIEF_MAX_CHARS } from '../jobs/ai-job-text-step'\nimport { aiJobAdmittedInputs } from '../jobs/ai-job-auto-confirm'\nimport {\n AI_JOB_INLINE_BUDGET_MS,\n aiJobNextStepMinimumMs,\n aiJobSummary,\n createAiJob,\n listAiJobs,\n runAiJobStep,\n} from '../jobs/ai-jobs'\nimport { releaseAssistMessage } from '../usage/assist-usage'\nimport { aiUsageMeter } from '../usage/ai-usage-meter'\nimport { aiJobsGate } from './ai-jobs-gate'\nimport { withoutErasedSites } from './ai-jobs-live-sites'\nimport { AI_JOB_ACTIVE_STATUSES } from '../model/ai-job-activity'\n\n/**\n * AI generation jobs: create and list (AGL-2904).\n *\n * `POST` is a door that spends, so it climbs the whole ladder (AGL-2903) —\n * `aiGenerative`, `release_ai_generative`, the `ai-generate` switch, a\n * per-uid window, and a reservation — and then creates the job and runs\n * its first step INLINE under `AI_JOB_INLINE_BUDGET_MS`. A step that\n * finishes in time answers with the job `done` (or `queued` behind its\n * next step); one that does not is aborted, its reservation handed back,\n * and the job answers `queued` for the beat to resume. Either way the\n * caller gets the job document, and the events route is how it watches\n * from there.\n *\n * `GET` lists the org's jobs, newest first, through the read gate: the\n * same rungs up to the lockdown verdict, no reservation. A job naming a\n * site that no longer exists is left out, so a page can come back shorter\n * than its `limit`.\n *\n * The request must NAME the org it is metered against (AGL-1934). There\n * is no fallback to \"the caller's first org\".\n */\n\nconst AI_JOBS_RATE_LIMIT = { key: 'ai-jobs', limit: 10, windowMs: 60_000 }\n\n/** Kind-specific inputs, bounded: a runner reads scalars, not a document. */\nconst MAX_INPUTS_JSON_CHARS = 8_000\n\n/** The admitted statuses for the list filter, as the union spells them. */\nconst AI_JOB_STATUSES: readonly AiJobStatus[] = [\n 'queued',\n 'running',\n 'needs_input',\n 'needs_review',\n 'done',\n 'failed',\n 'canceled',\n]\n\nexport interface CreateAiJobBody {\n orgId: string\n hostId: string | null\n kind: AiJobKind\n brief: string\n inputs: Record<string, string | number | boolean>\n /** A catalog model the creator picked (AGL-2942), or `null` for Auto. */\n model: string | null\n}\n\nconst ID_CHARS = /^[A-Za-z0-9_-]{1,100}$/\n\n/** The longest model id a body may carry; the catalog's ids are far shorter. */\nconst MAX_MODEL_CHARS = 100\n\n/** Validate + clamp the request body; a string names what is wrong. */\nexport function parseCreateAiJobBody(payload: unknown): CreateAiJobBody | string {\n const body = (payload ?? {}) as Record<string, unknown>\n const orgId = String(body.orgId ?? '').trim()\n if (!orgId) return 'Open a workspace before using this feature'\n const kind = String(body.kind ?? '')\n if (!(AI_JOB_KINDS as readonly string[]).includes(kind)) {\n return `kind must be one of ${AI_JOB_KINDS.join(', ')}`\n }\n const brief = String(body.brief ?? '').trim()\n if (!brief) return 'Write a brief for the job'\n if (brief.length > AI_JOB_BRIEF_MAX_CHARS) {\n return `Keep the brief under ${AI_JOB_BRIEF_MAX_CHARS.toLocaleString('en-US')} characters`\n }\n const rawHost = body.hostId\n const hostId =\n rawHost === undefined || rawHost === null || rawHost === ''\n ? null\n : typeof rawHost === 'string' && ID_CHARS.test(rawHost)\n ? rawHost\n : undefined\n if (hostId === undefined) return 'hostId is not a site id'\n // A theme is fields on one site's document, so a theme job that names no\n // site has nothing to propose a change to (AGL-2938).\n if (kind === 'theme' && !hostId) return 'Open a site before changing its theme'\n const rawInputs = body.inputs\n const inputs: Record<string, string | number | boolean> = {}\n if (rawInputs !== undefined && rawInputs !== null) {\n if (typeof rawInputs !== 'object' || Array.isArray(rawInputs)) {\n return 'inputs must be an object'\n }\n for (const [key, value] of Object.entries(rawInputs as Record<string, unknown>)) {\n if (\n typeof value !== 'string' &&\n typeof value !== 'number' &&\n typeof value !== 'boolean'\n ) {\n return `inputs.${key} must be a string, number or boolean`\n }\n inputs[key] = value\n }\n if (JSON.stringify(inputs).length > MAX_INPUTS_JSON_CHARS) {\n return 'inputs are too large'\n }\n }\n const rawModel = typeof body.model === 'string' ? body.model.trim() : ''\n if (rawModel.length > MAX_MODEL_CHARS) return 'model is not a model id'\n // Validated against the plan and the allotment allowlists when each step\n // runs, not here: the allowlists are read inside the step's reservation.\n const model = rawModel && rawModel !== 'auto' ? rawModel : null\n return { orgId, hostId, kind: kind as AiJobKind, brief, inputs, model }\n}\n\nexport async function POST(request: Request): Promise<Response> {\n let payload: unknown\n try {\n payload = await request.json()\n } catch {\n payload = null\n }\n const parsed = parseCreateAiJobBody(payload)\n // The org is parsed BEFORE the ladder so a request that named none is\n // refused with the ladder's 400 rather than a shape error; every other\n // shape fault waits until the caller has proven who they are.\n const orgId = typeof parsed === 'string' ? String((payload as Record<string, unknown> | null)?.orgId ?? '') : parsed.orgId\n // The site rides along for the same reason: a collaborator's `ai.generate`\n // is decided per site (AGL-2927), so the ladder needs it before it can say\n // whether this member may generate here at all.\n const hostId = typeof parsed === 'string' ? null : parsed.hostId\n const gate = await aiGateLadder(\n { request, orgId, hostId },\n {\n feature: 'aiGenerative',\n releaseFlag: 'release_ai_generative',\n lockdownFeature: 'ai-generate',\n permission: 'ai.generate',\n rateLimit: AI_JOBS_RATE_LIMIT,\n },\n )\n if (gate instanceof Response) return gate\n if (typeof parsed === 'string') {\n // Admitted, reserved, and then found to have sent nothing runnable: the\n // reservation goes back, because no token was spent.\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n return Response.json({ error: parsed }, { status: 400 })\n }\n // What only this kind can say about the request (AGL-2909): a site it\n // needs, inputs it reads, an allowance its draft counts against. Asked\n // before the job exists, so a refusal spends nothing.\n let refusal: Awaited<ReturnType<typeof aiJobAdmissionRefusal>>\n try {\n // A site that switched AI off first (AGL-3028), then the kind's own check.\n refusal =\n (await aiJobSiteRefusal({\n firestore: gate.firestore,\n org: gate.org,\n hostId: parsed.hostId,\n })) ??\n (await aiJobAdmissionRefusal(parsed.kind, {\n firestore: gate.firestore,\n orgId: gate.orgId,\n hostId: parsed.hostId,\n inputs: parsed.inputs,\n org: gate.org,\n uid: gate.uid,\n }))\n } catch (error) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n console.error('ai job admission failed', { orgId: gate.orgId, kind: parsed.kind, error })\n return Response.json({ error: 'The AI job could not be created' }, { status: 500 })\n }\n if (refusal) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n return Response.json({ error: refusal.error }, { status: refusal.status })\n }\n\n const now = new Date()\n let created: Awaited<ReturnType<typeof createAiJob>>\n try {\n // The guided start's own plan confirmation (AGL-3594), kept only for a\n // site job on a site that has published nothing of the owner's yet.\n const inputs = await aiJobAdmittedInputs(gate.firestore, {\n kind: parsed.kind,\n hostId: parsed.hostId,\n inputs: parsed.inputs,\n })\n created = await createAiJob(\n gate.firestore,\n {\n orgId: gate.orgId,\n hostId: parsed.hostId,\n kind: parsed.kind,\n brief: parsed.brief,\n inputs,\n model: parsed.model,\n createdBy: gate.uid,\n createdByEmail: gate.decoded.email ?? null,\n },\n now,\n )\n } catch (error) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n console.error('ai job create failed', { orgId: gate.orgId, error })\n return Response.json({ error: 'The AI job could not be created' }, { status: 500 })\n }\n const jobId = created.$id\n\n // A first step that needs more time than this request has (AGL-2907) is left\n // queued for the beat, which starts it with a budget of its own: a provider\n // call this request's timeout cut off would be billed upstream and metered\n // nowhere. Nothing ran, so the reservation goes back.\n if (aiJobNextStepMinimumMs(created) > AI_JOB_INLINE_BUDGET_MS) {\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n return Response.json(\n {\n job: aiJobSummary(created, now),\n meter: aiUsageMeter(gate.reservation, { lastCredits: null }),\n },\n { status: 200 },\n )\n }\n\n // The first step, inline, on the reservation the ladder already holds.\n // The runner hands that reservation back itself if the provider is never\n // reached, and re-queues the step when the budget ends first.\n const run = await runAiJobStep(gate.firestore, gate.orgId, jobId, {\n owner: `route:${randomUUID()}`,\n now,\n reservation: gate.reservation,\n org: gate.org,\n signal: AbortSignal.timeout(AI_JOB_INLINE_BUDGET_MS),\n // The caller is on the request, so what the inline step produces is\n // attributed with their address; the beat's steps carry the uid alone.\n actor: { uid: gate.uid, email: gate.decoded.email ?? null },\n // The workspace's AI pause lets staff through, as the ladder above did.\n staff: gate.staff,\n })\n if (run.outcome === 'not-claimable') {\n // A job created a moment ago has a claimable first step; anything else\n // is a fault in the machine, and the reservation must not be stranded.\n await releaseAssistMessage(gate.firestore, gate.orgId, gate.reservation).catch(\n () => undefined,\n )\n console.error('ai job first step not claimable', { orgId: gate.orgId, jobId })\n return Response.json({ error: 'The AI job could not be started' }, { status: 500 })\n }\n return Response.json(\n {\n job: aiJobSummary(run.job),\n // The usage strip's envelope (AGL-2942): the reservation the ladder\n // took, with what the inline step spent.\n meter: aiUsageMeter(gate.reservation, {\n lastCredits: run.job.creditsSpent > 0 ? run.job.creditsSpent : null,\n }),\n },\n { status: 200 },\n )\n}\n\nexport async function GET(request: Request): Promise<Response> {\n const url = new URL(request.url)\n const gate = await aiJobsGate(request, url.searchParams.get('orgId') ?? '')\n if (gate instanceof Response) return gate\n const rawStatus = url.searchParams.get('status') ?? ''\n const status = (AI_JOB_STATUSES as readonly string[]).includes(rawStatus)\n ? (rawStatus as AiJobStatus)\n : undefined\n // `active` (AGL-3593): every job not yet settled, which is what the\n // console's top-bar indicator and the Assist launcher count.\n const active = rawStatus === 'active'\n const limit = Number(url.searchParams.get('limit') ?? '')\n // `hostId` (AGL-3596): one site's jobs, for the site's AI jobs page — a\n // query on the field under the (hostId, createdAt) index, never a filter\n // of a loaded window. An id that is not one is refused rather than ignored,\n // which would answer with every site's jobs.\n const rawHost = url.searchParams.get('hostId')\n if (rawHost !== null && !ID_CHARS.test(rawHost)) {\n return Response.json({ error: 'hostId is not a site id' }, { status: 400 })\n }\n const now = new Date()\n // A job naming a site that has been deleted is not listed (AGL-3596), so\n // no surface counts or shows work on a site nobody can open.\n const jobs = await withoutErasedSites(\n gate.firestore,\n await listAiJobs(gate.firestore, gate.orgId, {\n ...(status ? { status } : {}),\n ...(active ? { statuses: AI_JOB_ACTIVE_STATUSES } : {}),\n ...(rawHost ? { hostId: rawHost } : {}),\n ...(Number.isFinite(limit) && limit > 0 ? { limit } : {}),\n }),\n )\n return Response.json(\n {\n jobs: jobs.map((job) => aiJobSummary(job, now)),\n // Whether the workspace spends the Free taste (AGL-3594), so the guided\n // start offers the Free page band from the request it already makes.\n freeTaste: resolveEffectivePlan(gate.org as never) === 'free',\n },\n { status: 200, headers: { 'Cache-Control': 'no-store' } },\n )\n}\n\nexport const dynamic = 'force-dynamic'\nexport const maxDuration = 60\n"],"names":["randomUUID","resolveEffectivePlan","AI_JOB_KINDS","aiGateLadder","aiJobAdmissionRefusal","aiJobSiteRefusal","AI_JOB_BRIEF_MAX_CHARS","aiJobAdmittedInputs","AI_JOB_INLINE_BUDGET_MS","aiJobNextStepMinimumMs","aiJobSummary","createAiJob","listAiJobs","runAiJobStep","releaseAssistMessage","aiUsageMeter","aiJobsGate","withoutErasedSites","AI_JOB_ACTIVE_STATUSES","AI_JOBS_RATE_LIMIT","key","limit","windowMs","MAX_INPUTS_JSON_CHARS","AI_JOB_STATUSES","ID_CHARS","MAX_MODEL_CHARS","parseCreateAiJobBody","payload","body","orgId","String","trim","kind","includes","join","brief","length","toLocaleString","rawHost","hostId","undefined","test","rawInputs","inputs","Array","isArray","value","Object","entries","JSON","stringify","rawModel","model","POST","request","gate","json","parsed","feature","releaseFlag","lockdownFeature","permission","rateLimit","Response","firestore","reservation","catch","error","status","refusal","org","uid","console","now","Date","created","createdBy","createdByEmail","decoded","email","jobId","$id","job","meter","lastCredits","run","owner","signal","AbortSignal","timeout","actor","staff","outcome","creditsSpent","GET","url","URL","searchParams","get","rawStatus","active","Number","jobs","statuses","isFinite","map","freeTaste","headers","dynamic","maxDuration"],"mappings":";AAAA;;;;;;;;;;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ArBH,yBAAiC;IACtD,wEAAwE;IACxE,yEAAyE;IACzE,4EAA4E;IAC5E,6CAA6C;IAC7C,MAAMzD,UAAUyD,IAAIE,YAAY,CAACC,GAAG,CAAC;IACrC,IAAI5D,YAAY,QAAQ,CAACd,SAASiB,IAAI,CAACH,UAAU;QAC/C,OAAOyB,SAASP,IAAI,CAAC;YAAEW,OAAO;QAA0B,GAAG;YAAEC,QAAQ;QAAI;IAC3E;IACA,MAAMK,MAAM,IAAIC;IAChB,yEAAyE;IACzE,6DAA6D;IAC7D,MAAM4B,OAAO,MAAMtF,mBACjBuC,KAAKS,SAAS,EACd,MAAMrD,WAAW4C,KAAKS,SAAS,EAAET,KAAK1B,KAAK,EAAE,aACvCuC,SAAS;QAAEA;IAAO,IAAI,CAAC,GACvBgC,SAAS;QAAEG,UAAUtF;IAAuB,IAAI,CAAC,GACjDqB,UAAU;QAAEC,QAAQD;IAAQ,IAAI,CAAC,GACjC+D,OAAOG,QAAQ,CAACpF,UAAUA,QAAQ,IAAI;QAAEA;IAAM,IAAI,CAAC;IAG3D,OAAO2C,SAASP,IAAI,CAClB;QACE8C,MAAMA,KAAKG,GAAG,CAAC,CAACvB,MAAQzE,aAAayE,KAAKT;QAC1C,wEAAwE;QACxE,qEAAqE;QACrEiC,WAAW1G,qBAAqBuD,KAAKe,GAAG,MAAe;IACzD,GACA;QAAEF,QAAQ;QAAKuC,SAAS;YAAE,iBAAiB;QAAW;IAAE;AAE5D;AAEA,OAAO,MAAMC,UAAU,gBAAe;AACtC,OAAO,MAAMC,cAAc,GAAE"}
|
|
@@ -20,7 +20,8 @@ import type { FreeAssistAccount } from './assist-free-taste';
|
|
|
20
20
|
* A job that failed on our side gives back what it spent (AGL-3594).
|
|
21
21
|
*
|
|
22
22
|
* "On our side" is the machine's to say, and it says it for: a plan the plan
|
|
23
|
-
* rules still refused after their re-ask, a
|
|
23
|
+
* rules still refused after their re-ask, a building step whose answer still
|
|
24
|
+
* broke a building rule after its re-ask (AGL-3596), a provider or model error, a step
|
|
24
25
|
* the machine gave up on after its attempts (a timeout or a lease that kept
|
|
25
26
|
* expiring), a step that failed of its own accord, and a step no runner could
|
|
26
27
|
* take. Never for a person canceling — they pay for what ran until they did —
|
|
@@ -53,7 +54,7 @@ export declare const AI_JOB_REFUND_SOURCE = "job-refund";
|
|
|
53
54
|
/** Who gives it back: the platform, not a member of staff. */
|
|
54
55
|
export declare const AI_JOB_REFUND_ACTOR = "system:job-refund";
|
|
55
56
|
/** Why a job's credits went back, as the job records it. */
|
|
56
|
-
export type AiJobRefundReason = 'plan-refused' | 'provider' | 'timeout' | 'step-failure' | 'unavailable';
|
|
57
|
+
export type AiJobRefundReason = 'plan-refused' | 'doctrine-refused' | 'provider' | 'timeout' | 'step-failure' | 'unavailable';
|
|
57
58
|
/**
|
|
58
59
|
* The give-back's key. Per job and per give-back on it (`ordinal`, the job's
|
|
59
60
|
* count of give-backs so far), so one failure gives back once however often
|
|
@@ -19,7 +19,8 @@ import { accountCreditMeter, returnAssistCredits, workspaceCreditMeter } from ".
|
|
|
19
19
|
* A job that failed on our side gives back what it spent (AGL-3594).
|
|
20
20
|
*
|
|
21
21
|
* "On our side" is the machine's to say, and it says it for: a plan the plan
|
|
22
|
-
* rules still refused after their re-ask, a
|
|
22
|
+
* rules still refused after their re-ask, a building step whose answer still
|
|
23
|
+
* broke a building rule after its re-ask (AGL-3596), a provider or model error, a step
|
|
23
24
|
* the machine gave up on after its attempts (a timeout or a lease that kept
|
|
24
25
|
* expiring), a step that failed of its own accord, and a step no runner could
|
|
25
26
|
* take. Never for a person canceling — they pay for what ran until they did —
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/usage/assist-job-refund.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ASSIST_CREDIT_RETURNS_FIELD } from './assist-credit-returns'\nimport {\n accountCreditMeter,\n returnAssistCredits,\n workspaceCreditMeter,\n type AssistCreditReturnOutcome,\n} from './assist-credit-returns-write'\nimport type { FreeAssistAccount } from './assist-free-taste'\n\n/**\n * A job that failed on our side gives back what it spent (AGL-3594).\n *\n * \"On our side\" is the machine's to say, and it says it for: a plan the plan\n * rules still refused after their re-ask, a provider or model error, a step\n * the machine gave up on after its attempts (a timeout or a lease that kept\n * expiring), a step that failed of its own accord, and a step no runner could\n * take. Never for a person canceling — they pay for what ran until they did —\n * nor for a model declining the brief, which the Free taste already meters as\n * a refusal and the refusal pause bounds.\n *\n * WHAT IS GIVEN BACK. A job that delivered nothing gives back everything it\n * spent and has not already given back. A job that delivered drafts and then\n * failed keeps them and pays for them: only the failing step's own spend goes\n * back. The site's listing proposal is not a delivery — it is derived from the\n * answers, costs nothing, and rides out with the first unit.\n *\n * HOW. Through the one give-back writer (`returnAssistCredits`, AGL-3595), to\n * the workspace's band and, on the Free taste, the owner's allowance — the\n * meters the spend was charged to — recorded as `system:job-refund`. The\n * tokens stay on the bill and the signal; the give-back nets them out of what\n * every reader calls \"used\".\n *\n * BOUNDED. The writer never returns more than a meter's month used. On top\n * of it, at most `AI_JOB_REFUNDS_PER_DAY` automatic give-backs an account a\n * UTC day (the workspace's own month where it names no owner), counted off\n * the give-backs the month already records, so a brief that keeps failing\n * cannot keep spending for free. Past it, the failure is metered as it always\n * was.\n */\n\n/** Automatic give-backs an account may have a UTC day. */\nexport const AI_JOB_REFUNDS_PER_DAY = 3\n\n/** The `source` a job's give-back is recorded under. */\nexport const AI_JOB_REFUND_SOURCE = 'job-refund'\n\n/** Who gives it back: the platform, not a member of staff. */\nexport const AI_JOB_REFUND_ACTOR = `system:${AI_JOB_REFUND_SOURCE}`\n\n/** Why a job's credits went back, as the job records it. */\nexport type AiJobRefundReason =\n | 'plan-refused'\n | 'provider'\n | 'timeout'\n | 'step-failure'\n | 'unavailable'\n\n/**\n * The give-back's key. Per job and per give-back on it (`ordinal`, the job's\n * count of give-backs so far), so one failure gives back once however often\n * it is handled, and a later failure of the same job — a plan tried again and\n * refused again — is a give-back of its own. The day leads, so a day's\n * give-backs are counted off the month's keys. The writer holds a key to\n * `[A-Za-z0-9_-]{8,100}`; the job id is cut to fit.\n */\nexport function aiJobRefundKey(input: { day: string; jobId: string; ordinal: number }): string {\n const job = input.jobId.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 48)\n return `${AI_JOB_REFUND_SOURCE}-${input.day.replace(/-/g, '')}-${job}-${Math.max(0, Math.floor(input.ordinal))}`\n}\n\n/** How many give-backs a meter's month already records for `day`. */\nexport function aiJobRefundsOn(returns: unknown, day: string): number {\n if (!returns || typeof returns !== 'object') return 0\n const prefix = `${AI_JOB_REFUND_SOURCE}-${day.replace(/-/g, '')}-`\n return Object.keys(returns).filter((key) => key.startsWith(prefix)).length\n}\n\n/**\n * What a failure gives back: everything the job spent and has not already\n * given back when it delivered nothing, else the failing step's own spend.\n */\nexport function aiJobRefundCredits(input: {\n delivered: boolean\n jobCredits: number\n stepCredits: number\n alreadyRefunded: number\n}): number {\n const step = Math.max(0, Math.floor(input.stepCredits))\n if (input.delivered) return step\n return Math.max(0, Math.floor(input.jobCredits) - Math.max(0, Math.floor(input.alreadyRefunded)))\n}\n\nexport type AiJobRefundOutcome = AssistCreditReturnOutcome | { status: 'bounded'; lines: [] }\n\n/**\n * Give a failed job's credits back to the meters it was charged to, or say\n * why not.\n */\nexport async function refundJobCredits(\n firestore: FirebaseFirestore.Firestore,\n input: {\n orgId: string\n /** The Free taste's attribution, or `null` on a paid workspace. */\n free: FreeAssistAccount | null\n jobId: string\n ordinal: number\n credits: number\n month: string\n day: string\n reason: AiJobRefundReason\n },\n): Promise<AiJobRefundOutcome> {\n const workspace = workspaceCreditMeter(firestore, input.orgId, input.month)\n const account = input.free?.accountUid\n ? accountCreditMeter(firestore, input.free.accountUid, input.month)\n : null\n const counter = await (account ?? workspace).ref.get()\n if (aiJobRefundsOn(counter.get(ASSIST_CREDIT_RETURNS_FIELD), input.day) >= AI_JOB_REFUNDS_PER_DAY) {\n return { status: 'bounded', lines: [] }\n }\n return returnAssistCredits(firestore, {\n month: input.month,\n meters: account ? [workspace, account] : [workspace],\n credits: input.credits,\n key: aiJobRefundKey({ day: input.day, jobId: input.jobId, ordinal: input.ordinal }),\n reason: `An AI job failed on our side (${input.reason})`,\n actorUid: AI_JOB_REFUND_ACTOR,\n source: AI_JOB_REFUND_SOURCE,\n jobId: input.jobId,\n })\n}\n"],"names":["ASSIST_CREDIT_RETURNS_FIELD","accountCreditMeter","returnAssistCredits","workspaceCreditMeter","AI_JOB_REFUNDS_PER_DAY","AI_JOB_REFUND_SOURCE","AI_JOB_REFUND_ACTOR","aiJobRefundKey","input","job","jobId","replace","slice","day","Math","max","floor","ordinal","aiJobRefundsOn","returns","prefix","Object","keys","filter","key","startsWith","length","aiJobRefundCredits","step","stepCredits","delivered","jobCredits","alreadyRefunded","refundJobCredits","firestore","workspace","orgId","month","account","free","accountUid","counter","ref","get","status","lines","meters","credits","reason","actorUid","source"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,2BAA2B,QAAQ,6BAAyB;AACrE,SACEC,kBAAkB,EAClBC,mBAAmB,EACnBC,oBAAoB,QAEf,mCAA+B;AAGtC
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/ai/src/lib/usage/assist-job-refund.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ASSIST_CREDIT_RETURNS_FIELD } from './assist-credit-returns'\nimport {\n accountCreditMeter,\n returnAssistCredits,\n workspaceCreditMeter,\n type AssistCreditReturnOutcome,\n} from './assist-credit-returns-write'\nimport type { FreeAssistAccount } from './assist-free-taste'\n\n/**\n * A job that failed on our side gives back what it spent (AGL-3594).\n *\n * \"On our side\" is the machine's to say, and it says it for: a plan the plan\n * rules still refused after their re-ask, a building step whose answer still\n * broke a building rule after its re-ask (AGL-3596), a provider or model error, a step\n * the machine gave up on after its attempts (a timeout or a lease that kept\n * expiring), a step that failed of its own accord, and a step no runner could\n * take. Never for a person canceling — they pay for what ran until they did —\n * nor for a model declining the brief, which the Free taste already meters as\n * a refusal and the refusal pause bounds.\n *\n * WHAT IS GIVEN BACK. A job that delivered nothing gives back everything it\n * spent and has not already given back. A job that delivered drafts and then\n * failed keeps them and pays for them: only the failing step's own spend goes\n * back. The site's listing proposal is not a delivery — it is derived from the\n * answers, costs nothing, and rides out with the first unit.\n *\n * HOW. Through the one give-back writer (`returnAssistCredits`, AGL-3595), to\n * the workspace's band and, on the Free taste, the owner's allowance — the\n * meters the spend was charged to — recorded as `system:job-refund`. The\n * tokens stay on the bill and the signal; the give-back nets them out of what\n * every reader calls \"used\".\n *\n * BOUNDED. The writer never returns more than a meter's month used. On top\n * of it, at most `AI_JOB_REFUNDS_PER_DAY` automatic give-backs an account a\n * UTC day (the workspace's own month where it names no owner), counted off\n * the give-backs the month already records, so a brief that keeps failing\n * cannot keep spending for free. Past it, the failure is metered as it always\n * was.\n */\n\n/** Automatic give-backs an account may have a UTC day. */\nexport const AI_JOB_REFUNDS_PER_DAY = 3\n\n/** The `source` a job's give-back is recorded under. */\nexport const AI_JOB_REFUND_SOURCE = 'job-refund'\n\n/** Who gives it back: the platform, not a member of staff. */\nexport const AI_JOB_REFUND_ACTOR = `system:${AI_JOB_REFUND_SOURCE}`\n\n/** Why a job's credits went back, as the job records it. */\nexport type AiJobRefundReason =\n | 'plan-refused'\n | 'doctrine-refused'\n | 'provider'\n | 'timeout'\n | 'step-failure'\n | 'unavailable'\n\n/**\n * The give-back's key. Per job and per give-back on it (`ordinal`, the job's\n * count of give-backs so far), so one failure gives back once however often\n * it is handled, and a later failure of the same job — a plan tried again and\n * refused again — is a give-back of its own. The day leads, so a day's\n * give-backs are counted off the month's keys. The writer holds a key to\n * `[A-Za-z0-9_-]{8,100}`; the job id is cut to fit.\n */\nexport function aiJobRefundKey(input: { day: string; jobId: string; ordinal: number }): string {\n const job = input.jobId.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 48)\n return `${AI_JOB_REFUND_SOURCE}-${input.day.replace(/-/g, '')}-${job}-${Math.max(0, Math.floor(input.ordinal))}`\n}\n\n/** How many give-backs a meter's month already records for `day`. */\nexport function aiJobRefundsOn(returns: unknown, day: string): number {\n if (!returns || typeof returns !== 'object') return 0\n const prefix = `${AI_JOB_REFUND_SOURCE}-${day.replace(/-/g, '')}-`\n return Object.keys(returns).filter((key) => key.startsWith(prefix)).length\n}\n\n/**\n * What a failure gives back: everything the job spent and has not already\n * given back when it delivered nothing, else the failing step's own spend.\n */\nexport function aiJobRefundCredits(input: {\n delivered: boolean\n jobCredits: number\n stepCredits: number\n alreadyRefunded: number\n}): number {\n const step = Math.max(0, Math.floor(input.stepCredits))\n if (input.delivered) return step\n return Math.max(0, Math.floor(input.jobCredits) - Math.max(0, Math.floor(input.alreadyRefunded)))\n}\n\nexport type AiJobRefundOutcome = AssistCreditReturnOutcome | { status: 'bounded'; lines: [] }\n\n/**\n * Give a failed job's credits back to the meters it was charged to, or say\n * why not.\n */\nexport async function refundJobCredits(\n firestore: FirebaseFirestore.Firestore,\n input: {\n orgId: string\n /** The Free taste's attribution, or `null` on a paid workspace. */\n free: FreeAssistAccount | null\n jobId: string\n ordinal: number\n credits: number\n month: string\n day: string\n reason: AiJobRefundReason\n },\n): Promise<AiJobRefundOutcome> {\n const workspace = workspaceCreditMeter(firestore, input.orgId, input.month)\n const account = input.free?.accountUid\n ? accountCreditMeter(firestore, input.free.accountUid, input.month)\n : null\n const counter = await (account ?? workspace).ref.get()\n if (aiJobRefundsOn(counter.get(ASSIST_CREDIT_RETURNS_FIELD), input.day) >= AI_JOB_REFUNDS_PER_DAY) {\n return { status: 'bounded', lines: [] }\n }\n return returnAssistCredits(firestore, {\n month: input.month,\n meters: account ? [workspace, account] : [workspace],\n credits: input.credits,\n key: aiJobRefundKey({ day: input.day, jobId: input.jobId, ordinal: input.ordinal }),\n reason: `An AI job failed on our side (${input.reason})`,\n actorUid: AI_JOB_REFUND_ACTOR,\n source: AI_JOB_REFUND_SOURCE,\n jobId: input.jobId,\n })\n}\n"],"names":["ASSIST_CREDIT_RETURNS_FIELD","accountCreditMeter","returnAssistCredits","workspaceCreditMeter","AI_JOB_REFUNDS_PER_DAY","AI_JOB_REFUND_SOURCE","AI_JOB_REFUND_ACTOR","aiJobRefundKey","input","job","jobId","replace","slice","day","Math","max","floor","ordinal","aiJobRefundsOn","returns","prefix","Object","keys","filter","key","startsWith","length","aiJobRefundCredits","step","stepCredits","delivered","jobCredits","alreadyRefunded","refundJobCredits","firestore","workspace","orgId","month","account","free","accountUid","counter","ref","get","status","lines","meters","credits","reason","actorUid","source"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,2BAA2B,QAAQ,6BAAyB;AACrE,SACEC,kBAAkB,EAClBC,mBAAmB,EACnBC,oBAAoB,QAEf,mCAA+B;AAGtC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GAED,wDAAwD,GACxD,OAAO,MAAMC,yBAAyB,EAAC;AAEvC,sDAAsD,GACtD,OAAO,MAAMC,uBAAuB,aAAY;AAEhD,4DAA4D,GAC5D,OAAO,MAAMC,sBAAsB,CAAC,O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