plugin-agent-orchestrator 1.1.0 → 1.1.3

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 (162) hide show
  1. package/dist/externalVersion.js +6 -6
  2. package/dist/locale/en-US.json +7 -1
  3. package/dist/locale/vi-VN.json +7 -1
  4. package/dist/locale/zh-CN.json +7 -1
  5. package/dist/node_modules/ajv/.tonic_example.js +20 -0
  6. package/dist/node_modules/ajv/LICENSE +22 -0
  7. package/dist/node_modules/ajv/dist/ajv.bundle.js +7189 -0
  8. package/dist/node_modules/ajv/dist/ajv.min.js +3 -0
  9. package/dist/node_modules/ajv/lib/ajv.d.ts +397 -0
  10. package/dist/node_modules/ajv/lib/ajv.js +3 -0
  11. package/dist/node_modules/ajv/lib/cache.js +26 -0
  12. package/dist/node_modules/ajv/lib/compile/async.js +90 -0
  13. package/dist/node_modules/ajv/lib/compile/equal.js +5 -0
  14. package/dist/node_modules/ajv/lib/compile/error_classes.js +34 -0
  15. package/dist/node_modules/ajv/lib/compile/formats.js +142 -0
  16. package/dist/node_modules/ajv/lib/compile/index.js +387 -0
  17. package/dist/node_modules/ajv/lib/compile/resolve.js +270 -0
  18. package/dist/node_modules/ajv/lib/compile/rules.js +66 -0
  19. package/dist/node_modules/ajv/lib/compile/schema_obj.js +9 -0
  20. package/dist/node_modules/ajv/lib/compile/ucs2length.js +20 -0
  21. package/dist/node_modules/ajv/lib/compile/util.js +239 -0
  22. package/dist/node_modules/ajv/lib/data.js +49 -0
  23. package/dist/node_modules/ajv/lib/definition_schema.js +37 -0
  24. package/dist/node_modules/ajv/lib/dot/_limit.jst +113 -0
  25. package/dist/node_modules/ajv/lib/dot/_limitItems.jst +12 -0
  26. package/dist/node_modules/ajv/lib/dot/_limitLength.jst +12 -0
  27. package/dist/node_modules/ajv/lib/dot/_limitProperties.jst +12 -0
  28. package/dist/node_modules/ajv/lib/dot/allOf.jst +32 -0
  29. package/dist/node_modules/ajv/lib/dot/anyOf.jst +46 -0
  30. package/dist/node_modules/ajv/lib/dot/coerce.def +51 -0
  31. package/dist/node_modules/ajv/lib/dot/comment.jst +9 -0
  32. package/dist/node_modules/ajv/lib/dot/const.jst +11 -0
  33. package/dist/node_modules/ajv/lib/dot/contains.jst +55 -0
  34. package/dist/node_modules/ajv/lib/dot/custom.jst +191 -0
  35. package/dist/node_modules/ajv/lib/dot/defaults.def +47 -0
  36. package/dist/node_modules/ajv/lib/dot/definitions.def +203 -0
  37. package/dist/node_modules/ajv/lib/dot/dependencies.jst +79 -0
  38. package/dist/node_modules/ajv/lib/dot/enum.jst +30 -0
  39. package/dist/node_modules/ajv/lib/dot/errors.def +194 -0
  40. package/dist/node_modules/ajv/lib/dot/format.jst +106 -0
  41. package/dist/node_modules/ajv/lib/dot/if.jst +73 -0
  42. package/dist/node_modules/ajv/lib/dot/items.jst +98 -0
  43. package/dist/node_modules/ajv/lib/dot/missing.def +39 -0
  44. package/dist/node_modules/ajv/lib/dot/multipleOf.jst +22 -0
  45. package/dist/node_modules/ajv/lib/dot/not.jst +43 -0
  46. package/dist/node_modules/ajv/lib/dot/oneOf.jst +54 -0
  47. package/dist/node_modules/ajv/lib/dot/pattern.jst +14 -0
  48. package/dist/node_modules/ajv/lib/dot/properties.jst +245 -0
  49. package/dist/node_modules/ajv/lib/dot/propertyNames.jst +52 -0
  50. package/dist/node_modules/ajv/lib/dot/ref.jst +85 -0
  51. package/dist/node_modules/ajv/lib/dot/required.jst +108 -0
  52. package/dist/node_modules/ajv/lib/dot/uniqueItems.jst +62 -0
  53. package/dist/node_modules/ajv/lib/dot/validate.jst +276 -0
  54. package/dist/node_modules/ajv/lib/dotjs/_limit.js +163 -0
  55. package/dist/node_modules/ajv/lib/dotjs/_limitItems.js +80 -0
  56. package/dist/node_modules/ajv/lib/dotjs/_limitLength.js +85 -0
  57. package/dist/node_modules/ajv/lib/dotjs/_limitProperties.js +80 -0
  58. package/dist/node_modules/ajv/lib/dotjs/allOf.js +42 -0
  59. package/dist/node_modules/ajv/lib/dotjs/anyOf.js +73 -0
  60. package/dist/node_modules/ajv/lib/dotjs/comment.js +14 -0
  61. package/dist/node_modules/ajv/lib/dotjs/const.js +56 -0
  62. package/dist/node_modules/ajv/lib/dotjs/contains.js +81 -0
  63. package/dist/node_modules/ajv/lib/dotjs/custom.js +228 -0
  64. package/dist/node_modules/ajv/lib/dotjs/dependencies.js +168 -0
  65. package/dist/node_modules/ajv/lib/dotjs/enum.js +66 -0
  66. package/dist/node_modules/ajv/lib/dotjs/format.js +150 -0
  67. package/dist/node_modules/ajv/lib/dotjs/if.js +103 -0
  68. package/dist/node_modules/ajv/lib/dotjs/index.js +33 -0
  69. package/dist/node_modules/ajv/lib/dotjs/items.js +140 -0
  70. package/dist/node_modules/ajv/lib/dotjs/multipleOf.js +80 -0
  71. package/dist/node_modules/ajv/lib/dotjs/not.js +84 -0
  72. package/dist/node_modules/ajv/lib/dotjs/oneOf.js +73 -0
  73. package/dist/node_modules/ajv/lib/dotjs/pattern.js +75 -0
  74. package/dist/node_modules/ajv/lib/dotjs/properties.js +335 -0
  75. package/dist/node_modules/ajv/lib/dotjs/propertyNames.js +81 -0
  76. package/dist/node_modules/ajv/lib/dotjs/ref.js +124 -0
  77. package/dist/node_modules/ajv/lib/dotjs/required.js +270 -0
  78. package/dist/node_modules/ajv/lib/dotjs/uniqueItems.js +86 -0
  79. package/dist/node_modules/ajv/lib/dotjs/validate.js +482 -0
  80. package/dist/node_modules/ajv/lib/keyword.js +146 -0
  81. package/dist/node_modules/ajv/lib/refs/data.json +17 -0
  82. package/dist/node_modules/ajv/lib/refs/json-schema-draft-04.json +149 -0
  83. package/dist/node_modules/ajv/lib/refs/json-schema-draft-06.json +154 -0
  84. package/dist/node_modules/ajv/lib/refs/json-schema-draft-07.json +168 -0
  85. package/dist/node_modules/ajv/lib/refs/json-schema-secure.json +94 -0
  86. package/dist/node_modules/ajv/node_modules/json-schema-traverse/.eslintrc.yml +27 -0
  87. package/dist/node_modules/ajv/node_modules/json-schema-traverse/.travis.yml +8 -0
  88. package/dist/node_modules/ajv/node_modules/json-schema-traverse/index.js +89 -0
  89. package/dist/node_modules/ajv/node_modules/json-schema-traverse/package.json +43 -0
  90. package/dist/node_modules/ajv/node_modules/json-schema-traverse/spec/.eslintrc.yml +6 -0
  91. package/dist/node_modules/ajv/node_modules/json-schema-traverse/spec/fixtures/schema.js +125 -0
  92. package/dist/node_modules/ajv/node_modules/json-schema-traverse/spec/index.spec.js +171 -0
  93. package/dist/node_modules/ajv/package.json +1 -0
  94. package/dist/node_modules/ajv/scripts/.eslintrc.yml +3 -0
  95. package/dist/node_modules/ajv/scripts/bundle.js +61 -0
  96. package/dist/node_modules/ajv/scripts/compile-dots.js +73 -0
  97. package/dist/node_modules/ajv/scripts/info +10 -0
  98. package/dist/node_modules/ajv/scripts/prepare-tests +12 -0
  99. package/dist/node_modules/ajv/scripts/publish-built-version +32 -0
  100. package/dist/node_modules/ajv/scripts/travis-gh-pages +23 -0
  101. package/dist/server/collections/skill-definitions.js +31 -0
  102. package/dist/server/collections/skill-executions.js +19 -0
  103. package/dist/server/collections/skill-registry-installations.js +70 -0
  104. package/dist/server/migrations/20260727010000-backfill-skill-tool-names.js +66 -0
  105. package/dist/server/plugin.js +96 -1
  106. package/dist/server/services/AgentExecutionContext.js +45 -0
  107. package/dist/server/services/CodeValidator.js +1 -0
  108. package/dist/server/services/ExecutionSpanService.js +10 -2
  109. package/dist/server/services/InputSchemaValidator.js +83 -0
  110. package/dist/server/services/NativeSubAgentObserver.js +55 -8
  111. package/dist/server/services/SandboxRunner.js +6 -2
  112. package/dist/server/services/SkillAccessService.js +109 -0
  113. package/dist/server/services/SkillManager.js +2 -0
  114. package/dist/server/services/SkillRepositoryService.js +70 -0
  115. package/dist/server/skill-hub/actions/git-import.js +479 -216
  116. package/dist/server/skill-hub/mcp/McpController.js +8 -5
  117. package/dist/server/skill-hub/middlewares/git-import-request-method-policy.js +69 -0
  118. package/dist/server/skill-hub/plugin.js +68 -14
  119. package/dist/server/skill-hub/services/RegistrySkillInstallationService.js +249 -0
  120. package/dist/server/skill-hub/services/RegistrySkillSnapshotService.js +228 -0
  121. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +15 -3
  122. package/dist/server/tools/skill-execute.js +23 -2
  123. package/dist/server/utils/ctx-utils.js +2 -2
  124. package/dist/server/utils/skill-tool-name.js +73 -0
  125. package/package.json +9 -3
  126. package/src/locale/en-US.json +7 -1
  127. package/src/locale/vi-VN.json +7 -1
  128. package/src/locale/zh-CN.json +7 -1
  129. package/src/server/__tests__/agent-execution-context.test.ts +18 -0
  130. package/src/server/__tests__/input-schema-validator.test.ts +26 -0
  131. package/src/server/__tests__/native-sub-agent-observer.test.ts +52 -2
  132. package/src/server/__tests__/skill-access-service.test.ts +64 -0
  133. package/src/server/__tests__/skill-execute.test.ts +37 -0
  134. package/src/server/__tests__/skill-tool-name.test.ts +23 -0
  135. package/src/server/collections/skill-definitions.ts +31 -0
  136. package/src/server/collections/skill-executions.ts +19 -0
  137. package/src/server/collections/skill-registry-installations.ts +41 -0
  138. package/src/server/migrations/20260727010000-backfill-skill-tool-names.ts +45 -0
  139. package/src/server/plugin.ts +104 -1
  140. package/src/server/services/AgentExecutionContext.ts +23 -0
  141. package/src/server/services/CodeValidator.ts +1 -0
  142. package/src/server/services/ExecutionSpanService.ts +119 -110
  143. package/src/server/services/InputSchemaValidator.ts +44 -0
  144. package/src/server/services/NativeSubAgentObserver.ts +64 -10
  145. package/src/server/services/SandboxRunner.ts +6 -0
  146. package/src/server/services/SkillAccessService.ts +100 -0
  147. package/src/server/services/SkillManager.ts +2 -0
  148. package/src/server/services/SkillRepositoryService.ts +98 -2
  149. package/src/server/services/__tests__/SkillRepositoryService.test.ts +33 -0
  150. package/src/server/skill-hub/actions/__tests__/git-import.test.ts +549 -0
  151. package/src/server/skill-hub/actions/git-import.ts +682 -236
  152. package/src/server/skill-hub/mcp/McpController.ts +8 -14
  153. package/src/server/skill-hub/middlewares/git-import-request-method-policy.ts +51 -0
  154. package/src/server/skill-hub/plugin.ts +79 -13
  155. package/src/server/skill-hub/services/RegistrySkillInstallationService.ts +281 -0
  156. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +239 -0
  157. package/src/server/skill-hub/services/__tests__/RegistrySkillInstallationService.test.ts +295 -0
  158. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +63 -0
  159. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +14 -2
  160. package/src/server/tools/skill-execute.ts +24 -2
  161. package/src/server/utils/ctx-utils.ts +1 -1
  162. package/src/server/utils/skill-tool-name.ts +58 -0
@@ -1,110 +1,119 @@
1
- import { toPlain } from '../utils/ctx-utils';
2
-
3
- export const ORCHESTRATOR_TRACE_CONTEXT_KEY = '__orchestratorTraceContext';
4
-
5
- export type OrchestratorTraceContext = {
6
- rootRunId: string;
7
- spanId?: string;
8
- parentSpanId?: string;
9
- toolCallId?: string;
10
- leaderUsername?: string;
11
- employeeUsername?: string;
12
- toolName?: string;
13
- agentLoopRunId?: string;
14
- agentLoopStepId?: string;
15
- };
16
-
17
- type SpanValues = {
18
- rootRunId: string;
19
- parentSpanId?: string;
20
- source?: string;
21
- parentSessionId?: string;
22
- subSessionId?: string;
23
- toolCallId?: string;
24
- type: string;
25
- status: string;
26
- leaderUsername?: string;
27
- employeeUsername?: string;
28
- toolName?: string;
29
- title?: string;
30
- input?: any;
31
- output?: string;
32
- error?: string;
33
- durationMs?: number;
34
- startedAt?: Date;
35
- endedAt?: Date;
36
- orchestratorLogId?: string | number;
37
- skillExecutionId?: string | number;
38
- metadata?: any;
39
- userId?: string | number;
40
- };
41
-
42
- export class ExecutionSpanService {
43
- constructor(private readonly plugin: any) {}
44
-
45
- async create(values: SpanValues) {
46
- try {
47
- const repo = this.plugin.db.getRepository('agentExecutionSpans');
48
- if (!repo) return null;
49
-
50
- const record = await repo.create({
51
- values: {
52
- ...values,
53
- startedAt: values.startedAt || new Date(),
54
- createdAt: new Date(),
55
- },
56
- });
57
- return toPlain(record);
58
- } catch (error) {
59
- this.plugin.app.logger?.warn?.('[AgentOrchestrator] Failed to create execution span', error);
60
- return null;
61
- }
62
- }
63
-
64
- async update(spanId: string | number | undefined, values: Record<string, any>) {
65
- if (!spanId) return null;
66
- try {
67
- const repo = this.plugin.db.getRepository('agentExecutionSpans');
68
- if (!repo) return null;
69
- await repo.update({
70
- filterByTk: spanId,
71
- values: {
72
- ...values,
73
- updatedAt: new Date(),
74
- },
75
- });
76
- return { id: spanId };
77
- } catch (error) {
78
- this.plugin.app.logger?.warn?.(`[AgentOrchestrator] Failed to update execution span ${spanId}`, error);
79
- return null;
80
- }
81
- }
82
-
83
- async finish(
84
- spanId: string | number | undefined,
85
- status: 'success' | 'error' | 'canceled' | 'timeout',
86
- startedAt: number,
87
- values: Record<string, any> = {},
88
- ) {
89
- return this.update(spanId, {
90
- ...values,
91
- status,
92
- endedAt: new Date(),
93
- durationMs: Date.now() - startedAt,
94
- });
95
- }
96
- }
97
-
98
- export function getOrchestratorTraceContext(ctx: any): OrchestratorTraceContext | null {
99
- return (
100
- ctx?.[ORCHESTRATOR_TRACE_CONTEXT_KEY] ||
101
- ctx?.state?.orchestratorTraceContext ||
102
- ctx?.runtime?.context?.orchestratorTraceContext ||
103
- null
104
- );
105
- }
106
-
107
- export function setOrchestratorTraceContext(ctx: any, traceContext: OrchestratorTraceContext) {
108
- ctx[ORCHESTRATOR_TRACE_CONTEXT_KEY] = traceContext;
109
- return ctx;
110
- }
1
+ import { toPlain } from '../utils/ctx-utils';
2
+ import { getAgentExecutionContext } from './AgentExecutionContext';
3
+
4
+ export const ORCHESTRATOR_TRACE_CONTEXT_KEY = '__orchestratorTraceContext';
5
+
6
+ export type OrchestratorTraceContext = {
7
+ rootRunId: string;
8
+ spanId?: string;
9
+ parentSpanId?: string;
10
+ toolCallId?: string;
11
+ leaderUsername?: string;
12
+ employeeUsername?: string;
13
+ toolName?: string;
14
+ agentLoopRunId?: string;
15
+ agentLoopStepId?: string;
16
+ sessionId?: string;
17
+ };
18
+
19
+ type SpanValues = {
20
+ rootRunId: string;
21
+ parentSpanId?: string;
22
+ source?: string;
23
+ parentSessionId?: string;
24
+ subSessionId?: string;
25
+ toolCallId?: string;
26
+ type: string;
27
+ status: string;
28
+ leaderUsername?: string;
29
+ employeeUsername?: string;
30
+ toolName?: string;
31
+ title?: string;
32
+ input?: any;
33
+ output?: string;
34
+ error?: string;
35
+ durationMs?: number;
36
+ startedAt?: Date;
37
+ endedAt?: Date;
38
+ orchestratorLogId?: string | number;
39
+ skillExecutionId?: string | number;
40
+ metadata?: any;
41
+ userId?: string | number;
42
+ };
43
+
44
+ export class ExecutionSpanService {
45
+ constructor(private readonly plugin: any) {}
46
+
47
+ async create(values: SpanValues) {
48
+ try {
49
+ const repo = this.plugin.db.getRepository('agentExecutionSpans');
50
+ if (!repo) return null;
51
+
52
+ const record = await repo.create({
53
+ values: {
54
+ ...values,
55
+ startedAt: values.startedAt || new Date(),
56
+ createdAt: new Date(),
57
+ },
58
+ });
59
+ return toPlain(record);
60
+ } catch (error) {
61
+ this.plugin.app.logger?.warn?.('[AgentOrchestrator] Failed to create execution span', error);
62
+ return null;
63
+ }
64
+ }
65
+
66
+ async update(spanId: string | number | undefined, values: Record<string, any>) {
67
+ if (!spanId) return null;
68
+ try {
69
+ const repo = this.plugin.db.getRepository('agentExecutionSpans');
70
+ if (!repo) return null;
71
+ await repo.update({
72
+ filterByTk: spanId,
73
+ values: {
74
+ ...values,
75
+ updatedAt: new Date(),
76
+ },
77
+ });
78
+ return { id: spanId };
79
+ } catch (error) {
80
+ this.plugin.app.logger?.warn?.(`[AgentOrchestrator] Failed to update execution span ${spanId}`, error);
81
+ return null;
82
+ }
83
+ }
84
+
85
+ async finish(
86
+ spanId: string | number | undefined,
87
+ status: 'success' | 'error' | 'canceled' | 'timeout',
88
+ startedAt: number,
89
+ values: Record<string, any> = {},
90
+ ) {
91
+ return this.update(spanId, {
92
+ ...values,
93
+ status,
94
+ endedAt: new Date(),
95
+ durationMs: Date.now() - startedAt,
96
+ });
97
+ }
98
+ }
99
+
100
+ export function getOrchestratorTraceContext(ctx: any): OrchestratorTraceContext | null {
101
+ const requestContext =
102
+ ctx?.[ORCHESTRATOR_TRACE_CONTEXT_KEY] ||
103
+ ctx?.state?.orchestratorTraceContext ||
104
+ ctx?.runtime?.context?.orchestratorTraceContext ||
105
+ null;
106
+ const agentContext = getAgentExecutionContext();
107
+ if (!requestContext && !agentContext) return null;
108
+
109
+ return {
110
+ ...(agentContext || {}),
111
+ ...(requestContext || {}),
112
+ toolCallId: ctx?.runtime?.toolCallId || requestContext?.toolCallId || agentContext?.toolCallId,
113
+ };
114
+ }
115
+
116
+ export function setOrchestratorTraceContext(ctx: any, traceContext: OrchestratorTraceContext) {
117
+ ctx[ORCHESTRATOR_TRACE_CONTEXT_KEY] = traceContext;
118
+ return ctx;
119
+ }
@@ -0,0 +1,44 @@
1
+ import Ajv from 'ajv';
2
+ import { parseJsonText } from '../skill-hub/utils/json-fields';
3
+
4
+ type JsonSchema = Record<string, unknown> | boolean;
5
+
6
+ const ajv = new Ajv({
7
+ allErrors: true,
8
+ jsonPointers: true,
9
+ });
10
+
11
+ function parseSchema(value: unknown): JsonSchema | null {
12
+ if (value === undefined || value === null || value === '') return null;
13
+ const schema = parseJsonText<unknown>(value, undefined);
14
+ if (typeof schema === 'boolean') return schema;
15
+ if (schema && typeof schema === 'object' && !Array.isArray(schema)) {
16
+ return schema as Record<string, unknown>;
17
+ }
18
+ throw new Error('Input Schema must be a valid JSON Schema object.');
19
+ }
20
+
21
+ export function validateInputSchemaDefinition(value: unknown): void {
22
+ const schema = parseSchema(value);
23
+ if (schema === null) return;
24
+ try {
25
+ ajv.compile(schema);
26
+ } catch (error) {
27
+ throw new Error(`Invalid Input Schema: ${error instanceof Error ? error.message : String(error)}`);
28
+ }
29
+ }
30
+
31
+ export function validateSkillInput(schemaValue: unknown, input: unknown): void {
32
+ const schema = parseSchema(schemaValue);
33
+ if (schema === null) return;
34
+
35
+ let validate;
36
+ try {
37
+ validate = ajv.compile(schema);
38
+ } catch (error) {
39
+ throw new Error(`Invalid Input Schema: ${error instanceof Error ? error.message : String(error)}`);
40
+ }
41
+
42
+ if (validate(input)) return;
43
+ throw new Error(`Skill input validation failed: ${ajv.errorsText(validate.errors, { separator: '; ' })}`);
44
+ }
@@ -2,6 +2,7 @@ import { createHash } from 'crypto';
2
2
  import { ExecutionSpanService } from './ExecutionSpanService';
3
3
  import { AgentMemoryContextService } from './AgentMemoryContextService';
4
4
  import { TokenTracker } from './TokenTracker';
5
+ import { runWithAgentExecutionContext } from './AgentExecutionContext';
5
6
  import { asObject, currentUserId, toPlain, trimText } from '../utils/ctx-utils';
6
7
 
7
8
  const WRAP_STATE_KEY = Symbol.for('plugin-agent-orchestrator.nativeSubAgentObserver');
@@ -106,6 +107,20 @@ function chunkCurrentConversation(chunk: Record<string, unknown>) {
106
107
  return asObject(chunk.currentConversation);
107
108
  }
108
109
 
110
+ function readSkillExecutionId(result: Record<string, unknown>): string | number | undefined {
111
+ const nestedResult = asObject(result.result);
112
+ const direct = nestedResult.execId || result.execId;
113
+ if (typeof direct === 'string' || typeof direct === 'number') return direct;
114
+
115
+ if (typeof result.content !== 'string') return undefined;
116
+ try {
117
+ const content = asObject(JSON.parse(result.content));
118
+ return typeof content.execId === 'string' || typeof content.execId === 'number' ? content.execId : undefined;
119
+ } catch {
120
+ return undefined;
121
+ }
122
+ }
123
+
109
124
  export class NativeSubAgentObserver {
110
125
  private readonly spanService: ExecutionSpanService;
111
126
  private readonly memoryService: AgentMemoryContextService;
@@ -181,12 +196,14 @@ export class NativeSubAgentObserver {
181
196
  aiEmployeeUsername: employeeUsername,
182
197
  settings,
183
198
  });
184
- const observedTask = memory.context
185
- ? {
186
- ...task,
187
- question: `${memory.context}\n\n<agent_task>\n${task.question}\n</agent_task>`,
188
- }
189
- : task;
199
+ const observedTask: NativeSubAgentTask = {
200
+ ...task,
201
+ // Native dispatch passes the leader conversation's skillSettings to the
202
+ // sub-agent. Clear that inherited filter so plugin-ai resolves tools from
203
+ // the sub-agent employee's own bindings instead.
204
+ skillSettings: undefined,
205
+ question: memory.context ? `${memory.context}\n\n<agent_task>\n${task.question}\n</agent_task>` : task.question,
206
+ };
190
207
 
191
208
  const state: RunState = {
192
209
  rootRunId,
@@ -225,7 +242,17 @@ export class NativeSubAgentObserver {
225
242
  };
226
243
 
227
244
  try {
228
- const result = await this.runWithKnowledgeBaseAgentContext(employeeUsername, () => originalRun(observedTask));
245
+ const result = await runWithAgentExecutionContext(
246
+ {
247
+ rootRunId,
248
+ spanId: state.rootSpanId ? String(state.rootSpanId) : undefined,
249
+ toolCallId,
250
+ leaderUsername,
251
+ employeeUsername,
252
+ sessionId: subSessionId,
253
+ },
254
+ () => this.runWithKnowledgeBaseAgentContext(employeeUsername, () => originalRun(observedTask)),
255
+ );
229
256
  await this.flushPending(state);
230
257
  await this.spanService.finish(state.rootSpanId, 'success', state.rootStartedAt, {
231
258
  output: trimText(result, 20000),
@@ -355,6 +382,7 @@ export class NativeSubAgentObserver {
355
382
  };
356
383
  state.toolSpans.set(toolCallId, toolSpan);
357
384
 
385
+ const toolName = normalizeString(toolCall.name);
358
386
  toolSpan.ready = this.spanService
359
387
  .create({
360
388
  rootRunId: state.rootRunId,
@@ -363,12 +391,17 @@ export class NativeSubAgentObserver {
363
391
  parentSessionId: state.parentSessionId || undefined,
364
392
  subSessionId: normalizeString(conversation.sessionId) || state.subSessionId || undefined,
365
393
  toolCallId,
366
- type: normalizeString(toolCall.name) === 'dispatch-sub-agent-task' ? 'dispatch' : 'tool',
394
+ type:
395
+ toolName === 'dispatch-sub-agent-task'
396
+ ? 'dispatch'
397
+ : toolName === 'skill_hub_execute' || toolName.startsWith('skill_hub_')
398
+ ? 'skill'
399
+ : 'tool',
367
400
  status: 'running',
368
401
  leaderUsername: state.leaderUsername,
369
402
  employeeUsername: normalizeString(conversation.username) || state.employeeUsername,
370
- toolName: normalizeString(toolCall.name),
371
- title: normalizeString(toolCall.name) || 'tool call',
403
+ toolName,
404
+ title: toolName || 'tool call',
372
405
  input: asObject(toolCall.args),
373
406
  metadata: {
374
407
  source: NATIVE_SOURCE,
@@ -396,6 +429,9 @@ export class NativeSubAgentObserver {
396
429
  const error = body.error;
397
430
  const status = forceError || result.status === 'error' ? 'error' : 'success';
398
431
  const output = result.content ?? result.result ?? result;
432
+ const toolName = normalizeString(toolCall.name);
433
+ const skillExecutionId =
434
+ toolName === 'skill_hub_execute' || toolName.startsWith('skill_hub_') ? readSkillExecutionId(result) : undefined;
399
435
  const invokeStart = Number(result.invokeStartTime);
400
436
  const invokeEnd = Number(result.invokeEndTime);
401
437
  const durationMs =
@@ -409,6 +445,7 @@ export class NativeSubAgentObserver {
409
445
  durationMs,
410
446
  output: forceError ? undefined : trimText(output, 20000),
411
447
  error: forceError ? trimText(errorMessage(error), 10000) : undefined,
448
+ skillExecutionId,
412
449
  metadata: {
413
450
  source: NATIVE_SOURCE,
414
451
  toolCallResultStatus: result.status,
@@ -417,6 +454,10 @@ export class NativeSubAgentObserver {
417
454
  },
418
455
  });
419
456
 
457
+ if (skillExecutionId && existing.spanId) {
458
+ await this.linkExecutionToSpan(skillExecutionId, existing.spanId);
459
+ }
460
+
420
461
  await this.tokenTracker.estimateAndTrack(
421
462
  existing.spanId,
422
463
  normalizeString(toolCall.name),
@@ -424,6 +465,19 @@ export class NativeSubAgentObserver {
424
465
  );
425
466
  }
426
467
 
468
+ private async linkExecutionToSpan(skillExecutionId: string | number, spanId: string | number) {
469
+ try {
470
+ const repo = this.plugin.db.getRepository('skillExecutions');
471
+ if (!repo) return;
472
+ await repo.update({
473
+ filterByTk: skillExecutionId,
474
+ values: { orchestratorSpanId: spanId },
475
+ });
476
+ } catch (error) {
477
+ this.plugin.app.logger?.warn?.('[AgentOrchestrator] Failed to link skill execution to native span', error);
478
+ }
479
+ }
480
+
427
481
  private resolveParentSessionId(task: NativeSubAgentTask) {
428
482
  const values = task.ctx?.action?.params?.values || {};
429
483
  return normalizeString(values.sessionId) || undefined;
@@ -39,6 +39,8 @@ export interface ExecuteOptions {
39
39
  packageWhitelist?: string[];
40
40
  /** Optional installed/copied skill package root exposed to the runtime as SKILL_DIR. */
41
41
  skillDir?: string;
42
+ /** Validated input exposed as a JSON file to avoid source-code interpolation. */
43
+ inputArgs?: Record<string, unknown>;
42
44
  }
43
45
 
44
46
  export interface ProgressUpdate {
@@ -196,6 +198,7 @@ export class SandboxRunner {
196
198
  signal,
197
199
  packageWhitelist,
198
200
  skillDir,
201
+ inputArgs,
199
202
  } = options;
200
203
 
201
204
  // 1. Validate code against forbidden patterns
@@ -212,6 +215,8 @@ export class SandboxRunner {
212
215
  // 3. Prepare workspace
213
216
  const workDir = this.fileManager.createExecDir(execId);
214
217
  const outputDir = this.fileManager.getOutputDir(execId);
218
+ const inputFile = resolve(workDir, 'input.json');
219
+ writeFileSync(inputFile, JSON.stringify(inputArgs || {}, null, 2), 'utf-8');
215
220
 
216
221
  const filename = language === 'node' ? 'script.js' : 'script.py';
217
222
  const scriptPath = resolve(workDir, filename);
@@ -268,6 +273,7 @@ export class SandboxRunner {
268
273
  // Consumed by the sitecustomize.py guard to scope file writes.
269
274
  SKILL_HUB_WRITE_ROOTS: [workDir, outputDir, tmpdir()].join(delimiter),
270
275
  SKILL_DIR: skillDir || '',
276
+ SKILL_INPUT_FILE: inputFile,
271
277
  // DO NOT pass: DB credentials, API keys, APP_KEY, etc.
272
278
  };
273
279
 
@@ -0,0 +1,100 @@
1
+ import { getAgentExecutionContext } from './AgentExecutionContext';
2
+ import { asObject, isAdminUser, normalizeEmployeeUsername, valuesFromCtx } from '../utils/ctx-utils';
3
+ import { getSkillToolName, normalizeSkillToolScope, readRecordValue } from '../utils/skill-tool-name';
4
+
5
+ type ToolBinding = { name?: unknown } | string;
6
+
7
+ function bindingName(binding: ToolBinding): string {
8
+ if (typeof binding === 'string') return binding.trim();
9
+ return typeof binding?.name === 'string' ? binding.name.trim() : '';
10
+ }
11
+
12
+ export class SkillAccessService {
13
+ constructor(private readonly plugin: { db: { getRepository: (name: string) => any } }) {}
14
+
15
+ async resolveAgentUsername(ctx: any): Promise<string | undefined> {
16
+ const executionIdentity = getAgentExecutionContext();
17
+ if (executionIdentity?.employeeUsername) return executionIdentity.employeeUsername;
18
+
19
+ const values = valuesFromCtx(ctx);
20
+ const direct = normalizeEmployeeUsername(
21
+ ctx?._currentAIEmployee ||
22
+ ctx?.state?.currentAIEmployee ||
23
+ ctx?.runtime?.context?.currentAIEmployee ||
24
+ values.aiEmployee ||
25
+ values.aiEmployeeUsername,
26
+ );
27
+ if (direct) return direct;
28
+
29
+ const sessionId =
30
+ executionIdentity?.sessionId || values.sessionId || ctx?.action?.params?.sessionId || ctx?.state?.sessionId;
31
+ if (!sessionId) return undefined;
32
+
33
+ try {
34
+ const conversation = await this.plugin.db.getRepository('aiConversations').findOne({
35
+ filter: { sessionId },
36
+ });
37
+ return (
38
+ normalizeEmployeeUsername(readRecordValue(conversation, 'aiEmployeeUsername')) ||
39
+ normalizeEmployeeUsername(readRecordValue(conversation, 'aiEmployee')) ||
40
+ undefined
41
+ );
42
+ } catch {
43
+ return undefined;
44
+ }
45
+ }
46
+
47
+ async canAgentUseSkill(agentUsername: string, skill: unknown): Promise<boolean> {
48
+ if (normalizeSkillToolScope(readRecordValue(skill, 'toolScope')) === 'GENERAL') return true;
49
+
50
+ const employee = await this.plugin.db.getRepository('aiEmployees').findOne({
51
+ filter: { username: agentUsername },
52
+ });
53
+ if (!employee) return false;
54
+
55
+ const skillSettings = asObject(readRecordValue(employee, 'skillSettings'));
56
+ const tools = Array.isArray(skillSettings.tools) ? (skillSettings.tools as ToolBinding[]) : [];
57
+ const targetToolName = getSkillToolName(skill);
58
+ return tools.some((binding) => bindingName(binding) === targetToolName);
59
+ }
60
+
61
+ async assertCanExecute(
62
+ ctx: any,
63
+ skill: unknown,
64
+ options: { privileged?: boolean } = {},
65
+ ): Promise<string | undefined> {
66
+ if (options.privileged) return this.resolveAgentUsername(ctx);
67
+ if (isAdminUser(ctx)) return this.resolveAgentUsername(ctx);
68
+
69
+ const agentUsername = await this.resolveAgentUsername(ctx);
70
+ if (!agentUsername) {
71
+ throw new Error('Skill execution requires an AI employee context.');
72
+ }
73
+ if (!(await this.canAgentUseSkill(agentUsername, skill))) {
74
+ throw new Error(`AI employee "${agentUsername}" is not bound to skill tool "${getSkillToolName(skill)}".`);
75
+ }
76
+ return agentUsername;
77
+ }
78
+
79
+ async filterAccessibleSkills(ctx: any, skills: unknown[]): Promise<unknown[]> {
80
+ if (isAdminUser(ctx)) return skills;
81
+ const agentUsername = await this.resolveAgentUsername(ctx);
82
+ if (!agentUsername) return [];
83
+
84
+ const checks = await Promise.all(skills.map((skill) => this.canAgentUseSkill(agentUsername, skill)));
85
+ return skills.filter((_skill, index) => checks[index]);
86
+ }
87
+
88
+ async findAgentUsernamesUsingTool(toolName: string): Promise<string[]> {
89
+ const employees = await this.plugin.db.getRepository('aiEmployees').find({});
90
+ const usernames: string[] = [];
91
+ for (const employee of employees || []) {
92
+ const settings = asObject(readRecordValue(employee, 'skillSettings'));
93
+ const tools = Array.isArray(settings.tools) ? (settings.tools as ToolBinding[]) : [];
94
+ if (!tools.some((binding) => bindingName(binding) === toolName)) continue;
95
+ const username = normalizeEmployeeUsername(readRecordValue(employee, 'username'));
96
+ if (username) usernames.push(username);
97
+ }
98
+ return usernames;
99
+ }
100
+ }
@@ -1,5 +1,6 @@
1
1
  import { Database } from '@nocobase/database';
2
2
  import { stringifyJsonText } from '../skill-hub/utils/json-fields';
3
+ import { buildSkillToolName } from '../utils/skill-tool-name';
3
4
 
4
5
  export class SkillManager {
5
6
  constructor(private db: Database) {}
@@ -208,6 +209,7 @@ export class SkillManager {
208
209
  await repo.create({
209
210
  values: {
210
211
  ...seed,
212
+ toolName: buildSkillToolName(seed.name),
211
213
  inputSchema: stringifyJsonText(seed.inputSchema),
212
214
  packages: stringifyJsonText(seed.packages, []),
213
215
  },