holycodex 0.15.1-dev.35.1 → 0.15.2-dev.37.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +3 -2
  2. package/dist/assets/plugin/agents/explorer.md +3 -0
  3. package/dist/assets/plugin/agents/librarian.md +4 -0
  4. package/dist/assets/plugin/agents/reviewer.md +4 -0
  5. package/dist/assets/plugin/agents/root.md +3 -5
  6. package/dist/assets/plugin/agents/worker.md +4 -2
  7. package/dist/assets/plugin/plugin.json +1 -2
  8. package/dist/assets/plugin/rules/holycodex.md +12 -11
  9. package/dist/assets/plugin/skills/babysit-ci/SKILL.md +1 -1
  10. package/dist/assets/plugin/skills/code-review/SKILL.md +2 -0
  11. package/dist/assets/plugin/skills/commit/SKILL.md +2 -2
  12. package/dist/assets/plugin/skills/compress/SKILL.md +1 -1
  13. package/dist/assets/plugin/skills/handoff/SKILL.md +1 -1
  14. package/dist/assets/plugin/skills/lsp/SKILL.md +1 -1
  15. package/dist/assets/plugin/skills/lsp-setup/SKILL.md +1 -1
  16. package/dist/assets/plugin/skills/plan-review/SKILL.md +1 -1
  17. package/dist/assets/plugin/skills/ponytail/SKILL.md +1 -13
  18. package/dist/assets/plugin/skills/ponytail/metadata.json +1 -1
  19. package/dist/assets/plugin/skills/programming/SKILL.md +2 -0
  20. package/dist/assets/plugin/skills/refactor/SKILL.md +1 -1
  21. package/dist/assets/plugin/skills/rules/SKILL.md +1 -1
  22. package/dist/assets/plugin/skills/stop-slop/LICENSE +21 -0
  23. package/dist/assets/plugin/skills/stop-slop/SKILL.md +42 -0
  24. package/dist/assets/plugin/skills/stop-slop/agents/openai.yaml +6 -0
  25. package/dist/assets/plugin/skills/stop-slop/references/examples.md +69 -0
  26. package/dist/assets/plugin/skills/stop-slop/references/phrases.md +128 -0
  27. package/dist/assets/plugin/skills/stop-slop/references/structures.md +134 -0
  28. package/dist/assets/plugin/skills/testing-quality.md +15 -0
  29. package/dist/assets/plugin/skills/workflows/SKILL.md +1 -1
  30. package/dist/assets/plugin/skills/writing-for-agents/LICENSE +21 -0
  31. package/dist/assets/plugin/skills/writing-for-agents/SKILL-MECHANICS.md +19 -0
  32. package/dist/assets/plugin/skills/writing-for-agents/SKILL.md +25 -14
  33. package/dist/{binary-BCtnZPMA.js → binary-CPh9zpjK.js} +2731 -2793
  34. package/dist/binary-th3XjkPd.js +3 -0
  35. package/dist/index.js +4 -4
  36. package/dist/src-d8LOMF1j.js +3 -0
  37. package/dist/{src-BmUZJGuC.js → src-le8tAupU.js} +249 -260
  38. package/package.json +2 -2
  39. package/dist/assets/plugin/hooks/hooks.json +0 -17
  40. package/dist/assets/plugin/hooks/version.ts +0 -54
  41. package/dist/assets/plugin/skills/ast-grep/SKILL.md +0 -7
  42. package/dist/assets/plugin/skills/ast-grep/agents/openai.yaml +0 -6
  43. package/dist/assets/plugin/skills/remove-slop/SKILL.md +0 -7
  44. package/dist/assets/plugin/skills/remove-slop/agents/openai.yaml +0 -6
  45. package/dist/binary-K1P4tTUI.js +0 -3
  46. package/dist/src-BrjytttX.js +0 -3
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env bun
2
2
  import { createRequire } from "node:module";
3
3
  import { dirname, join } from "node:path";
4
- import { fileURLToPath } from "node:url";
5
4
  import { spawnSync } from "node:child_process";
5
+ import { fileURLToPath } from "node:url";
6
6
  import { newQuickJSWASMModule } from "quickjs-emscripten";
7
7
  import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
8
8
  import { tmpdir } from "node:os";
@@ -8888,15 +8888,6 @@ const exitFailCause$1 = (cause) => {
8888
8888
  return effect;
8889
8889
  };
8890
8890
  /** @internal */
8891
- const exitFlatMap = /*#__PURE__*/ dual(2, (self, f) => {
8892
- switch (self._tag) {
8893
- case OP_FAILURE: return exitFailCause$1(self.effect_instruction_i0);
8894
- case OP_SUCCESS: return f(self.effect_instruction_i0);
8895
- }
8896
- });
8897
- /** @internal */
8898
- const exitFlatten = (self) => pipe(self, exitFlatMap(identity));
8899
- /** @internal */
8900
8891
  const exitInterrupt$1 = (fiberId) => exitFailCause$1(interrupt(fiberId));
8901
8892
  /** @internal */
8902
8893
  const exitMap = /*#__PURE__*/ dual(2, (self, f) => {
@@ -14236,25 +14227,6 @@ const makeSemaphore$1 = (permits) => sync$1(() => unsafeMakeSemaphore(permits));
14236
14227
  /** @internal */
14237
14228
  const raceFirst$1 = /*#__PURE__*/ dual(2, (self, that) => pipe(exit(self), race(exit(that)), (effect) => flatten$1(effect)));
14238
14229
  /** @internal */
14239
- const timeoutFail$1 = /*#__PURE__*/ dual(2, (self, { duration, onTimeout }) => flatten$1(timeoutTo(self, {
14240
- onTimeout: () => failSync$1(onTimeout),
14241
- onSuccess: succeed$4,
14242
- duration
14243
- })));
14244
- /** @internal */
14245
- const timeoutTo = /*#__PURE__*/ dual(2, (self, { duration, onSuccess, onTimeout }) => fiberIdWith((parentFiberId) => uninterruptibleMask$1((restore) => raceFibersWith(exit(restore(self)), interruptible$1(sleep(duration)), {
14246
- onSelfWin: (winner, loser) => flatMap$3(winner.await, (exit) => {
14247
- const selfExit = exitFlatten(exit);
14248
- if (selfExit._tag === "Success") return flatMap$3(winner.inheritAll, () => as(interruptAsFiber(loser, parentFiberId), onSuccess(selfExit.value)));
14249
- else return flatMap$3(interruptAsFiber(loser, parentFiberId), () => exitFailCause$1(selfExit.cause));
14250
- }),
14251
- onOtherWin: (winner, loser) => flatMap$3(winner.await, (exit) => {
14252
- if (exit._tag === "Success") return flatMap$3(winner.inheritAll, () => as(interruptAsFiber(loser, parentFiberId), onTimeout()));
14253
- else return flatMap$3(interruptAsFiber(loser, parentFiberId), () => exitFailCause$1(exit.cause));
14254
- }),
14255
- otherScope: globalScope
14256
- }))));
14257
- /** @internal */
14258
14230
  const SynchronizedTypeId = /*#__PURE__*/ Symbol.for("effect/Ref/SynchronizedRef");
14259
14231
  /** @internal */
14260
14232
  const synchronizedVariance = {
@@ -16241,72 +16213,6 @@ const ensuring = ensuring$1;
16241
16213
  */
16242
16214
  const scoped = scopedEffect;
16243
16215
  /**
16244
- * Specifies a custom error to be produced when a timeout occurs.
16245
- *
16246
- * **Details**
16247
- *
16248
- * This function allows you to handle timeouts in a customized way by defining a
16249
- * specific error to be raised when an effect exceeds the given duration. Unlike
16250
- * default timeout behaviors that use generic exceptions, this function gives
16251
- * you the flexibility to specify a meaningful error type that aligns with your
16252
- * application's needs.
16253
- *
16254
- * When you apply this function, you provide:
16255
- * - A `duration`: The time limit for the effect.
16256
- * - An `onTimeout` function: A lazy evaluation function that generates the
16257
- * custom error if the timeout occurs.
16258
- *
16259
- * If the effect completes within the time limit, its result is returned
16260
- * normally. Otherwise, the `onTimeout` function is triggered, and its output is
16261
- * used as the error for the effect.
16262
- *
16263
- * **Example**
16264
- *
16265
- * ```ts
16266
- * import { Effect } from "effect"
16267
- *
16268
- * const task = Effect.gen(function* () {
16269
- * console.log("Start processing...")
16270
- * yield* Effect.sleep("2 seconds") // Simulates a delay in processing
16271
- * console.log("Processing complete.")
16272
- * return "Result"
16273
- * })
16274
- *
16275
- * class MyTimeoutError {
16276
- * readonly _tag = "MyTimeoutError"
16277
- * }
16278
- *
16279
- * const program = task.pipe(
16280
- * Effect.timeoutFail({
16281
- * duration: "1 second",
16282
- * onTimeout: () => new MyTimeoutError() // Custom timeout error
16283
- * })
16284
- * )
16285
- *
16286
- * Effect.runPromiseExit(program).then(console.log)
16287
- * // Output:
16288
- * // Start processing...
16289
- * // {
16290
- * // _id: 'Exit',
16291
- * // _tag: 'Failure',
16292
- * // cause: {
16293
- * // _id: 'Cause',
16294
- * // _tag: 'Fail',
16295
- * // failure: MyTimeoutError { _tag: 'MyTimeoutError' }
16296
- * // }
16297
- * // }
16298
- * ```
16299
- *
16300
- * @see {@link timeout} for a version that raises a `TimeoutException`.
16301
- * @see {@link timeoutFailCause} for a version that raises a custom defect.
16302
- * @see {@link timeoutTo} for a version that allows specifying both success and
16303
- * timeout handlers.
16304
- *
16305
- * @since 2.0.0
16306
- * @category Delays & Timeouts
16307
- */
16308
- const timeoutFail = timeoutFail$1;
16309
- /**
16310
16216
  * Provides necessary dependencies to an effect, removing its environmental
16311
16217
  * requirements.
16312
16218
  *
@@ -21707,14 +21613,6 @@ const DEFAULT_OPTIONAL_CAPABILITY_SELECTIONS = Object.freeze({
21707
21613
  web: false,
21708
21614
  security: false
21709
21615
  });
21710
- function migrateOptionalCapabilitySelections(input) {
21711
- return {
21712
- computer_use: input?.[CAPABILITY_REGISTRY.computer_use.migrationKey] === true,
21713
- work: input?.[CAPABILITY_REGISTRY.work.migrationKey] === true,
21714
- web: input?.[CAPABILITY_REGISTRY.web.migrationKey] === true,
21715
- security: input?.[CAPABILITY_REGISTRY.security.migrationKey] === true
21716
- };
21717
- }
21718
21616
  function resolveOptionalCapabilitySelections(requested, previous) {
21719
21617
  const fallback = previous ?? DEFAULT_OPTIONAL_CAPABILITY_SELECTIONS;
21720
21618
  return {
@@ -21740,18 +21638,8 @@ function pluginIdsForOptionalCapabilities(selections, additionalPluginIds = [])
21740
21638
  }
21741
21639
  return ids;
21742
21640
  }
21743
- function capabilityHealth(selected, providerStatus) {
21744
- if (!selected) return "healthy";
21745
- switch (providerStatus) {
21746
- case "installed": return "healthy";
21747
- case "disabled": return "disabled";
21748
- case "uncertain": return "uncertain";
21749
- case "missing":
21750
- case void 0: return "missing";
21751
- }
21752
- }
21753
21641
  Struct({
21754
- identifier: Literal("workflow.create", "workflow.run", "workflow.resume", "local.repository.edit", "local.repository.check", "local.repository.lint", "local.repository.format", "implementation.plan", "origin.mutation", "ci.trigger"),
21642
+ identifier: Literal("workflow.create", "workflow.run", "workflow.resume", "local.repository.edit", "local.repository.check", "local.repository.lint", "local.repository.format", "local.repository.commit", "external.read", "specialist.dispatch", "vcs.server.mutation", "vcs.server.ci-trigger", "unknown.effect"),
21755
21643
  label: String$,
21756
21644
  requiresRootApproval: Boolean$
21757
21645
  });
@@ -21770,9 +21658,12 @@ Struct({
21770
21658
  localRepositoryCheck: approvalPolicyEntrySchema("local.repository.check"),
21771
21659
  localRepositoryLint: approvalPolicyEntrySchema("local.repository.lint"),
21772
21660
  localRepositoryFormat: approvalPolicyEntrySchema("local.repository.format"),
21773
- implementationPlan: approvalPolicyEntrySchema("implementation.plan"),
21774
- originMutation: approvalPolicyEntrySchema("origin.mutation"),
21775
- ciTrigger: approvalPolicyEntrySchema("ci.trigger")
21661
+ localRepositoryCommit: approvalPolicyEntrySchema("local.repository.commit"),
21662
+ externalRead: approvalPolicyEntrySchema("external.read"),
21663
+ specialistDispatch: approvalPolicyEntrySchema("specialist.dispatch"),
21664
+ versionControlServerMutation: approvalPolicyEntrySchema("vcs.server.mutation"),
21665
+ versionControlServerCiTrigger: approvalPolicyEntrySchema("vcs.server.ci-trigger"),
21666
+ unknownEffect: approvalPolicyEntrySchema("unknown.effect")
21776
21667
  });
21777
21668
  const APPROVAL_POLICY = {
21778
21669
  workflowCreate: {
@@ -21810,19 +21701,34 @@ const APPROVAL_POLICY = {
21810
21701
  label: "local repository format",
21811
21702
  requiresRootApproval: false
21812
21703
  },
21813
- implementationPlan: {
21814
- identifier: "implementation.plan",
21815
- label: "implementation plans",
21704
+ localRepositoryCommit: {
21705
+ identifier: "local.repository.commit",
21706
+ label: "local repository commit",
21707
+ requiresRootApproval: false
21708
+ },
21709
+ externalRead: {
21710
+ identifier: "external.read",
21711
+ label: "external read",
21712
+ requiresRootApproval: false
21713
+ },
21714
+ specialistDispatch: {
21715
+ identifier: "specialist.dispatch",
21716
+ label: "specialist dispatch",
21717
+ requiresRootApproval: false
21718
+ },
21719
+ versionControlServerMutation: {
21720
+ identifier: "vcs.server.mutation",
21721
+ label: "version-control-server mutation",
21816
21722
  requiresRootApproval: true
21817
21723
  },
21818
- originMutation: {
21819
- identifier: "origin.mutation",
21820
- label: "origin mutation",
21724
+ versionControlServerCiTrigger: {
21725
+ identifier: "vcs.server.ci-trigger",
21726
+ label: "version-control-server CI triggering",
21821
21727
  requiresRootApproval: true
21822
21728
  },
21823
- ciTrigger: {
21824
- identifier: "ci.trigger",
21825
- label: "CI triggering",
21729
+ unknownEffect: {
21730
+ identifier: "unknown.effect",
21731
+ label: "unclassified effect",
21826
21732
  requiresRootApproval: true
21827
21733
  }
21828
21734
  };
@@ -21925,7 +21831,13 @@ const PONYTAIL_ROLE_SKILL = Object.freeze({
21925
21831
  const ROLE_DEFINITIONS = [
21926
21832
  {
21927
21833
  role: "Explorer",
21928
- tasks: ["lookup", "trace"],
21834
+ tasks: [{
21835
+ name: "lookup",
21836
+ instruction: "Locate the exact requested repository fact."
21837
+ }, {
21838
+ name: "trace",
21839
+ instruction: "Trace the complete in-scope execution or reference path."
21840
+ }],
21929
21841
  capability: "repository-read",
21930
21842
  authority: "Read only the assigned repository scope; Root owns decisions.",
21931
21843
  evidence: "Return exact paths, symbols, callers, tests, and constraints.",
@@ -21940,7 +21852,13 @@ const ROLE_DEFINITIONS = [
21940
21852
  },
21941
21853
  {
21942
21854
  role: "Librarian",
21943
- tasks: ["lookup", "research"],
21855
+ tasks: [{
21856
+ name: "lookup",
21857
+ instruction: "Locate the exact requested authoritative external fact."
21858
+ }, {
21859
+ name: "research",
21860
+ instruction: "Synthesize the assigned current sources with citations."
21861
+ }],
21944
21862
  capability: "current-research",
21945
21863
  authority: "Research only the assigned current sources; Root owns decisions.",
21946
21864
  evidence: "Return sourced facts, dates, and explicit uncertainty.",
@@ -21956,10 +21874,22 @@ const ROLE_DEFINITIONS = [
21956
21874
  {
21957
21875
  role: "Worker",
21958
21876
  tasks: [
21959
- "mechanical",
21960
- "implementation",
21961
- "integration",
21962
- "operations"
21877
+ {
21878
+ name: "mechanical",
21879
+ instruction: "Apply only deterministic, already-decided edits."
21880
+ },
21881
+ {
21882
+ name: "implementation",
21883
+ instruction: "Implement and verify the bounded behavior seam."
21884
+ },
21885
+ {
21886
+ name: "integration",
21887
+ instruction: "Integrate the decided seams and verify them together."
21888
+ },
21889
+ {
21890
+ name: "operations",
21891
+ instruction: "Perform only the explicitly approved stateful operation."
21892
+ }
21963
21893
  ],
21964
21894
  capability: "bounded-write",
21965
21895
  authority: "Change only the assigned seam; Root owns material choices.",
@@ -21976,9 +21906,18 @@ const ROLE_DEFINITIONS = [
21976
21906
  {
21977
21907
  role: "Reviewer",
21978
21908
  tasks: [
21979
- "plan",
21980
- "code",
21981
- "artifact"
21909
+ {
21910
+ name: "plan",
21911
+ instruction: "Review the complete plan to a fixed point."
21912
+ },
21913
+ {
21914
+ name: "code",
21915
+ instruction: "Review and repair the implemented code to a fixed point."
21916
+ },
21917
+ {
21918
+ name: "artifact",
21919
+ instruction: "Review and repair the produced artifact to a fixed point."
21920
+ }
21982
21921
  ],
21983
21922
  capability: "bounded-review",
21984
21923
  authority: "Inspect and repair only reviewer-owned defects; Root owns material choices.",
@@ -21996,8 +21935,10 @@ const ROLE_DEFINITIONS = [
21996
21935
  freezeDeep(ROLE_DEFINITIONS);
21997
21936
  const roleDefinitionsByName = new Map(ROLE_DEFINITIONS.map((definition) => [definition.role, definition]));
21998
21937
  const roleNameSet = new Set(ROLE_DEFINITIONS.map((definition) => definition.role));
21999
- const routeKeys$1 = ROLE_DEFINITIONS.flatMap((definition) => definition.tasks.map((task) => `${definition.role}:${task}`));
21938
+ const routeKeys$1 = ROLE_DEFINITIONS.flatMap((definition) => definition.tasks.map((task) => `${definition.role}:${task.name}`));
22000
21939
  const routeKeySet = new Set(routeKeys$1);
21940
+ const nativeAgentTypes = routeKeys$1.map((key) => key.replace(":", "."));
21941
+ const nativeAgentTypeSet = new Set(nativeAgentTypes);
22001
21942
  function isRole(value) {
22002
21943
  return typeof value === "string" && roleNameSet.has(value);
22003
21944
  }
@@ -22006,10 +21947,10 @@ function isRoleTask(value) {
22006
21947
  const role = value.role;
22007
21948
  const task = value.task;
22008
21949
  if (!isRole(role) || typeof task !== "string") return false;
22009
- return roleDefinitionsByName.get(role)?.tasks.some((candidate) => candidate === task) === true;
21950
+ return roleDefinitionsByName.get(role)?.tasks.some((candidate) => candidate.name === task) === true;
22010
21951
  }
22011
21952
  function isTaskForRole(role, value) {
22012
- return typeof value === "string" && roleDefinitionsByName.get(role)?.tasks.some((candidate) => candidate === value) === true;
21953
+ return typeof value === "string" && roleDefinitionsByName.get(role)?.tasks.some((candidate) => candidate.name === value) === true;
22013
21954
  }
22014
21955
  function isRouteKey(value) {
22015
21956
  return typeof value === "string" && routeKeySet.has(value);
@@ -22022,6 +21963,18 @@ declare((value) => isTaskForRole("Reviewer", value));
22022
21963
  const RoleTaskSchema = declare(isRoleTask);
22023
21964
  const ROUTE_KEYS = Object.freeze(routeKeys$1.filter((key) => isRouteKey(key)));
22024
21965
  const RouteKeySchema = declare(isRouteKey);
21966
+ Object.freeze(nativeAgentTypes.filter((agentType) => nativeAgentTypeSet.has(agentType)));
21967
+ const NativeAgentTypeSchema = declare((value) => typeof value === "string" && nativeAgentTypeSet.has(value));
21968
+ function nativeAgentTypeFor(route) {
21969
+ const value = `${route.role}.${route.task}`;
21970
+ if (!nativeAgentTypeSet.has(value)) throw new Error("Unknown native specialist agent type.");
21971
+ return value;
21972
+ }
21973
+ function taskInstructionFor(route) {
21974
+ const task = roleDefinitionsByName.get(route.role)?.tasks.find((candidate) => candidate.name === route.task);
21975
+ if (task === void 0) throw new Error("Unknown specialist task policy.");
21976
+ return task.instruction;
21977
+ }
22025
21978
  function lookupRoleDefinition(role) {
22026
21979
  const definition = roleDefinitionsByName.get(role);
22027
21980
  if (definition === void 0) throw new Error("Unknown specialist role.");
@@ -22152,7 +22105,6 @@ function toCryptoBuffer(bytes) {
22152
22105
  copy.set(bytes);
22153
22106
  return copy;
22154
22107
  }
22155
- const sha256DomainDigest = domainSeparatedSha256;
22156
22108
  //#endregion
22157
22109
  //#region packages/core/src/envelopes.ts
22158
22110
  const SpecialistStatusSchema = Literal("blocked", "completed", "failed", "partial");
@@ -22487,13 +22439,13 @@ function routesForPlan(plan) {
22487
22439
  const override = effortOverridesByPlan.get(plan);
22488
22440
  if (override === void 0) throw new CoreError("catalog_invalid", "A specialist plan has no route effort policy.", { plan });
22489
22441
  return ROLE_DEFINITIONS.flatMap((definition) => definition.tasks.map((task) => {
22490
- const key = `${definition.role}:${task}`;
22442
+ const key = `${definition.role}:${task.name}`;
22491
22443
  const effort = override.efforts[key];
22492
22444
  if (effort === void 0) throw new CoreError("catalog_invalid", "A route effort policy is incomplete.", {
22493
22445
  plan,
22494
22446
  route: key
22495
22447
  });
22496
- return route(definition.role, task, effort);
22448
+ return route(definition.role, task.name, effort);
22497
22449
  }));
22498
22450
  }
22499
22451
  function specialistPlan(input) {
@@ -22527,7 +22479,7 @@ const planDefinitions = [
22527
22479
  budget: {
22528
22480
  costTarget: 1,
22529
22481
  costMax: 1.5,
22530
- maxCalls: 10,
22482
+ maxCalls: 1e4,
22531
22483
  maxConcurrency: 3
22532
22484
  }
22533
22485
  }),
@@ -22540,7 +22492,7 @@ const planDefinitions = [
22540
22492
  budget: {
22541
22493
  costTarget: 1.6,
22542
22494
  costMax: 2.5,
22543
- maxCalls: 16,
22495
+ maxCalls: 1e4,
22544
22496
  maxConcurrency: 3
22545
22497
  }
22546
22498
  }),
@@ -22553,7 +22505,7 @@ const planDefinitions = [
22553
22505
  budget: {
22554
22506
  costTarget: 3,
22555
22507
  costMax: 4.5,
22556
- maxCalls: 24,
22508
+ maxCalls: 1e4,
22557
22509
  maxConcurrency: 4
22558
22510
  }
22559
22511
  }),
@@ -22566,7 +22518,7 @@ const planDefinitions = [
22566
22518
  budget: {
22567
22519
  costTarget: 5,
22568
22520
  costMax: 7.5,
22569
- maxCalls: 40,
22521
+ maxCalls: 1e4,
22570
22522
  maxConcurrency: 6
22571
22523
  }
22572
22524
  }),
@@ -22579,7 +22531,7 @@ const planDefinitions = [
22579
22531
  budget: {
22580
22532
  costTarget: 12,
22581
22533
  costMax: 20,
22582
- maxCalls: 64,
22534
+ maxCalls: 1e4,
22583
22535
  maxConcurrency: 8
22584
22536
  }
22585
22537
  })
@@ -23642,8 +23594,7 @@ const PredicateSchema = Struct({
23642
23594
  });
23643
23595
  const RepeatUntilSchema = Struct({
23644
23596
  path: PathSchema,
23645
- equals: JsonValueSchema,
23646
- maxIterations: Number$.pipe(int(), greaterThanOrEqualTo(1), lessThanOrEqualTo(16))
23597
+ equals: JsonValueSchema
23647
23598
  });
23648
23599
  const AssignmentMetadataSchema = Struct({
23649
23600
  id: optional(IdentifierSchema),
@@ -23651,7 +23602,6 @@ const AssignmentMetadataSchema = Struct({
23651
23602
  dependencies: optional(Array$(IdentifierSchema)),
23652
23603
  retries: optional(NonNegativeIntegerSchema),
23653
23604
  attempt: optional(NonNegativeIntegerSchema),
23654
- timeoutMs: optional(PositiveIntegerSchema$1),
23655
23605
  writes: optional(Array$(WriteScopeSchema)),
23656
23606
  when: optional(ConditionSchema),
23657
23607
  stopWhen: optional(PredicateSchema),
@@ -24021,14 +23971,11 @@ function normalizeMetadata(input, policy) {
24021
23971
  }
24022
23972
  const retries = metadata.retries ?? 0;
24023
23973
  if (!Number.isInteger(retries) || retries < 0 || retries > policy.capacity.maxRetries) throw workflowFailure("validation", "The workflow retry policy is invalid.");
24024
- const timeoutMs = metadata.timeoutMs;
24025
- if (timeoutMs !== void 0 && (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 6e4)) throw workflowFailure("validation", "The workflow timeout policy is invalid.");
24026
23974
  return Object.freeze({
24027
23975
  capabilities: Object.freeze(capabilities),
24028
23976
  dependencies: Object.freeze(dependencies),
24029
23977
  retries,
24030
23978
  writes: Object.freeze(uniqueStrings$1((metadata.writes ?? []).map(normalizeWriteScope))),
24031
- ...timeoutMs === void 0 ? {} : { timeoutMs },
24032
23979
  ...metadata.when === void 0 ? {} : { when: freezeCondition(metadata.when) },
24033
23980
  ...metadata.stopWhen === void 0 ? {} : { stopWhen: freezePredicate(metadata.stopWhen) },
24034
23981
  ...metadata.repeatUntil === void 0 ? {} : { repeatUntil: freezeRepeatUntil(metadata.repeatUntil) }
@@ -24202,10 +24149,7 @@ function freezePredicate(input) {
24202
24149
  });
24203
24150
  }
24204
24151
  function freezeRepeatUntil(input) {
24205
- return Object.freeze({
24206
- ...freezePredicate(input),
24207
- maxIterations: input.maxIterations
24208
- });
24152
+ return freezePredicate(input);
24209
24153
  }
24210
24154
  function isAncestor(nodeById, nodeId, candidate) {
24211
24155
  const visited = /* @__PURE__ */ new Set();
@@ -29483,6 +29427,7 @@ interface WorkflowAssignment<I extends WorkflowJsonValue = WorkflowJsonValue, O
29483
29427
  interface WorkflowStepDefinition<I extends WorkflowJsonValue = WorkflowJsonValue, O extends WorkflowJsonValue = WorkflowJsonValue> { readonly id: string; readonly assignment: WorkflowAssignment<I, O>; }
29484
29428
  interface WorkflowValue<I extends WorkflowJsonValue = WorkflowJsonValue, O extends WorkflowJsonValue = WorkflowJsonValue> { readonly input: I; readonly output: O; }
29485
29429
  interface WorkflowWait<I extends WorkflowJsonValue = WorkflowJsonValue, O extends WorkflowJsonValue = WorkflowJsonValue> { readonly input: I; readonly result: O; }
29430
+ interface WorkflowDefinition<I extends WorkflowJsonValue = WorkflowJsonValue, O extends WorkflowJsonValue = WorkflowJsonValue> { readonly name: string; readonly workflow: WorkflowWait<I, O>; }
29486
29431
  type WorkflowQueueStageOutput<Current extends WorkflowJsonValue, Stage> = Stage extends WorkflowValue<Current, infer Output> ? Output : Stage extends WorkflowWait<Current, infer Output> ? Output : Stage extends (input: Current) => WorkflowValue<Current, infer Output> ? Output : Stage extends (input: Current) => WorkflowWait<Current, infer Output> ? Output : never;
29487
29432
  type WorkflowQueueStageChain<Current extends WorkflowJsonValue, Stages extends readonly unknown[]> = Stages extends readonly [infer Stage, ...infer Rest] ? [WorkflowQueueStageOutput<Current, Stage>] extends [never] ? never : readonly [Stage, ...WorkflowQueueStageChain<WorkflowQueueStageOutput<Current, Stage>, Rest>] : readonly [];
29488
29433
  type WorkflowQueueOutput<Current extends WorkflowJsonValue, Stages extends readonly unknown[]> = Stages extends readonly [infer Stage, ...infer Rest] ? WorkflowQueueOutput<WorkflowQueueStageOutput<Current, Stage>, Rest> : Current;
@@ -29503,6 +29448,7 @@ declare module "@holycodex/workflow" {
29503
29448
  export type StepDefinition<I extends WorkflowJsonValue = WorkflowJsonValue, O extends WorkflowJsonValue = WorkflowJsonValue> = WorkflowStepDefinition<I, O>;
29504
29449
  export type Workflow<I extends WorkflowJsonValue = WorkflowJsonValue, O extends WorkflowJsonValue = WorkflowJsonValue> = WorkflowValue<I, O>;
29505
29450
  export type Wait<I extends WorkflowJsonValue = WorkflowJsonValue, O extends WorkflowJsonValue = WorkflowJsonValue> = WorkflowWait<I, O>;
29451
+ export type Definition<I extends WorkflowJsonValue = WorkflowJsonValue, O extends WorkflowJsonValue = WorkflowJsonValue> = WorkflowDefinition<I, O>;
29506
29452
  export const workflow: WorkflowDsl;
29507
29453
  export function createCodec<T extends WorkflowJsonValue = WorkflowJsonValue>(name: string, decoder: ((value: unknown) => T) | WorkflowPortableSchema<T>): ValueCodec<T>;
29508
29454
  }
@@ -29512,6 +29458,7 @@ declare module "@holycodex/workflow-runtime" {
29512
29458
  export type StepDefinition<I extends WorkflowJsonValue = WorkflowJsonValue, O extends WorkflowJsonValue = WorkflowJsonValue> = WorkflowStepDefinition<I, O>;
29513
29459
  export type Workflow<I extends WorkflowJsonValue = WorkflowJsonValue, O extends WorkflowJsonValue = WorkflowJsonValue> = WorkflowValue<I, O>;
29514
29460
  export type Wait<I extends WorkflowJsonValue = WorkflowJsonValue, O extends WorkflowJsonValue = WorkflowJsonValue> = WorkflowWait<I, O>;
29461
+ export type Definition<I extends WorkflowJsonValue = WorkflowJsonValue, O extends WorkflowJsonValue = WorkflowJsonValue> = WorkflowDefinition<I, O>;
29515
29462
  export const workflow: WorkflowDsl;
29516
29463
  export function createCodec<T extends WorkflowJsonValue = WorkflowJsonValue>(name: string, decoder: ((value: unknown) => T) | WorkflowPortableSchema<T>): ValueCodec<T>;
29517
29464
  }
@@ -29632,7 +29579,7 @@ function rewriteNativeSource(source) {
29632
29579
  if (token.text === "{") braceDepth += 1;
29633
29580
  if (token.text === "}") braceDepth = Math.max(0, braceDepth - 1);
29634
29581
  }
29635
- if (exports !== 1) throw sourceError("The native workflow must export exactly one workflow.wait(...) value.");
29582
+ if (exports !== 1) throw sourceError("The native workflow must export exactly one named workflow definition.");
29636
29583
  return applyReplacements(source, replacements);
29637
29584
  }
29638
29585
  function nativeImportReplacement(statement) {
@@ -29805,6 +29752,7 @@ async function evaluateNativeWorkflowSource(input) {
29805
29752
  if (new TextEncoder().encode(canonicalJson(ir)).byteLength > limits.maxSerializedIRBytes) throw new WorkflowRuntimeError("resource_limit", "The native workflow IR is too large.");
29806
29753
  const codecMap = session.codecProxies();
29807
29754
  return Object.freeze({
29755
+ name: graph.name,
29808
29756
  ir,
29809
29757
  codecs: codecMap,
29810
29758
  dispose: () => session.dispose()
@@ -29983,17 +29931,23 @@ var NativeSourceSession = class {
29983
29931
  const dumped = this.context.dump(result.value);
29984
29932
  result.value.dispose();
29985
29933
  let finalHandle;
29934
+ let name = "workflow";
29986
29935
  try {
29987
- finalHandle = this.readHandle(dumped);
29936
+ if (isRecord(dumped) && "name" in dumped && "workflow" in dumped) {
29937
+ if (typeof dumped["name"] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/u.test(dumped["name"])) throw new Error("invalid workflow definition");
29938
+ name = dumped["name"];
29939
+ finalHandle = this.readHandle(dumped["workflow"]);
29940
+ } else finalHandle = this.readHandle(dumped);
29988
29941
  } catch {
29989
- throw new WorkflowRuntimeError("source_rejected", "The native workflow default export must be workflow.wait(...).");
29942
+ throw new WorkflowRuntimeError("source_rejected", "The native workflow default export is invalid.");
29990
29943
  }
29991
- if (finalHandle.kind !== "wait") throw new WorkflowRuntimeError("source_rejected", "The native workflow default export must be workflow.wait(...).");
29944
+ if (finalHandle.kind !== "wait") throw new WorkflowRuntimeError("source_rejected", "The native workflow definition must contain workflow.wait(...).");
29992
29945
  if (this.handles.size > this.limits.maxPlanNodes * 4) throw new WorkflowRuntimeError("resource_limit", "The native workflow graph metadata is too large.");
29993
29946
  const targets = finalHandle.targets;
29994
29947
  const nodes = mergeTargets(targets).nodes;
29995
29948
  if (nodes.length > this.limits.maxPlanNodes) throw new WorkflowRuntimeError("resource_limit", "The native workflow graph exceeds its node limit.");
29996
29949
  return {
29950
+ name,
29997
29951
  nodes,
29998
29952
  roots: uniqueStrings(targets.flatMap((target) => target.graph.roots)),
29999
29953
  output: targets.length === 1 ? targets[0]?.output ?? {
@@ -30370,7 +30324,6 @@ function readMetadata(value) {
30370
30324
  const dependencies = readOptionalStringArray(value["dependencies"], "metadata.dependencies");
30371
30325
  const retries = readOptionalInteger(value["retries"], "metadata.retries");
30372
30326
  const attempt = readOptionalInteger(value["attempt"], "metadata.attempt");
30373
- const timeoutMs = readOptionalInteger(value["timeoutMs"], "metadata.timeoutMs");
30374
30327
  const writes = readOptionalStringArray(value["writes"], "metadata.writes");
30375
30328
  const when = readCondition(value["when"]);
30376
30329
  const stopWhen = readPredicate(value["stopWhen"]);
@@ -30381,7 +30334,6 @@ function readMetadata(value) {
30381
30334
  ...dependencies === void 0 ? {} : { dependencies },
30382
30335
  ...retries === void 0 ? {} : { retries },
30383
30336
  ...attempt === void 0 ? {} : { attempt },
30384
- ...timeoutMs === void 0 ? {} : { timeoutMs },
30385
30337
  ...writes === void 0 ? {} : { writes },
30386
30338
  ...when === void 0 ? {} : { when },
30387
30339
  ...stopWhen === void 0 ? {} : { stopWhen },
@@ -30393,7 +30345,6 @@ function readMetadata(value) {
30393
30345
  "dependencies",
30394
30346
  "retries",
30395
30347
  "attempt",
30396
- "timeoutMs",
30397
30348
  "writes",
30398
30349
  "when",
30399
30350
  "stopWhen",
@@ -30436,11 +30387,10 @@ function readPredicate(value) {
30436
30387
  }
30437
30388
  function readRepeatUntil(value) {
30438
30389
  if (value === void 0) return void 0;
30439
- if (!isRecord(value) || !isStringArray(value["path"]) || !isJsonValue$1(value["equals"]) || typeof value["maxIterations"] !== "number" || !Number.isInteger(value["maxIterations"])) throw new Error("The workflow repeat policy is invalid.");
30390
+ if (!isRecord(value) || !isStringArray(value["path"]) || !isJsonValue$1(value["equals"])) throw new Error("The workflow repeat policy is invalid.");
30440
30391
  return {
30441
30392
  path: value["path"],
30442
- equals: value["equals"],
30443
- maxIterations: value["maxIterations"]
30393
+ equals: value["equals"]
30444
30394
  };
30445
30395
  }
30446
30396
  function isStringArray(value) {
@@ -30644,6 +30594,7 @@ function makeCapacityService(capacity) {
30644
30594
  const session = yield* makeSemaphore(capacity.sessionConcurrency);
30645
30595
  const codex = yield* makeSemaphore(capacity.codexConcurrency);
30646
30596
  const transaction = yield* makeSemaphore(1);
30597
+ const runGates = /* @__PURE__ */ new Map();
30647
30598
  const state = {
30648
30599
  runs: /* @__PURE__ */ new Map(),
30649
30600
  committedByRun: /* @__PURE__ */ new Map(),
@@ -30653,80 +30604,108 @@ function makeCapacityService(capacity) {
30653
30604
  overflow: false
30654
30605
  };
30655
30606
  const globalConcurrency = Math.min(capacity.planConcurrency, capacity.sessionConcurrency, capacity.codexConcurrency);
30607
+ const dispatch = yield* makeSemaphore(globalConcurrency);
30656
30608
  const globalCostMax = capacity.costMax ?? Number.MAX_SAFE_INTEGER;
30657
30609
  const globalCallsMax = capacity.maxCalls ?? Number.MAX_SAFE_INTEGER;
30658
- const acquire = (request) => transaction.withPermits(1)(gen(function* () {
30659
- const invalid = validateDispatchRequest(request);
30660
- if (invalid !== void 0) return yield* fail$1(invalid);
30661
- if (state.overflow) return yield* fail$1(workflowFailure("settlement_overflow", "The workflow cost ledger is closed after an overage.", { retryable: false }));
30662
- const existing = state.runs.get(request.runId);
30663
- const run = existing ?? createRunState(request);
30664
- if (run.maxCalls !== request.maxCalls || run.maxCost !== request.maxCost) {
30665
- run.maxCalls = Math.min(run.maxCalls, request.maxCalls);
30666
- run.maxCost = Math.min(run.maxCost, request.maxCost);
30667
- }
30668
- if (run.calls >= run.maxCalls) return yield* fail$1(workflowFailure("admission_exceeded", "The workflow call capacity was exhausted."));
30669
- if (state.globalCalls >= globalCallsMax) return yield* fail$1(workflowFailure("admission_exceeded", "The shared workflow call capacity was exhausted."));
30670
- if (run.inFlight >= request.maxConcurrency || state.inFlight >= globalConcurrency) return yield* fail$1(workflowFailure("admission_exceeded", "The workflow concurrency capacity was exhausted."));
30671
- const plannedCoverage = Math.min(run.plannedCost, request.estimatedCost);
30672
- const incrementalReservation = request.estimatedCost - plannedCoverage;
30673
- const nextRunCost = safeSum([
30674
- run.committedCost,
30675
- run.plannedCost,
30676
- run.outstandingCost,
30677
- incrementalReservation
30678
- ]);
30679
- if (nextRunCost === void 0 || nextRunCost > run.maxCost) return yield* fail$1(workflowFailure("admission_exceeded", "The workflow cost capacity was exhausted."));
30680
- const nextGlobalCost = safeAdd(state.globalCost, incrementalReservation);
30681
- if (nextGlobalCost === void 0 || nextGlobalCost > globalCostMax) return yield* fail$1(workflowFailure("admission_exceeded", "The shared workflow cost capacity was exhausted."));
30682
- if (existing === void 0) state.runs.set(request.runId, run);
30683
- run.calls += 1;
30684
- run.inFlight += 1;
30685
- run.plannedCost -= plannedCoverage;
30686
- run.outstandingCost += request.estimatedCost;
30687
- state.inFlight += 1;
30688
- state.globalCalls += 1;
30689
- state.globalCost = nextGlobalCost;
30690
- let released = false;
30691
- let settled = false;
30692
- return {
30693
- estimatedCost: request.estimatedCost,
30694
- settle: (settlement) => transaction.withPermits(1)(gen(function* () {
30695
- const invalidSettlement = validateSettlement(settlement);
30696
- if (invalidSettlement !== void 0) return yield* fail$1(invalidSettlement);
30697
- if (settled) return;
30698
- if (state.runs.get(request.runId) !== run || run.outstandingCost < request.estimatedCost) return yield* fail$1(workflowFailure("ledger_corruption", "The workflow cost lease is no longer tracked."));
30699
- settled = true;
30700
- run.outstandingCost -= request.estimatedCost;
30701
- const nextCommittedCost = safeAdd(run.committedCost, settlement.costUnits);
30702
- const nextGlobalCost = safeAdd(state.globalCost - request.estimatedCost, settlement.costUnits);
30703
- run.committedCost = nextCommittedCost ?? Number.MAX_SAFE_INTEGER;
30704
- state.globalCost = nextGlobalCost ?? Number.MAX_SAFE_INTEGER;
30705
- state.committedByRun.set(request.runId, {
30706
- calls: run.calls,
30707
- cost: run.committedCost
30708
- });
30709
- const runTotal = safeSum([
30610
+ const acquire = (request) => {
30611
+ let dispatchHeld = false;
30612
+ let runGate;
30613
+ let runHeld = false;
30614
+ const releasePermits = gen(function* () {
30615
+ if (runHeld && runGate !== void 0) {
30616
+ runHeld = false;
30617
+ yield* runGate.release(1);
30618
+ }
30619
+ if (dispatchHeld) {
30620
+ dispatchHeld = false;
30621
+ yield* dispatch.release(1);
30622
+ }
30623
+ });
30624
+ return gen(function* () {
30625
+ yield* dispatch.take(1);
30626
+ dispatchHeld = true;
30627
+ runGate = yield* transaction.withPermits(1)(gen(function* () {
30628
+ const existing = runGates.get(request.runId);
30629
+ if (existing !== void 0) return existing;
30630
+ const created = yield* makeSemaphore(request.maxConcurrency);
30631
+ runGates.set(request.runId, created);
30632
+ return created;
30633
+ }));
30634
+ yield* runGate.take(1);
30635
+ runHeld = true;
30636
+ return yield* transaction.withPermits(1)(gen(function* () {
30637
+ const invalid = validateDispatchRequest(request);
30638
+ if (invalid !== void 0) return yield* fail$1(invalid);
30639
+ if (state.overflow) return yield* fail$1(workflowFailure("settlement_overflow", "The workflow cost ledger is closed after an overage.", { retryable: false }));
30640
+ const existing = state.runs.get(request.runId);
30641
+ const run = existing ?? createRunState(request);
30642
+ if (run.maxCalls !== request.maxCalls || run.maxCost !== request.maxCost) {
30643
+ run.maxCalls = Math.min(run.maxCalls, request.maxCalls);
30644
+ run.maxCost = Math.min(run.maxCost, request.maxCost);
30645
+ }
30646
+ if (run.calls >= run.maxCalls) return yield* fail$1(workflowFailure("admission_exceeded", "The workflow call capacity was exhausted."));
30647
+ if (state.globalCalls >= globalCallsMax) return yield* fail$1(workflowFailure("admission_exceeded", "The shared workflow call capacity was exhausted."));
30648
+ const plannedCoverage = Math.min(run.plannedCost, request.estimatedCost);
30649
+ const incrementalReservation = request.estimatedCost - plannedCoverage;
30650
+ const nextRunCost = safeSum([
30710
30651
  run.committedCost,
30711
30652
  run.plannedCost,
30712
- run.outstandingCost
30653
+ run.outstandingCost,
30654
+ incrementalReservation
30713
30655
  ]);
30714
- const runOverflow = nextCommittedCost === void 0 || runTotal === void 0 || runTotal > run.maxCost;
30715
- const globalOverflow = nextGlobalCost === void 0 || state.globalCost > globalCostMax;
30716
- if (runOverflow || globalOverflow) {
30717
- run.overflow = true;
30718
- state.overflow = true;
30719
- return yield* fail$1(workflowFailure("settlement_overflow", "Measured workflow cost exceeded the hard budget.", { retryable: false }));
30720
- }
30721
- })),
30722
- release: transaction.withPermits(1)(sync(() => {
30723
- if (released) return;
30724
- released = true;
30725
- run.inFlight = Math.max(0, run.inFlight - 1);
30726
- state.inFlight = Math.max(0, state.inFlight - 1);
30727
- }))
30728
- };
30729
- }));
30656
+ if (nextRunCost === void 0 || nextRunCost > run.maxCost) return yield* fail$1(workflowFailure("admission_exceeded", "The workflow cost capacity was exhausted."));
30657
+ const nextGlobalCost = safeAdd(state.globalCost, incrementalReservation);
30658
+ if (nextGlobalCost === void 0 || nextGlobalCost > globalCostMax) return yield* fail$1(workflowFailure("admission_exceeded", "The shared workflow cost capacity was exhausted."));
30659
+ if (existing === void 0) state.runs.set(request.runId, run);
30660
+ run.calls += 1;
30661
+ run.inFlight += 1;
30662
+ run.plannedCost -= plannedCoverage;
30663
+ run.outstandingCost += request.estimatedCost;
30664
+ state.inFlight += 1;
30665
+ state.globalCalls += 1;
30666
+ state.globalCost = nextGlobalCost;
30667
+ let released = false;
30668
+ let settled = false;
30669
+ return {
30670
+ estimatedCost: request.estimatedCost,
30671
+ settle: (settlement) => transaction.withPermits(1)(gen(function* () {
30672
+ const invalidSettlement = validateSettlement(settlement);
30673
+ if (invalidSettlement !== void 0) return yield* fail$1(invalidSettlement);
30674
+ if (settled) return;
30675
+ if (state.runs.get(request.runId) !== run || run.outstandingCost < request.estimatedCost) return yield* fail$1(workflowFailure("ledger_corruption", "The workflow cost lease is no longer tracked."));
30676
+ settled = true;
30677
+ run.outstandingCost -= request.estimatedCost;
30678
+ const nextCommittedCost = safeAdd(run.committedCost, settlement.costUnits);
30679
+ const nextGlobalCost = safeAdd(state.globalCost - request.estimatedCost, settlement.costUnits);
30680
+ run.committedCost = nextCommittedCost ?? Number.MAX_SAFE_INTEGER;
30681
+ state.globalCost = nextGlobalCost ?? Number.MAX_SAFE_INTEGER;
30682
+ state.committedByRun.set(request.runId, {
30683
+ calls: run.calls,
30684
+ cost: run.committedCost
30685
+ });
30686
+ const runTotal = safeSum([
30687
+ run.committedCost,
30688
+ run.plannedCost,
30689
+ run.outstandingCost
30690
+ ]);
30691
+ const runOverflow = nextCommittedCost === void 0 || runTotal === void 0 || runTotal > run.maxCost;
30692
+ const globalOverflow = nextGlobalCost === void 0 || state.globalCost > globalCostMax;
30693
+ if (runOverflow || globalOverflow) {
30694
+ run.overflow = true;
30695
+ state.overflow = true;
30696
+ return yield* fail$1(workflowFailure("settlement_overflow", "Measured workflow cost exceeded the hard budget.", { retryable: false }));
30697
+ }
30698
+ })),
30699
+ release: transaction.withPermits(1)(sync(() => {
30700
+ if (released) return;
30701
+ released = true;
30702
+ run.inFlight = Math.max(0, run.inFlight - 1);
30703
+ state.inFlight = Math.max(0, state.inFlight - 1);
30704
+ })).pipe(andThen(releasePermits))
30705
+ };
30706
+ }));
30707
+ }).pipe(catchAllCause((cause) => releasePermits.pipe(andThen(failCause(cause)))));
30708
+ };
30730
30709
  const reserveRun = (request) => transaction.withPermits(1)(gen(function* () {
30731
30710
  const invalid = validateReservationRequest(request);
30732
30711
  if (invalid !== void 0) return yield* fail$1(invalid);
@@ -30754,6 +30733,7 @@ function makeCapacityService(capacity) {
30754
30733
  const current = state.runs.get(request.runId);
30755
30734
  if (current !== run) return;
30756
30735
  state.runs.delete(request.runId);
30736
+ runGates.delete(request.runId);
30757
30737
  state.inFlight = Math.max(0, state.inFlight - current.inFlight);
30758
30738
  state.globalCost = Math.max(0, state.globalCost - current.plannedCost - current.outstandingCost);
30759
30739
  })) };
@@ -30811,6 +30791,7 @@ function makeCapacityService(capacity) {
30811
30791
  const run = state.runs.get(runId);
30812
30792
  if (run === void 0) return;
30813
30793
  state.runs.delete(runId);
30794
+ runGates.delete(runId);
30814
30795
  state.inFlight = Math.max(0, state.inFlight - run.inFlight);
30815
30796
  state.globalCost = Math.max(0, state.globalCost - run.plannedCost - run.outstandingCost);
30816
30797
  }));
@@ -30924,8 +30905,7 @@ function runNode(node, results, rootInput, runId, capacity, planGate, options) {
30924
30905
  const agent = options.services?.agent;
30925
30906
  const repeatUntil = node.metadata.repeatUntil;
30926
30907
  let previousFingerprint;
30927
- const maxIterations = repeatUntil?.maxIterations ?? 1;
30928
- for (let iteration = 0; iteration < maxIterations; iteration += 1) {
30908
+ for (;;) {
30929
30909
  const output = yield* runNodeIteration(node, input, results, runId, capacity, planGate, options, agent, () => {
30930
30910
  attempt += 1;
30931
30911
  return attempt;
@@ -30941,10 +30921,6 @@ function runNode(node, results, rootInput, runId, capacity, planGate, options) {
30941
30921
  }));
30942
30922
  previousFingerprint = fingerprint;
30943
30923
  }
30944
- return yield* fail$1(workflowFailure("iteration_limit", "The workflow repeat iteration limit was exhausted.", {
30945
- nodeId: node.id,
30946
- retryable: false
30947
- }));
30948
30924
  }).pipe(catchAll((failure) => notifyJournal(options.services, {
30949
30925
  type: "failed",
30950
30926
  runId,
@@ -31001,11 +30977,7 @@ function runNodeIteration(node, input, results, runId, capacity, planGate, optio
31001
30977
  }).pipe(andThen(dispatch));
31002
30978
  });
31003
30979
  const retried = node.metadata.retries === 0 ? task : retryOrElse(task, recurs(node.metadata.retries).pipe(whileInput((failure) => failure.retryable !== false)), () => fail$1(workflowFailure("retry_exhausted", "The workflow retry schedule was exhausted.", { nodeId: node.id })));
31004
- const timed = node.metadata.timeoutMs === void 0 ? retried : timeoutFail({
31005
- duration: `${node.metadata.timeoutMs} millis`,
31006
- onTimeout: () => workflowFailure("timeout", "The workflow step timed out.", { nodeId: node.id })
31007
- })(retried);
31008
- return options.capacity.codex.withPermits(1)(options.capacity.session.withPermits(1)(options.capacity.plan.withPermits(1)(planGate.withPermits(1)(timed)))).pipe(flatMap$1((output) => notifyJournal(services, {
30980
+ return planGate.withPermits(1)(retried).pipe(flatMap$1((output) => notifyJournal(services, {
31009
30981
  type: "completed",
31010
30982
  runId,
31011
30983
  nodeId: node.id,
@@ -31656,10 +31628,23 @@ async function monitorChild(processHandle, input, limits) {
31656
31628
  let settled = false;
31657
31629
  let operationCount = 0;
31658
31630
  const outstanding = /* @__PURE__ */ new Map();
31659
- const timer = setTimeout(() => {
31631
+ const pending = [];
31632
+ let remainingEvaluationMs = limits.wallTimeMs;
31633
+ let evaluationStartedAt = performance.now();
31634
+ let timer;
31635
+ const timeOut = () => {
31660
31636
  sendCancellation(processHandle, limits, "timed_out");
31661
31637
  finish(failure(new WorkflowRuntimeError("timed_out", "The workflow timed out.")));
31662
- }, limits.wallTimeMs);
31638
+ };
31639
+ const resumeEvaluationTimer = () => {
31640
+ evaluationStartedAt = performance.now();
31641
+ timer = setTimeout(timeOut, remainingEvaluationMs);
31642
+ };
31643
+ const pauseEvaluationTimer = () => {
31644
+ clearTimeout(timer);
31645
+ remainingEvaluationMs = Math.max(0, remainingEvaluationMs - (performance.now() - evaluationStartedAt));
31646
+ };
31647
+ resumeEvaluationTimer();
31663
31648
  const abortListener = () => {
31664
31649
  sendCancellation(processHandle, limits, "cancelled");
31665
31650
  finish(failure(new WorkflowRuntimeError("cancelled", "The workflow was cancelled.")));
@@ -31685,6 +31670,17 @@ async function monitorChild(processHandle, input, limits) {
31685
31670
  finish(failure(new WorkflowRuntimeError("child_crashed", "The workflow child output is unavailable.")));
31686
31671
  return;
31687
31672
  }
31673
+ const startOperation = (message) => {
31674
+ const task = serviceOperation(processHandle, message, input.operationHandler, limits).catch(() => {
31675
+ finish(failure(new WorkflowRuntimeError("protocol_breach", "The workflow operation response failed.")));
31676
+ }).finally(() => {
31677
+ outstanding.delete(message.request_id);
31678
+ const next = pending.shift();
31679
+ if (next !== void 0) startOperation(next);
31680
+ else if (outstanding.size === 0 && !settled) resumeEvaluationTimer();
31681
+ });
31682
+ outstanding.set(message.request_id, task);
31683
+ };
31688
31684
  consumeStream(stdout, limits, (line) => {
31689
31685
  if (settled) return;
31690
31686
  let message;
@@ -31695,25 +31691,18 @@ async function monitorChild(processHandle, input, limits) {
31695
31691
  return;
31696
31692
  }
31697
31693
  if (message.type === "operation-request") {
31694
+ if (outstanding.size === 0 && pending.length === 0) pauseEvaluationTimer();
31698
31695
  if (operationCount >= limits.maxOperationCount) {
31699
31696
  finish(failure(new WorkflowRuntimeError("resource_limit", "The workflow operation limit was exceeded.")));
31700
31697
  return;
31701
31698
  }
31702
- if (outstanding.size >= limits.maxConcurrentOperations) {
31703
- finish(failure(new WorkflowRuntimeError("resource_limit", "The workflow concurrency limit was exceeded.")));
31704
- return;
31705
- }
31706
- if (outstanding.has(message.request_id)) {
31699
+ if (outstanding.has(message.request_id) || pending.some((request) => request.request_id === message.request_id)) {
31707
31700
  finish(failure(new WorkflowRuntimeError("protocol_breach", "The child reused a workflow operation request id.")));
31708
31701
  return;
31709
31702
  }
31710
31703
  operationCount += 1;
31711
- const task = serviceOperation(processHandle, message, input.operationHandler, limits).catch(() => {
31712
- finish(failure(new WorkflowRuntimeError("protocol_breach", "The workflow operation response failed.")));
31713
- }).finally(() => {
31714
- outstanding.delete(message.request_id);
31715
- });
31716
- outstanding.set(message.request_id, task);
31704
+ if (outstanding.size >= limits.maxConcurrentOperations) pending.push(message);
31705
+ else startOperation(message);
31717
31706
  return;
31718
31707
  }
31719
31708
  if (message.type === "terminal-success") {
@@ -31954,4 +31943,4 @@ function isAbsolutePath(value) {
31954
31943
  return value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value);
31955
31944
  }
31956
31945
  //#endregion
31957
- export { DelegationModeSchema as $, runSync as $t, DEFAULT_WORKFLOW_LIMITS as A, decodeUnknownEither as At, resolvePlanSelection as B, pattern as Bt, workflowFailure as C, Number$ as Ct, Step as D, Union as Dt, Run as E, Struct as Et, parseProtocolLine as F, maxItems as Ft, parseCapabilityResultV2 as G, async as Gt, SpecialistOutcomeSchema as H, is as Ht, serializeProtocolMessage as I, maxLength as It, canonicalIdentityUtf8 as J, mapError$1 as Jt, parseCliEnvelope as K, fail$1 as Kt, toWireLimits as L, minItems as Lt, WorkflowLimitsSchema as M, greaterThan as Mt, WorkflowProtocolMessageSchema as N, greaterThanOrEqualTo as Nt, Wait as O, Unknown as Ot, WorkflowRuntimeError as P, int as Pt, sha256DomainDigest as Q, runPromise as Qt, lookupPlan as R, minLength as Rt, isWorkflowFailure as S, Null as St, Queue as T, String$ as Tt, SpecialistOutcomeV2Schema as U, _void as Ut, SPECIALIST_OUTCOME_VERSION as V, positive as Vt, normalizeSpecialistOutcome as W, acquireRelease as Wt, canonicalJsonUtf8 as X, provide as Xt, canonicalJson as Y, orElseSucceed as Yt, domainSeparatedSha256 as Z, raceFirst as Zt, NATIVE_WORKFLOW_ABI_VERSION as _, resolveOptionalCapabilitySelections as _t, runExecutionPlan as a, fromEffect as an, RouteKeySchema as at, nativeWorkflowIdentityDigest as b, Boolean$ as bt, loadNativeWorkflowSource as c, scoped$1 as cn, createProjectId as ct, CompileOptionsSchema as d, isLeft as dn, CAPABILITY_REGISTRY as dt, scoped as en, EffortSchema as et, ExecutionPlan as f, isRight as fn, CapabilityNameSchema as ft, NATIVE_OUTPUT_REFERENCE_KEY as g, pluginIdsForOptionalCapabilities as gt, hydrateWorkflowPlanIR as h, migrateOptionalCapabilitySelections as ht, makeCapacityService as i, try_ as in, RoleTaskSchema as it, MAX_WORKFLOW_LIMITS as j, filter as jt, Workflow as k, declare as kt, mergeNativeWorkflowLimits as l, succeed$2 as ln, createSha256Digest as lt, compileWorkflowUnsafe as m, STATE_SCHEMA_EPOCH as mn, capabilityHealth as mt, evaluateWorkflowCompatibility as n, sync as nn, RoleSchema as nt, DEFAULT_NATIVE_WORKFLOW_LIMITS as o, mapError$2 as on, ServiceTierSchema as ot, compileWorkflow as p, CLI_SCHEMA_VERSION as pn, OPTIONAL_CAPABILITY_NAMES as pt, specialistOutcomeFromCapabilityResult as q, gen as qt, runWorkflowChild as r, tryPromise as rn, RoleSkillProfileSchema as rt, evaluateNativeWorkflowSource as s, provide$1 as sn, lookupRoleDefinition as st, evaluateWorkflow as t, succeed$1 as tn, PlanNameSchema as tt, transformNativeWorkflowSource as u, Tag as un, createTrustId as ut, freezeWorkflowPlanIR as v, decodeUnknown$1 as vt, decodePortableSchema as w, Record as wt, validateWorkflowPlanIR as x, Literal as xt, nativePlanJson as y, Array$ as yt, lookupRoute as z, optional as zt };
31946
+ export { EffortSchema as $, runPromise as $t, DEFAULT_WORKFLOW_LIMITS as A, declare as At, resolvePlanSelection as B, optional as Bt, workflowFailure as C, Null as Ct, Step as D, Struct as Dt, Run as E, String$ as Et, parseProtocolLine as F, int as Ft, parseCapabilityResultV2 as G, acquireRelease as Gt, SpecialistOutcomeSchema as H, positive as Ht, serializeProtocolMessage as I, maxItems as It, canonicalIdentityUtf8 as J, gen as Jt, parseCliEnvelope as K, async as Kt, toWireLimits as L, maxLength as Lt, WorkflowLimitsSchema as M, filter as Mt, WorkflowProtocolMessageSchema as N, greaterThan as Nt, Wait as O, Union as Ot, WorkflowRuntimeError as P, greaterThanOrEqualTo as Pt, DelegationModeSchema as Q, raceFirst as Qt, lookupPlan as R, minItems as Rt, isWorkflowFailure as S, Literal as St, Queue as T, Record as Tt, SpecialistOutcomeV2Schema as U, is as Ut, SPECIALIST_OUTCOME_VERSION as V, pattern as Vt, normalizeSpecialistOutcome as W, _void as Wt, canonicalJsonUtf8 as X, orElseSucceed as Xt, canonicalJson as Y, mapError$1 as Yt, domainSeparatedSha256 as Z, provide as Zt, NATIVE_WORKFLOW_ABI_VERSION as _, pluginIdsForOptionalCapabilities as _t, runExecutionPlan as a, try_ as an, RoleTaskSchema as at, nativeWorkflowIdentityDigest as b, Array$ as bt, loadNativeWorkflowSource as c, provide$1 as cn, lookupRoleDefinition as ct, CompileOptionsSchema as d, Tag as dn, createProjectId as dt, runSync as en, NativeAgentTypeSchema as et, ExecutionPlan as f, isLeft as fn, createSha256Digest as ft, NATIVE_OUTPUT_REFERENCE_KEY as g, OPTIONAL_CAPABILITY_NAMES as gt, hydrateWorkflowPlanIR as h, STATE_SCHEMA_EPOCH as hn, CapabilityNameSchema as ht, makeCapacityService as i, tryPromise as in, RoleSkillProfileSchema as it, MAX_WORKFLOW_LIMITS as j, decodeUnknownEither as jt, Workflow as k, Unknown as kt, mergeNativeWorkflowLimits as l, scoped$1 as ln, nativeAgentTypeFor as lt, compileWorkflowUnsafe as m, CLI_SCHEMA_VERSION as mn, CAPABILITY_REGISTRY as mt, evaluateWorkflowCompatibility as n, succeed$1 as nn, ROLE_DEFINITIONS as nt, DEFAULT_NATIVE_WORKFLOW_LIMITS as o, fromEffect as on, RouteKeySchema as ot, compileWorkflow as p, isRight as pn, createTrustId as pt, specialistOutcomeFromCapabilityResult as q, fail$1 as qt, runWorkflowChild as r, sync as rn, RoleSchema as rt, evaluateNativeWorkflowSource as s, mapError$2 as sn, ServiceTierSchema as st, evaluateWorkflow as t, scoped as tn, PlanNameSchema as tt, transformNativeWorkflowSource as u, succeed$2 as un, taskInstructionFor as ut, freezeWorkflowPlanIR as v, resolveOptionalCapabilitySelections as vt, decodePortableSchema as w, Number$ as wt, validateWorkflowPlanIR as x, Boolean$ as xt, nativePlanJson as y, decodeUnknown$1 as yt, lookupRoute as z, minLength as zt };