plugin-agent-orchestrator 1.1.4 → 1.1.5

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 (148) hide show
  1. package/README.md +204 -114
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/117.7565cff57c39318a.js +10 -0
  4. package/dist/client-v2/214.106635011859dede.js +10 -0
  5. package/dist/client-v2/418.41ed200e7d6da332.js +10 -0
  6. package/dist/client-v2/53.349fff8db80b19d4.js +10 -0
  7. package/dist/client-v2/981.e4a1f41cfc94a856.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +7 -8
  10. package/dist/locale/en-US.json +226 -170
  11. package/dist/locale/vi-VN.json +226 -170
  12. package/dist/locale/zh-CN.json +226 -170
  13. package/dist/server/collections/agent-execution-spans.js +8 -0
  14. package/dist/server/collections/agent-loop-action-approvals.js +1 -0
  15. package/dist/server/collections/agent-loop-runs.js +7 -1
  16. package/dist/server/collections/agent-loop-steps.js +7 -0
  17. package/dist/server/collections/skill-executions.js +8 -0
  18. package/dist/server/plugin.js +3 -1
  19. package/dist/server/resources/agent-harness-profile.js +117 -0
  20. package/dist/server/resources/agent-knowledge-insights.js +1 -3
  21. package/dist/server/resources/agent-loop-approval.js +25 -0
  22. package/dist/server/resources/agent-loop.js +3 -1
  23. package/dist/server/services/AgentMemoryContextService.js +34 -0
  24. package/dist/server/services/HarnessCompiler.js +35 -2
  25. package/dist/server/services/HarnessProfileService.js +74 -9
  26. package/dist/server/services/HarnessSchema.js +30 -3
  27. package/dist/server/services/LoopPatternSchema.js +16 -1
  28. package/dist/server/services/LoopRunRepository.js +80 -0
  29. package/dist/server/services/LoopRunStateMachine.js +92 -3
  30. package/dist/server/services/LoopTriggerService.js +37 -0
  31. package/dist/server/services/LoopWorkerService.js +261 -23
  32. package/dist/server/services/NativeSubAgentObserver.js +165 -23
  33. package/dist/server/services/PluginAiRuntimeAdapter.js +16 -5
  34. package/dist/server/services/ToolLoopDetectionService.js +210 -0
  35. package/dist/server/services/VerificationService.js +66 -0
  36. package/dist/server/services/harness-runtime-policy.js +139 -0
  37. package/dist/server/skill-hub/plugin.js +36 -3
  38. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +29 -0
  39. package/package.json +53 -53
  40. package/src/client/ApprovalsTab.tsx +2 -0
  41. package/src/client/OrchestratorSettings.tsx +11 -0
  42. package/src/client/skill-hub/components/GitSkillImport.tsx +3 -3
  43. package/src/client/skill-hub/components/SkillMetrics.tsx +15 -10
  44. package/src/client/skill-hub/index.tsx +0 -52
  45. package/src/client-v2/components/AgentRunsTab.tsx +576 -576
  46. package/src/client-v2/components/ApprovalsTab.tsx +337 -0
  47. package/src/client-v2/components/HarnessProfilesTab.tsx +385 -105
  48. package/src/client-v2/components/MemoryInspectorTab.tsx +141 -141
  49. package/src/client-v2/components/TracingTab.tsx +515 -515
  50. package/src/client-v2/hooks/useApiRequest.ts +141 -141
  51. package/src/client-v2/pages/ApprovalsPage.tsx +10 -0
  52. package/src/client-v2/plugin.tsx +6 -6
  53. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +5 -2
  54. package/src/locale/en-US.json +226 -174
  55. package/src/locale/vi-VN.json +226 -174
  56. package/src/locale/zh-CN.json +226 -174
  57. package/src/server/__tests__/circuit-breaker.test.ts +248 -248
  58. package/src/server/__tests__/harness-compiler.test.ts +83 -0
  59. package/src/server/__tests__/harness-profile-service.test.ts +51 -0
  60. package/src/server/__tests__/harness-runtime-policy.test.ts +293 -0
  61. package/src/server/__tests__/harness-tool-plan.test.ts +24 -0
  62. package/src/server/__tests__/loop-approval-decision.test.ts +512 -0
  63. package/src/server/__tests__/loop-approval-expiry.test.ts +258 -0
  64. package/src/server/__tests__/loop-budget-service.test.ts +255 -255
  65. package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -266
  66. package/src/server/__tests__/loop-pattern-schema.test.ts +18 -1
  67. package/src/server/__tests__/loop-pattern-service.test.ts +148 -148
  68. package/src/server/__tests__/loop-run-state-machine.test.ts +11 -0
  69. package/src/server/__tests__/loop-trigger-service.test.ts +148 -0
  70. package/src/server/__tests__/loop-worker-claim.test.ts +341 -341
  71. package/src/server/__tests__/loop-worker-execution.test.ts +82 -1
  72. package/src/server/__tests__/native-sub-agent-observer.test.ts +288 -4
  73. package/src/server/__tests__/path-lock-service.test.ts +254 -254
  74. package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -0
  75. package/src/server/__tests__/smoke.test.ts +162 -162
  76. package/src/server/__tests__/tool-loop-detection.test.ts +275 -0
  77. package/src/server/collections/agent-execution-spans.ts +8 -0
  78. package/src/server/collections/agent-harness-profile-versions.ts +26 -26
  79. package/src/server/collections/agent-harness-profiles.ts +71 -71
  80. package/src/server/collections/agent-loop-action-approvals.ts +1 -0
  81. package/src/server/collections/agent-loop-artifacts.ts +25 -25
  82. package/src/server/collections/agent-loop-circuit-states.ts +23 -23
  83. package/src/server/collections/agent-loop-control-settings.ts +21 -21
  84. package/src/server/collections/agent-loop-events.ts +98 -98
  85. package/src/server/collections/agent-loop-path-locks.ts +27 -27
  86. package/src/server/collections/agent-loop-patterns.ts +42 -42
  87. package/src/server/collections/agent-loop-runs.ts +7 -1
  88. package/src/server/collections/agent-loop-steps.ts +7 -0
  89. package/src/server/collections/agent-loop-usage-buckets.ts +22 -22
  90. package/src/server/collections/agent-loop-worktrees.ts +25 -25
  91. package/src/server/collections/skill-executions.ts +8 -0
  92. package/src/server/migrations/20260427000002-change-packages-to-text.ts +52 -52
  93. package/src/server/migrations/20260429000000-add-llm-fields.ts +47 -47
  94. package/src/server/migrations/20260429000001-fix-inputargs-json-to-text.ts +45 -45
  95. package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +33 -33
  96. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +31 -31
  97. package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -293
  98. package/src/server/plugin.ts +3 -1
  99. package/src/server/resources/agent-harness-profile.ts +94 -0
  100. package/src/server/resources/agent-knowledge-insights.ts +5 -3
  101. package/src/server/resources/agent-loop-approval.ts +32 -0
  102. package/src/server/resources/agent-loop-artifact.ts +56 -56
  103. package/src/server/resources/agent-loop-events-stream.ts +105 -105
  104. package/src/server/resources/agent-loop.ts +3 -1
  105. package/src/server/resources/resource-helpers.ts +33 -33
  106. package/src/server/resources/tracing.ts +266 -266
  107. package/src/server/services/AgentMemoryContextService.ts +44 -0
  108. package/src/server/services/DurableCircuitBreakerService.ts +239 -239
  109. package/src/server/services/ExecutionSpanService.ts +2 -0
  110. package/src/server/services/HarnessCompiler.ts +37 -0
  111. package/src/server/services/HarnessProfileService.ts +92 -10
  112. package/src/server/services/HarnessSchema.ts +31 -0
  113. package/src/server/services/LoopBudgetService.ts +275 -275
  114. package/src/server/services/LoopControlService.ts +124 -124
  115. package/src/server/services/LoopPatternSchema.ts +19 -1
  116. package/src/server/services/LoopPatternService.ts +143 -143
  117. package/src/server/services/LoopRunRepository.ts +99 -0
  118. package/src/server/services/LoopRunStateMachine.ts +100 -3
  119. package/src/server/services/LoopSchedulerService.ts +199 -199
  120. package/src/server/services/LoopTriggerService.ts +42 -0
  121. package/src/server/services/LoopWorkerService.ts +327 -27
  122. package/src/server/services/NativeSubAgentObserver.ts +186 -21
  123. package/src/server/services/PathLockService.ts +321 -321
  124. package/src/server/services/PluginAiRuntimeAdapter.ts +24 -7
  125. package/src/server/services/ToolLoopDetectionService.ts +213 -0
  126. package/src/server/services/VerificationSchema.ts +31 -31
  127. package/src/server/services/VerificationService.ts +81 -2
  128. package/src/server/services/harness-runtime-policy.ts +141 -0
  129. package/src/server/skill-hub/plugin.ts +41 -3
  130. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +235 -235
  131. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +61 -61
  132. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +43 -2
  133. package/src/server/utils/ensure-indexes.ts +96 -96
  134. package/src/server/utils/logging.ts +62 -62
  135. package/src/server/utils/loop-pattern-context.ts +20 -20
  136. package/dist/client-v2/214.b063f33ba044a808.js +0 -10
  137. package/dist/client-v2/373.f5d5292e53c4e832.js +0 -10
  138. package/dist/client-v2/418.58fa350f5496efd3.js +0 -10
  139. package/dist/client-v2/53.9a10455323390f14.js +0 -10
  140. package/dist/client-v2/677.a991ce0250ff5c77.js +0 -10
  141. package/dist/client-v2/925.e5925bf21ed68e7a.js +0 -10
  142. package/src/client/AIEmployeeSelect.tsx +0 -47
  143. package/src/client/AIEmployeesContext.tsx +0 -102
  144. package/src/client/RulesTab.tsx +0 -2
  145. package/src/client/TracingTab.tsx +0 -436
  146. package/src/client/skill-hub/components/ExecutionProgress.tsx +0 -51
  147. package/src/client-v2/components/RulesTab.tsx +0 -2
  148. package/src/client-v2/pages/AgentRunsPage.tsx +0 -13
@@ -30,6 +30,7 @@ __export(agent_loop_approval_exports, {
30
30
  });
31
31
  module.exports = __toCommonJS(agent_loop_approval_exports);
32
32
  var import_LoopRunRepository = require("../services/LoopRunRepository");
33
+ var import_ctx_utils = require("../utils/ctx-utils");
33
34
  var import_resource_helpers = require("./resource-helpers");
34
35
  function registerAgentLoopApprovalResource(plugin) {
35
36
  const repository = new import_LoopRunRepository.LoopRunRepository(plugin.db);
@@ -73,6 +74,30 @@ function registerAgentLoopApprovalResource(plugin) {
73
74
  (0, import_resource_helpers.throwResourceError)(ctx, error);
74
75
  }
75
76
  await next();
77
+ },
78
+ async decide(ctx, next) {
79
+ try {
80
+ const actor = (0, import_resource_helpers.requestActor)(ctx);
81
+ const approvalId = ctx.action.params.filterByTk;
82
+ if (!approvalId) ctx.throw(400, "approval id is required");
83
+ const values = (0, import_ctx_utils.valuesFromCtx)(ctx);
84
+ const decision = values.decision === "approve" ? "approved" : values.decision === "reject" ? "rejected" : null;
85
+ if (!decision) ctx.throw(400, 'decision must be "approve" or "reject"');
86
+ const editedInput = values.editedInput;
87
+ ctx.body = {
88
+ data: await repository.decideApproval({
89
+ approvalId,
90
+ userId: actor.userId,
91
+ isAdmin: actor.isAdmin,
92
+ decision,
93
+ note: typeof values.note === "string" ? values.note.trim() : "",
94
+ editedInput: decision === "approved" && editedInput !== void 0 ? Array.isArray(editedInput) ? editedInput : (0, import_ctx_utils.asObject)(editedInput) : void 0
95
+ })
96
+ };
97
+ } catch (error) {
98
+ (0, import_resource_helpers.throwResourceError)(ctx, error);
99
+ }
100
+ await next();
76
101
  }
77
102
  }
78
103
  });
@@ -197,7 +197,9 @@ function registerAgentLoopResource(plugin) {
197
197
  try {
198
198
  ctx.body = {
199
199
  data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, "queued", {
200
- values: { blockedReason: null, escalationReason: null },
200
+ // Retry is a fresh attempt from the leader: any interrupted-session resume point
201
+ // and prior approval outcome must not leak into the new attempt.
202
+ values: { blockedReason: null, escalationReason: null, resumeContext: null, approvalStatus: null },
201
203
  eventType: "run_retried"
202
204
  })
203
205
  };
@@ -30,6 +30,7 @@ __export(AgentMemoryContextService_exports, {
30
30
  });
31
31
  module.exports = __toCommonJS(AgentMemoryContextService_exports);
32
32
  var import_ctx_utils = require("../utils/ctx-utils");
33
+ var import_HarnessProfileService = require("./HarnessProfileService");
33
34
  const DEFAULT_MEMORY_SCOPES = ["public", "user", "agent_user"];
34
35
  const DEFAULT_MAX_CONTEXT_CHARS = 6e3;
35
36
  function readModelValue(record, key) {
@@ -43,6 +44,16 @@ function normalizeScopes(value) {
43
44
  function normalizeText(value) {
44
45
  return typeof value === "string" ? value.trim() : "";
45
46
  }
47
+ function flattenPublishedSettings(settings) {
48
+ return {
49
+ ...settings,
50
+ nativeObserverEnabled: settings.observability.enabled,
51
+ memoryInjectionEnabled: settings.memory.enabled,
52
+ memoryScopes: settings.memory.scopes,
53
+ maxMemoryContextChars: settings.memory.maxChars,
54
+ tracingRetentionDays: settings.observability.tracingRetentionDays
55
+ };
56
+ }
46
57
  function formatRecordSection(record) {
47
58
  const content = normalizeText(record.contentMd);
48
59
  const graph = normalizeText(record.graphMd);
@@ -59,6 +70,13 @@ class AgentMemoryContextService {
59
70
  const employeeSettings = (0, import_ctx_utils.asObject)(readModelValue(task == null ? void 0 : task.employee, "skillSettings"));
60
71
  const values = (0, import_ctx_utils.asObject)((_c = (_b = (_a = task == null ? void 0 : task.ctx) == null ? void 0 : _a.action) == null ? void 0 : _b.params) == null ? void 0 : _c.values);
61
72
  const requestedTag = normalizeText(values.harnessTag) || normalizeText(values.orchestratorHarnessTag) || normalizeText(directSettings.harnessTag) || normalizeText(directSettings.orchestratorHarnessTag) || normalizeText(employeeSettings.harnessTag) || normalizeText(employeeSettings.orchestratorHarnessTag) || await this.resolveConfiguredHarnessTag(task) || "default";
73
+ const published = await this.resolvePublishedSettings(requestedTag);
74
+ if (published) {
75
+ return {
76
+ ...published.settings,
77
+ harnessTag: published.tag
78
+ };
79
+ }
62
80
  const profile = await this.findHarnessProfile(requestedTag);
63
81
  const fallbackProfile = profile || (requestedTag === "default" ? null : await this.findHarnessProfile("default"));
64
82
  const profileSettings = (0, import_ctx_utils.asObject)(fallbackProfile ? readModelValue(fallbackProfile, "settings") : {});
@@ -138,6 +156,22 @@ ${(0, import_ctx_utils.trimText)(body, maxChars)}
138
156
  return null;
139
157
  }
140
158
  }
159
+ async resolvePublishedSettings(requestedTag) {
160
+ var _a, _b;
161
+ try {
162
+ const profiles = new import_HarnessProfileService.HarnessProfileService(this.plugin.db);
163
+ const direct = await profiles.getPublishedByTag(requestedTag);
164
+ if (direct) return { tag: requestedTag, settings: flattenPublishedSettings(direct.settings) };
165
+ if (requestedTag !== "default") {
166
+ const fallback = await profiles.getPublishedByTag("default");
167
+ if (fallback) return { tag: "default", settings: flattenPublishedSettings(fallback.settings) };
168
+ }
169
+ return null;
170
+ } catch (error) {
171
+ (_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Failed to load published policy profile", error);
172
+ return null;
173
+ }
174
+ }
141
175
  async resolveConfiguredHarnessTag(task) {
142
176
  var _a, _b, _c, _d, _e, _f, _g;
143
177
  const values = (0, import_ctx_utils.asObject)((_c = (_b = (_a = task == null ? void 0 : task.ctx) == null ? void 0 : _a.action) == null ? void 0 : _b.params) == null ? void 0 : _c.values);
@@ -67,6 +67,26 @@ function strictestNetwork(values) {
67
67
  "allow"
68
68
  );
69
69
  }
70
+ const sharingRank = {
71
+ full: 0,
72
+ "feedback-only": 1,
73
+ disabled: 2
74
+ };
75
+ function strictestSharing(values) {
76
+ return values.reduce(
77
+ (strictest, value) => sharingRank[value] > sharingRank[strictest] ? value : strictest,
78
+ "full"
79
+ );
80
+ }
81
+ function mergeTimeouts(settings) {
82
+ const timeouts = {};
83
+ for (const layer of settings) {
84
+ for (const [name, timeoutMs] of Object.entries(layer.tools.timeouts)) {
85
+ timeouts[name] = timeouts[name] === void 0 ? timeoutMs : Math.min(timeouts[name], timeoutMs);
86
+ }
87
+ }
88
+ return timeouts;
89
+ }
70
90
  function compileHarness(layers) {
71
91
  if (!layers.length) {
72
92
  throw new Error("At least one harness layer is required.");
@@ -88,8 +108,12 @@ function compileHarness(layers) {
88
108
  allow: intersectRestrictions(settings.map((layer) => layer.tools.allow)),
89
109
  ask: union(settings.map((layer) => layer.tools.ask)),
90
110
  deny: union(settings.map((layer) => layer.tools.deny)),
111
+ // Escalatable tools widen authority per approved call, so a child may only inherit the
112
+ // escalation surface every layer agrees on — same semantics as `allow`.
113
+ escalate: intersectRestrictions(settings.map((layer) => layer.tools.escalate)),
91
114
  effects,
92
- trustedPreHandlerTools: intersectRestrictions(settings.map((layer) => layer.tools.trustedPreHandlerTools))
115
+ trustedPreHandlerTools: intersectRestrictions(settings.map((layer) => layer.tools.trustedPreHandlerTools)),
116
+ timeouts: mergeTimeouts(settings)
93
117
  },
94
118
  memory: {
95
119
  enabled: settings.every((layer) => layer.memory.enabled),
@@ -113,6 +137,11 @@ function compileHarness(layers) {
113
137
  maxTotalTokens: minimumNullable(settings.map((layer) => layer.limits.maxTotalTokens)),
114
138
  maxCost: minimumNullable(settings.map((layer) => layer.limits.maxCost))
115
139
  },
140
+ context: {
141
+ spill: {
142
+ maxInlineBytes: minimumNullable(settings.map((layer) => layer.context.spill.maxInlineBytes))
143
+ }
144
+ },
116
145
  isolation: {
117
146
  mode: settings.some((layer) => layer.isolation.mode === "worktree") ? "worktree" : "none",
118
147
  requireWorktree: settings.some((layer) => layer.isolation.requireWorktree),
@@ -123,7 +152,11 @@ function compileHarness(layers) {
123
152
  enabled: settings.every((layer) => layer.observability.enabled),
124
153
  tracingRetentionDays: Math.min(...settings.map((layer) => layer.observability.tracingRetentionDays)),
125
154
  captureInputs: settings.every((layer) => layer.observability.captureInputs),
126
- captureOutputs: settings.every((layer) => layer.observability.captureOutputs)
155
+ captureOutputs: settings.every((layer) => layer.observability.captureOutputs),
156
+ // Any layer demanding redaction wins; any layer restricting sharing wins. Telemetry safety
157
+ // is union-of-concerns, not intersection.
158
+ redactSecrets: settings.some((layer) => layer.observability.redactSecrets),
159
+ sharing: strictestSharing(settings.map((layer) => layer.observability.sharing))
127
160
  }
128
161
  };
129
162
  }
@@ -60,10 +60,39 @@ class HarnessProfileService {
60
60
  validate(settings) {
61
61
  return (0, import_HarnessSchema.validateHarnessSettings)(settings);
62
62
  }
63
- async createDraft(input) {
63
+ async createDraft(input, transaction) {
64
64
  const profileId = positiveId(input.profileId, "Harness profile id");
65
65
  const schemaVersion = positiveId(input.schemaVersion || 1, "Harness schema version");
66
66
  const settings = (0, import_HarnessSchema.parseHarnessSettings)(input.settings);
67
+ const create = async (active) => {
68
+ await this.lockProfile(profileId, active);
69
+ const versions = this.database.getRepository("agentHarnessProfileVersions");
70
+ const latest = await versions.findOne({
71
+ filter: { profileId },
72
+ sort: ["-version"],
73
+ transaction: active
74
+ });
75
+ const nextVersion = latest ? positiveId(read(latest, "version"), "Harness profile version") + 1 : 1;
76
+ const draft = await versions.create({
77
+ values: {
78
+ profileId,
79
+ version: nextVersion,
80
+ schemaVersion,
81
+ status: "draft",
82
+ settings
83
+ },
84
+ transaction: active
85
+ });
86
+ return versionRecord(draft);
87
+ };
88
+ return transaction ? create(transaction) : this.database.sequelize.transaction(create);
89
+ }
90
+ // One open draft per profile: editing saves into the latest draft when it has not been
91
+ // published yet, and only starts a new version once the previous one shipped. This keeps the
92
+ // version history a clean publish trail instead of accumulating abandoned drafts.
93
+ async saveDraft(input) {
94
+ const profileId = positiveId(input.profileId, "Harness profile id");
95
+ const settings = (0, import_HarnessSchema.parseHarnessSettings)(input.settings);
67
96
  return this.database.sequelize.transaction(async (transaction) => {
68
97
  await this.lockProfile(profileId, transaction);
69
98
  const versions = this.database.getRepository("agentHarnessProfileVersions");
@@ -72,7 +101,14 @@ class HarnessProfileService {
72
101
  sort: ["-version"],
73
102
  transaction
74
103
  });
104
+ if (latest && read(latest, "status") !== "published") {
105
+ await versions.update({ filterByTk: read(latest, "id"), values: { settings }, transaction });
106
+ const updated = await versions.findOne({ filterByTk: read(latest, "id"), transaction });
107
+ if (!updated) throw new Error(`Harness profile version ${read(latest, "id")} was not found after update.`);
108
+ return versionRecord(updated);
109
+ }
75
110
  const nextVersion = latest ? positiveId(read(latest, "version"), "Harness profile version") + 1 : 1;
111
+ const schemaVersion = latest ? positiveId(read(latest, "schemaVersion") || 1, "Harness schema version") : 1;
76
112
  const draft = await versions.create({
77
113
  values: {
78
114
  profileId,
@@ -100,15 +136,15 @@ class HarnessProfileService {
100
136
  if (!updated) throw new Error(`Harness profile version ${id} was not found after update.`);
101
137
  return versionRecord(updated);
102
138
  }
103
- async publish(versionId, publishedById) {
139
+ async publish(versionId, publishedById, transaction) {
104
140
  const id = positiveId(versionId, "Harness profile version id");
105
- return this.database.sequelize.transaction(async (transaction) => {
141
+ const publishVersion = async (active) => {
106
142
  const versions = this.database.getRepository("agentHarnessProfileVersions");
107
- const candidate = await versions.findOne({ filterByTk: id, transaction });
143
+ const candidate = await versions.findOne({ filterByTk: id, transaction: active });
108
144
  if (!candidate) throw new Error(`Harness profile version ${id} was not found.`);
109
145
  const profileId = positiveId(read(candidate, "profileId"), "Harness profile id");
110
- await this.lockProfile(profileId, transaction);
111
- const current = await versions.findOne({ filterByTk: id, transaction });
146
+ await this.lockProfile(profileId, active);
147
+ const current = await versions.findOne({ filterByTk: id, transaction: active });
112
148
  if (!current) throw new Error(`Harness profile version ${id} was not found.`);
113
149
  if (read(current, "status") === "published") {
114
150
  return versionRecord(current);
@@ -123,7 +159,7 @@ class HarnessProfileService {
123
159
  publishedById: publishedById ? positiveId(publishedById, "Publisher id") : null,
124
160
  publishedAt: now
125
161
  },
126
- transaction
162
+ transaction: active
127
163
  });
128
164
  await this.database.getRepository("agentHarnessProfiles").update({
129
165
  filterByTk: profileId,
@@ -131,11 +167,40 @@ class HarnessProfileService {
131
167
  currentVersionId: id,
132
168
  schemaVersion: positiveId(read(current, "schemaVersion"), "Harness schema version")
133
169
  },
134
- transaction
170
+ transaction: active
135
171
  });
136
- const published = await versions.findOne({ filterByTk: id, transaction });
172
+ const published = await versions.findOne({ filterByTk: id, transaction: active });
137
173
  if (!published) throw new Error(`Harness profile version ${id} was not found after publish.`);
138
174
  return versionRecord(published);
175
+ };
176
+ return transaction ? publishVersion(transaction) : this.database.sequelize.transaction(publishVersion);
177
+ }
178
+ // Atomic bootstrap: the profile row and its first published version are created together, so a
179
+ // profile can never exist in a state where the row promises settings no version accounts for.
180
+ async createProfile(input) {
181
+ const tag = input.tag.trim();
182
+ if (!tag) throw new Error("Harness profile tag is required.");
183
+ const settings = (0, import_HarnessSchema.parseHarnessSettings)(input.settings);
184
+ return this.database.sequelize.transaction(async (transaction) => {
185
+ const profile = await this.database.getRepository("agentHarnessProfiles").create({
186
+ values: {
187
+ tag,
188
+ title: input.title || "",
189
+ description: input.description || "",
190
+ enabled: input.enabled !== false,
191
+ schemaVersion: 1
192
+ },
193
+ transaction
194
+ });
195
+ const profileId = positiveId(read(profile, "id"), "Harness profile id");
196
+ const draft = await this.createDraft({ profileId, settings }, transaction);
197
+ const published = await this.publish(draft.id, input.publishedById, transaction);
198
+ const created = await this.database.getRepository("agentHarnessProfiles").findOne({
199
+ filterByTk: profileId,
200
+ transaction
201
+ });
202
+ if (!created) throw new Error(`Harness profile ${profileId} was not found after create.`);
203
+ return { profile: created, version: published };
139
204
  });
140
205
  }
141
206
  async getPublishedByTag(tag) {
@@ -44,8 +44,15 @@ const harnessSettingsSchema = import_zod.z.object({
44
44
  allow: import_zod.z.array(import_zod.z.string().min(1)).default([]),
45
45
  ask: import_zod.z.array(import_zod.z.string().min(1)).default([]),
46
46
  deny: import_zod.z.array(import_zod.z.string().min(1)).default([]),
47
+ // Tools the harness does not grant but may be requested for a single call: invoking one
48
+ // interrupts exactly like `ask` and parks the run, but the approval row is tagged as an
49
+ // escalation. Approving widens authority for that one call only; the harness is unchanged.
50
+ escalate: import_zod.z.array(import_zod.z.string().min(1)).default([]),
47
51
  effects: import_zod.z.record(toolEffectSchema).default({}),
48
- trustedPreHandlerTools: import_zod.z.array(import_zod.z.string().min(1)).default([])
52
+ trustedPreHandlerTools: import_zod.z.array(import_zod.z.string().min(1)).default([]),
53
+ // Per-tool wall-clock caps in milliseconds. Only enforceable where this plugin owns the
54
+ // execution pipeline (skill hub sandbox); elsewhere it is advisory observability data.
55
+ timeouts: import_zod.z.record(import_zod.z.number().int().positive()).default({})
49
56
  }).default({}),
50
57
  memory: import_zod.z.object({
51
58
  enabled: import_zod.z.boolean().default(true),
@@ -67,6 +74,13 @@ const harnessSettingsSchema = import_zod.z.object({
67
74
  maxTotalTokens: import_zod.z.number().int().nonnegative().nullable().default(null),
68
75
  maxCost: nullableLimit
69
76
  }).default({}),
77
+ context: import_zod.z.object({
78
+ spill: import_zod.z.object({
79
+ // Tool/sub-agent outputs larger than this many UTF-8 bytes are stored on disk and
80
+ // replaced inline by a head/tail preview plus a locator. null keeps everything inline.
81
+ maxInlineBytes: import_zod.z.number().int().positive().nullable().default(null)
82
+ }).default({})
83
+ }).default({}),
70
84
  isolation: import_zod.z.object({
71
85
  mode: import_zod.z.enum(["none", "worktree"]).default("none"),
72
86
  requireWorktree: import_zod.z.boolean().default(false),
@@ -77,7 +91,13 @@ const harnessSettingsSchema = import_zod.z.object({
77
91
  enabled: import_zod.z.boolean().default(true),
78
92
  tracingRetentionDays: import_zod.z.number().int().positive().max(3650).default(30),
79
93
  captureInputs: import_zod.z.boolean().default(true),
80
- captureOutputs: import_zod.z.boolean().default(true)
94
+ captureOutputs: import_zod.z.boolean().default(true),
95
+ // Scrub values whose key names look secret-bearing (KEY/SECRET/TOKEN/PASSWORD/CREDENTIAL)
96
+ // before span inputs are persisted. Defaults on: telemetry must never be the leak vector.
97
+ redactSecrets: import_zod.z.boolean().default(true),
98
+ // Who span content may be shared with: full = inputs+outputs, feedback-only = outputs
99
+ // only, disabled = no span content persisted at all.
100
+ sharing: import_zod.z.enum(["full", "feedback-only", "disabled"]).default("full")
81
101
  }).default({})
82
102
  }).strict();
83
103
  function isRecord(value) {
@@ -96,6 +116,7 @@ function normalizeHarnessSettings(value) {
96
116
  const memory = isRecord(source.memory) ? source.memory : {};
97
117
  const delegation = isRecord(source.delegation) ? source.delegation : {};
98
118
  const limits = isRecord(source.limits) ? source.limits : {};
119
+ const context = isRecord(source.context) ? source.context : {};
99
120
  const isolation = isRecord(source.isolation) ? source.isolation : {};
100
121
  const observability = isRecord(source.observability) ? source.observability : {};
101
122
  const knownKeys = /* @__PURE__ */ new Set([
@@ -128,8 +149,10 @@ function normalizeHarnessSettings(value) {
128
149
  allow: stringArray(tools.allow),
129
150
  ask: stringArray(tools.ask),
130
151
  deny: stringArray(tools.deny),
152
+ escalate: stringArray(tools.escalate),
131
153
  effects: isRecord(tools.effects) ? tools.effects : {},
132
- trustedPreHandlerTools: stringArray(tools.trustedPreHandlerTools)
154
+ trustedPreHandlerTools: stringArray(tools.trustedPreHandlerTools),
155
+ timeouts: isRecord(tools.timeouts) ? tools.timeouts : {}
133
156
  },
134
157
  memory: {
135
158
  ...memory,
@@ -142,6 +165,10 @@ function normalizeHarnessSettings(value) {
142
165
  allowedEmployees: stringArray(delegation.allowedEmployees)
143
166
  },
144
167
  limits,
168
+ context: {
169
+ ...context,
170
+ spill: isRecord(context.spill) ? context.spill : {}
171
+ },
145
172
  isolation,
146
173
  observability: {
147
174
  ...observability,
@@ -72,8 +72,23 @@ const loopPatternPolicySchema = import_zod.z.object({
72
72
  verification: import_zod.z.object({
73
73
  requiredChecks: import_zod.z.array(import_zod.z.string().min(1)).min(1).default(["goal"]),
74
74
  maxAttempts: import_zod.z.number().int().positive().default(2)
75
+ }).default({}),
76
+ loopDetection: import_zod.z.object({
77
+ enabled: import_zod.z.boolean().default(true),
78
+ warnAt: import_zod.z.number().int().positive().default(3),
79
+ blockAt: import_zod.z.number().int().positive().default(5),
80
+ escalateAt: import_zod.z.number().int().positive().default(8)
75
81
  }).default({})
76
- }).strict();
82
+ }).strict().superRefine((policy, context) => {
83
+ const { warnAt, blockAt, escalateAt } = policy.loopDetection;
84
+ if (!(warnAt < blockAt && blockAt < escalateAt)) {
85
+ context.addIssue({
86
+ code: import_zod.z.ZodIssueCode.custom,
87
+ path: ["loopDetection"],
88
+ message: "Loop detection thresholds must satisfy warnAt < blockAt < escalateAt."
89
+ });
90
+ }
91
+ });
77
92
  const loopPatternSchema = import_zod.z.object({
78
93
  key: import_zod.z.string().trim().min(1).max(120).regex(/^[a-z0-9][a-z0-9._-]*$/),
79
94
  title: import_zod.z.string().trim().min(1).max(240),
@@ -30,6 +30,7 @@ __export(LoopRunRepository_exports, {
30
30
  LoopRunRepository: () => LoopRunRepository
31
31
  });
32
32
  module.exports = __toCommonJS(LoopRunRepository_exports);
33
+ var import_RunEventBus = require("./RunEventBus");
33
34
  class LoopRunAccessError extends Error {
34
35
  constructor(status, message) {
35
36
  super(message);
@@ -166,6 +167,85 @@ class LoopRunRepository {
166
167
  }
167
168
  return approval;
168
169
  }
170
+ // Records a human decision on one approval and requeues the run once every pending approval of
171
+ // the run has been decided. Fail-closed throughout: an expired window, a decided row, or a run
172
+ // that moved on all reject the decision instead of guessing what the human meant.
173
+ async decideApproval(input) {
174
+ const decidedById = requireUserId(input.userId);
175
+ const id = positiveId(input.approvalId, "Agent loop approval");
176
+ await this.requireAccessibleApproval(id, input.userId, input.isAdmin);
177
+ const committed = await this.database.sequelize.transaction(async (transaction) => {
178
+ const approvals = this.database.getRepository("agentLoopActionApprovals");
179
+ const runs = this.database.getRepository("agentLoopRuns");
180
+ const record = await approvals.findOne({ filterByTk: id, transaction, lock: transaction.LOCK.UPDATE });
181
+ if (!record) throw new LoopRunAccessError(404, `Agent loop approval ${id} was not found.`);
182
+ const approval = plain(record);
183
+ if (approval.status !== "pending") {
184
+ throw new LoopRunAccessError(409, `This approval has already been ${String(approval.status)}.`);
185
+ }
186
+ const expiresAt = approval.expiresAt ? new Date(String(approval.expiresAt)) : null;
187
+ if (expiresAt && !Number.isNaN(expiresAt.getTime()) && expiresAt.getTime() <= Date.now()) {
188
+ throw new LoopRunAccessError(409, "The approval window has expired. Retry the run to request approval again.");
189
+ }
190
+ const runId = positiveId(approval.runId, "Agent loop run");
191
+ const runRecord = await runs.findOne({ filterByTk: runId, transaction, lock: transaction.LOCK.UPDATE });
192
+ if (!runRecord) throw new LoopRunAccessError(404, `Agent loop run ${runId} was not found.`);
193
+ const run = plain(runRecord);
194
+ if (run.runtimeVersion !== "control-plane-v2") {
195
+ throw new LoopRunAccessError(409, "Historical plan-era runs are read-only.");
196
+ }
197
+ if (run.status !== "waiting_approval" && run.status !== "paused") {
198
+ throw new LoopRunAccessError(409, "The run is no longer waiting for approval.");
199
+ }
200
+ const now = /* @__PURE__ */ new Date();
201
+ await approvals.update({
202
+ filterByTk: id,
203
+ values: {
204
+ status: input.decision,
205
+ decidedById,
206
+ decidedAt: now,
207
+ decisionNote: input.note || null,
208
+ ...input.decision === "approved" && input.editedInput !== void 0 ? { editedInput: input.editedInput } : {}
209
+ },
210
+ transaction
211
+ });
212
+ const remaining = await approvals.find({ filter: { runId, status: "pending" }, transaction });
213
+ let requeued = false;
214
+ let event = null;
215
+ if (!remaining.length && run.status === "waiting_approval") {
216
+ await runs.update({
217
+ filterByTk: runId,
218
+ values: { status: "queued", approvalStatus: "decided" },
219
+ transaction
220
+ });
221
+ const created = await this.database.getRepository("agentLoopEvents").create({
222
+ values: {
223
+ runId,
224
+ type: "run_approval_decided",
225
+ title: "Approvals decided",
226
+ content: "All pending action approvals were decided. Run requeued to resume.",
227
+ status: "queued",
228
+ payload: { decision: input.decision },
229
+ actorType: "human",
230
+ actorIdentity: String(decidedById),
231
+ correlationKey: `approval-decided:${runId}`,
232
+ createdAt: now
233
+ },
234
+ transaction
235
+ });
236
+ event = typeof created.toJSON === "function" ? created.toJSON() : created;
237
+ requeued = true;
238
+ }
239
+ return { approval, runId, requeued, event };
240
+ });
241
+ if (committed.requeued && committed.event) (0, import_RunEventBus.getRunEventBus)().emit(committed.runId, committed.event);
242
+ return {
243
+ ...committed.approval,
244
+ status: input.decision,
245
+ decidedById,
246
+ requeued: committed.requeued
247
+ };
248
+ }
169
249
  async listArtifacts(input) {
170
250
  const userId = requireUserId(input.userId);
171
251
  const accessible = input.isAdmin ? {} : { "run.userId": userId };
@@ -52,10 +52,28 @@ const loopRunStatuses = [
52
52
  ];
53
53
  const transitions = {
54
54
  queued: /* @__PURE__ */ new Set(["preparing", "paused", "blocked", "canceled"]),
55
- preparing: /* @__PURE__ */ new Set(["queued", "waiting_lock", "running", "paused", "blocked", "failed", "canceled"]),
55
+ preparing: /* @__PURE__ */ new Set([
56
+ "queued",
57
+ "waiting_lock",
58
+ "waiting_approval",
59
+ "running",
60
+ "paused",
61
+ "blocked",
62
+ "failed",
63
+ "canceled"
64
+ ]),
56
65
  waiting_lock: /* @__PURE__ */ new Set(["preparing", "paused", "blocked", "canceled"]),
57
- running: /* @__PURE__ */ new Set(["queued", "waiting_approval", "verifying", "paused", "blocked", "failed", "canceled"]),
58
- waiting_approval: /* @__PURE__ */ new Set(["running", "waiting_human", "paused", "blocked", "failed", "canceled"]),
66
+ running: /* @__PURE__ */ new Set([
67
+ "queued",
68
+ "waiting_approval",
69
+ "verifying",
70
+ "waiting_human",
71
+ "paused",
72
+ "blocked",
73
+ "failed",
74
+ "canceled"
75
+ ]),
76
+ waiting_approval: /* @__PURE__ */ new Set(["queued", "running", "waiting_human", "paused", "blocked", "failed", "canceled"]),
59
77
  verifying: /* @__PURE__ */ new Set(["running", "waiting_human", "paused", "blocked", "succeeded", "failed", "canceled"]),
60
78
  waiting_human: /* @__PURE__ */ new Set(["running", "succeeded", "failed", "canceled"]),
61
79
  paused: /* @__PURE__ */ new Set(["queued", "preparing", "running", "waiting_approval", "verifying", "blocked", "canceled"]),
@@ -281,6 +299,77 @@ class LoopRunStateMachine {
281
299
  leaseUntil: committed.claimed.leaseUntil
282
300
  };
283
301
  }
302
+ // Approval windows fail closed: an unanswered request blocks the run instead of silently
303
+ // turning into an approval. Runs only move while they are still `waiting_approval`, so a
304
+ // decision recorded through another path always wins the race against this sweep.
305
+ async expireOverdueApprovals(now) {
306
+ const blockedRunIds = [];
307
+ const committedEvents = [];
308
+ await this.database.sequelize.transaction(async (transaction) => {
309
+ const approvals = this.database.getRepository("agentLoopActionApprovals");
310
+ const runs = this.database.getRepository("agentLoopRuns");
311
+ const pending = await approvals.find({ filter: { status: "pending" }, transaction });
312
+ const overdueByRun = /* @__PURE__ */ new Map();
313
+ for (const approval of pending) {
314
+ const expiresAt = asDate(read(approval, "expiresAt"));
315
+ if (!expiresAt || expiresAt.getTime() > now.getTime()) continue;
316
+ const runId = Number(read(approval, "runId"));
317
+ if (!Number.isSafeInteger(runId) || runId <= 0) continue;
318
+ const bucket = overdueByRun.get(runId) || [];
319
+ bucket.push(approval);
320
+ overdueByRun.set(runId, bucket);
321
+ }
322
+ for (const [runId, overdue] of overdueByRun) {
323
+ const run = await runs.findOne({ filterByTk: runId, transaction, lock: transaction.LOCK.UPDATE });
324
+ if (!run) continue;
325
+ if (String(read(run, "runtimeVersion")) !== "control-plane-v2") continue;
326
+ if (asStatus(read(run, "status")) !== "waiting_approval") continue;
327
+ assertRunTransition({
328
+ from: "waiting_approval",
329
+ to: "blocked",
330
+ runtimeVersion: String(read(run, "runtimeVersion") || "")
331
+ });
332
+ for (const approval of overdue) {
333
+ await approvals.update({
334
+ filterByTk: Number(read(approval, "id")),
335
+ values: { status: "expired", decidedAt: now },
336
+ transaction
337
+ });
338
+ }
339
+ const reason = `${overdue.length} action approval(s) expired before a decision was made.`;
340
+ await runs.update({
341
+ filterByTk: runId,
342
+ values: {
343
+ status: "blocked",
344
+ blockedReason: reason,
345
+ approvalStatus: "expired",
346
+ lockedBy: null,
347
+ lockedUntil: null
348
+ },
349
+ transaction
350
+ });
351
+ const event = await this.createEvent(
352
+ {
353
+ runId,
354
+ type: "run_approval_expired",
355
+ title: "Approval window expired",
356
+ content: reason,
357
+ status: "blocked",
358
+ payload: { reason, expiredApprovals: overdue.length },
359
+ actorType: "system",
360
+ actorIdentity: "approval-reaper",
361
+ correlationKey: `approval-expired:${runId}`,
362
+ createdAt: now
363
+ },
364
+ transaction
365
+ );
366
+ blockedRunIds.push(runId);
367
+ committedEvents.push({ runId, event });
368
+ }
369
+ });
370
+ for (const blocked of committedEvents) (0, import_RunEventBus.getRunEventBus)().emit(blocked.runId, blocked.event);
371
+ return blockedRunIds;
372
+ }
284
373
  async renewLease(runId, leaseToken, leaseMs) {
285
374
  if (!leaseToken.trim()) throw new Error("Worker lease token is required.");
286
375
  if (!Number.isSafeInteger(leaseMs) || leaseMs < 5e3) throw new Error("Worker lease must be at least 5000ms.");
@@ -41,6 +41,18 @@ function plain(record) {
41
41
  function isUniqueConstraintError(error) {
42
42
  return error instanceof Error && error.name === "SequelizeUniqueConstraintError";
43
43
  }
44
+ function harnessAppliedEvents(compiled) {
45
+ const roles = [
46
+ { role: "leader", username: compiled.roleBindings.leader, snapshot: compiled.leaderHarness },
47
+ ...compiled.roleBindings.makers.map((username) => ({
48
+ role: "maker",
49
+ username,
50
+ snapshot: compiled.makerHarnesses[username]
51
+ })),
52
+ { role: "verifier", username: compiled.roleBindings.verifier, snapshot: compiled.verifierHarness }
53
+ ];
54
+ return roles.filter((entry) => entry.snapshot);
55
+ }
44
56
  class LoopTriggerService {
45
57
  constructor(database, patterns) {
46
58
  this.database = database;
@@ -110,6 +122,31 @@ class LoopTriggerService {
110
122
  },
111
123
  transaction
112
124
  });
125
+ for (const entry of harnessAppliedEvents(compiled)) {
126
+ await this.database.getRepository("agentLoopEvents").create({
127
+ values: {
128
+ runId,
129
+ type: "harness_applied",
130
+ title: `Harness ${entry.snapshot.tag}@v${entry.snapshot.version} applied to ${entry.role}`,
131
+ content: `${entry.role} ${entry.username} executes under harness profile ${entry.snapshot.tag} version ${entry.snapshot.version}.`,
132
+ status: "queued",
133
+ payload: {
134
+ role: entry.role,
135
+ username: entry.username,
136
+ tag: entry.snapshot.tag,
137
+ version: entry.snapshot.version,
138
+ versionId: entry.snapshot.versionId,
139
+ schemaVersion: entry.snapshot.schemaVersion
140
+ },
141
+ actorType: input.triggerType === "manual" ? "user" : "system",
142
+ actorIdentity: input.userId ? String(input.userId) : input.triggerType,
143
+ correlationKey: `harness:${entry.role}:${entry.username}`,
144
+ userId: input.userId || null,
145
+ createdAt: now
146
+ },
147
+ transaction
148
+ });
149
+ }
113
150
  return { created: true, run: plain(run) };
114
151
  });
115
152
  } catch (error) {