@wenathlan/extension 1.1.52 → 1.1.53

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.
@@ -2282,6 +2282,107 @@ var sessionmemory = class {
2282
2282
  async listmanualruns() {
2283
2283
  return await this.adapter.get("manualruns") ?? [];
2284
2284
  }
2285
+ /** Stores one workflow version record with its change note; saving the same version again replaces its note while older versions survive for the timeline. */
2286
+ async addworkflowversion(version) {
2287
+ const versions = (await this.listworkflowversions()).filter((entry) => !(entry.workflowid === version.workflowid && entry.version === version.version));
2288
+ await this.adapter.set("workflowversions", [version, ...versions]);
2289
+ }
2290
+ /** Returns every stored workflow version record, newest first, optionally filtered to one workflow. */
2291
+ async listworkflowversions(workflowid) {
2292
+ const versions = await this.adapter.get("workflowversions") ?? [];
2293
+ return workflowid === void 0 ? versions : versions.filter((entry) => entry.workflowid === workflowid);
2294
+ }
2295
+ /** Stores one version diff result for the history view. */
2296
+ async addversiondiff(diff) {
2297
+ const diffs = (await this.listversiondiffs()).filter((entry) => !(entry.workflowid === diff.workflowid && entry.from === diff.from && entry.to === diff.to));
2298
+ await this.adapter.set("versiondiffs", [diff, ...diffs]);
2299
+ }
2300
+ /** Returns every stored version diff result, newest first, optionally filtered to one workflow. */
2301
+ async listversiondiffs(workflowid) {
2302
+ const diffs = await this.adapter.get("versiondiffs") ?? [];
2303
+ return workflowid === void 0 ? diffs : diffs.filter((entry) => entry.workflowid === workflowid);
2304
+ }
2305
+ /** Records one run history entry — the outcome, duration and trigger cause of one execution — under the user configured retention window with no code ceiling. */
2306
+ async addrunhistory(entry) {
2307
+ const entries = await this.gethistory();
2308
+ const combined = [entry, ...entries];
2309
+ const retention = (await this.getsettings())?.runhistoryretention;
2310
+ await this.adapter.set("runhistory", retention === void 0 ? combined : combined.slice(0, retention));
2311
+ }
2312
+ /** Returns the stored run history, newest first, filtered by workflow, outcome and time floor; the filters stay user choices. */
2313
+ async gethistory(filter) {
2314
+ const entries = await this.adapter.get("runhistory") ?? [];
2315
+ let filtered = entries;
2316
+ if (filter?.workflowid !== void 0) filtered = filtered.filter((entry) => entry.workflowid === filter.workflowid);
2317
+ if (filter?.outcome !== void 0) filtered = filtered.filter((entry) => entry.outcome === filter.outcome);
2318
+ if (filter?.since !== void 0) filtered = filtered.filter((entry) => entry.endedat >= filter.since);
2319
+ if (filter?.limit !== void 0) filtered = filtered.slice(0, filter.limit);
2320
+ return filtered;
2321
+ }
2322
+ /** Stores the editor layout of one workflow so the canvas reopens exactly as left. */
2323
+ async seteditorlayout(workflowid, layout) {
2324
+ return this.adapter.set(`editorlayout${workflowid}`, layout);
2325
+ }
2326
+ /** Returns the stored editor layout of one workflow. */
2327
+ async geteditorlayout(workflowid) {
2328
+ return await this.adapter.get(`editorlayout${workflowid}`) ?? void 0;
2329
+ }
2330
+ /** Stores the breakpoint step ids of one workflow. */
2331
+ async setworkflowbreakpoints(workflowid, stepids) {
2332
+ return this.adapter.set(`workflowbreakpoints${workflowid}`, stepids);
2333
+ }
2334
+ /** Returns the stored breakpoint step ids of one workflow, oldest first. */
2335
+ async getworkflowbreakpoints(workflowid) {
2336
+ return await this.adapter.get(`workflowbreakpoints${workflowid}`) ?? [];
2337
+ }
2338
+ /** Stores one per site policy override; re-adding the same id replaces its deltas. */
2339
+ async addsiteoverride(override) {
2340
+ const overrides = (await this.listsiteoverrides()).filter((entry) => entry.id !== override.id);
2341
+ await this.adapter.set("siteoverrides", [override, ...overrides]);
2342
+ }
2343
+ /** Returns every stored per site override, newest first, optionally filtered to one workflow. */
2344
+ async listsiteoverrides(workflowid) {
2345
+ const overrides = await this.adapter.get("siteoverrides") ?? [];
2346
+ return workflowid === void 0 ? overrides : overrides.filter((entry) => entry.workflowid === workflowid);
2347
+ }
2348
+ /** Removes one per site override when the user deletes it. */
2349
+ async removesiteoverride(id) {
2350
+ await this.adapter.set("siteoverrides", (await this.listsiteoverrides()).filter((entry) => entry.id !== id));
2351
+ }
2352
+ /** Stores one watchdog event with its recovery outcome; the event history keeps the audit trail of every scan. */
2353
+ async addwatchdogevent(event) {
2354
+ const events = (await this.listwatchdogevents()).filter((entry) => entry.id !== event.id);
2355
+ await this.adapter.set("watchdogevents", [event, ...events]);
2356
+ }
2357
+ /** Returns every stored watchdog event, newest first. */
2358
+ async listwatchdogevents() {
2359
+ return await this.adapter.get("watchdogevents") ?? [];
2360
+ }
2361
+ /** Stores one pending workflow import held for review; approving it later stores the record as runnable. */
2362
+ async addworkflowimport(entry) {
2363
+ const imports = (await this.listworkflowimports()).filter((candidate) => candidate.id !== entry.id);
2364
+ await this.adapter.set("workflowimports", [entry, ...imports]);
2365
+ }
2366
+ /** Returns every pending workflow import, newest first. */
2367
+ async listworkflowimports() {
2368
+ return await this.adapter.get("workflowimports") ?? [];
2369
+ }
2370
+ /** Removes one pending import when the user approves or rejects it. */
2371
+ async removeworkflowimport(id) {
2372
+ await this.adapter.set("workflowimports", (await this.listworkflowimports()).filter((entry) => entry.id !== id));
2373
+ }
2374
+ /** Stores the per workflow background run flags so a workflow keeps running with the panel closed. */
2375
+ async setbackgroundruns(flags) {
2376
+ return this.adapter.set("backgroundruns", flags);
2377
+ }
2378
+ /** Returns the per workflow background run flags. */
2379
+ async getbackgroundruns() {
2380
+ return await this.adapter.get("backgroundruns") ?? {};
2381
+ }
2382
+ /** Removes one stored workflow record version; a rejected import or rollback disappears from the library while every other version survives. */
2383
+ async removeworkflowversion(id, version) {
2384
+ await this.adapter.set("workflowrecords", (await this.getworkflowrecordversions()).filter((entry) => !(entry.id === id && entry.version === version)));
2385
+ }
2285
2386
  };
2286
2387
  function mediakindof(record2) {
2287
2388
  if ("pages" in record2) return "pdf";
@@ -3942,6 +4043,14 @@ async function runcontrolstep(input) {
3942
4043
 
3943
4044
  // workflow.ts
3944
4045
  var workflowkinds = ["composeworkflow", "savetemplate", "runworkflow", "dryrun", "delay", "waitelement", "compute", "extractvars"];
4046
+ function nestedparamof(value) {
4047
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
4048
+ const candidate = value;
4049
+ if (typeof candidate.name !== "string" || !/^[a-z][a-z0-9]*$/.test(candidate.name)) return void 0;
4050
+ if (!variablekinds.includes(candidate.kind)) return void 0;
4051
+ if (candidate.default !== void 0 && !["string", "number", "boolean"].includes(typeof candidate.default) && !Array.isArray(candidate.default)) return void 0;
4052
+ return { name: candidate.name, kind: candidate.kind, ...candidate.default !== void 0 ? { default: candidate.default } : {} };
4053
+ }
3945
4054
  function workflowstepof(value) {
3946
4055
  if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
3947
4056
  const candidate = value;
@@ -3951,6 +4060,7 @@ function workflowstepof(value) {
3951
4060
  if (candidate.target !== void 0 && (typeof candidate.target !== "string" || !candidate.target)) return void 0;
3952
4061
  if (candidate.value !== void 0 && typeof candidate.value !== "string") return void 0;
3953
4062
  if (candidate.options !== void 0 && typeof candidate.options !== "string") return void 0;
4063
+ if (candidate.breakpoint !== void 0 && typeof candidate.breakpoint !== "boolean") return void 0;
3954
4064
  const bindings = Array.isArray(candidate.bindings) ? candidate.bindings.flatMap((binding) => bindingof(binding) !== void 0 ? [bindingof(binding)] : []) : void 0;
3955
4065
  if (candidate.bindings !== void 0 && bindings === void 0) return void 0;
3956
4066
  if (Array.isArray(candidate.bindings) && bindings !== void 0 && bindings.length !== candidate.bindings.length) return void 0;
@@ -3958,14 +4068,20 @@ function workflowstepof(value) {
3958
4068
  if (candidate.expression !== void 0 && expression === void 0) return void 0;
3959
4069
  const extract = candidate.extract === void 0 ? void 0 : regexruleof(candidate.extract);
3960
4070
  if (candidate.extract !== void 0 && extract === void 0) return void 0;
3961
- return { id: candidate.id, kind: candidate.kind, label: candidate.label, ...candidate.target !== void 0 ? { target: candidate.target } : {}, ...candidate.value !== void 0 ? { value: candidate.value } : {}, ...candidate.options !== void 0 ? { options: candidate.options } : {}, ...bindings !== void 0 && bindings.length > 0 ? { bindings } : {}, ...expression !== void 0 ? { expression } : {}, ...extract !== void 0 ? { extract } : {} };
4071
+ const params = Array.isArray(candidate.params) ? candidate.params.flatMap((param) => nestedparamof(param) !== void 0 ? [nestedparamof(param)] : []) : void 0;
4072
+ if (candidate.params !== void 0 && params === void 0) return void 0;
4073
+ if (Array.isArray(candidate.params) && params !== void 0 && params.length !== candidate.params.length) return void 0;
4074
+ return { id: candidate.id, kind: candidate.kind, label: candidate.label, ...candidate.target !== void 0 ? { target: candidate.target } : {}, ...candidate.value !== void 0 ? { value: candidate.value } : {}, ...candidate.options !== void 0 ? { options: candidate.options } : {}, ...bindings !== void 0 && bindings.length > 0 ? { bindings } : {}, ...expression !== void 0 ? { expression } : {}, ...extract !== void 0 ? { extract } : {}, ...candidate.breakpoint === true ? { breakpoint: true } : {}, ...params !== void 0 && params.length > 0 ? { params } : {} };
3962
4075
  }
3963
4076
  function blockinvocationof(value) {
3964
4077
  if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
3965
4078
  const candidate = value;
3966
4079
  if (typeof candidate.block !== "string" || !candidate.block.trim()) return void 0;
3967
4080
  if (typeof candidate.label !== "string" || !candidate.label.trim()) return void 0;
3968
- return { block: candidate.block, label: candidate.label };
4081
+ const params = Array.isArray(candidate.params) ? candidate.params.flatMap((param) => nestedparamof(param) !== void 0 ? [nestedparamof(param)] : []) : void 0;
4082
+ if (candidate.params !== void 0 && params === void 0) return void 0;
4083
+ if (Array.isArray(candidate.params) && params !== void 0 && params.length !== candidate.params.length) return void 0;
4084
+ return { block: candidate.block, label: candidate.label, ...params !== void 0 && params.length > 0 ? { params } : {} };
3969
4085
  }
3970
4086
  function workflowblockof(value) {
3971
4087
  if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
@@ -4044,10 +4160,15 @@ function regexruleof(value) {
4044
4160
  function expandblocks(steps, blocks) {
4045
4161
  const byname = new Map(blocks.map((block) => [block.name, block]));
4046
4162
  const expanded = [];
4047
- const visit = (entries, path, inside) => {
4163
+ const visit = (entries, path, inside, params) => {
4164
+ let stamped = params === void 0;
4048
4165
  for (const entry of entries) {
4049
4166
  if ("kind" in entry && "label" in entry && !("block" in entry)) {
4050
- expanded.push(inside === void 0 ? entry : { ...entry, block: inside });
4167
+ const marked = inside === void 0 ? entry : { ...entry, block: inside };
4168
+ if (!stamped && params !== void 0) {
4169
+ expanded.push({ ...marked, params });
4170
+ stamped = true;
4171
+ } else expanded.push(marked);
4051
4172
  continue;
4052
4173
  }
4053
4174
  const invocation = blockinvocationof(entry);
@@ -4055,7 +4176,7 @@ function expandblocks(steps, blocks) {
4055
4176
  if (path.includes(invocation.block)) throw new Error(`The block ${invocation.block} recurs inside itself and cannot expand.`);
4056
4177
  const block = byname.get(invocation.block);
4057
4178
  if (!block) throw new Error(`The block ${invocation.block} is not defined in the workflow.`);
4058
- visit(block.steps, [...path, invocation.block], invocation.block);
4179
+ visit(block.steps, [...path, invocation.block], invocation.block, invocation.params ?? params);
4059
4180
  }
4060
4181
  };
4061
4182
  visit(steps, [], void 0);
@@ -4423,6 +4544,17 @@ async function runworkflow(input) {
4423
4544
  if (step.block !== void 0 && step.block !== activeblock) {
4424
4545
  scopes = pushscope(scopes, step.block, scopes[scopes.length - 1].name);
4425
4546
  activeblock = step.block;
4547
+ if (step.params) {
4548
+ try {
4549
+ for (const param of step.params) {
4550
+ if (param.default === void 0) continue;
4551
+ scopes = setvariable(scopes, param.name, param.kind, coercevariable(param.default, param.kind), input.now);
4552
+ }
4553
+ } catch (error) {
4554
+ const reason = error instanceof Error ? error.message : String(error);
4555
+ return { run: { ...run, state: "failed", endedat: Date.now(), failreason: `The nested parameter of block ${step.block} failed: ${reason}` }, scopes, log, outputs };
4556
+ }
4557
+ }
4426
4558
  } else if (step.block === void 0 && activeblock !== void 0) {
4427
4559
  while (scopes.length > 1) scopes = popscope(scopes);
4428
4560
  activeblock = void 0;
@@ -4455,6 +4587,27 @@ function dryrunworkflow(input) {
4455
4587
  }
4456
4588
  return { run: { ...run, state: "done", cursor: input.record.steps.length, endedat: input.now }, scopes, log };
4457
4589
  }
4590
+ function watchdogpass(input) {
4591
+ const verdicts = [];
4592
+ for (const run of input.runs) {
4593
+ if (run.state !== "running") continue;
4594
+ const lastcompletedat = input.lastcompletedat[run.id] ?? run.startedat;
4595
+ const live = input.liveexecutors.includes(run.id);
4596
+ const silence = input.now - lastcompletedat;
4597
+ if (!live && input.config.zombiewindow !== void 0 && silence >= input.config.zombiewindow) {
4598
+ verdicts.push({ runid: run.id, verdict: "zombie", action: "reap", reason: `The run ${run.id} lost its executor ${silence} ms ago and reaps as a zombie of a browser shutdown at its last checkpoint ${run.cursor}.`, ...lastcompletedat !== run.startedat ? { lastcompletedat } : {} });
4599
+ continue;
4600
+ }
4601
+ if (!live) continue;
4602
+ if (silence >= input.config.stallthreshold) {
4603
+ const action = input.config.action;
4604
+ verdicts.push({ runid: run.id, verdict: "stalled", action, reason: `The run ${run.id} completed no step for ${silence} ms past the reviewed threshold and the watchdog recovers it with ${action} at cursor ${run.cursor}.`, ...lastcompletedat !== run.startedat ? { lastcompletedat } : {} });
4605
+ continue;
4606
+ }
4607
+ verdicts.push({ runid: run.id, verdict: "healthy", action: "none", reason: `The run ${run.id} completed its last step ${silence} ms ago and stays healthy.`, ...lastcompletedat !== run.startedat ? { lastcompletedat } : {} });
4608
+ }
4609
+ return verdicts;
4610
+ }
4458
4611
 
4459
4612
  // trigger.ts
4460
4613
  var triggerkinds = ["visitrule", "urlrule", "menurule", "keyrule", "buttonrule", "cronrule", "intervalrule", "urllistrule", "webhookrule", "eventrule"];
@@ -7838,6 +7991,134 @@ function canpreview(input) {
7838
7991
  if (!targetactions.has(input.step.kind) && options.targetref === void 0) return { allowed: false, reason: "Only a target-based action can be previewed." };
7839
7992
  return validatestep(input.step, input.origin);
7840
7993
  }
7994
+ function reviewedkinds() {
7995
+ return [...allowedactions].sort();
7996
+ }
7997
+ function editorsavegate(input) {
7998
+ const gate = sessiongate({ session: input.session, tabid: input.session?.tabid ?? 0, origin: input.session?.origin ?? "https://example.com", now: input.now, action: "save the workflow editor canvas" });
7999
+ if (!gate.allowed) return gate;
8000
+ if (!input.plan || input.plan.state !== "approved") return { allowed: false, reason: "Editor saves need the approved plan review before a new workflow version composes." };
8001
+ const model = input.model;
8002
+ if (typeof model.name !== "string" || !model.name.trim()) return { allowed: false, reason: "The workflow name of the canvas must be a non-empty string." };
8003
+ if (typeof model.version !== "number" || !Number.isInteger(model.version) || model.version < 1) return { allowed: false, reason: "The workflow version of the canvas must be a positive integer." };
8004
+ if (!Array.isArray(model.origins) || model.origins.length === 0) return { allowed: false, reason: "The canvas needs at least one granted HTTPS origin." };
8005
+ const ids = /* @__PURE__ */ new Set();
8006
+ for (const node of model.nodes) {
8007
+ if (node.step === void 0 === (node.invocation === void 0)) return { allowed: false, reason: "Every canvas node must be exactly one workflow step or one block invocation." };
8008
+ const id = node.id ?? (node.step !== void 0 ? node.step.id : node.invocation.block);
8009
+ if (!id || ids.has(id)) return { allowed: false, reason: `The canvas node id ${id || "(empty)"} must be unique.` };
8010
+ ids.add(id);
8011
+ }
8012
+ const reachable = /* @__PURE__ */ new Set();
8013
+ for (const node of model.nodes) {
8014
+ if (node.step !== void 0) {
8015
+ reachable.add(node.step.id);
8016
+ continue;
8017
+ }
8018
+ const walk = (entries) => {
8019
+ for (const entry of entries) {
8020
+ if (typeof entry.id === "string" && typeof entry.kind === "string") {
8021
+ reachable.add(entry.id);
8022
+ continue;
8023
+ }
8024
+ if (typeof entry.block === "string") {
8025
+ const nested = model.blocks.find((candidate) => candidate.name === entry.block);
8026
+ if (nested) walk(nested.steps);
8027
+ }
8028
+ }
8029
+ };
8030
+ const block = model.blocks.find((candidate) => candidate.name === node.invocation.block);
8031
+ if (!block) return { allowed: false, reason: `The block ${node.invocation.block} of the canvas has no definition.` };
8032
+ walk(block.steps);
8033
+ }
8034
+ let order = 0;
8035
+ const positionof = /* @__PURE__ */ new Map();
8036
+ for (const node of model.nodes) {
8037
+ if (node.step !== void 0) {
8038
+ positionof.set(node.step.id, order);
8039
+ order += 1;
8040
+ continue;
8041
+ }
8042
+ const walk = (entries) => {
8043
+ for (const entry of entries) {
8044
+ if (typeof entry.id === "string" && typeof entry.kind === "string") {
8045
+ positionof.set(entry.id, order);
8046
+ order += 1;
8047
+ continue;
8048
+ }
8049
+ if (typeof entry.block === "string") {
8050
+ const nested = model.blocks.find((candidate) => candidate.name === entry.block);
8051
+ if (nested) walk(nested.steps);
8052
+ }
8053
+ }
8054
+ };
8055
+ walk(model.blocks.find((candidate) => candidate.name === node.invocation.block).steps);
8056
+ }
8057
+ for (const edge of model.edges) {
8058
+ if (!reachable.has(edge.from)) return { allowed: false, reason: `The canvas edge of ${edge.variable} references the unknown source step ${edge.from}.` };
8059
+ if (!reachable.has(edge.to)) return { allowed: false, reason: `The canvas edge of ${edge.variable} references the unknown target step ${edge.to}.` };
8060
+ if ((positionof.get(edge.from) ?? -1) >= (positionof.get(edge.to) ?? -1)) return { allowed: false, reason: `The canvas edge of ${edge.variable} runs backwards and would form a cycle.` };
8061
+ }
8062
+ return { allowed: true };
8063
+ }
8064
+ function runreviewgranted(record2) {
8065
+ if (record2.reviewstate === "pending") return { allowed: false, reason: "The workflow stays unreviewed: the import or rollback review must approve its expanded step list before any run." };
8066
+ return { allowed: true };
8067
+ }
8068
+ var overrideknobs = ["loopbound", "stepms", "runms", "waitms", "delaybase"];
8069
+ function validatesiteoverride(override) {
8070
+ if (typeof override.pattern !== "string" || !override.pattern.startsWith("https://") || !/[a-z0-9.-]+/i.test(override.pattern.slice(8))) return { allowed: false, reason: "The override pattern must be an https origin or a `*` subdomain glob of one." };
8071
+ if (!override.pattern.includes("*")) {
8072
+ try {
8073
+ if (new URL(override.pattern).origin !== override.pattern) return { allowed: false, reason: "The override pattern must be a bare https origin or a `*` subdomain glob, never a path." };
8074
+ } catch {
8075
+ return { allowed: false, reason: "The override pattern must parse as an https origin or a `*` subdomain glob of one." };
8076
+ }
8077
+ }
8078
+ for (const [knob, delta] of Object.entries(override.deltas)) {
8079
+ if (!overrideknobs.includes(knob)) return { allowed: false, reason: `The override knob ${knob} is not one of the reviewed knobs: ${overrideknobs.join(", ")}.` };
8080
+ if (typeof delta !== "number" || !Number.isFinite(delta) || delta <= 0) return { allowed: false, reason: `The override delta of ${knob} must be a positive user value with no code ceiling.` };
8081
+ }
8082
+ return { allowed: true };
8083
+ }
8084
+ function exportcontentreview(file) {
8085
+ const secretkeys = /(secret|token|apikey|api_key|password|authorization|credential)/i;
8086
+ const scan = (label, options) => {
8087
+ if (options === void 0) return void 0;
8088
+ let payload;
8089
+ try {
8090
+ payload = JSON.parse(options);
8091
+ } catch {
8092
+ return void 0;
8093
+ }
8094
+ const walk = (value, path) => {
8095
+ if (!value || typeof value !== "object") return void 0;
8096
+ for (const [key, entry] of Object.entries(value)) {
8097
+ if (secretkeys.test(key)) return { allowed: false, reason: `The export of ${label} carries the secret field ${path}${key} and secrets never leave the browser.` };
8098
+ const nested = walk(entry, `${path}${key}.`);
8099
+ if (nested !== void 0) return nested;
8100
+ }
8101
+ return void 0;
8102
+ };
8103
+ return walk(payload, "");
8104
+ };
8105
+ for (const step of file.workflow.steps) {
8106
+ const refusal = scan(`the step ${step.id}`, step.options);
8107
+ if (refusal !== void 0) return refusal;
8108
+ }
8109
+ for (const template of file.templates) {
8110
+ const refusal = scan(`the template ${template.name}`, template.step.options);
8111
+ if (refusal !== void 0) return refusal;
8112
+ }
8113
+ return { allowed: true };
8114
+ }
8115
+ function watchdogconfigvalid(config) {
8116
+ if (typeof config.enabled !== "boolean") return { allowed: false, reason: "The watchdog enabled flag must be a boolean." };
8117
+ if (typeof config.stallthreshold !== "number" || !Number.isFinite(config.stallthreshold) || config.stallthreshold <= 0) return { allowed: false, reason: "The watchdog stall threshold must be a positive number of milliseconds with no code ceiling." };
8118
+ if (!["retry", "pause", "cancel"].includes(config.action)) return { allowed: false, reason: "The watchdog recovery action must be retry, pause or cancel." };
8119
+ if (config.zombiewindow !== void 0 && (typeof config.zombiewindow !== "number" || !Number.isFinite(config.zombiewindow) || config.zombiewindow <= 0)) return { allowed: false, reason: "The watchdog zombie window, when configured, must be a positive number of milliseconds with no code ceiling." };
8120
+ return { allowed: true };
8121
+ }
7841
8122
 
7842
8123
  // progress.ts
7843
8124
  function emptyprogress(planid, now) {
@@ -8012,7 +8293,7 @@ function recordtrigger(progress, planid, stepid, entry, now) {
8012
8293
  }
8013
8294
 
8014
8295
  // version.ts
8015
- var packageversion = "1.1.52";
8296
+ var packageversion = "1.1.53";
8016
8297
 
8017
8298
  // types.ts
8018
8299
  var protocolversion = packageversion;
@@ -8525,6 +8806,36 @@ function triggersummaryof(rule) {
8525
8806
  if (rule.schema !== void 0) summary.fields = rule.schema.length;
8526
8807
  return summary;
8527
8808
  }
8809
+ var workflowfileversion = 1;
8810
+ function editorstate(input) {
8811
+ const editor = { versions: input.versions, diffs: input.diffs ?? [], history: input.history, breakpoints: input.breakpoints ?? [], overrides: input.overrides, imports: input.imports, backgroundruns: input.backgroundruns ?? {}, watchdog: { ...input.watchdog.config !== void 0 ? { config: input.watchdog.config } : {}, events: input.watchdog.events } };
8812
+ return { version: protocolversion, editor, ...input.model !== void 0 ? { model: input.model } : {} };
8813
+ }
8814
+ function runhistoryquery(value) {
8815
+ if (value === void 0 || value === null) return {};
8816
+ const candidate = record(value);
8817
+ const query = {};
8818
+ if (candidate.workflowid !== void 0) {
8819
+ if (typeof candidate.workflowid !== "string" || !candidate.workflowid.trim()) throw new Error("The run history workflow filter must be a non-empty string.");
8820
+ query.workflowid = candidate.workflowid;
8821
+ }
8822
+ if (candidate.outcome !== void 0) {
8823
+ if (typeof candidate.outcome !== "string" || !candidate.outcome.trim()) throw new Error("The run history outcome filter must be a non-empty string.");
8824
+ query.outcome = candidate.outcome;
8825
+ }
8826
+ if (candidate.since !== void 0) {
8827
+ if (typeof candidate.since !== "number" || !Number.isFinite(candidate.since)) throw new Error("The run history time floor must be a finite timestamp.");
8828
+ query.since = candidate.since;
8829
+ }
8830
+ if (candidate.limit !== void 0) {
8831
+ if (typeof candidate.limit !== "number" || !Number.isInteger(candidate.limit) || candidate.limit < 1) throw new Error("The run history entry count must be a positive integer with no code ceiling.");
8832
+ query.limit = candidate.limit;
8833
+ }
8834
+ return query;
8835
+ }
8836
+ function runhistoryreport(input) {
8837
+ return { version: protocolversion, entries: input.entries, query: input.query ?? {} };
8838
+ }
8528
8839
 
8529
8840
  // capture.ts
8530
8841
  var capturekinds = ["shotview", "shotfullpage", "shotelement", "shotregion", "contactsheet"];
@@ -9101,6 +9412,488 @@ async function runbrowseraction(step, sessiontabid, windowid) {
9101
9412
  }
9102
9413
  }
9103
9414
 
9415
+ // workfloweditor.ts
9416
+ var palettecategories = ["actions", "controlflow", "waits", "variables", "triggers"];
9417
+ var palettenodes = [
9418
+ { kind: "click", label: "Click an element", category: "actions", description: "Clicks the reviewed selector target." },
9419
+ { kind: "type", label: "Type text", category: "actions", description: "Types the reviewed text into the target field." },
9420
+ { kind: "navigate", label: "Navigate", category: "actions", description: "Navigates the tab to the reviewed url." },
9421
+ { kind: "readtext", label: "Read text", category: "actions", description: "Reads the text of the target element." },
9422
+ { kind: "scrapetable", label: "Scrape a table", category: "actions", description: "Extracts the reviewed table into a dataset." },
9423
+ { kind: "fillform", label: "Fill a form", category: "actions", description: "Fills the reviewed form fields from a saved profile." },
9424
+ { kind: "querytabs", label: "Query tabs", category: "actions", description: "Lists the tabs matching the reviewed query." },
9425
+ { kind: "fetchurl", label: "Fetch a url", category: "actions", description: "Fetches the reviewed endpoint behind the call consent." },
9426
+ { kind: "condition", label: "Condition", category: "controlflow", description: "Evaluates one reviewed boolean expression with no page side effect." },
9427
+ { kind: "branch", label: "Branch", category: "controlflow", description: "Chooses one reviewed path by page state with a mandatory else path." },
9428
+ { kind: "loop", label: "Loop a list", category: "controlflow", description: "Iterates a list variable binding the item and index per pass." },
9429
+ { kind: "repeatuntil", label: "Repeat until", category: "controlflow", description: "Reruns the body until the convergence expression holds." },
9430
+ { kind: "whileloop", label: "While loop", category: "controlflow", description: "Loops while the condition holds inside the reviewed bound." },
9431
+ { kind: "foreach", label: "For each element", category: "controlflow", description: "Iterates the elements of the reviewed selector." },
9432
+ { kind: "parallel", label: "Parallel branches", category: "controlflow", description: "Runs branches concurrently and joins them under the reviewed strategy." },
9433
+ { kind: "trycatch", label: "Try catch", category: "controlflow", description: "Wraps fragile steps with a catch handler, retries and timeouts." },
9434
+ { kind: "delay", label: "Delay", category: "waits", description: "Sleeps the reviewed base inside the jitter window." },
9435
+ { kind: "waitelement", label: "Wait for element", category: "waits", description: "Polls the reviewed selector until appearance or timeout." },
9436
+ { kind: "wait", label: "Wait", category: "waits", description: "Waits the reviewed duration." },
9437
+ { kind: "waitfor", label: "Wait for target", category: "waits", description: "Waits until the reviewed target exists." },
9438
+ { kind: "waittext", label: "Wait for text", category: "waits", description: "Waits until the reviewed text appears." },
9439
+ { kind: "waitquiet", label: "Wait for quiet", category: "waits", description: "Waits until the page stops mutating." },
9440
+ { kind: "waitload", label: "Wait for load", category: "waits", description: "Waits until the navigation settles." },
9441
+ { kind: "compute", label: "Compute", category: "variables", description: "Evaluates one reviewed expression into the result variable." },
9442
+ { kind: "extractvars", label: "Extract variables", category: "variables", description: "Applies the reviewed regex and stores the named captures." },
9443
+ { kind: "savetemplate", label: "Save template", category: "variables", description: "Shares the reviewed step as a reusable template." },
9444
+ { kind: "visitrule", label: "Visit rule", category: "triggers", description: "Fires on navigations to the reviewed origins." },
9445
+ { kind: "urlrule", label: "Url rule", category: "triggers", description: "Fires when the url matches the reviewed glob pattern." },
9446
+ { kind: "cronrule", label: "Cron rule", category: "triggers", description: "Fires on the reviewed five field cron schedule." },
9447
+ { kind: "intervalrule", label: "Interval rule", category: "triggers", description: "Fires every reviewed period with the jitter spread." },
9448
+ { kind: "webhookrule", label: "Webhook rule", category: "triggers", description: "Fires on a secret verified webhook delivery." },
9449
+ { kind: "eventrule", label: "Event rule", category: "triggers", description: "Fires on the observed page events of the catalog." }
9450
+ ];
9451
+ var optionschemas = {
9452
+ delay: [{ name: "base", kind: "number", required: true }, { name: "jitter", kind: "number" }],
9453
+ waitelement: [{ name: "timeout", kind: "number" }, { name: "poll", kind: "number" }],
9454
+ compute: [{ name: "expression", kind: "string", required: true }],
9455
+ extractvars: [{ name: "rule", kind: "string", required: true }],
9456
+ composeworkflow: [{ name: "name", kind: "string", required: true }, { name: "version", kind: "number" }],
9457
+ runworkflow: [{ name: "workflowid", kind: "string", required: true }, { name: "reviewed", kind: "boolean", required: true }, { name: "variables", kind: "string" }, { name: "background", kind: "boolean" }],
9458
+ dryrun: [{ name: "workflowid", kind: "string", required: true }],
9459
+ loop: [{ name: "loop", kind: "string", required: true }],
9460
+ repeatuntil: [{ name: "repeatuntil", kind: "string", required: true }],
9461
+ whileloop: [{ name: "whileloop", kind: "string", required: true }],
9462
+ foreach: [{ name: "foreach", kind: "string", required: true }],
9463
+ parallel: [{ name: "parallel", kind: "string", required: true }],
9464
+ trycatch: [{ name: "trycatch", kind: "string", required: true }]
9465
+ };
9466
+ function stepcategory(kind) {
9467
+ if (triggerkinds.includes(kind)) return "triggers";
9468
+ if (controlflowkinds.includes(kind)) return "controlflow";
9469
+ if (kind.startsWith("wait") || kind === "spawait" || kind === "delay") return "waits";
9470
+ if (kind === "compute" || kind === "extractvars" || kind === "savetemplate") return "variables";
9471
+ return "actions";
9472
+ }
9473
+ function buildsteplibrary(kinds) {
9474
+ return [...new Set(kinds)].sort().map((kind) => ({ kind, category: stepcategory(kind), optionschema: optionschemas[kind] ?? [] }));
9475
+ }
9476
+ var noderowheight = 96;
9477
+ var blockcolumnwidth = 280;
9478
+ var canvasoriginx = 40;
9479
+ function nodeidof(node) {
9480
+ return node.id ?? (node.step !== void 0 ? node.step.id : node.invocation !== void 0 ? node.invocation.block : "");
9481
+ }
9482
+ function layoutsizeof(nodes) {
9483
+ const width = Math.max(640, ...nodes.map((node) => node.x + blockcolumnwidth)) + 40;
9484
+ const height = Math.max(480, ...nodes.map((node) => node.y + noderowheight)) + 40;
9485
+ return { width, height };
9486
+ }
9487
+ function loadworkflow(record2, layout) {
9488
+ const blocks = record2.blocks.map((block) => ({ ...block, steps: block.steps.map((entry) => ({ ...entry })) }));
9489
+ const blockcolumn = (blockname) => {
9490
+ const index2 = blocks.findIndex((block) => block.name === blockname);
9491
+ return index2 < 0 ? canvasoriginx : canvasoriginx + (index2 + 1) * blockcolumnwidth;
9492
+ };
9493
+ const invocationcount = /* @__PURE__ */ new Map();
9494
+ const nodes = [];
9495
+ const edges = [];
9496
+ let index = 0;
9497
+ while (index < record2.steps.length) {
9498
+ const step = record2.steps[index];
9499
+ for (const binding of step.bindings ?? []) edges.push({ from: binding.stepid, to: step.id, variable: binding.variable, kind: binding.kind, ...binding.path !== void 0 ? { path: binding.path } : {} });
9500
+ if (step.block === void 0) {
9501
+ const { bindings, block, params: params2, ...rest } = step;
9502
+ void bindings;
9503
+ void block;
9504
+ void params2;
9505
+ nodes.push({ step: { ...rest }, x: canvasoriginx, y: 60 + nodes.length * noderowheight });
9506
+ index += 1;
9507
+ continue;
9508
+ }
9509
+ const blockname = step.block;
9510
+ let end = index;
9511
+ while (end < record2.steps.length && record2.steps[end].block === blockname) end += 1;
9512
+ const region = record2.steps.slice(index, end);
9513
+ const count = (invocationcount.get(blockname) ?? 0) + 1;
9514
+ invocationcount.set(blockname, count);
9515
+ const params = region.flatMap((entry) => entry.params ?? []);
9516
+ nodes.push({ id: count === 1 ? blockname : `${blockname}${count}`, invocation: { block: blockname, label: blockname, ...params.length > 0 ? { params: params.map((param) => ({ ...param })) } : {} }, x: blockcolumn(blockname), y: 60 + nodes.length * noderowheight });
9517
+ index = end;
9518
+ }
9519
+ const size = layouttypeof(nodes, layout);
9520
+ const model = { workflowid: record2.id, name: record2.name, version: record2.version, origins: [...record2.origins], nodes, edges, blocks, layout: size, minimap: emptyminimap(), dirty: false };
9521
+ return { ...model, minimap: renderminimap(model).minimap };
9522
+ }
9523
+ function layouttypeof(nodes, layout) {
9524
+ const size = layoutsizeof(nodes);
9525
+ if (!layout) return { width: size.width, height: size.height, viewportx: 0, viewporty: 0, zoom: 1 };
9526
+ return { width: Math.max(size.width, layout.width), height: Math.max(size.height, layout.height), viewportx: layout.viewportx, viewporty: layout.viewporty, zoom: layout.zoom };
9527
+ }
9528
+ function emptyminimap() {
9529
+ return { width: 160, height: 100, scale: 0, zoom: 1, viewport: { x: 0, y: 0, width: 0, height: 0 } };
9530
+ }
9531
+ function saveworkflow(model, input) {
9532
+ if (typeof model.name !== "string" || !model.name.trim()) throw new Error("The workflow name must be a non-empty string.");
9533
+ if (typeof model.version !== "number" || !Number.isInteger(model.version) || model.version < 1) throw new Error("The workflow version must be a positive integer.");
9534
+ if (!Array.isArray(model.origins) || model.origins.length === 0) throw new Error("A workflow needs at least one granted HTTPS origin.");
9535
+ const ids = /* @__PURE__ */ new Set();
9536
+ for (const node of model.nodes) {
9537
+ if (node.step === void 0 === (node.invocation === void 0)) throw new Error("Every canvas node must be exactly one workflow step or one block invocation.");
9538
+ const id = nodeidof(node);
9539
+ if (!id || ids.has(id)) throw new Error(`The canvas node id ${id || "(empty)"} must be unique.`);
9540
+ ids.add(id);
9541
+ }
9542
+ const positionof = /* @__PURE__ */ new Map();
9543
+ let position = 0;
9544
+ for (const node of model.nodes) {
9545
+ if (node.step !== void 0) {
9546
+ positionof.set(node.step.id, position);
9547
+ position += 1;
9548
+ continue;
9549
+ }
9550
+ const block = model.blocks.find((entry) => entry.name === node.invocation?.block);
9551
+ if (!block) throw new Error(`The block ${node.invocation?.block ?? ""} of the canvas has no definition.`);
9552
+ const walk = (entries2) => {
9553
+ for (const entry of entries2) {
9554
+ if ("kind" in entry && "label" in entry && !("block" in entry)) {
9555
+ positionof.set(entry.id, position);
9556
+ position += 1;
9557
+ continue;
9558
+ }
9559
+ const nested = model.blocks.find((candidate) => candidate.name === entry.block);
9560
+ if (!nested) throw new Error(`The block ${entry.block} of the canvas has no definition.`);
9561
+ walk(nested.steps);
9562
+ }
9563
+ };
9564
+ walk(block.steps);
9565
+ }
9566
+ for (const edge of model.edges) {
9567
+ if (!positionof.has(edge.from)) throw new Error(`The edge of ${edge.variable} references the unknown source step ${edge.from}.`);
9568
+ if (!positionof.has(edge.to)) throw new Error(`The edge of ${edge.variable} references the unknown target step ${edge.to}.`);
9569
+ if (positionof.get(edge.from) >= positionof.get(edge.to)) throw new Error(`The edge of ${edge.variable} runs backwards from ${edge.from} into ${edge.to} and would form a cycle.`);
9570
+ }
9571
+ const bindingsof = (stepid) => model.edges.filter((edge) => edge.to === stepid).map((edge) => ({ variable: edge.variable, kind: edge.kind, stepid: edge.from, ...edge.path !== void 0 ? { path: edge.path } : {} }));
9572
+ const entries = [];
9573
+ const attached = /* @__PURE__ */ new Map();
9574
+ for (const node of model.nodes) {
9575
+ if (node.invocation !== void 0) {
9576
+ entries.push({ ...node.invocation });
9577
+ continue;
9578
+ }
9579
+ const step = node.step;
9580
+ const bindings = bindingsof(step.id);
9581
+ const { block, params, ...rest } = { ...step, ...bindings.length > 0 ? { bindings } : {} };
9582
+ void params;
9583
+ const carried = rest;
9584
+ if (block !== void 0) {
9585
+ if (!model.blocks.some((candidate) => candidate.name === block)) throw new Error(`The step ${step.id} attaches to the unknown block ${block}.`);
9586
+ const list = attached.get(block) ?? [];
9587
+ list.push(carried);
9588
+ attached.set(block, list);
9589
+ continue;
9590
+ }
9591
+ entries.push(carried);
9592
+ }
9593
+ const blocks = model.blocks.map((block) => {
9594
+ const snapped = attached.get(block.name) ?? [];
9595
+ const snappedids = new Set(snapped.map((step) => step.id));
9596
+ const carried = [];
9597
+ for (const entry of block.steps) {
9598
+ if ("kind" in entry && "label" in entry && !("block" in entry) && snappedids.has(entry.id)) continue;
9599
+ carried.push(entry);
9600
+ }
9601
+ const steps = [...carried, ...snapped];
9602
+ const withbindings = [];
9603
+ for (const entry of steps) {
9604
+ if (!("kind" in entry && "label" in entry && !("block" in entry))) {
9605
+ withbindings.push(entry);
9606
+ continue;
9607
+ }
9608
+ const bindings = bindingsof(entry.id);
9609
+ const { block: inner, params, ...rest } = { ...entry, ...bindings.length > 0 ? { bindings } : {} };
9610
+ void inner;
9611
+ void params;
9612
+ withbindings.push(rest);
9613
+ }
9614
+ return { ...block, steps: withbindings };
9615
+ });
9616
+ const composed = composeworkflow({ id: model.workflowid, name: model.name, version: model.version, origins: [...model.origins], steps: entries, blocks: blocks.map((block) => ({ ...block })), now: input.now, ...input.kindallowed !== void 0 ? { kindallowed: input.kindallowed } : {}, ...input.riskof !== void 0 ? { riskof: input.riskof } : {} });
9617
+ const checked = validateworkflow(composed, input.kindallowed !== void 0 ? { kindallowed: input.kindallowed } : {});
9618
+ if (!checked.allowed) throw new Error(checked.reason ?? "The canvas model failed the workflow grammar.");
9619
+ return composed;
9620
+ }
9621
+ function renderminimap(model, width = 160, height = 100) {
9622
+ if (!Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0) throw new Error("The mini map size must be positive.");
9623
+ const canvaswidth = Math.max(1, model.layout.width);
9624
+ const canvasheight = Math.max(1, model.layout.height);
9625
+ const scale = Math.min(width / canvaswidth, height / canvasheight);
9626
+ const zoom = model.layout.zoom > 0 ? model.layout.zoom : 1;
9627
+ const visiblewidth = canvaswidth / zoom;
9628
+ const visibleheight = canvasheight / zoom;
9629
+ const viewport = {
9630
+ x: Math.max(0, Math.min(model.layout.viewportx, canvaswidth)) * scale,
9631
+ y: Math.max(0, Math.min(model.layout.viewporty, canvasheight)) * scale,
9632
+ width: visiblewidth * scale,
9633
+ height: visibleheight * scale
9634
+ };
9635
+ const nodes = model.nodes.map((node) => ({ id: nodeidof(node), x: node.x * scale, y: node.y * scale }));
9636
+ return { minimap: { width, height, scale, zoom, viewport }, nodes };
9637
+ }
9638
+ function runtobreakpoint(input) {
9639
+ const cursor = input.cursor !== void 0 && Number.isInteger(input.cursor) && input.cursor >= 0 ? input.cursor : 0;
9640
+ const marked = new Set(input.breakpoints);
9641
+ for (let index = cursor; index < input.record.steps.length; index += 1) {
9642
+ const step = input.record.steps[index];
9643
+ if (step.breakpoint === true || marked.has(step.id)) {
9644
+ return { until: index, pausat: step.id, remaining: input.record.steps.length - index };
9645
+ }
9646
+ }
9647
+ return { until: input.record.steps.length, pausat: void 0, remaining: 0 };
9648
+ }
9649
+ function diffversions(from, to, now) {
9650
+ const fromsteps = new Map(from.steps.map((step) => [step.id, step]));
9651
+ const tosteps = new Map(to.steps.map((step) => [step.id, step]));
9652
+ const added = [];
9653
+ const removed = [];
9654
+ const changed = [];
9655
+ for (const step of to.steps) {
9656
+ const prior = fromsteps.get(step.id);
9657
+ if (!prior) {
9658
+ added.push({ stepid: step.id, kind: step.kind, label: step.label });
9659
+ continue;
9660
+ }
9661
+ const changes = [];
9662
+ if (prior.label !== step.label) changes.push("label");
9663
+ if (prior.kind !== step.kind) changes.push("kind");
9664
+ if (prior.target !== step.target) changes.push("target");
9665
+ if (prior.value !== step.value) changes.push("value");
9666
+ if (prior.options !== step.options) changes.push("options");
9667
+ if (JSON.stringify(prior.expression) !== JSON.stringify(step.expression)) changes.push("expression");
9668
+ if (JSON.stringify(prior.extract) !== JSON.stringify(step.extract)) changes.push("extract");
9669
+ if (JSON.stringify(prior.bindings) !== JSON.stringify(step.bindings)) changes.push("bindings");
9670
+ if (changes.length > 0) changed.push({ stepid: step.id, kind: step.kind, label: step.label, changes });
9671
+ }
9672
+ for (const step of from.steps) {
9673
+ if (!tosteps.has(step.id)) removed.push({ stepid: step.id, kind: step.kind, label: step.label });
9674
+ }
9675
+ return { workflowid: to.id, from: from.version, to: to.version, added, removed, changed, at: now };
9676
+ }
9677
+ function exportworkflow(record2, format, note, now) {
9678
+ const file = { format: workflowfileversion, exportedat: now ?? Date.now(), workflow: record2, ...note !== void 0 && note.trim() !== "" ? { note } : {}, templates: [] };
9679
+ return { format, contents: serializefile(file, format), file };
9680
+ }
9681
+ function shareworkflow(record2, templates, format, note, now) {
9682
+ const file = { format: workflowfileversion, exportedat: now ?? Date.now(), workflow: record2, ...note !== void 0 && note.trim() !== "" ? { note } : {}, templates: templates.map((template) => ({ ...template })) };
9683
+ return { format, contents: serializefile(file, format), file };
9684
+ }
9685
+ function importworkflow(input) {
9686
+ const format = input.format ?? (input.contents.trimStart().startsWith("{") ? "json" : "yaml");
9687
+ const parsed = parsefile(input.contents, format);
9688
+ if (parsed.format !== workflowfileversion) throw new Error(`The workflow file format ${String(parsed.format)} is not the reviewed format ${workflowfileversion}.`);
9689
+ const candidate = parsed.workflow;
9690
+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) throw new Error("The workflow file carries no workflow record.");
9691
+ const fields = candidate;
9692
+ const stepsvalue = fields.steps;
9693
+ if (!Array.isArray(stepsvalue) || stepsvalue.length === 0) throw new Error("An imported workflow needs at least one step.");
9694
+ const steps = [];
9695
+ for (const entry of stepsvalue) {
9696
+ const step = workflowstepof(entry);
9697
+ if (step) {
9698
+ steps.push(step);
9699
+ continue;
9700
+ }
9701
+ throw new Error("Every imported workflow entry must be a reviewed step.");
9702
+ }
9703
+ const composed = composeworkflow({
9704
+ id: typeof fields.id === "string" && fields.id.trim() !== "" ? fields.id : crypto.randomUUID(),
9705
+ name: typeof fields.name === "string" ? fields.name : "",
9706
+ version: typeof fields.version === "number" ? fields.version : 1,
9707
+ origins: Array.isArray(fields.origins) ? fields.origins.filter((origin) => typeof origin === "string") : [],
9708
+ steps,
9709
+ now: input.now ?? Date.now(),
9710
+ ...input.kindallowed !== void 0 ? { kindallowed: input.kindallowed } : {},
9711
+ ...input.riskof !== void 0 ? { riskof: input.riskof } : {}
9712
+ });
9713
+ const templatesvalue = parsed.templates;
9714
+ if (templatesvalue !== void 0 && !Array.isArray(templatesvalue)) throw new Error("The packed templates of the workflow file must be a list.");
9715
+ const templates = [];
9716
+ for (const entry of templatesvalue ?? []) {
9717
+ const template = steptemplateof(entry);
9718
+ if (!template) throw new Error("A packed template of the workflow file does not carry one reviewed step.");
9719
+ templates.push(template);
9720
+ }
9721
+ const record2 = { ...composed, reviewstate: "pending" };
9722
+ return { record: record2, templates, file: { ...parsed, workflow: record2 } };
9723
+ }
9724
+ function originmatches(pattern, origin) {
9725
+ if (pattern === origin) return true;
9726
+ const glob = pattern.replace(/\./g, "\\.").replace(/\*/g, "[^.]+");
9727
+ if (!glob.startsWith("https://")) return false;
9728
+ return new RegExp(`^${glob}$`).test(origin);
9729
+ }
9730
+ function applyoverride(record2, override) {
9731
+ const matching = record2.origins.filter((origin) => originmatches(override.pattern, origin));
9732
+ if (matching.length === 0) throw new Error(`The override pattern ${override.pattern} matches none of the workflow origins ${record2.origins.join(", ")}.`);
9733
+ const knobs = /* @__PURE__ */ new Set(["loopbound", "stepms", "runms", "waitms", "delaybase"]);
9734
+ for (const knob of Object.keys(override.deltas)) {
9735
+ if (!knobs.has(knob)) throw new Error(`The override knob ${knob} is not one of the reviewed knobs: ${[...knobs].join(", ")}.`);
9736
+ if (typeof override.deltas[knob] !== "number" || !Number.isFinite(override.deltas[knob]) || override.deltas[knob] <= 0) throw new Error(`The override delta of ${knob} must be a positive number with no code ceiling.`);
9737
+ }
9738
+ const apply = (step) => {
9739
+ if (Object.keys(override.deltas).length === 0) return step;
9740
+ let payload = {};
9741
+ try {
9742
+ payload = step.options !== void 0 ? JSON.parse(step.options) : {};
9743
+ } catch {
9744
+ payload = {};
9745
+ }
9746
+ const bodyof = (key) => payload[key] !== void 0 && typeof payload[key] === "object" && !Array.isArray(payload[key]) ? payload[key] : {};
9747
+ if (override.deltas.loopbound !== void 0 && ["loop", "repeatuntil", "whileloop"].includes(step.kind)) {
9748
+ const body = bodyof(step.kind);
9749
+ body.bound = override.deltas.loopbound;
9750
+ payload[step.kind] = body;
9751
+ }
9752
+ if ((override.deltas.stepms !== void 0 || override.deltas.runms !== void 0) && step.kind === "trycatch") {
9753
+ const body = bodyof("trycatch");
9754
+ const timeout = body.timeout !== void 0 && typeof body.timeout === "object" && !Array.isArray(body.timeout) ? body.timeout : {};
9755
+ if (override.deltas.stepms !== void 0) timeout.stepms = override.deltas.stepms;
9756
+ if (override.deltas.runms !== void 0) timeout.runms = override.deltas.runms;
9757
+ body.timeout = timeout;
9758
+ payload.trycatch = body;
9759
+ }
9760
+ if (override.deltas.waitms !== void 0 && step.kind === "waitelement") {
9761
+ payload.timeout = override.deltas.waitms;
9762
+ }
9763
+ if (override.deltas.delaybase !== void 0 && step.kind === "delay") {
9764
+ payload.base = override.deltas.delaybase;
9765
+ }
9766
+ const changed = Object.keys(payload).length > 0;
9767
+ return changed ? { ...step, options: JSON.stringify(payload) } : step;
9768
+ };
9769
+ return { ...record2, steps: record2.steps.map(apply) };
9770
+ }
9771
+ function serializefile(file, format) {
9772
+ if (format === "json") return JSON.stringify(file, null, 2);
9773
+ return yamlvalue(file, 0).join("\n") + "\n";
9774
+ }
9775
+ function parsefile(contents, format) {
9776
+ if (format === "json") {
9777
+ const parsed = JSON.parse(contents);
9778
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("The workflow file is not a json object.");
9779
+ return parsed;
9780
+ }
9781
+ const lines = contents.split(/\r?\n/).map((line) => line.replace(/\t/g, " ")).filter((line) => line.trim() !== "" && !line.trim().startsWith("#"));
9782
+ if (lines.length === 0) throw new Error("The yaml workflow file is empty.");
9783
+ const { value, next } = yamlblock(lines, 0, indentof(lines[0]));
9784
+ if (next < lines.length) throw new Error("The yaml workflow file carries content outside the documented subset.");
9785
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("The yaml workflow file is not a mapping.");
9786
+ return value;
9787
+ }
9788
+ function indentof(line) {
9789
+ const match = /^ */.exec(line);
9790
+ return match ? match[0].length : 0;
9791
+ }
9792
+ function yamlscalar(value) {
9793
+ if (value === null || value === void 0) return "null";
9794
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
9795
+ return JSON.stringify(String(value));
9796
+ }
9797
+ function yamlvalue(value, indent) {
9798
+ const pad = " ".repeat(indent);
9799
+ if (value === null || value === void 0 || typeof value !== "object") return [`${pad}${yamlscalar(value)}`];
9800
+ if (Array.isArray(value)) {
9801
+ if (value.length === 0) return [`${pad}[]`];
9802
+ const lines2 = [];
9803
+ for (const item of value) {
9804
+ if (item !== null && typeof item === "object") {
9805
+ lines2.push(`${pad}-`);
9806
+ lines2.push(...yamlvalue(item, indent + 2));
9807
+ } else {
9808
+ lines2.push(`${pad}- ${yamlscalar(item)}`);
9809
+ }
9810
+ }
9811
+ return lines2;
9812
+ }
9813
+ const entries = Object.entries(value);
9814
+ if (entries.length === 0) return [`${pad}{}`];
9815
+ const lines = [];
9816
+ for (const [key, entry] of entries) {
9817
+ if (entry !== null && typeof entry === "object") {
9818
+ if (Array.isArray(entry) && entry.length === 0) {
9819
+ lines.push(`${pad}${key}: []`);
9820
+ continue;
9821
+ }
9822
+ if (!Array.isArray(entry) && Object.keys(entry).length === 0) {
9823
+ lines.push(`${pad}${key}: {}`);
9824
+ continue;
9825
+ }
9826
+ lines.push(`${pad}${key}:`);
9827
+ lines.push(...yamlvalue(entry, indent + 2));
9828
+ } else {
9829
+ lines.push(`${pad}${key}: ${yamlscalar(entry)}`);
9830
+ }
9831
+ }
9832
+ return lines;
9833
+ }
9834
+ function yamlblock(lines, start, indent) {
9835
+ const first = lines[start];
9836
+ if (/^\s*-\s/.test(first) || /^\s*-$/.test(first)) {
9837
+ const items = [];
9838
+ let index2 = start;
9839
+ while (index2 < lines.length) {
9840
+ const line = lines[index2];
9841
+ if (indentof(line) !== indent || !/^\s*-\s?/.test(line)) break;
9842
+ const rest = line.slice(indent + 1).trim();
9843
+ if (rest !== "") {
9844
+ items.push(yamlscalarvalue(rest));
9845
+ index2 += 1;
9846
+ continue;
9847
+ }
9848
+ const nested = yamlblock(lines, index2 + 1, indent + 2);
9849
+ items.push(nested.value);
9850
+ index2 = nested.next;
9851
+ }
9852
+ return { value: items, next: index2 };
9853
+ }
9854
+ const mapping = {};
9855
+ let index = start;
9856
+ while (index < lines.length) {
9857
+ const line = lines[index];
9858
+ if (indentof(line) !== indent) break;
9859
+ const match = /^([A-Za-z][A-Za-z0-9]*):(?:\s(.*))?$/.exec(line.slice(indent));
9860
+ if (!match) break;
9861
+ const key = match[1];
9862
+ const rest = match[2];
9863
+ if (rest !== void 0 && rest !== "") {
9864
+ if (rest === "[]") {
9865
+ mapping[key] = [];
9866
+ index += 1;
9867
+ continue;
9868
+ }
9869
+ if (rest === "{}") {
9870
+ mapping[key] = {};
9871
+ index += 1;
9872
+ continue;
9873
+ }
9874
+ mapping[key] = yamlscalarvalue(rest);
9875
+ index += 1;
9876
+ continue;
9877
+ }
9878
+ const nested = yamlblock(lines, index + 1, indent + 2);
9879
+ mapping[key] = nested.value;
9880
+ index = nested.next;
9881
+ }
9882
+ if (index === start) throw new Error("The yaml workflow file left the documented subset.");
9883
+ return { value: mapping, next: index };
9884
+ }
9885
+ function yamlscalarvalue(text2) {
9886
+ if (text2.startsWith('"')) {
9887
+ const parsed = JSON.parse(text2);
9888
+ return typeof parsed === "string" ? parsed : text2;
9889
+ }
9890
+ if (text2 === "true") return true;
9891
+ if (text2 === "false") return false;
9892
+ if (text2 === "null") return null;
9893
+ if (/^-?\d+(?:\.\d+)?$/.test(text2)) return Number(text2);
9894
+ return text2;
9895
+ }
9896
+
9104
9897
  // extension/pagesession.ts
9105
9898
  function capturepagestate(sections) {
9106
9899
  const wants = (section) => sections.includes(section);
@@ -14853,12 +15646,24 @@ function workflowstepofentry(value) {
14853
15646
  async function executeworkflowrun(step, session, plan, tabid2, origin, dry) {
14854
15647
  const options = stepoptions2(step);
14855
15648
  const workflowid = typeof options.workflowid === "string" ? options.workflowid : "";
14856
- const record2 = await memory.getworkflowrecord(workflowid);
14857
- if (!record2) throw new Error(`No composed workflow matches ${workflowid || "the reviewed id"}.`);
14858
- for (const workfloworigin of record2.origins) {
15649
+ const storedrecord = await memory.getworkflowrecord(workflowid);
15650
+ if (!storedrecord) throw new Error(`No composed workflow matches ${workflowid || "the reviewed id"}.`);
15651
+ for (const workfloworigin of storedrecord.origins) {
14859
15652
  if (!origingranted(session, workfloworigin)) throw new Error(`The workflow origin ${workfloworigin} falls outside the session grants.`);
14860
15653
  }
14861
- const run = newworkflowrun({ workflowid: record2.id, dryrun: dry, now: Date.now() });
15654
+ const reviewgate = runreviewgranted(storedrecord);
15655
+ if (!reviewgate.allowed) throw new Error(reviewgate.reason ?? "The workflow stays unreviewed until its import or rollback review approves the expanded step list.");
15656
+ let record2 = storedrecord;
15657
+ for (const override of await memory.listsiteoverrides(storedrecord.id)) {
15658
+ try {
15659
+ record2 = applyoverride(record2, override);
15660
+ await audit("workflow", `Applied the per site override ${override.id} of the pattern ${override.pattern} to the workflow ${record2.name}: ${Object.entries(override.deltas).map(([knob, delta]) => `${knob} ${delta}`).join(", ") || "no delta"}.`, { sessionid: session.id, planid: plan.id, stepid: step.id });
15661
+ } catch (error) {
15662
+ await audit("workflow", `Skipped the per site override ${override.id} of the pattern ${override.pattern} for the workflow ${storedrecord.name}: ${error instanceof Error ? error.message : String(error)}.`, { sessionid: session.id, planid: plan.id, stepid: step.id });
15663
+ }
15664
+ }
15665
+ const backgroundflag = (await memory.getbackgroundruns())[record2.id] === true || options.background === true;
15666
+ const run = { ...newworkflowrun({ workflowid: record2.id, dryrun: dry, now: Date.now() }), ...backgroundflag === true && !dry ? { background: true } : {} };
14862
15667
  await memory.setworkflowrun(run);
14863
15668
  await memory.setrunscopes(run.id, runscopes(options.variables));
14864
15669
  if (dry) {
@@ -14870,6 +15675,30 @@ async function executeworkflowrun(step, session, plan, tabid2, origin, dry) {
14870
15675
  await audit("workflow", `The dry run of the workflow ${record2.name} evaluated ${evaluated.log.length} step${evaluated.log.length === 1 ? "" : "s"} read only; ${refused} step${refused === 1 ? "" : "s"} refused for lacking a read only projection and nothing was mutated.`, { sessionid: session.id, planid: plan.id, stepid: step.id });
14871
15676
  return { ok: true, summary: `The dry run evaluated ${evaluated.log.length} steps read only; ${refused} refused for lacking a read only projection.`, details: { runid: run.id, state: evaluated.run.state, dryrun: true, executed: evaluated.log.length - refused, refused, total: record2.steps.length } };
14872
15677
  }
15678
+ if (run.background === true) {
15679
+ await audit("workflow", `Started the background run ${run.id} of the workflow ${record2.name} version ${record2.version} with ${record2.steps.length} reviewed steps; the panel may close, every step checkpoints and the worker wake restores the run through the same gates.`, { sessionid: session.id, planid: plan.id, stepid: step.id });
15680
+ void performworkflowrun({ record: record2, run, step, session, plan, tabid: tabid2, origin, options, dry }).catch(async (error) => {
15681
+ const reason = error instanceof Error ? error.message : String(error);
15682
+ await memory.setworkflowrun({ ...run, state: "failed", endedat: Date.now(), failreason: reason });
15683
+ await memory.addrunhistory({ runid: run.id, workflowid: record2.id, outcome: "failed", steps: run.cursor, total: record2.steps.length, duration: Date.now() - run.startedat, cause: runcauseof(options), startedat: run.startedat, endedat: Date.now() });
15684
+ await audit("error", `The background run ${run.id} of the workflow ${record2.name} failed: ${reason}.`, { sessionid: session.id, planid: plan.id, stepid: step.id });
15685
+ await refreshbadge().catch(() => {
15686
+ });
15687
+ });
15688
+ return { ok: true, summary: `The workflow run ${run.id} started in the background with ${record2.steps.length} reviewed steps and the panel may close; the checkpoints restore it on every worker wake.`, details: { runid: run.id, state: "running", background: true, executed: 0, total: record2.steps.length } };
15689
+ }
15690
+ return await performworkflowrun({ record: record2, run, step, session, plan, tabid: tabid2, origin, options, dry });
15691
+ }
15692
+ function runcauseof(options) {
15693
+ const variables = options.variables;
15694
+ if (variables !== null && typeof variables === "object" && !Array.isArray(variables)) {
15695
+ const cause = variables.triggercause;
15696
+ if (typeof cause === "string" && cause.trim() !== "") return cause;
15697
+ }
15698
+ return "manual";
15699
+ }
15700
+ async function performworkflowrun(input) {
15701
+ const { record: record2, run, step, session, plan, tabid: tabid2, origin, options, dry } = input;
14873
15702
  const guards = { cancelled: false };
14874
15703
  activeworkflowruns.set(run.id, guards);
14875
15704
  await audit("workflow", `Started the run ${run.id} of the workflow ${record2.name} version ${record2.version} with ${record2.steps.length} reviewed steps; every step passes the session, plan review and origin gates.`, { sessionid: session.id, planid: plan.id, stepid: step.id });
@@ -14951,6 +15780,8 @@ async function executeworkflowrun(step, session, plan, tabid2, origin, dry) {
14951
15780
  }
14952
15781
  const executed = result.run.cursor;
14953
15782
  await memory.setprogress(recordworkflow(await memory.getprogress(), plan.id, step.id, { family: "run", detail: `Ran the workflow ${record2.name}`, runid: run.id, executed, total: record2.steps.length }, Date.now()));
15783
+ const endedat = result.run.endedat ?? Date.now();
15784
+ await memory.addrunhistory({ runid: run.id, workflowid: record2.id, outcome: result.run.state, steps: executed, total: record2.steps.length, duration: Math.max(0, endedat - run.startedat), cause: runcauseof(options), startedat: run.startedat, endedat, ...dry === true ? { dryrun: true } : {} });
14954
15785
  await audit("workflow", `The run ${run.id} of the workflow ${record2.name} ended ${result.run.state} after ${executed} of ${record2.steps.length} steps${result.run.failreason !== void 0 ? ` with the failure ${result.run.failreason}` : ""}.`, { sessionid: session.id, planid: plan.id, stepid: step.id });
14955
15786
  await refreshbadge();
14956
15787
  return { ok: result.run.state === "done", summary: `The workflow run ended ${result.run.state} after ${executed} of ${record2.steps.length} steps.`, details: { runid: run.id, state: result.run.state, executed, total: record2.steps.length, ...result.run.failreason !== void 0 ? { failreason: result.run.failreason } : {} } };
@@ -15506,7 +16337,7 @@ async function handlerequest(message, sender) {
15506
16337
  const livetab = session ? await chrome.tabs.get(session.tabid).catch(() => void 0) : void 0;
15507
16338
  const waitprofile = session ? waitprofiles.find((record2) => record2.origin === session.origin) : void 0;
15508
16339
  const livestate = { phase: livetab?.status === "loading" ? "loading" : "complete", ...navrecords[0] ? { finalurl: navrecords[0].finalurl, redirects: navrecords[0].chain } : {} };
15509
- return { config: await memory.getconfig(), session, plan, progress: plan && progress?.planid === plan.id ? progress : void 0, diagnostic: await memory.getdiagnostic(), audit: await memory.getaudit(), capabilities: await refreshcapabilities(), outcomes: await memory.getoutcomes(), holds: heldkeysreport({ tabid: session?.tabid ?? 0, holds }), dialogs: await memory.getdialogs(), retries: await memory.getretries(), ...signals ? { signals: signalsreport({ signals }) } : { signals: signalsreport({}) }, banners: await memory.getbanners(), mutationevents: await memory.getmutationevents(), focusevents: await memory.getfocusevents(), diffs: await memory.getdiffs(), selectors: await memory.getselectors(), ...a11y ? { a11y } : {}, ...reader ? { reader } : {}, ...map ? { map } : {}, trail: trailreport({ ...session ? { sessionid: session.id } : {}, trail }), navrecords, ratestates, safeties, curated, waitprofiles, auths, navcontrol, navqueues, artifacts, navstate: livestate, ...waitprofile ? { waitprofile } : {}, offline: !navigator.onLine, tabs, windows, layouts: layoutreport({ layouts }), tabgroups, tabmetas, badges, snapshots, closedtabs, tabwatchevents, clones, tasktabgauge: taskgauge, ...controltab ? { controltab } : {}, tabreport: report, profiles, tickets, wizards: wizardreport({ ...session ? { sessionid: session.id } : {}, wizards, picks }), picks, errorreports, captchas, detections, ...codeentry !== void 0 ? { codeentry: true } : {}, datasets, imports, extractsessions, streams, exports, provenances, taskrules, sheetendpoints: sheetgrants, downloads, netlogs, clipconsents, clips, quarantines, cleanuprules, cleanupruns, capturecounters, inventory, mimefilters, scanhooks, captures: capturemetadata, capturepairs, capturepolicy: runsettings?.capturepolicy ?? "manual", media: mediarecords, imagebatches, recordingconsents, recordingactive: [...activerecordings.values()].map((active) => ({ id: active.record.id, kind: active.record.kind, scope: active.record.scope, startedat: active.record.startedat, stopat: active.stopat })), recordingwindow: runsettings?.recordingwindow, calls, endpoints, fetchconsents, apikeys, callretention: runsettings?.callretention, fetchesactive: activefetches.size, exchanges, channels, subscriptions, apimap, messages: messagecount, webrequestgrant: runsettings?.webrequestgrant === true, bodyretention: runsettings?.bodyretention, timelineretention: runsettings?.timelineretention, timeline, consoleconsents: await memory.getconsoleconsents(), rotationtargets: await memory.getrotationtargets(), levelsummaries: await memory.getlevelsummaries(), cdpsessions: await memory.getcdpsessions(), cdpcommands: await memory.getcdpcommands(), cdpeventrules: await memory.getcdpeventrules(), breakpoints: await memory.getbreakpoints(), pauses: await memory.getpauses(), watchexpressions: await memory.getwatchexpressions(), scriptoverrides: await memory.getscriptoverrides(), debuggergrants: await memory.getdebuggergrants(), pauseretention: runsettings?.pauseretention, breakpointceiling: runsettings?.breakpointceiling, cdpattached: [...activecdpsessions.values()].filter((active) => active.session.detachedat === void 0).length, profileretention: runsettings?.profileretention, traceceiling: runsettings?.traceceiling, profile: profilereport({ flows: await memory.getflowmetrics(), heaps: await memory.getheaprecords(), samples: await memory.getgrowsamples(), trends: await memory.gettrends(), profiles: await memory.getcpuprofiles(), shifts: await memory.getshiftentries(), traces: await memory.gettracerecords(), sourcemaps: await memory.getsourcemaps(), consents: await memory.getsourcemapconsents() }), profileactive: activememorytrackers.size + activeprofiletargets.size, profiletargets: [...activeprofiletargets.values()].flatMap((entry) => entry.targets), socketsactive: activesockets.size, emulation: emulationreport({ ...plan && await loademulationstate(plan.id) !== void 0 ? { state: await loademulationstate(plan.id) } : {}, devices: await memory.getdevicepresets(), networks: await memory.getnetworkpresets(), locations: await memory.getlocationpresets(), agents: await memory.getagentpresets(), blackbox: await memory.getblackboxrules(), permissions: await memory.getpermissionoverrides(), consents: await memory.getlocationconsents() }), emulatedlayers: plan ? layernames(await loademulationstate(plan.id)) : [], emulationretention: runsettings?.emulationretention, traffic, tokens, authflows, activerules: [...activerules.values()].reduce((total, ruleset) => total + ruleset.blocks.filter((rule) => rule.revertedat === void 0).length + ruleset.mocks.filter((rule) => rule.revertedat === void 0).length + ruleset.rewrites.filter((rule) => rule.revertedat === void 0).length + (ruleset.proxy !== void 0 && ruleset.proxy.revertedat === void 0 ? 1 : 0), 0), sessionmemory: sessionreport({ records: sessionrecords, events: await memory.getsessionevents(), folders: await memory.getsessionfolders(), diffs: await memory.getsessiondiffs(), ...autosnapshot !== void 0 ? { auto: autosnapshot.interval } : {}, ...crashed ? { crashed: true } : {} }), autosnapshotstate: autosnapshot, sessionretention: runsettings?.sessionretention, trigger: triggerlist({ rules: await memory.gettriggerules(), workflows: await memory.listworkflows(), queue: await memory.gettriggerqueue() }), triggerretention: runsettings?.triggerretention, workflow: workflowreport({ workflows: await memory.listworkflows(), runs: await memory.listworkflowruns(), templates: await memory.getsteptemplates(), ...newestworkflowrun !== void 0 ? { log: await memory.getrunlog(newestworkflowrun.id), scopes: await memory.getrunscopes(newestworkflowrun.id), provenance: await memory.getworkflowprovenance(newestworkflowrun.id), control: await memory.listcontroldecisions(newestworkflowrun.id) } : {} }), runlogretention: runsettings?.runlogretention, ...taskstate !== void 0 ? { taskstate } : {}, ...stitchprogress.size > 0 ? { stitchprogress: [...stitchprogress.values()] } : {} };
16340
+ return { config: await memory.getconfig(), session, plan, progress: plan && progress?.planid === plan.id ? progress : void 0, diagnostic: await memory.getdiagnostic(), audit: await memory.getaudit(), capabilities: await refreshcapabilities(), outcomes: await memory.getoutcomes(), holds: heldkeysreport({ tabid: session?.tabid ?? 0, holds }), dialogs: await memory.getdialogs(), retries: await memory.getretries(), ...signals ? { signals: signalsreport({ signals }) } : { signals: signalsreport({}) }, banners: await memory.getbanners(), mutationevents: await memory.getmutationevents(), focusevents: await memory.getfocusevents(), diffs: await memory.getdiffs(), selectors: await memory.getselectors(), ...a11y ? { a11y } : {}, ...reader ? { reader } : {}, ...map ? { map } : {}, trail: trailreport({ ...session ? { sessionid: session.id } : {}, trail }), navrecords, ratestates, safeties, curated, waitprofiles, auths, navcontrol, navqueues, artifacts, navstate: livestate, ...waitprofile ? { waitprofile } : {}, offline: !navigator.onLine, tabs, windows, layouts: layoutreport({ layouts }), tabgroups, tabmetas, badges, snapshots, closedtabs, tabwatchevents, clones, tasktabgauge: taskgauge, ...controltab ? { controltab } : {}, tabreport: report, profiles, tickets, wizards: wizardreport({ ...session ? { sessionid: session.id } : {}, wizards, picks }), picks, errorreports, captchas, detections, ...codeentry !== void 0 ? { codeentry: true } : {}, datasets, imports, extractsessions, streams, exports, provenances, taskrules, sheetendpoints: sheetgrants, downloads, netlogs, clipconsents, clips, quarantines, cleanuprules, cleanupruns, capturecounters, inventory, mimefilters, scanhooks, captures: capturemetadata, capturepairs, capturepolicy: runsettings?.capturepolicy ?? "manual", media: mediarecords, imagebatches, recordingconsents, recordingactive: [...activerecordings.values()].map((active) => ({ id: active.record.id, kind: active.record.kind, scope: active.record.scope, startedat: active.record.startedat, stopat: active.stopat })), recordingwindow: runsettings?.recordingwindow, calls, endpoints, fetchconsents, apikeys, callretention: runsettings?.callretention, fetchesactive: activefetches.size, exchanges, channels, subscriptions, apimap, messages: messagecount, webrequestgrant: runsettings?.webrequestgrant === true, bodyretention: runsettings?.bodyretention, timelineretention: runsettings?.timelineretention, timeline, consoleconsents: await memory.getconsoleconsents(), rotationtargets: await memory.getrotationtargets(), levelsummaries: await memory.getlevelsummaries(), cdpsessions: await memory.getcdpsessions(), cdpcommands: await memory.getcdpcommands(), cdpeventrules: await memory.getcdpeventrules(), breakpoints: await memory.getbreakpoints(), pauses: await memory.getpauses(), watchexpressions: await memory.getwatchexpressions(), scriptoverrides: await memory.getscriptoverrides(), debuggergrants: await memory.getdebuggergrants(), pauseretention: runsettings?.pauseretention, breakpointceiling: runsettings?.breakpointceiling, cdpattached: [...activecdpsessions.values()].filter((active) => active.session.detachedat === void 0).length, profileretention: runsettings?.profileretention, traceceiling: runsettings?.traceceiling, profile: profilereport({ flows: await memory.getflowmetrics(), heaps: await memory.getheaprecords(), samples: await memory.getgrowsamples(), trends: await memory.gettrends(), profiles: await memory.getcpuprofiles(), shifts: await memory.getshiftentries(), traces: await memory.gettracerecords(), sourcemaps: await memory.getsourcemaps(), consents: await memory.getsourcemapconsents() }), profileactive: activememorytrackers.size + activeprofiletargets.size, profiletargets: [...activeprofiletargets.values()].flatMap((entry) => entry.targets), socketsactive: activesockets.size, emulation: emulationreport({ ...plan && await loademulationstate(plan.id) !== void 0 ? { state: await loademulationstate(plan.id) } : {}, devices: await memory.getdevicepresets(), networks: await memory.getnetworkpresets(), locations: await memory.getlocationpresets(), agents: await memory.getagentpresets(), blackbox: await memory.getblackboxrules(), permissions: await memory.getpermissionoverrides(), consents: await memory.getlocationconsents() }), emulatedlayers: plan ? layernames(await loademulationstate(plan.id)) : [], emulationretention: runsettings?.emulationretention, traffic, tokens, authflows, activerules: [...activerules.values()].reduce((total, ruleset) => total + ruleset.blocks.filter((rule) => rule.revertedat === void 0).length + ruleset.mocks.filter((rule) => rule.revertedat === void 0).length + ruleset.rewrites.filter((rule) => rule.revertedat === void 0).length + (ruleset.proxy !== void 0 && ruleset.proxy.revertedat === void 0 ? 1 : 0), 0), sessionmemory: sessionreport({ records: sessionrecords, events: await memory.getsessionevents(), folders: await memory.getsessionfolders(), diffs: await memory.getsessiondiffs(), ...autosnapshot !== void 0 ? { auto: autosnapshot.interval } : {}, ...crashed ? { crashed: true } : {} }), autosnapshotstate: autosnapshot, sessionretention: runsettings?.sessionretention, trigger: triggerlist({ rules: await memory.gettriggerules(), workflows: await memory.listworkflows(), queue: await memory.gettriggerqueue() }), triggerretention: runsettings?.triggerretention, workflow: workflowreport({ workflows: await memory.listworkflows(), runs: await memory.listworkflowruns(), templates: await memory.getsteptemplates(), ...newestworkflowrun !== void 0 ? { log: await memory.getrunlog(newestworkflowrun.id), scopes: await memory.getrunscopes(newestworkflowrun.id), provenance: await memory.getworkflowprovenance(newestworkflowrun.id), control: await memory.listcontroldecisions(newestworkflowrun.id) } : {} }), runlogretention: runsettings?.runlogretention, runhistoryretention: runsettings?.runhistoryretention, editor: editorstate({ versions: await memory.listworkflowversions(), diffs: await memory.listversiondiffs(), history: await memory.gethistory(), overrides: await memory.listsiteoverrides(), imports: (await memory.listworkflowimports()).map((entry) => ({ id: entry.id, workflowid: entry.record.id, name: entry.record.name, version: entry.record.version, steps: entry.record.steps.length, risk: entry.record.risk, importedat: entry.importedat, ...entry.filename !== void 0 ? { filename: entry.filename } : {} })), backgroundruns: await memory.getbackgroundruns(), watchdog: { ...runsettings?.watchdog !== void 0 ? { config: runsettings.watchdog } : {}, events: await memory.listwatchdogevents() } }), ...taskstate !== void 0 ? { taskstate } : {}, ...stitchprogress.size > 0 ? { stitchprogress: [...stitchprogress.values()] } : {} };
15510
16341
  }
15511
16342
  case "capabilities":
15512
16343
  return refreshcapabilities();
@@ -16728,8 +17559,13 @@ async function handlerequest(message, sender) {
16728
17559
  if (!session || session.stoppedat || session.expiresat <= Date.now()) throw new Error("Workflow runs need an active browser session behind the consent gates.");
16729
17560
  const record2 = await memory.getworkflowrecord(inputapprove.workflowid?.trim() ?? "");
16730
17561
  if (!record2) throw new Error(`No composed workflow matches ${inputapprove.workflowid ?? ""}.`);
16731
- await audit("workflow", `The user approved the run review of the workflow ${record2.name} version ${record2.version} with its ${record2.steps.length} expanded step${record2.steps.length === 1 ? "" : "s"} shown; the run still passes every consent gate per step.`, { sessionid: session.id });
16732
- return { approved: true, steps: record2.steps.length, risk: record2.risk };
17562
+ if (record2.reviewstate === "pending") {
17563
+ await memory.addworkflowrecord({ ...record2, reviewstate: "approved" });
17564
+ await memory.removeworkflowversion(record2.id, record2.version).catch(() => {
17565
+ });
17566
+ }
17567
+ await audit("workflow", `The user approved the run review of the workflow ${record2.name} version ${record2.version} with its ${record2.steps.length} expanded step${record2.steps.length === 1 ? "" : "s"} shown${record2.reviewstate === "pending" ? "; the pending import or rollback review cleared and the workflow may run again" : ""}; the run still passes every consent gate per step.`, { sessionid: session.id });
17568
+ return { approved: true, steps: record2.steps.length, risk: record2.risk, ...record2.reviewstate === "pending" ? { reviewstate: "approved" } : {} };
16733
17569
  }
16734
17570
  case "executeworkflowstep": {
16735
17571
  const inputsingle = message;
@@ -16775,8 +17611,8 @@ async function handlerequest(message, sender) {
16775
17611
  const guards = activeworkflowruns.get(stored.id);
16776
17612
  if (guards) guards.cancelled = true;
16777
17613
  const paused = pauserun(stored, Date.now());
16778
- await memory.setworkflowrun(paused);
16779
- await audit("workflow", `Paused the workflow run ${paused.id} at the checkpoint of step cursor ${paused.cursor}; the resume continues exactly there.`, {});
17614
+ await memory.setworkflowrun({ ...paused, pausekind: "user" });
17615
+ await audit("workflow", `Paused the workflow run ${paused.id} at the checkpoint of step cursor ${paused.cursor}; the resume continues exactly there and the worker wake never auto-resumes a user pause.`, {});
16780
17616
  await refreshbadge();
16781
17617
  return { runid: paused.id, state: paused.state, cursor: paused.cursor };
16782
17618
  }
@@ -16801,6 +17637,27 @@ async function handlerequest(message, sender) {
16801
17637
  }
16802
17638
  return await dispatchworkflowstep(dispatched, { session, plan, tabid: tab.id, origin });
16803
17639
  };
17640
+ const debugbreakpoints = Array.isArray(message.breakpoints) ? message.breakpoints.filter((id) => typeof id === "string") : void 0;
17641
+ if (debugbreakpoints !== void 0) {
17642
+ const startcursor = stored.run.cursor;
17643
+ let segment = runtobreakpoint({ record: record2, cursor: startcursor, breakpoints: debugbreakpoints });
17644
+ if (segment.until === startcursor && startcursor < record2.steps.length) segment = runtobreakpoint({ record: record2, cursor: startcursor + 1, breakpoints: debugbreakpoints });
17645
+ if (segment.until === startcursor) {
17646
+ await memory.setworkflowrun({ ...stored.run, state: "paused", pausedat: Date.now(), cursor: startcursor });
17647
+ return { runid: stored.run.id, state: "paused", cursor: startcursor, ...segment.pausat !== void 0 ? { pausat: segment.pausat } : {}, remaining: segment.remaining };
17648
+ }
17649
+ const segmentresult = await runworkflowsegment({ record: record2, run: stored.run, startcursor, until: segment.until, session, plan, tabid: tab.id, origin, scopes, log, storedentries, execute: executeresume });
17650
+ if (segmentresult.failed !== void 0) {
17651
+ await memory.setworkflowrun({ ...stored.run, state: "failed", endedat: Date.now(), cursor: segmentresult.run.cursor, failreason: segmentresult.failed });
17652
+ await audit("workflow", `The debug resume of the run ${stored.run.id} failed at step cursor ${segmentresult.run.cursor}: ${segmentresult.failed}.`, { sessionid: session.id, planid: plan.id });
17653
+ await refreshbadge();
17654
+ return { runid: stored.run.id, state: "failed", cursor: segmentresult.run.cursor, failreason: segmentresult.failed };
17655
+ }
17656
+ await memory.setworkflowrun({ ...stored.run, state: "paused", pausedat: Date.now(), cursor: segment.until });
17657
+ await audit("workflow", `The debug resume of the run ${stored.run.id} ran ${segment.until - startcursor} step${segment.until - startcursor === 1 ? "" : "s"} and paused at the breakpoint ${segment.pausat ?? "end"} of step cursor ${segment.until}; ${segment.remaining} step${segment.remaining === 1 ? "" : "s"} remain.`, { sessionid: session.id, planid: plan.id });
17658
+ await refreshbadge();
17659
+ return { runid: stored.run.id, state: "paused", cursor: segment.until, ...segment.pausat !== void 0 ? { pausat: segment.pausat } : {}, remaining: segment.remaining };
17660
+ }
16804
17661
  const resumed = await runworkflow({ record: record2, run: stored.run, scopes, log, execute: executeresume, now: Date.now(), gates: { sessionactive: Boolean(session && !session.stoppedat && !session.pausedat && session.expiresat > Date.now()), planapproved: plan.state === "approved", origingranted: (workfloworigin) => origingranted(session, workfloworigin) }, oncheckpoint: async (state) => {
16805
17662
  await memory.setworkflowrun(state.run);
16806
17663
  for (const entry of state.log.slice(storedentries)) await memory.addrunlogentry(state.run.id, entry);
@@ -17018,10 +17875,369 @@ async function handlerequest(message, sender) {
17018
17875
  const fires = await memory.listtriggerfires();
17019
17876
  return triggerlist({ rules: await memory.gettriggerules(), workflows: await memory.listworkflows(), queue: await memory.gettriggerqueue() });
17020
17877
  }
17878
+ case "runtobreakpoint": {
17879
+ const inputdebug = message;
17880
+ const session = await memory.getsession();
17881
+ const plan = await memory.getplan();
17882
+ if (!session || session.stoppedat || session.pausedat || session.expiresat <= Date.now()) throw new Error("Debug runs need a live, unpaused browser session behind the consent gates.");
17883
+ if (!plan || plan.state !== "approved") throw new Error("Debug runs need the approved plan review.");
17884
+ const record2 = await memory.getworkflowrecord(inputdebug.workflowid?.trim() ?? "");
17885
+ if (!record2) throw new Error(`No composed workflow matches ${inputdebug.workflowid ?? ""}.`);
17886
+ for (const workfloworigin of record2.origins) {
17887
+ if (!origingranted(session, workfloworigin)) throw new Error(`The workflow origin ${workfloworigin} falls outside the session grants.`);
17888
+ }
17889
+ const reviewgate = runreviewgranted(record2);
17890
+ if (!reviewgate.allowed) throw new Error(reviewgate.reason ?? "The workflow stays unreviewed until its import or rollback review approves the expanded step list.");
17891
+ const marked = [.../* @__PURE__ */ new Set([...await memory.getworkflowbreakpoints(record2.id), ...record2.steps.filter((step) => step.breakpoint === true).map((step) => step.id)])];
17892
+ const segment = runtobreakpoint({ record: record2, cursor: 0, breakpoints: marked });
17893
+ if (segment.pausat === void 0) throw new Error("No breakpoint marks any step of the workflow; mark one on the canvas before the debug run starts.");
17894
+ const run = newworkflowrun({ workflowid: record2.id, now: Date.now() });
17895
+ await memory.setworkflowrun(run);
17896
+ await memory.setrunscopes(run.id, []);
17897
+ if (segment.until === 0) {
17898
+ await memory.setworkflowrun({ ...run, state: "paused", pausedat: Date.now(), cursor: 0 });
17899
+ await audit("workflow", `The debug run ${run.id} of the workflow ${record2.name} paused at the first breakpoint ${segment.pausat} before any step ran; ${record2.steps.length} step${record2.steps.length === 1 ? "" : "s"} remain.`, { sessionid: session.id, planid: plan.id });
17900
+ await refreshbadge();
17901
+ return { runid: run.id, state: "paused", cursor: 0, pausat: segment.pausat, remaining: record2.steps.length };
17902
+ }
17903
+ const { tab, origin } = await activecontext();
17904
+ const executedebug = async (dispatched, stepcontext) => {
17905
+ if (iscontrolflowkind(dispatched.kind)) {
17906
+ const controlled = await runcontrolstep({ step: dispatched, scopes: stepcontext.scopes, outputs: stepcontext.outputs ?? {}, execute: executedebug, now: Date.now(), runid: run.id, pagestate: await pagestateof(tab.id), resolveelements: async (selector) => await resolveelements(tab.id, selector) });
17907
+ return { ...controlled.output, scopes: controlled.scopes, log: controlled.log };
17908
+ }
17909
+ return await dispatchworkflowstep(dispatched, { session, plan, tabid: tab.id, origin });
17910
+ };
17911
+ const segmentresult = await runworkflowsegment({ record: record2, run, startcursor: 0, until: segment.until, session, plan, tabid: tab.id, origin, scopes: [{ name: "root", variables: [] }], log: [], storedentries: 0, execute: executedebug });
17912
+ if (segmentresult.failed !== void 0) {
17913
+ await memory.setworkflowrun({ ...run, state: "failed", endedat: Date.now(), cursor: segmentresult.run.cursor, failreason: segmentresult.failed });
17914
+ await memory.addrunhistory({ runid: run.id, workflowid: record2.id, outcome: "failed", steps: segmentresult.run.cursor, total: record2.steps.length, duration: Date.now() - run.startedat, cause: "debug", startedat: run.startedat, endedat: Date.now() });
17915
+ await audit("workflow", `The debug run ${run.id} of the workflow ${record2.name} failed at step cursor ${segmentresult.run.cursor} before the breakpoint ${segment.pausat}: ${segmentresult.failed}.`, { sessionid: session.id, planid: plan.id });
17916
+ await refreshbadge();
17917
+ return { runid: run.id, state: "failed", cursor: segmentresult.run.cursor, failreason: segmentresult.failed };
17918
+ }
17919
+ await memory.setworkflowrun({ ...run, state: "paused", pausedat: Date.now(), cursor: segment.until });
17920
+ await memory.addrunhistory({ runid: run.id, workflowid: record2.id, outcome: "paused", steps: segment.until, total: record2.steps.length, duration: Date.now() - run.startedat, cause: "debug", startedat: run.startedat, endedat: Date.now() });
17921
+ await audit("workflow", `The debug run ${run.id} of the workflow ${record2.name} ran ${segment.until} step${segment.until === 1 ? "" : "s"} and paused at the breakpoint ${segment.pausat}; ${segment.remaining} step${segment.remaining === 1 ? "" : "s"} remain and the resume continues exactly there.`, { sessionid: session.id, planid: plan.id });
17922
+ await refreshbadge();
17923
+ return { runid: run.id, state: "paused", cursor: segment.until, pausat: segment.pausat, remaining: segment.remaining };
17924
+ }
17925
+ case "editormodel": {
17926
+ const inputmodel = message;
17927
+ const record2 = await memory.getworkflowrecord(inputmodel.workflowid?.trim() ?? "");
17928
+ if (!record2) throw new Error(`No composed workflow matches ${inputmodel.workflowid ?? ""}.`);
17929
+ const layout = await memory.geteditorlayout(record2.id);
17930
+ const model = loadworkflow(record2, layout);
17931
+ const breakpoints = await memory.getworkflowbreakpoints(record2.id);
17932
+ const nodes = model.nodes.map((node) => node.step !== void 0 && breakpoints.includes(node.step.id) && node.step.breakpoint !== true ? { step: { ...node.step, breakpoint: true }, x: node.x, y: node.y } : node);
17933
+ return { model: { ...model, nodes }, record: record2, versions: await memory.listworkflowversions(record2.id), breakpoints };
17934
+ }
17935
+ case "editorsave": {
17936
+ const inputsave = message;
17937
+ const session = await memory.getsession();
17938
+ const plan = await memory.getplan();
17939
+ const model = inputsave.model;
17940
+ if (!model) throw new Error("The editor save needs the canvas model.");
17941
+ const gate = editorsavegate({ session, plan, model, now: Date.now() });
17942
+ if (!gate.allowed) throw new Error(gate.reason ?? "The editor save failed its consent gate.");
17943
+ const record2 = saveworkflow(model, { now: Date.now(), kindallowed: (kind) => {
17944
+ try {
17945
+ actionrisk(kind);
17946
+ return true;
17947
+ } catch {
17948
+ return false;
17949
+ }
17950
+ }, riskof: (kind) => actionrisk(kind) });
17951
+ await memory.addworkflowrecord(record2);
17952
+ await memory.addworkflowversion({ workflowid: record2.id, version: record2.version, createdat: Date.now(), note: typeof inputsave.note === "string" && inputsave.note.trim() !== "" ? inputsave.note.trim() : `Edited on the canvas with ${record2.steps.length} expanded steps`, steps: record2.steps.length, risk: record2.risk });
17953
+ await memory.seteditorlayout(record2.id, model.layout);
17954
+ await memory.setworkflowbreakpoints(record2.id, model.nodes.flatMap((node) => node.step?.breakpoint === true ? [node.step.id] : []));
17955
+ await audit("workflow", `The user saved the workflow ${record2.name} as version ${record2.version} from the canvas editor: ${record2.steps.length} expanded step${record2.steps.length === 1 ? "" : "s"} graded ${record2.risk}; the composition ran the full workflow grammar and every older version survives for the timeline.`, { ...session !== void 0 ? { sessionid: session.id } : {}, ...plan !== void 0 ? { planid: plan.id } : {} });
17956
+ return { workflowid: record2.id, version: record2.version, steps: record2.steps.length, risk: record2.risk };
17957
+ }
17958
+ case "seteditorlayout": {
17959
+ const inputlayout = message;
17960
+ const workflowid = inputlayout.workflowid?.trim() ?? "";
17961
+ const layout = inputlayout.layout;
17962
+ if (!workflowid || !layout || !Number.isFinite(layout.width) || !Number.isFinite(layout.height) || !Number.isFinite(layout.zoom) || layout.zoom <= 0) throw new Error("The layout save needs the workflow id and a positive canvas layout.");
17963
+ await memory.seteditorlayout(workflowid, layout);
17964
+ return { workflowid, saved: true };
17965
+ }
17966
+ case "setworkflowbreakpoints": {
17967
+ const inputbreakpoints = message;
17968
+ const workflowid = inputbreakpoints.workflowid?.trim() ?? "";
17969
+ if (!workflowid) throw new Error("The breakpoint save needs the workflow id.");
17970
+ const stepids = Array.isArray(inputbreakpoints.stepids) ? inputbreakpoints.stepids.filter((id) => typeof id === "string" && id.trim() !== "") : [];
17971
+ await memory.setworkflowbreakpoints(workflowid, stepids);
17972
+ await audit("workflow", `The user set ${stepids.length} breakpoint${stepids.length === 1 ? "" : "s"} on the workflow ${workflowid}; a debug run pauses before every marked step.`, {});
17973
+ return { workflowid, breakpoints: stepids.length };
17974
+ }
17975
+ case "steplibrarystore": {
17976
+ return { categories: palettecategories, palette: palettenodes, library: buildsteplibrary(reviewedkinds()) };
17977
+ }
17978
+ case "importworkflow": {
17979
+ const inputimport = message;
17980
+ const session = await memory.getsession();
17981
+ if (!session || session.stoppedat || session.expiresat <= Date.now()) throw new Error("Importing a workflow file needs an active browser session behind the consent gates.");
17982
+ if (typeof inputimport.contents !== "string" || inputimport.contents.trim() === "") throw new Error("The workflow import needs the file contents.");
17983
+ const format = inputimport.format === "yaml" ? "yaml" : inputimport.format === "json" ? "json" : inputimport.contents.trimStart().startsWith("{") ? "json" : "yaml";
17984
+ const loaded = importworkflow({ contents: inputimport.contents, format, now: Date.now(), kindallowed: (kind) => {
17985
+ try {
17986
+ actionrisk(kind);
17987
+ return true;
17988
+ } catch {
17989
+ return false;
17990
+ }
17991
+ }, riskof: (kind) => actionrisk(kind) });
17992
+ const importid = randomid();
17993
+ await memory.addworkflowrecord(loaded.record);
17994
+ await memory.addworkflowimport({ id: importid, record: loaded.record, importedat: Date.now(), ...typeof inputimport.filename === "string" && inputimport.filename.trim() !== "" ? { filename: inputimport.filename.trim() } : {} });
17995
+ for (const template of loaded.templates) await memory.addsteptemplate(template);
17996
+ await audit("workflow", `Imported the workflow ${loaded.record.name} version ${loaded.record.version} from a ${format} file with ${loaded.record.steps.length} expanded step${loaded.record.steps.length === 1 ? "" : "s"} and ${loaded.templates.length} packed template${loaded.templates.length === 1 ? "" : "s"}; the record stays unreviewed until the import review approves its step list.`, { sessionid: session.id });
17997
+ return { importid, workflowid: loaded.record.id, name: loaded.record.name, version: loaded.record.version, steps: loaded.record.steps.length, risk: loaded.record.risk, reviewstate: "pending", templates: loaded.templates.length };
17998
+ }
17999
+ case "approveimport": {
18000
+ const inputapproveimport = message;
18001
+ const session = await memory.getsession();
18002
+ const pending = (await memory.listworkflowimports()).find((entry) => entry.id === (inputapproveimport.importid ?? ""));
18003
+ if (!pending) throw new Error(`No pending workflow import matches ${inputapproveimport.importid ?? ""}.`);
18004
+ const approved = { ...pending.record, reviewstate: "approved" };
18005
+ await memory.addworkflowrecord(approved);
18006
+ await memory.removeworkflowimport(pending.id);
18007
+ await audit("workflow", `The user approved the import review of the workflow ${approved.name} version ${approved.version} with its ${approved.steps.length} expanded step${approved.steps.length === 1 ? "" : "s"} shown; the workflow may now run behind the same gates as every composed workflow.`, { ...session !== void 0 ? { sessionid: session.id } : {} });
18008
+ return { workflowid: approved.id, version: approved.version, reviewstate: "approved" };
18009
+ }
18010
+ case "rejectimport": {
18011
+ const inputreject = message;
18012
+ const session = await memory.getsession();
18013
+ const pending = (await memory.listworkflowimports()).find((entry) => entry.id === (inputreject.importid ?? ""));
18014
+ if (!pending) throw new Error(`No pending workflow import matches ${inputreject.importid ?? ""}.`);
18015
+ await memory.removeworkflowversion(pending.record.id, pending.record.version);
18016
+ await memory.removeworkflowimport(pending.id);
18017
+ await audit("workflow", `The user rejected the import review of the workflow ${pending.record.name} version ${pending.record.version}; the pending record left the library and nothing of the import runs.`, { ...session !== void 0 ? { sessionid: session.id } : {} });
18018
+ return { rejected: true, importid: pending.id };
18019
+ }
18020
+ case "exportworkflow": {
18021
+ const inputexport = message;
18022
+ const session = await memory.getsession();
18023
+ const record2 = await memory.getworkflowrecord(inputexport.workflowid?.trim() ?? "");
18024
+ if (!record2) throw new Error(`No composed workflow matches ${inputexport.workflowid ?? ""}.`);
18025
+ const format = inputexport.format === "yaml" ? "yaml" : "json";
18026
+ const exported = exportworkflow(record2, format, typeof inputexport.note === "string" ? inputexport.note : void 0, Date.now());
18027
+ const review = exportcontentreview(exported.file);
18028
+ if (!review.allowed) throw new Error(review.reason ?? "The export carries a secret field and secrets never leave the browser.");
18029
+ await audit("workflow", `Exported the workflow ${record2.name} version ${record2.version} as a ${format} file with ${record2.steps.length} expanded step${record2.steps.length === 1 ? "" : "s"}; the export content review verified that no secret field leaves the browser.`, { ...session !== void 0 ? { sessionid: session.id } : {} });
18030
+ return { format, contents: exported.contents, filename: `${record2.name.replace(/[^a-z0-9]+/gi, "-").toLowerCase()}-v${record2.version}.${format}` };
18031
+ }
18032
+ case "shareworkflow": {
18033
+ const inputshare = message;
18034
+ const session = await memory.getsession();
18035
+ const record2 = await memory.getworkflowrecord(inputshare.workflowid?.trim() ?? "");
18036
+ if (!record2) throw new Error(`No composed workflow matches ${inputshare.workflowid ?? ""}.`);
18037
+ const format = inputshare.format === "yaml" ? "yaml" : "json";
18038
+ const templates = await memory.getsteptemplates();
18039
+ const shared = shareworkflow(record2, templates, format, typeof inputshare.note === "string" ? inputshare.note : void 0, Date.now());
18040
+ const review = exportcontentreview(shared.file);
18041
+ if (!review.allowed) throw new Error(review.reason ?? "The share bundle carries a secret field and secrets never leave the browser.");
18042
+ await audit("workflow", `Packed the workflow ${record2.name} version ${record2.version} with ${templates.length} shared step template${templates.length === 1 ? "" : "s"} into one ${format} share file; the export content review verified that no secret field leaves the browser.`, { ...session !== void 0 ? { sessionid: session.id } : {} });
18043
+ return { format, contents: shared.contents, filename: `${record2.name.replace(/[^a-z0-9]+/gi, "-").toLowerCase()}-share-v${record2.version}.${format}` };
18044
+ }
18045
+ case "rollbackversion": {
18046
+ const inputrollback = message;
18047
+ const session = await memory.getsession();
18048
+ if (!session || session.stoppedat || session.expiresat <= Date.now()) throw new Error("A version rollback needs an active browser session behind the consent gates.");
18049
+ const versions = await memory.getworkflowrecordversions();
18050
+ const target = versions.find((entry) => entry.id === (inputrollback.workflowid?.trim() ?? "") && entry.version === inputrollback.version);
18051
+ if (!target) throw new Error(`No stored workflow version matches ${inputrollback.workflowid ?? ""} version ${String(inputrollback.version ?? "")}.`);
18052
+ const latest = versions.filter((entry) => entry.id === target.id).reduce((max, entry) => Math.max(max, entry.version), 0);
18053
+ const rolledback = composeworkflow({ id: target.id, name: target.name, version: latest + 1, origins: [...target.origins], steps: target.steps.map((step) => ({ ...step })), blocks: target.blocks.map((block) => ({ ...block })), now: Date.now(), kindallowed: (kind) => {
18054
+ try {
18055
+ actionrisk(kind);
18056
+ return true;
18057
+ } catch {
18058
+ return false;
18059
+ }
18060
+ }, riskof: (kind) => actionrisk(kind) });
18061
+ const pendingrollback = { ...rolledback, reviewstate: "pending" };
18062
+ await memory.addworkflowrecord(pendingrollback);
18063
+ await memory.addworkflowversion({ workflowid: rolledback.id, version: rolledback.version, createdat: Date.now(), note: `Rolled back to version ${target.version} of ${target.steps.length} steps`, steps: rolledback.steps.length, risk: rolledback.risk, rollback: true });
18064
+ await audit("workflow", `The user rolled the workflow ${target.name} back to version ${target.version}; the restored steps stored as version ${rolledback.version} and the rollback review gates its first run like a fresh import.`, { sessionid: session.id });
18065
+ return { workflowid: rolledback.id, version: rolledback.version, restoredfrom: target.version, steps: rolledback.steps.length, reviewstate: "pending" };
18066
+ }
18067
+ case "diffversions": {
18068
+ const inputdiff = message;
18069
+ const versions = await memory.getworkflowrecordversions();
18070
+ const from = versions.find((entry) => entry.id === (inputdiff.workflowid?.trim() ?? "") && entry.version === inputdiff.from);
18071
+ const to = versions.find((entry) => entry.id === (inputdiff.workflowid?.trim() ?? "") && entry.version === inputdiff.to);
18072
+ if (!from || !to) throw new Error(`The version diff needs two stored versions of ${inputdiff.workflowid ?? ""}.`);
18073
+ const diff = diffversions(from, to, Date.now());
18074
+ await memory.addversiondiff(diff);
18075
+ return diff;
18076
+ }
18077
+ case "runhistory": {
18078
+ const query = runhistoryquery(message);
18079
+ return runhistoryreport({ entries: await memory.gethistory(query), query });
18080
+ }
18081
+ case "setrunhistoryretention": {
18082
+ const inputretention = message;
18083
+ const settings = await memory.getsettings();
18084
+ const retention = typeof inputretention.retention === "number" && Number.isInteger(inputretention.retention) && inputretention.retention >= 0 ? inputretention.retention : void 0;
18085
+ await memory.setsettings({ ...settings, ...retention !== void 0 ? { runhistoryretention: retention } : {} });
18086
+ await audit("configure", `The user set the run history retention to ${retention === void 0 ? "keep every entry" : `${retention} entr${retention === 1 ? "y" : "ies"}`}; no code ceiling applies.`);
18087
+ return { runhistoryretention: retention };
18088
+ }
18089
+ case "setbackgroundrun": {
18090
+ const inputbackground = message;
18091
+ const workflowid = inputbackground.workflowid?.trim() ?? "";
18092
+ if (!workflowid) throw new Error("The background run toggle needs the workflow id.");
18093
+ const flags = await memory.getbackgroundruns();
18094
+ const enabled = inputbackground.enabled === true;
18095
+ await memory.setbackgroundruns({ ...flags, [workflowid]: enabled });
18096
+ await audit("workflow", `The user ${enabled ? "enabled" : "disabled"} the background run toggle of the workflow ${workflowid}${enabled ? "; its runs keep executing in the service worker with the panel closed and every worker wake restores an interrupted run through the same gates" : ""}.`, {});
18097
+ return { workflowid, enabled };
18098
+ }
18099
+ case "setwatchdog": {
18100
+ const inputwatchdog = message;
18101
+ const config = inputwatchdog.config;
18102
+ if (!config) throw new Error("The watchdog save needs the configuration.");
18103
+ const check = watchdogconfigvalid(config);
18104
+ if (!check.allowed) throw new Error(check.reason ?? "The watchdog configuration failed its review.");
18105
+ const settings = await memory.getsettings();
18106
+ await memory.setsettings({ ...settings, watchdog: config });
18107
+ await audit("configure", `The user configured the workflow watchdog: stall threshold ${config.stallthreshold} ms, recovery ${config.action}${config.zombiewindow !== void 0 ? `, zombie window ${config.zombiewindow} ms` : ""}; both stay user values with no code ceiling.`, {});
18108
+ return { watchdog: config };
18109
+ }
18110
+ case "watchdogscan": {
18111
+ const events = await runwatchdog();
18112
+ return { events, config: (await memory.getsettings())?.watchdog };
18113
+ }
18114
+ case "setsiteoverride": {
18115
+ const inputoverride = message;
18116
+ const session = await memory.getsession();
18117
+ if (!session || session.stoppedat || session.expiresat <= Date.now()) throw new Error("A per site override needs an active browser session behind the consent gates.");
18118
+ const workflowid = inputoverride.workflowid?.trim() ?? "";
18119
+ if (!workflowid) throw new Error("The per site override needs the workflow id.");
18120
+ const record2 = await memory.getworkflowrecord(workflowid);
18121
+ if (!record2) throw new Error(`No composed workflow matches ${workflowid}.`);
18122
+ const deltas = inputoverride.deltas !== void 0 && typeof inputoverride.deltas === "object" && !Array.isArray(inputoverride.deltas) ? inputoverride.deltas : {};
18123
+ const check = validatesiteoverride({ pattern: inputoverride.pattern ?? "", deltas });
18124
+ if (!check.allowed) throw new Error(check.reason ?? "The per site override failed its review.");
18125
+ const override = { id: typeof inputoverride.id === "string" && inputoverride.id.trim() !== "" ? inputoverride.id : randomid(), workflowid, pattern: inputoverride.pattern.trim(), deltas, createdat: Date.now() };
18126
+ await memory.addsiteoverride(override);
18127
+ await audit("workflow", `The user attached the per site override ${override.pattern} to the workflow ${record2.name}: ${Object.entries(deltas).map(([knob, delta]) => `${knob} ${delta}`).join(", ") || "no delta"}; the override adjusts only the reviewed knobs.`, { sessionid: session.id });
18128
+ return { override };
18129
+ }
18130
+ case "removesiteoverride": {
18131
+ const inputremove = message;
18132
+ const removed = (await memory.listsiteoverrides()).find((entry) => entry.id === (inputremove.id ?? ""));
18133
+ if (!removed) throw new Error(`No per site override matches ${inputremove.id ?? ""}.`);
18134
+ await memory.removesiteoverride(removed.id);
18135
+ await audit("workflow", `The user removed the per site override ${removed.pattern} of the workflow ${removed.workflowid}.`, {});
18136
+ return { removed: removed.id };
18137
+ }
17021
18138
  default:
17022
18139
  throw new Error("Unknown Devthink request.");
17023
18140
  }
17024
18141
  }
18142
+ async function runworkflowsegment(input) {
18143
+ const segmentids = new Set(input.record.steps.slice(input.startcursor, input.until).map((entry) => entry.id));
18144
+ const steps = input.record.steps.slice(input.startcursor, input.until).map((entry) => {
18145
+ const bindings = (entry.bindings ?? []).filter((binding) => segmentids.has(binding.stepid));
18146
+ return { ...entry, ...bindings.length > 0 ? { bindings } : {} };
18147
+ });
18148
+ const segmentrecord = composeworkflow({ id: input.record.id, name: input.record.name, version: input.record.version, origins: [...input.record.origins], steps, blocks: [], now: Date.now(), kindallowed: (kind) => {
18149
+ try {
18150
+ actionrisk(kind);
18151
+ return true;
18152
+ } catch {
18153
+ return false;
18154
+ }
18155
+ }, riskof: (kind) => actionrisk(kind) });
18156
+ const { pausedat, ...baserun } = input.run;
18157
+ void pausedat;
18158
+ const segmentrun = { ...baserun, state: "running", cursor: 0 };
18159
+ let storedentries = input.storedentries;
18160
+ const result = await runworkflow({ record: segmentrecord, run: segmentrun, scopes: input.scopes, log: input.log, execute: input.execute, now: Date.now(), gates: { sessionactive: Boolean(input.session && !input.session.stoppedat && !input.session.pausedat && input.session.expiresat > Date.now()), planapproved: input.plan.state === "approved", origingranted: (workfloworigin) => origingranted(input.session, workfloworigin) }, oncheckpoint: async (state) => {
18161
+ await memory.setworkflowrun({ ...state.run, cursor: input.startcursor + state.run.cursor, ...state.run.background === true ? { background: true } : {} });
18162
+ for (const entry of state.log.slice(storedentries)) await memory.addrunlogentry(state.run.id, entry);
18163
+ storedentries = state.log.length;
18164
+ await memory.setrunscopes(state.run.id, state.scopes);
18165
+ } });
18166
+ for (const entry of result.log.slice(storedentries)) await memory.addrunlogentry(input.run.id, entry);
18167
+ for (const entry of result.log.slice(input.log.length)) {
18168
+ const control = entry.details?.control;
18169
+ if (control && typeof control === "object" && !Array.isArray(control)) {
18170
+ const decision = control;
18171
+ await memory.addcontroldecision(input.run.id, decision);
18172
+ await auditcontroldecision(input.run.id, decision, input.session.id, input.plan.id);
18173
+ }
18174
+ }
18175
+ await memory.setrunscopes(input.run.id, result.scopes);
18176
+ const mapped = { ...input.run, state: result.run.state, cursor: input.startcursor + result.run.cursor, ...result.run.failreason !== void 0 ? { failreason: result.run.failreason } : {}, ...result.run.endedat !== void 0 ? { endedat: result.run.endedat } : {} };
18177
+ return { run: mapped, scopes: result.scopes, log: result.log, ...result.run.state === "failed" ? { failed: result.run.failreason ?? "The segment failed." } : {} };
18178
+ }
18179
+ async function runwatchdog() {
18180
+ const config = (await memory.getsettings())?.watchdog;
18181
+ if (!config || !config.enabled) return [];
18182
+ const runs = await memory.listworkflowruns();
18183
+ const lastcompletedat = {};
18184
+ for (const run of runs) {
18185
+ const log = await memory.getrunlog(run.id);
18186
+ const last = [...log].reverse().find((entry) => entry.state === "done");
18187
+ lastcompletedat[run.id] = last !== void 0 ? last.startedat + last.duration : run.startedat;
18188
+ }
18189
+ const verdicts = watchdogpass({ runs, lastcompletedat, liveexecutors: [...activeworkflowruns.keys()], config, now: Date.now() });
18190
+ const events = [];
18191
+ for (const verdict of verdicts) {
18192
+ if (verdict.verdict === "healthy") continue;
18193
+ const run = runs.find((entry) => entry.id === verdict.runid);
18194
+ if (!run) continue;
18195
+ let outcome = "";
18196
+ if (verdict.action === "pause") {
18197
+ const guards = activeworkflowruns.get(run.id);
18198
+ if (guards) guards.cancelled = true;
18199
+ await memory.setworkflowrun({ ...run, state: "paused", pausedat: Date.now(), pausekind: "watchdog" });
18200
+ outcome = `Paused at the checkpoint of step cursor ${run.cursor}; a user resume continues exactly there.`;
18201
+ } else if (verdict.action === "cancel" || verdict.action === "reap") {
18202
+ const guards = activeworkflowruns.get(run.id);
18203
+ if (guards) guards.cancelled = true;
18204
+ const cancelled = cancelrun(run, verdict.action === "reap" ? "The watchdog reaped the run as a zombie of a browser shutdown." : "The watchdog cancelled the stalled run.", Date.now());
18205
+ await memory.setworkflowrun(cancelled);
18206
+ outcome = verdict.action === "reap" ? "Reaped as a zombie of a browser shutdown at its last checkpoint." : "Cancelled as stalled beyond the reviewed threshold.";
18207
+ } else if (verdict.action === "retry") {
18208
+ await handlerequest({ kind: "resumeworkflowrun", runid: run.id }, {}).catch(() => {
18209
+ });
18210
+ outcome = `Retried the stalled step at cursor ${run.cursor} through the run gates.`;
18211
+ }
18212
+ const event = { id: randomid(), runid: run.id, verdict: verdict.verdict, action: verdict.action, outcome: `${verdict.reason} ${outcome}`.trim(), at: Date.now() };
18213
+ await memory.addwatchdogevent(event);
18214
+ await audit("workflow", `The watchdog marked the run ${run.id} ${verdict.verdict} and recovered it with ${verdict.action}: ${outcome}`, {});
18215
+ events.push(event);
18216
+ }
18217
+ await refreshbadge().catch(() => {
18218
+ });
18219
+ return events;
18220
+ }
18221
+ async function restorebackgroundruns() {
18222
+ const session = await memory.getsession();
18223
+ const plan = await memory.getplan();
18224
+ if (!session || session.stoppedat || session.pausedat || session.expiresat <= Date.now() || !plan || plan.state !== "approved") return;
18225
+ const flags = await memory.getbackgroundruns();
18226
+ for (const run of await memory.listworkflowruns()) {
18227
+ if (run.state !== "paused" || run.background !== true || run.pausekind === "user" || run.pausekind === "watchdog") continue;
18228
+ if (flags[run.workflowid] !== true) continue;
18229
+ const record2 = await memory.getworkflowrecord(run.workflowid);
18230
+ if (!record2) continue;
18231
+ let granted = true;
18232
+ for (const workfloworigin of record2.origins) {
18233
+ if (!origingranted(session, workfloworigin)) granted = false;
18234
+ }
18235
+ if (!granted) continue;
18236
+ const resumed = await handlerequest({ kind: "resumeworkflowrun", runid: run.id }, {}).catch(() => void 0);
18237
+ if (resumed === void 0) continue;
18238
+ await audit("workflow", `The worker wake restored the background run ${run.id} of the workflow ${record2.name} from its checkpoint at step cursor ${run.cursor}; the session, plan and origin gates re-passed.`, { sessionid: session.id, planid: plan.id });
18239
+ }
18240
+ }
17025
18241
  chrome.runtime.onMessage.addListener((message, sender, sendresponse) => {
17026
18242
  handlerequest(message, sender).then((value) => sendresponse({ ok: true, value })).catch((error) => sendresponse({ ok: false, error: error instanceof Error ? error.message : String(error) }));
17027
18243
  return true;
@@ -17042,12 +18258,15 @@ async function detectcrash() {
17042
18258
  }
17043
18259
  chrome.runtime.onStartup.addListener(() => {
17044
18260
  void detectcrash();
17045
- void pauseinterruptedworkflowruns();
18261
+ void pauseinterruptedworkflowruns().then(() => restorebackgroundruns()).catch(() => {
18262
+ });
18263
+ void runwatchdog().catch(() => {
18264
+ });
17046
18265
  });
17047
18266
  async function pauseinterruptedworkflowruns() {
17048
18267
  for (const run of await memory.listworkflowruns()) {
17049
18268
  if (run.state !== "running") continue;
17050
- await memory.setworkflowrun({ ...run, state: "paused", pausedat: Date.now() });
18269
+ await memory.setworkflowrun({ ...run, state: "paused", pausedat: Date.now(), pausekind: "interrupt" });
17051
18270
  await audit("workflow", `The service worker restart paused the workflow run ${run.id} at its last checkpoint of step cursor ${run.cursor}; the resume continues exactly there.`, {});
17052
18271
  }
17053
18272
  }
@@ -17181,13 +18400,17 @@ chrome.runtime.onConnect.addListener((port) => {
17181
18400
  }
17182
18401
  }
17183
18402
  setInterval(() => {
17184
- void evaluatelistedtriggers().then(() => draintriggerqueue()).catch(() => {
18403
+ void evaluatelistedtriggers().then(() => draintriggerqueue()).then(() => runwatchdog()).then(() => restorebackgroundruns()).catch(() => {
17185
18404
  });
17186
18405
  }, 3e4);
17187
18406
  async function restoretriggers() {
17188
18407
  await registermenurules();
17189
18408
  await evaluatelistedtriggers();
17190
18409
  await draintriggerqueue();
18410
+ await runwatchdog().catch(() => {
18411
+ });
18412
+ await restorebackgroundruns().catch(() => {
18413
+ });
17191
18414
  }
17192
18415
  restoretriggers().catch(() => {
17193
18416
  });