plugin-agent-orchestrator 1.1.4 → 1.1.6

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
@@ -0,0 +1,94 @@
1
+ import type { Plugin } from '@nocobase/server';
2
+ import { HarnessProfileService } from '../services/HarnessProfileService';
3
+ import { valuesFromCtx } from '../utils/ctx-utils';
4
+ import { requestActor, throwResourceError } from './resource-helpers';
5
+
6
+ // Versioning surface for harness policy profiles. Draft/publish go through HarnessProfileService
7
+ // so the revision guards (validated settings, immutable published versions, row-locked version
8
+ // numbering) apply to HTTP callers exactly as they do to the loop compiler.
9
+ export function registerAgentHarnessProfileResource(plugin: Plugin) {
10
+ const service = new HarnessProfileService(plugin.db);
11
+
12
+ plugin.app.resource({
13
+ name: 'agentHarnessProfiles',
14
+ actions: {
15
+ async listVersions(ctx, next) {
16
+ try {
17
+ const profileId = ctx.action.params.filterByTk;
18
+ if (!profileId) ctx.throw(400, 'profile id is required');
19
+ const rows = await plugin.db.getRepository('agentHarnessProfileVersions').find({
20
+ filter: { profileId },
21
+ sort: ['-version'],
22
+ });
23
+ ctx.body = { data: rows };
24
+ } catch (error) {
25
+ throwResourceError(ctx, error);
26
+ }
27
+ await next();
28
+ },
29
+
30
+ async saveDraft(ctx, next) {
31
+ try {
32
+ const profileId = ctx.action.params.filterByTk;
33
+ if (!profileId) ctx.throw(400, 'profile id is required');
34
+ const values = valuesFromCtx(ctx);
35
+ ctx.body = {
36
+ data: await service.saveDraft({ profileId, settings: values.settings }),
37
+ };
38
+ } catch (error) {
39
+ throwResourceError(ctx, error);
40
+ }
41
+ await next();
42
+ },
43
+
44
+ async publish(ctx, next) {
45
+ try {
46
+ const actor = requestActor(ctx);
47
+ const values = valuesFromCtx(ctx);
48
+ const versionId = values.versionId ?? ctx.action.params.filterByTk;
49
+ if (!versionId) ctx.throw(400, 'version id is required');
50
+ ctx.body = {
51
+ data: await service.publish(versionId, actor.userId),
52
+ };
53
+ } catch (error) {
54
+ throwResourceError(ctx, error);
55
+ }
56
+ await next();
57
+ },
58
+
59
+ async createProfile(ctx, next) {
60
+ try {
61
+ const actor = requestActor(ctx);
62
+ const values = valuesFromCtx(ctx);
63
+ const result = await service.createProfile({
64
+ tag: typeof values.tag === 'string' ? values.tag : '',
65
+ title: typeof values.title === 'string' ? values.title : '',
66
+ description: typeof values.description === 'string' ? values.description : '',
67
+ enabled: values.enabled !== false,
68
+ settings: values.settings,
69
+ publishedById: actor.userId,
70
+ });
71
+ ctx.body = { data: result };
72
+ } catch (error) {
73
+ throwResourceError(ctx, error);
74
+ }
75
+ await next();
76
+ },
77
+
78
+ async validate(ctx, next) {
79
+ try {
80
+ const values = valuesFromCtx(ctx);
81
+ const result = service.validate(values.settings);
82
+ ctx.body = {
83
+ data: result.success
84
+ ? { success: true, issues: [] }
85
+ : { success: false, issues: result.error.issues.map((issue) => issue.message) },
86
+ };
87
+ } catch (error) {
88
+ throwResourceError(ctx, error);
89
+ }
90
+ await next();
91
+ },
92
+ },
93
+ });
94
+ }
@@ -220,9 +220,11 @@ export function registerAgentKnowledgeInsightsResource(plugin: Plugin) {
220
220
  sort: ['username'],
221
221
  appends: ['roles'],
222
222
  });
223
- const knowledgeBases = await ctx.db.getRepository('aiKnowledgeBases').find({
224
- sort: ['name'],
225
- });
223
+ // plugin-knowledge-base is an optional integration: when it is disabled the collection
224
+ // is not registered, and the matrix degrades to employees without knowledge bases.
225
+ const knowledgeBases = ctx.db.hasCollection('aiKnowledgeBases')
226
+ ? await ctx.db.getRepository('aiKnowledgeBases').find({ sort: ['name'] })
227
+ : [];
226
228
  ctx.body = { data: buildKnowledgeAccessMatrix(employees, knowledgeBases) };
227
229
  await next();
228
230
  },
@@ -1,5 +1,6 @@
1
1
  import type { Plugin } from '@nocobase/server';
2
2
  import { LoopRunRepository } from '../services/LoopRunRepository';
3
+ import { asObject, valuesFromCtx } from '../utils/ctx-utils';
3
4
  import { requestActor, throwResourceError } from './resource-helpers';
4
5
 
5
6
  export function registerAgentLoopApprovalResource(plugin: Plugin) {
@@ -47,6 +48,37 @@ export function registerAgentLoopApprovalResource(plugin: Plugin) {
47
48
  }
48
49
  await next();
49
50
  },
51
+
52
+ async decide(ctx, next) {
53
+ try {
54
+ const actor = requestActor(ctx);
55
+ const approvalId = ctx.action.params.filterByTk;
56
+ if (!approvalId) ctx.throw(400, 'approval id is required');
57
+ const values = valuesFromCtx(ctx);
58
+ const decision =
59
+ values.decision === 'approve' ? 'approved' : values.decision === 'reject' ? 'rejected' : null;
60
+ if (!decision) ctx.throw(400, 'decision must be "approve" or "reject"');
61
+ const editedInput = values.editedInput;
62
+ ctx.body = {
63
+ data: await repository.decideApproval({
64
+ approvalId,
65
+ userId: actor.userId,
66
+ isAdmin: actor.isAdmin,
67
+ decision,
68
+ note: typeof values.note === 'string' ? values.note.trim() : '',
69
+ editedInput:
70
+ decision === 'approved' && editedInput !== undefined
71
+ ? Array.isArray(editedInput)
72
+ ? editedInput
73
+ : asObject(editedInput)
74
+ : undefined,
75
+ }),
76
+ };
77
+ } catch (error) {
78
+ throwResourceError(ctx, error);
79
+ }
80
+ await next();
81
+ },
50
82
  },
51
83
  });
52
84
  }
@@ -1,56 +1,56 @@
1
- import type { Plugin } from '@nocobase/server';
2
- import { LoopRunRepository, type LoopRunRecord } from '../services/LoopRunRepository';
3
- import { requestActor, throwResourceError } from './resource-helpers';
4
-
5
- function artifactMetadata(artifact: LoopRunRecord) {
6
- const { uri: _storageReference, ...metadata } = artifact;
7
- return metadata;
8
- }
9
-
10
- export function registerAgentLoopArtifactResource(plugin: Plugin) {
11
- const repository = new LoopRunRepository(plugin.db);
12
-
13
- plugin.app.resource({
14
- name: 'agentLoopArtifactsView',
15
- actions: {
16
- async list(ctx, next) {
17
- try {
18
- const actor = requestActor(ctx);
19
- const result = await repository.listArtifacts({
20
- userId: actor.userId,
21
- isAdmin: actor.isAdmin,
22
- filter: ctx.action.params.filter || {},
23
- sort: ctx.action.params.sort,
24
- page: Number(ctx.action.params.page),
25
- pageSize: Number(ctx.action.params.pageSize),
26
- });
27
- ctx.body = {
28
- data: result.rows.map(artifactMetadata),
29
- meta: {
30
- count: result.count,
31
- page: result.page,
32
- pageSize: result.pageSize,
33
- totalPage: result.totalPage,
34
- },
35
- };
36
- } catch (error) {
37
- throwResourceError(ctx, error);
38
- }
39
- await next();
40
- },
41
-
42
- async get(ctx, next) {
43
- try {
44
- const actor = requestActor(ctx);
45
- const artifactId = ctx.action.params.filterByTk;
46
- if (!artifactId) ctx.throw(400, 'artifact id is required');
47
- const artifact = await repository.requireOwnedArtifact(artifactId, actor.userId, actor.isAdmin);
48
- ctx.body = { data: artifactMetadata(artifact) };
49
- } catch (error) {
50
- throwResourceError(ctx, error);
51
- }
52
- await next();
53
- },
54
- },
55
- });
56
- }
1
+ import type { Plugin } from '@nocobase/server';
2
+ import { LoopRunRepository, type LoopRunRecord } from '../services/LoopRunRepository';
3
+ import { requestActor, throwResourceError } from './resource-helpers';
4
+
5
+ function artifactMetadata(artifact: LoopRunRecord) {
6
+ const { uri: _storageReference, ...metadata } = artifact;
7
+ return metadata;
8
+ }
9
+
10
+ export function registerAgentLoopArtifactResource(plugin: Plugin) {
11
+ const repository = new LoopRunRepository(plugin.db);
12
+
13
+ plugin.app.resource({
14
+ name: 'agentLoopArtifactsView',
15
+ actions: {
16
+ async list(ctx, next) {
17
+ try {
18
+ const actor = requestActor(ctx);
19
+ const result = await repository.listArtifacts({
20
+ userId: actor.userId,
21
+ isAdmin: actor.isAdmin,
22
+ filter: ctx.action.params.filter || {},
23
+ sort: ctx.action.params.sort,
24
+ page: Number(ctx.action.params.page),
25
+ pageSize: Number(ctx.action.params.pageSize),
26
+ });
27
+ ctx.body = {
28
+ data: result.rows.map(artifactMetadata),
29
+ meta: {
30
+ count: result.count,
31
+ page: result.page,
32
+ pageSize: result.pageSize,
33
+ totalPage: result.totalPage,
34
+ },
35
+ };
36
+ } catch (error) {
37
+ throwResourceError(ctx, error);
38
+ }
39
+ await next();
40
+ },
41
+
42
+ async get(ctx, next) {
43
+ try {
44
+ const actor = requestActor(ctx);
45
+ const artifactId = ctx.action.params.filterByTk;
46
+ if (!artifactId) ctx.throw(400, 'artifact id is required');
47
+ const artifact = await repository.requireOwnedArtifact(artifactId, actor.userId, actor.isAdmin);
48
+ ctx.body = { data: artifactMetadata(artifact) };
49
+ } catch (error) {
50
+ throwResourceError(ctx, error);
51
+ }
52
+ await next();
53
+ },
54
+ },
55
+ });
56
+ }
@@ -1,105 +1,105 @@
1
- import type { Context } from '@nocobase/actions';
2
- import type { Plugin } from '@nocobase/server';
3
- import { LoopRunRepository } from '../services/LoopRunRepository';
4
- import { getRunEventBus } from '../services/RunEventBus';
5
- import { requestActor, throwResourceError } from './resource-helpers';
6
-
7
- const POLL_INTERVAL_MS = 1500;
8
-
9
- function eventId(event: unknown) {
10
- if (!event || typeof event !== 'object') return 0;
11
- const id = Number((event as Record<string, unknown>).id);
12
- return Number.isSafeInteger(id) && id > 0 ? id : 0;
13
- }
14
-
15
- function plainEvent(event: unknown) {
16
- if (!event || typeof event !== 'object') return event;
17
- const record = event as { toJSON?: () => unknown };
18
- return typeof record.toJSON === 'function' ? record.toJSON() : event;
19
- }
20
-
21
- function writeEvent(ctx: Context, event: unknown) {
22
- const id = eventId(event);
23
- if (id > 0) ctx.res.write(`id: ${id}\n`);
24
- ctx.res.write(`data: ${JSON.stringify(plainEvent(event))}\n\n`);
25
- }
26
-
27
- export function registerAgentLoopEventsStreamResource(plugin: Plugin) {
28
- const repository = new LoopRunRepository(plugin.db);
29
-
30
- plugin.app.resource({
31
- name: 'agentLoopEventsStream',
32
- actions: {
33
- async stream(ctx, next) {
34
- try {
35
- const actor = requestActor(ctx);
36
- const runId = Number(ctx.action.params.runId || ctx.action.params.filterByTk);
37
- if (!Number.isSafeInteger(runId) || runId <= 0) ctx.throw(400, 'runId is required');
38
- await repository.requireOwnedRun(runId, actor.userId, actor.isAdmin);
39
-
40
- ctx.set({
41
- 'Content-Type': 'text/event-stream',
42
- 'Cache-Control': 'no-cache',
43
- Connection: 'keep-alive',
44
- });
45
- ctx.status = 200;
46
-
47
- let closed = false;
48
- let lastEventId = Number(ctx.get('Last-Event-ID')) || 0;
49
- const close = () => {
50
- closed = true;
51
- };
52
- const send = (event: unknown) => {
53
- const id = eventId(event);
54
- if (closed || ctx.res.destroyed || ctx.res.writableEnded || (id > 0 && id <= lastEventId)) return;
55
- writeEvent(ctx, event);
56
- if (id > 0) lastEventId = id;
57
- };
58
-
59
- ctx.req.once('aborted', close);
60
- ctx.res.once('close', close);
61
- const unsubscribe = getRunEventBus().subscribe(runId, send);
62
-
63
- try {
64
- const initial = await ctx.db.getRepository('agentLoopEvents').find({
65
- filter: lastEventId > 0 ? { runId, id: { $gt: lastEventId } } : { runId },
66
- sort: ['id'],
67
- pageSize: 1000,
68
- });
69
- for (const event of initial) send(event);
70
-
71
- await new Promise<void>((resolve) => {
72
- const poll = async () => {
73
- if (closed || ctx.res.destroyed || ctx.res.writableEnded) {
74
- resolve();
75
- return;
76
- }
77
- try {
78
- const events = await ctx.db.getRepository('agentLoopEvents').find({
79
- filter: { runId, id: { $gt: lastEventId } },
80
- sort: ['id'],
81
- pageSize: 1000,
82
- });
83
- for (const event of events) send(event);
84
- } catch (error) {
85
- ctx.log.error('[AgentOrchestrator] Failed to poll loop events', error);
86
- }
87
- if (closed || ctx.res.destroyed || ctx.res.writableEnded) resolve();
88
- else setTimeout(poll, POLL_INTERVAL_MS);
89
- };
90
- setTimeout(poll, POLL_INTERVAL_MS);
91
- });
92
- } finally {
93
- unsubscribe();
94
- ctx.req.off('aborted', close);
95
- ctx.res.off('close', close);
96
- if (!ctx.res.destroyed && !ctx.res.writableEnded) ctx.res.end();
97
- }
98
- } catch (error) {
99
- throwResourceError(ctx, error);
100
- }
101
- await next();
102
- },
103
- },
104
- });
105
- }
1
+ import type { Context } from '@nocobase/actions';
2
+ import type { Plugin } from '@nocobase/server';
3
+ import { LoopRunRepository } from '../services/LoopRunRepository';
4
+ import { getRunEventBus } from '../services/RunEventBus';
5
+ import { requestActor, throwResourceError } from './resource-helpers';
6
+
7
+ const POLL_INTERVAL_MS = 1500;
8
+
9
+ function eventId(event: unknown) {
10
+ if (!event || typeof event !== 'object') return 0;
11
+ const id = Number((event as Record<string, unknown>).id);
12
+ return Number.isSafeInteger(id) && id > 0 ? id : 0;
13
+ }
14
+
15
+ function plainEvent(event: unknown) {
16
+ if (!event || typeof event !== 'object') return event;
17
+ const record = event as { toJSON?: () => unknown };
18
+ return typeof record.toJSON === 'function' ? record.toJSON() : event;
19
+ }
20
+
21
+ function writeEvent(ctx: Context, event: unknown) {
22
+ const id = eventId(event);
23
+ if (id > 0) ctx.res.write(`id: ${id}\n`);
24
+ ctx.res.write(`data: ${JSON.stringify(plainEvent(event))}\n\n`);
25
+ }
26
+
27
+ export function registerAgentLoopEventsStreamResource(plugin: Plugin) {
28
+ const repository = new LoopRunRepository(plugin.db);
29
+
30
+ plugin.app.resource({
31
+ name: 'agentLoopEventsStream',
32
+ actions: {
33
+ async stream(ctx, next) {
34
+ try {
35
+ const actor = requestActor(ctx);
36
+ const runId = Number(ctx.action.params.runId || ctx.action.params.filterByTk);
37
+ if (!Number.isSafeInteger(runId) || runId <= 0) ctx.throw(400, 'runId is required');
38
+ await repository.requireOwnedRun(runId, actor.userId, actor.isAdmin);
39
+
40
+ ctx.set({
41
+ 'Content-Type': 'text/event-stream',
42
+ 'Cache-Control': 'no-cache',
43
+ Connection: 'keep-alive',
44
+ });
45
+ ctx.status = 200;
46
+
47
+ let closed = false;
48
+ let lastEventId = Number(ctx.get('Last-Event-ID')) || 0;
49
+ const close = () => {
50
+ closed = true;
51
+ };
52
+ const send = (event: unknown) => {
53
+ const id = eventId(event);
54
+ if (closed || ctx.res.destroyed || ctx.res.writableEnded || (id > 0 && id <= lastEventId)) return;
55
+ writeEvent(ctx, event);
56
+ if (id > 0) lastEventId = id;
57
+ };
58
+
59
+ ctx.req.once('aborted', close);
60
+ ctx.res.once('close', close);
61
+ const unsubscribe = getRunEventBus().subscribe(runId, send);
62
+
63
+ try {
64
+ const initial = await ctx.db.getRepository('agentLoopEvents').find({
65
+ filter: lastEventId > 0 ? { runId, id: { $gt: lastEventId } } : { runId },
66
+ sort: ['id'],
67
+ pageSize: 1000,
68
+ });
69
+ for (const event of initial) send(event);
70
+
71
+ await new Promise<void>((resolve) => {
72
+ const poll = async () => {
73
+ if (closed || ctx.res.destroyed || ctx.res.writableEnded) {
74
+ resolve();
75
+ return;
76
+ }
77
+ try {
78
+ const events = await ctx.db.getRepository('agentLoopEvents').find({
79
+ filter: { runId, id: { $gt: lastEventId } },
80
+ sort: ['id'],
81
+ pageSize: 1000,
82
+ });
83
+ for (const event of events) send(event);
84
+ } catch (error) {
85
+ ctx.log.error('[AgentOrchestrator] Failed to poll loop events', error);
86
+ }
87
+ if (closed || ctx.res.destroyed || ctx.res.writableEnded) resolve();
88
+ else setTimeout(poll, POLL_INTERVAL_MS);
89
+ };
90
+ setTimeout(poll, POLL_INTERVAL_MS);
91
+ });
92
+ } finally {
93
+ unsubscribe();
94
+ ctx.req.off('aborted', close);
95
+ ctx.res.off('close', close);
96
+ if (!ctx.res.destroyed && !ctx.res.writableEnded) ctx.res.end();
97
+ }
98
+ } catch (error) {
99
+ throwResourceError(ctx, error);
100
+ }
101
+ await next();
102
+ },
103
+ },
104
+ });
105
+ }
@@ -194,7 +194,9 @@ export function registerAgentLoopResource(plugin: LoopResourcePlugin) {
194
194
  try {
195
195
  ctx.body = {
196
196
  data: await transitionOwnedRun(plugin, stateMachine, repository, ctx, 'queued', {
197
- values: { blockedReason: null, escalationReason: null },
197
+ // Retry is a fresh attempt from the leader: any interrupted-session resume point
198
+ // and prior approval outcome must not leak into the new attempt.
199
+ values: { blockedReason: null, escalationReason: null, resumeContext: null, approvalStatus: null },
198
200
  eventType: 'run_retried',
199
201
  }),
200
202
  };
@@ -1,33 +1,33 @@
1
- import type { Context } from '@nocobase/actions';
2
- import { ZodError } from 'zod';
3
- import { currentUserId, isAdminUser } from '../utils/ctx-utils';
4
- import { LoopRunAccessError } from '../services/LoopRunRepository';
5
-
6
- export type RequestActor = {
7
- userId: number;
8
- isAdmin: boolean;
9
- };
10
-
11
- export function requestActor(ctx: Context): RequestActor {
12
- const userId = Number(currentUserId(ctx));
13
- if (!Number.isSafeInteger(userId) || userId <= 0) {
14
- throw new LoopRunAccessError(401, 'Authentication is required.');
15
- }
16
- return { userId, isAdmin: isAdminUser(ctx) };
17
- }
18
-
19
- export function requireAdminActor(ctx: Context) {
20
- const actor = requestActor(ctx);
21
- if (!actor.isAdmin) throw new LoopRunAccessError(403, 'Administrator access is required.');
22
- return actor;
23
- }
24
-
25
- export function throwResourceError(ctx: Context, error: unknown): never {
26
- if (error instanceof LoopRunAccessError) {
27
- ctx.throw(error.status, error.message);
28
- }
29
- if (error instanceof ZodError) {
30
- ctx.throw(400, error.issues.map((issue) => issue.message).join(' '));
31
- }
32
- ctx.throw(409, error instanceof Error ? error.message : 'The requested operation could not be completed.');
33
- }
1
+ import type { Context } from '@nocobase/actions';
2
+ import { ZodError } from 'zod';
3
+ import { currentUserId, isAdminUser } from '../utils/ctx-utils';
4
+ import { LoopRunAccessError } from '../services/LoopRunRepository';
5
+
6
+ export type RequestActor = {
7
+ userId: number;
8
+ isAdmin: boolean;
9
+ };
10
+
11
+ export function requestActor(ctx: Context): RequestActor {
12
+ const userId = Number(currentUserId(ctx));
13
+ if (!Number.isSafeInteger(userId) || userId <= 0) {
14
+ throw new LoopRunAccessError(401, 'Authentication is required.');
15
+ }
16
+ return { userId, isAdmin: isAdminUser(ctx) };
17
+ }
18
+
19
+ export function requireAdminActor(ctx: Context) {
20
+ const actor = requestActor(ctx);
21
+ if (!actor.isAdmin) throw new LoopRunAccessError(403, 'Administrator access is required.');
22
+ return actor;
23
+ }
24
+
25
+ export function throwResourceError(ctx: Context, error: unknown): never {
26
+ if (error instanceof LoopRunAccessError) {
27
+ ctx.throw(error.status, error.message);
28
+ }
29
+ if (error instanceof ZodError) {
30
+ ctx.throw(400, error.issues.map((issue) => issue.message).join(' '));
31
+ }
32
+ ctx.throw(409, error instanceof Error ? error.message : 'The requested operation could not be completed.');
33
+ }