devworkspace 0.4.5 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (263) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +7 -0
  3. package/dist/cli/args.d.ts +30 -0
  4. package/dist/cli/args.js +10 -0
  5. package/dist/cli/args.js.map +1 -1
  6. package/dist/cli/help.js +134 -0
  7. package/dist/cli/help.js.map +1 -1
  8. package/dist/cli/render.d.ts +6 -0
  9. package/dist/cli/render.js +106 -0
  10. package/dist/cli/render.js.map +1 -1
  11. package/dist/cli/run.js +351 -1
  12. package/dist/cli/run.js.map +1 -1
  13. package/dist/core/contracts.d.ts +70 -0
  14. package/dist/core/contracts.js +88 -0
  15. package/dist/core/contracts.js.map +1 -0
  16. package/dist/discovery/commands.d.ts +1 -1
  17. package/dist/discovery/commands.js.map +1 -1
  18. package/dist/discovery/detect.d.ts +2 -70
  19. package/dist/discovery/detect.js.map +1 -1
  20. package/dist/discovery/entrypoints.d.ts +2 -11
  21. package/dist/discovery/entrypoints.js.map +1 -1
  22. package/dist/discovery/types.d.ts +79 -0
  23. package/dist/discovery/types.js +2 -0
  24. package/dist/discovery/types.js.map +1 -0
  25. package/dist/dx/dashboard.d.ts +21 -0
  26. package/dist/dx/dashboard.js +274 -0
  27. package/dist/dx/dashboard.js.map +1 -0
  28. package/dist/dx/guidance.d.ts +21 -0
  29. package/dist/dx/guidance.js +266 -0
  30. package/dist/dx/guidance.js.map +1 -0
  31. package/dist/dx/index.d.ts +4 -0
  32. package/dist/dx/index.js +5 -0
  33. package/dist/dx/index.js.map +1 -0
  34. package/dist/dx/onboarding.d.ts +23 -0
  35. package/dist/dx/onboarding.js +155 -0
  36. package/dist/dx/onboarding.js.map +1 -0
  37. package/dist/dx/types.d.ts +70 -0
  38. package/dist/dx/types.js +3 -0
  39. package/dist/dx/types.js.map +1 -0
  40. package/dist/index.d.ts +35 -0
  41. package/dist/index.js +28 -0
  42. package/dist/index.js.map +1 -1
  43. package/dist/integrations/persistentPath.d.ts +2 -9
  44. package/dist/integrations/persistentPath.js.map +1 -1
  45. package/dist/integrations/types.d.ts +4 -1
  46. package/dist/integrations/types.js.map +1 -1
  47. package/dist/intelligence/agents/profiles.d.ts +2 -0
  48. package/dist/intelligence/agents/profiles.js +326 -0
  49. package/dist/intelligence/agents/profiles.js.map +1 -0
  50. package/dist/intelligence/agents/registry.d.ts +15 -0
  51. package/dist/intelligence/agents/registry.js +108 -0
  52. package/dist/intelligence/agents/registry.js.map +1 -0
  53. package/dist/intelligence/agents/types.d.ts +43 -0
  54. package/dist/intelligence/agents/types.js +2 -0
  55. package/dist/intelligence/agents/types.js.map +1 -0
  56. package/dist/intelligence/observability/tracer.d.ts +13 -0
  57. package/dist/intelligence/observability/tracer.js +129 -0
  58. package/dist/intelligence/observability/tracer.js.map +1 -0
  59. package/dist/intelligence/observability/types.d.ts +38 -0
  60. package/dist/intelligence/observability/types.js +2 -0
  61. package/dist/intelligence/observability/types.js.map +1 -0
  62. package/dist/intelligence/orchestration/engine.d.ts +51 -0
  63. package/dist/intelligence/orchestration/engine.js +578 -0
  64. package/dist/intelligence/orchestration/engine.js.map +1 -0
  65. package/dist/intelligence/orchestration/lock-manager.d.ts +21 -0
  66. package/dist/intelligence/orchestration/lock-manager.js +70 -0
  67. package/dist/intelligence/orchestration/lock-manager.js.map +1 -0
  68. package/dist/intelligence/orchestration/store.d.ts +11 -0
  69. package/dist/intelligence/orchestration/store.js +73 -0
  70. package/dist/intelligence/orchestration/store.js.map +1 -0
  71. package/dist/intelligence/orchestration/types.d.ts +111 -0
  72. package/dist/intelligence/orchestration/types.js +48 -0
  73. package/dist/intelligence/orchestration/types.js.map +1 -0
  74. package/dist/intelligence/routing/matcher.d.ts +7 -0
  75. package/dist/intelligence/routing/matcher.js +96 -0
  76. package/dist/intelligence/routing/matcher.js.map +1 -0
  77. package/dist/intelligence/routing/router.d.ts +9 -0
  78. package/dist/intelligence/routing/router.js +198 -0
  79. package/dist/intelligence/routing/router.js.map +1 -0
  80. package/dist/intelligence/routing/types.d.ts +64 -0
  81. package/dist/intelligence/routing/types.js +2 -0
  82. package/dist/intelligence/routing/types.js.map +1 -0
  83. package/dist/intelligence/runtime/adk/adapter.d.ts +7 -0
  84. package/dist/intelligence/runtime/adk/adapter.js +49 -0
  85. package/dist/intelligence/runtime/adk/adapter.js.map +1 -0
  86. package/dist/intelligence/runtime/adk/detector.d.ts +7 -0
  87. package/dist/intelligence/runtime/adk/detector.js +28 -0
  88. package/dist/intelligence/runtime/adk/detector.js.map +1 -0
  89. package/dist/intelligence/runtime/boundary.d.ts +30 -0
  90. package/dist/intelligence/runtime/boundary.js +163 -0
  91. package/dist/intelligence/runtime/boundary.js.map +1 -0
  92. package/dist/intelligence/runtime/external.d.ts +9 -0
  93. package/dist/intelligence/runtime/external.js +76 -0
  94. package/dist/intelligence/runtime/external.js.map +1 -0
  95. package/dist/intelligence/runtime/native.d.ts +19 -0
  96. package/dist/intelligence/runtime/native.js +67 -0
  97. package/dist/intelligence/runtime/native.js.map +1 -0
  98. package/dist/intelligence/runtime/types.d.ts +77 -0
  99. package/dist/intelligence/runtime/types.js +12 -0
  100. package/dist/intelligence/runtime/types.js.map +1 -0
  101. package/dist/intelligence/security/audit.d.ts +8 -0
  102. package/dist/intelligence/security/audit.js +43 -0
  103. package/dist/intelligence/security/audit.js.map +1 -0
  104. package/dist/intelligence/security/policy.d.ts +12 -0
  105. package/dist/intelligence/security/policy.js +153 -0
  106. package/dist/intelligence/security/policy.js.map +1 -0
  107. package/dist/intelligence/security/types.d.ts +25 -0
  108. package/dist/intelligence/security/types.js +2 -0
  109. package/dist/intelligence/security/types.js.map +1 -0
  110. package/dist/intelligence/skills/builtins.d.ts +2 -0
  111. package/dist/intelligence/skills/builtins.js +379 -0
  112. package/dist/intelligence/skills/builtins.js.map +1 -0
  113. package/dist/intelligence/skills/loader.d.ts +4 -0
  114. package/dist/intelligence/skills/loader.js +84 -0
  115. package/dist/intelligence/skills/loader.js.map +1 -0
  116. package/dist/intelligence/skills/registry.d.ts +15 -0
  117. package/dist/intelligence/skills/registry.js +134 -0
  118. package/dist/intelligence/skills/registry.js.map +1 -0
  119. package/dist/intelligence/skills/types.d.ts +35 -0
  120. package/dist/intelligence/skills/types.js +2 -0
  121. package/dist/intelligence/skills/types.js.map +1 -0
  122. package/dist/intelligence/verification/engine.d.ts +37 -0
  123. package/dist/intelligence/verification/engine.js +127 -0
  124. package/dist/intelligence/verification/engine.js.map +1 -0
  125. package/dist/intelligence/verification/reviewer.d.ts +8 -0
  126. package/dist/intelligence/verification/reviewer.js +55 -0
  127. package/dist/intelligence/verification/reviewer.js.map +1 -0
  128. package/dist/intelligence/verification/types.d.ts +43 -0
  129. package/dist/intelligence/verification/types.js +2 -0
  130. package/dist/intelligence/verification/types.js.map +1 -0
  131. package/dist/mcp/setup.d.ts +2 -4
  132. package/dist/mcp/setup.js.map +1 -1
  133. package/dist/mcp/tools.js +6 -6
  134. package/dist/mcp/tools.js.map +1 -1
  135. package/dist/mcp/types.d.ts +4 -0
  136. package/dist/mcp/types.js.map +1 -1
  137. package/dist/mcp/verify.d.ts +1 -1
  138. package/dist/mcp/verify.js.map +1 -1
  139. package/dist/security/redact.js +3 -2
  140. package/dist/security/redact.js.map +1 -1
  141. package/dist/services/doctor.js +4 -0
  142. package/dist/services/doctor.js.map +1 -1
  143. package/dist/services/intelligence.d.ts +44 -0
  144. package/dist/services/intelligence.js +119 -0
  145. package/dist/services/intelligence.js.map +1 -0
  146. package/dist/services/standards.d.ts +85 -0
  147. package/dist/services/standards.js +230 -0
  148. package/dist/services/standards.js.map +1 -0
  149. package/dist/services/taskContext.js +4 -0
  150. package/dist/services/taskContext.js.map +1 -1
  151. package/dist/standards/acquisition/ingest.d.ts +12 -0
  152. package/dist/standards/acquisition/ingest.js +98 -0
  153. package/dist/standards/acquisition/ingest.js.map +1 -0
  154. package/dist/standards/applicability/engine.d.ts +38 -0
  155. package/dist/standards/applicability/engine.js +250 -0
  156. package/dist/standards/applicability/engine.js.map +1 -0
  157. package/dist/standards/builtin/code-quality.d.ts +2 -0
  158. package/dist/standards/builtin/code-quality.js +53 -0
  159. package/dist/standards/builtin/code-quality.js.map +1 -0
  160. package/dist/standards/builtin/database-safety.d.ts +2 -0
  161. package/dist/standards/builtin/database-safety.js +56 -0
  162. package/dist/standards/builtin/database-safety.js.map +1 -0
  163. package/dist/standards/builtin/index.d.ts +8 -0
  164. package/dist/standards/builtin/index.js +14 -0
  165. package/dist/standards/builtin/index.js.map +1 -0
  166. package/dist/standards/builtin/security-baseline.d.ts +2 -0
  167. package/dist/standards/builtin/security-baseline.js +64 -0
  168. package/dist/standards/builtin/security-baseline.js.map +1 -0
  169. package/dist/standards/builtin/testing-contracts.d.ts +2 -0
  170. package/dist/standards/builtin/testing-contracts.js +54 -0
  171. package/dist/standards/builtin/testing-contracts.js.map +1 -0
  172. package/dist/standards/builtin/undo-kit.d.ts +8 -0
  173. package/dist/standards/builtin/undo-kit.js +106 -0
  174. package/dist/standards/builtin/undo-kit.js.map +1 -0
  175. package/dist/standards/config/config.d.ts +12 -0
  176. package/dist/standards/config/config.js +110 -0
  177. package/dist/standards/config/config.js.map +1 -0
  178. package/dist/standards/distribution/cache.d.ts +58 -0
  179. package/dist/standards/distribution/cache.js +425 -0
  180. package/dist/standards/distribution/cache.js.map +1 -0
  181. package/dist/standards/distribution/index.d.ts +6 -0
  182. package/dist/standards/distribution/index.js +7 -0
  183. package/dist/standards/distribution/index.js.map +1 -0
  184. package/dist/standards/distribution/keys.d.ts +53 -0
  185. package/dist/standards/distribution/keys.js +269 -0
  186. package/dist/standards/distribution/keys.js.map +1 -0
  187. package/dist/standards/distribution/package.d.ts +25 -0
  188. package/dist/standards/distribution/package.js +254 -0
  189. package/dist/standards/distribution/package.js.map +1 -0
  190. package/dist/standards/distribution/server.d.ts +38 -0
  191. package/dist/standards/distribution/server.js +204 -0
  192. package/dist/standards/distribution/server.js.map +1 -0
  193. package/dist/standards/distribution/sync.d.ts +56 -0
  194. package/dist/standards/distribution/sync.js +245 -0
  195. package/dist/standards/distribution/sync.js.map +1 -0
  196. package/dist/standards/distribution/types.d.ts +140 -0
  197. package/dist/standards/distribution/types.js +26 -0
  198. package/dist/standards/distribution/types.js.map +1 -0
  199. package/dist/standards/engine/compliance.d.ts +2 -0
  200. package/dist/standards/engine/compliance.js +45 -0
  201. package/dist/standards/engine/compliance.js.map +1 -0
  202. package/dist/standards/engine/engine.d.ts +14 -0
  203. package/dist/standards/engine/engine.js +114 -0
  204. package/dist/standards/engine/engine.js.map +1 -0
  205. package/dist/standards/engine/reporter.d.ts +2 -0
  206. package/dist/standards/engine/reporter.js +42 -0
  207. package/dist/standards/engine/reporter.js.map +1 -0
  208. package/dist/standards/index.d.ts +18 -0
  209. package/dist/standards/index.js +19 -0
  210. package/dist/standards/index.js.map +1 -0
  211. package/dist/standards/registry/registry.d.ts +29 -0
  212. package/dist/standards/registry/registry.js +210 -0
  213. package/dist/standards/registry/registry.js.map +1 -0
  214. package/dist/standards/schema/types.d.ts +133 -0
  215. package/dist/standards/schema/types.js +33 -0
  216. package/dist/standards/schema/types.js.map +1 -0
  217. package/dist/standards/schema/validate.d.ts +6 -0
  218. package/dist/standards/schema/validate.js +131 -0
  219. package/dist/standards/schema/validate.js.map +1 -0
  220. package/dist/standards/templates/index.d.ts +11 -0
  221. package/dist/standards/templates/index.js +176 -0
  222. package/dist/standards/templates/index.js.map +1 -0
  223. package/dist/standards/validators/database.d.ts +5 -0
  224. package/dist/standards/validators/database.js +122 -0
  225. package/dist/standards/validators/database.js.map +1 -0
  226. package/dist/standards/validators/quality.d.ts +6 -0
  227. package/dist/standards/validators/quality.js +91 -0
  228. package/dist/standards/validators/quality.js.map +1 -0
  229. package/dist/standards/validators/registry.d.ts +11 -0
  230. package/dist/standards/validators/registry.js +83 -0
  231. package/dist/standards/validators/registry.js.map +1 -0
  232. package/dist/standards/validators/security.d.ts +7 -0
  233. package/dist/standards/validators/security.js +182 -0
  234. package/dist/standards/validators/security.js.map +1 -0
  235. package/dist/standards/validators/testing.d.ts +6 -0
  236. package/dist/standards/validators/testing.js +142 -0
  237. package/dist/standards/validators/testing.js.map +1 -0
  238. package/dist/standards/validators/types.d.ts +11 -0
  239. package/dist/standards/validators/types.js +2 -0
  240. package/dist/standards/validators/types.js.map +1 -0
  241. package/dist/standards/validators/undo-kit.d.ts +7 -0
  242. package/dist/standards/validators/undo-kit.js +334 -0
  243. package/dist/standards/validators/undo-kit.js.map +1 -0
  244. package/dist/tasks/routing.js +5 -3
  245. package/dist/tasks/routing.js.map +1 -1
  246. package/dist/utils/fs.d.ts +1 -1
  247. package/dist/utils/fs.js.map +1 -1
  248. package/dist/utils/lock.js +11 -3
  249. package/dist/utils/lock.js.map +1 -1
  250. package/dist/utils/paths.js +29 -0
  251. package/dist/utils/paths.js.map +1 -1
  252. package/dist/utils/proc.d.ts +4 -0
  253. package/dist/utils/proc.js +60 -4
  254. package/dist/utils/proc.js.map +1 -1
  255. package/docs/agents.md +15 -0
  256. package/docs/contributing.md +13 -5
  257. package/docs/getting-started.md +7 -0
  258. package/docs/mcp.md +13 -0
  259. package/docs/security/HOME_SERVER_THREAT_MODEL.md +72 -0
  260. package/docs/security/THREAT_MODEL.md +101 -0
  261. package/docs/security.md +8 -2
  262. package/docs/standards.md +143 -0
  263. package/package.json +1 -1
@@ -0,0 +1,9 @@
1
+ import { AgentRegistry } from '../agents/registry.js';
2
+ import { SkillRegistry } from '../skills/registry.js';
3
+ import type { RoutingContext, RoutingDecision } from './types.js';
4
+ export declare class IntelligentRouter {
5
+ private agentRegistry;
6
+ private skillRegistry;
7
+ constructor(agentRegistry: AgentRegistry, skillRegistry: SkillRegistry);
8
+ route(context: RoutingContext): Promise<RoutingDecision>;
9
+ }
@@ -0,0 +1,198 @@
1
+ import { classifyRequest } from '../../tasks/routing.js';
2
+ import { deriveRequiredCapabilities, estimateComplexity } from './matcher.js';
3
+ export class IntelligentRouter {
4
+ agentRegistry;
5
+ skillRegistry;
6
+ constructor(agentRegistry, skillRegistry) {
7
+ this.agentRegistry = agentRegistry;
8
+ this.skillRegistry = skillRegistry;
9
+ }
10
+ async route(context) {
11
+ const text = (context.request || context.prompt || context.userPrompt || '').trim();
12
+ // 1. Classify task type using existing deterministic classifier
13
+ const existingClassification = classifyRequest(text);
14
+ const taskType = context.taskType || existingClassification.type;
15
+ // 2. Derive required capabilities & suggested skills from request
16
+ const { capabilities, suggestedSkills, score } = deriveRequiredCapabilities(text);
17
+ const hasDatabaseOrSecurity = suggestedSkills.includes('database-design') || suggestedSkills.includes('security-audit');
18
+ // 3. Compute complexity tier
19
+ const complexity = estimateComplexity(text, taskType, score, hasDatabaseOrSecurity);
20
+ // 4. Determine execution strategy based on complexity
21
+ let strategy;
22
+ switch (complexity) {
23
+ case 'CRITICAL':
24
+ strategy = 'APPROVAL_GATED_CRITICAL';
25
+ break;
26
+ case 'COMPLEX':
27
+ strategy = 'MULTI_AGENT_WORKFLOW';
28
+ break;
29
+ case 'MEDIUM':
30
+ strategy = 'SPECIALIST_WITH_REVIEWER';
31
+ break;
32
+ case 'SIMPLE':
33
+ default:
34
+ strategy = 'SINGLE_AGENT';
35
+ break;
36
+ }
37
+ // 5. Select appropriate agents from the registry
38
+ const allAgents = await this.agentRegistry.listAllAgents();
39
+ const selectedAgents = [];
40
+ const excludedAgents = [];
41
+ // Helper to evaluate an agent
42
+ const consider = (agentId, reason, priority) => {
43
+ const a = allAgents.find((p) => p.id === agentId);
44
+ if (a) {
45
+ selectedAgents.push({
46
+ agentId: a.id,
47
+ id: a.id,
48
+ role: a.name,
49
+ reason,
50
+ priority,
51
+ });
52
+ }
53
+ };
54
+ if (strategy === 'APPROVAL_GATED_CRITICAL' || strategy === 'MULTI_AGENT_WORKFLOW') {
55
+ consider('planner', 'Complex/critical objective requires structured breakdown and dependency ordering.', 1);
56
+ }
57
+ // Primary specialist based on task type and capabilities
58
+ if (suggestedSkills.includes('security-audit') || taskType === 'SECURITY') {
59
+ consider('security-auditor', 'Security concerns detected in request; requires specialized vulnerability analysis.', 2);
60
+ }
61
+ if (suggestedSkills.includes('database-design') || suggestedSkills.includes('database-optimization')) {
62
+ consider('database-specialist', 'Database schema, query, or migration operations requested.', 2);
63
+ }
64
+ if (suggestedSkills.includes('performance-optimization') || taskType === 'PERFORMANCE') {
65
+ consider('performance-engineer', 'Performance tuning and bottleneck profiling requested.', 2);
66
+ }
67
+ if (taskType === 'BUG' || suggestedSkills.includes('debugging')) {
68
+ consider('debugger', 'Bug investigation and regression test authoring required.', 2);
69
+ }
70
+ if (taskType === 'DOCUMENTATION' || suggestedSkills.includes('documentation')) {
71
+ consider('documentation', 'Documentation authoring and markdown guide updates.', 2);
72
+ }
73
+ if (taskType === 'RELEASE') {
74
+ consider('release-manager', 'Release preparation, changelog, and packaging verification.', 2);
75
+ }
76
+ // Fallback or core developer for implementation work
77
+ if (!existingClassification.readOnly && !selectedAgents.some((a) => a.agentId === 'developer')) {
78
+ consider('developer', 'Core implementation specialist for code changes and feature development.', 3);
79
+ }
80
+ // Question or read-only research
81
+ if (existingClassification.readOnly && selectedAgents.length === 0) {
82
+ consider('research', 'Read-only inquiry and symbol tracing without file modifications.', 1);
83
+ }
84
+ // If medium or higher, include code reviewer
85
+ if (strategy !== 'SINGLE_AGENT' && !existingClassification.readOnly) {
86
+ consider('code-reviewer', 'Independent verification agent for diff inspection, quality, and invariant checks.', 4);
87
+ }
88
+ // Document why other agents were excluded
89
+ const selectedIds = new Set(selectedAgents.map((a) => a.agentId));
90
+ for (const a of allAgents) {
91
+ if (!selectedIds.has(a.id)) {
92
+ let reason = 'Role not required for current task scope.';
93
+ if (existingClassification.readOnly && (a.role === 'DEVELOPER' || a.role === 'DATABASE_SPECIALIST')) {
94
+ reason = 'Excluded because the request is read-only and requires no file writes.';
95
+ }
96
+ else if (a.riskClassification === 'HIGH' && complexity === 'SIMPLE') {
97
+ reason = 'Excluded to avoid unnecessary high-risk agent invocation on a simple task.';
98
+ }
99
+ excludedAgents.push({ agentId: a.id, reason });
100
+ }
101
+ }
102
+ // 6. Select appropriate skills from registry
103
+ const allSkills = await this.skillRegistry.listAllSkills();
104
+ const selectedSkills = [];
105
+ for (const skillId of suggestedSkills) {
106
+ const s = allSkills.find((item) => item.id === skillId);
107
+ if (s) {
108
+ selectedSkills.push({
109
+ skillId: s.id,
110
+ id: s.id,
111
+ name: s.name,
112
+ reason: `Capabilities [${s.capabilities.join(', ')}] directly address task requirements.`,
113
+ });
114
+ }
115
+ }
116
+ // Ensure at least basic skill matches task type
117
+ if (selectedSkills.length === 0) {
118
+ const defaultSkillMap = {
119
+ FEATURE: 'api-development',
120
+ BUG: 'debugging',
121
+ REFACTOR: 'refactoring',
122
+ DOCUMENTATION: 'documentation',
123
+ TESTING: 'test-driven-development',
124
+ SECURITY: 'security-audit',
125
+ PERFORMANCE: 'performance-optimization',
126
+ };
127
+ const def = defaultSkillMap[taskType] || 'api-development';
128
+ const s = allSkills.find((item) => item.id === def);
129
+ if (s) {
130
+ selectedSkills.push({
131
+ skillId: s.id,
132
+ id: s.id,
133
+ name: s.name,
134
+ reason: `Default foundational skill for ${taskType} tasks.`,
135
+ });
136
+ }
137
+ }
138
+ // 7. Calculate estimated resources
139
+ const baseDuration = complexity === 'CRITICAL' ? 400 : complexity === 'COMPLEX' ? 300 : complexity === 'MEDIUM' ? 150 : 60;
140
+ const baseTokens = selectedAgents.length * 25_000;
141
+ const estimatedResources = {
142
+ tokensEstimate: baseTokens,
143
+ maxDurationSeconds: baseDuration,
144
+ concurrencyLimit: complexity === 'SIMPLE' ? 1 : 4,
145
+ };
146
+ // 8. Required approvals & security implications
147
+ const requiredApprovals = [];
148
+ const securityImplications = [];
149
+ if (complexity === 'CRITICAL') {
150
+ requiredApprovals.push('Mandatory human sign-off on plan before any mutations occur.');
151
+ securityImplications.push('Request touches sensitive operations, data stores, or credential policies.');
152
+ }
153
+ if (selectedAgents.some((a) => a.agentId === 'database-specialist')) {
154
+ requiredApprovals.push('Review database migration files before execution.');
155
+ securityImplications.push('Database schema alterations can introduce non-reversible table state changes.');
156
+ }
157
+ if (!existingClassification.readOnly) {
158
+ securityImplications.push('Filesystem writes permitted under single-writer policy with rollback checkpoint.');
159
+ }
160
+ // 9. Generate transparent explanation
161
+ const agentNames = selectedAgents.map((a) => a.role).join(', ');
162
+ const skillNames = selectedSkills.map((s) => s.name).join(', ');
163
+ const summaryStr = `Task classified as ${taskType} (${complexity} complexity, ${strategy.replace(/_/g, ' ')} strategy). ` +
164
+ `Selected ${selectedAgents.length} specialist(s) [${agentNames}] with ${selectedSkills.length} skill(s) [${skillNames}]. ` +
165
+ `Single-writer file boundaries and independent verification enforced.`;
166
+ const explanationObj = Object.assign(new String(summaryStr), {
167
+ summary: summaryStr,
168
+ whyAgentSelected: `Selected ${selectedAgents.map((a) => `${a.role} (${a.reason})`).join('; ')}`,
169
+ whySkillSelected: `Activated ${selectedSkills.map((s) => `${s.name} (${s.reason})`).join('; ')}`,
170
+ expectedStrategy: `Execution plan under ${strategy} with single-writer lock protection.`,
171
+ approvalRequired: requiredApprovals.length > 0,
172
+ toString() {
173
+ return summaryStr;
174
+ },
175
+ });
176
+ const riskTier = complexity === 'CRITICAL' ? 'CRITICAL' : complexity === 'COMPLEX' ? 'HIGH' : complexity === 'MEDIUM' ? 'MEDIUM' : 'LOW';
177
+ return {
178
+ request: text,
179
+ taskType,
180
+ complexity,
181
+ strategy,
182
+ executionStrategy: strategy,
183
+ riskTier,
184
+ confidence: existingClassification.confidence === 'high' ? 0.95 : 0.8,
185
+ singleWriterRequired: !existingClassification.readOnly,
186
+ selectedAgents,
187
+ selectedSkills,
188
+ excludedAgents,
189
+ requiredCapabilities: capabilities,
190
+ relevantFiles: context.knownFiles || [],
191
+ explanation: explanationObj,
192
+ estimatedResources,
193
+ requiredApprovals,
194
+ securityImplications,
195
+ };
196
+ }
197
+ }
198
+ //# sourceMappingURL=router.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file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YAC3B,kBAAkB;YAClB,iBAAiB;YACjB,oBAAoB;SACrB,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { AgentRegistry } from '../agents/registry.js';\nimport { SkillRegistry } from '../skills/registry.js';\nimport { classifyRequest } from '../../tasks/routing.js';\nimport type { TaskType } from '../../tasks/task.js';\nimport { deriveRequiredCapabilities, estimateComplexity } from './matcher.js';\nimport type {\n AgentSelection,\n ComplexityTier,\n EstimatedResources,\n ExcludedAgent,\n ExecutionStrategy,\n RoutingContext,\n RoutingDecision,\n SkillSelection,\n} from './types.js';\n\nexport class IntelligentRouter {\n private agentRegistry: AgentRegistry;\n private skillRegistry: SkillRegistry;\n\n constructor(agentRegistry: AgentRegistry, skillRegistry: SkillRegistry) {\n this.agentRegistry = agentRegistry;\n this.skillRegistry = skillRegistry;\n }\n\n async route(context: RoutingContext): Promise<RoutingDecision> {\n const text = (context.request || context.prompt || context.userPrompt || '').trim();\n\n // 1. Classify task type using existing deterministic classifier\n const existingClassification = classifyRequest(text);\n const taskType: TaskType = context.taskType || existingClassification.type;\n\n // 2. Derive required capabilities & suggested skills from request\n const { capabilities, suggestedSkills, score } = deriveRequiredCapabilities(text);\n const hasDatabaseOrSecurity = suggestedSkills.includes('database-design') || suggestedSkills.includes('security-audit');\n\n // 3. Compute complexity tier\n const complexity: ComplexityTier = estimateComplexity(text, taskType, score, hasDatabaseOrSecurity);\n\n // 4. Determine execution strategy based on complexity\n let strategy: ExecutionStrategy;\n switch (complexity) {\n case 'CRITICAL':\n strategy = 'APPROVAL_GATED_CRITICAL';\n break;\n case 'COMPLEX':\n strategy = 'MULTI_AGENT_WORKFLOW';\n break;\n case 'MEDIUM':\n strategy = 'SPECIALIST_WITH_REVIEWER';\n break;\n case 'SIMPLE':\n default:\n strategy = 'SINGLE_AGENT';\n break;\n }\n\n // 5. Select appropriate agents from the registry\n const allAgents = await this.agentRegistry.listAllAgents();\n const selectedAgents: AgentSelection[] = [];\n const excludedAgents: ExcludedAgent[] = [];\n\n // Helper to evaluate an agent\n const consider = (agentId: string, reason: string, priority: number) => {\n const a = allAgents.find((p) => p.id === agentId);\n if (a) {\n selectedAgents.push({\n agentId: a.id,\n id: a.id,\n role: a.name,\n reason,\n priority,\n });\n }\n };\n\n if (strategy === 'APPROVAL_GATED_CRITICAL' || strategy === 'MULTI_AGENT_WORKFLOW') {\n consider('planner', 'Complex/critical objective requires structured breakdown and dependency ordering.', 1);\n }\n\n // Primary specialist based on task type and capabilities\n if (suggestedSkills.includes('security-audit') || taskType === 'SECURITY') {\n consider('security-auditor', 'Security concerns detected in request; requires specialized vulnerability analysis.', 2);\n }\n if (suggestedSkills.includes('database-design') || suggestedSkills.includes('database-optimization')) {\n consider('database-specialist', 'Database schema, query, or migration operations requested.', 2);\n }\n if (suggestedSkills.includes('performance-optimization') || taskType === 'PERFORMANCE') {\n consider('performance-engineer', 'Performance tuning and bottleneck profiling requested.', 2);\n }\n if (taskType === 'BUG' || suggestedSkills.includes('debugging')) {\n consider('debugger', 'Bug investigation and regression test authoring required.', 2);\n }\n if (taskType === 'DOCUMENTATION' || suggestedSkills.includes('documentation')) {\n consider('documentation', 'Documentation authoring and markdown guide updates.', 2);\n }\n if (taskType === 'RELEASE') {\n consider('release-manager', 'Release preparation, changelog, and packaging verification.', 2);\n }\n\n // Fallback or core developer for implementation work\n if (!existingClassification.readOnly && !selectedAgents.some((a) => a.agentId === 'developer')) {\n consider('developer', 'Core implementation specialist for code changes and feature development.', 3);\n }\n\n // Question or read-only research\n if (existingClassification.readOnly && selectedAgents.length === 0) {\n consider('research', 'Read-only inquiry and symbol tracing without file modifications.', 1);\n }\n\n // If medium or higher, include code reviewer\n if (strategy !== 'SINGLE_AGENT' && !existingClassification.readOnly) {\n consider('code-reviewer', 'Independent verification agent for diff inspection, quality, and invariant checks.', 4);\n }\n\n // Document why other agents were excluded\n const selectedIds = new Set(selectedAgents.map((a) => a.agentId));\n for (const a of allAgents) {\n if (!selectedIds.has(a.id)) {\n let reason = 'Role not required for current task scope.';\n if (existingClassification.readOnly && (a.role === 'DEVELOPER' || a.role === 'DATABASE_SPECIALIST')) {\n reason = 'Excluded because the request is read-only and requires no file writes.';\n } else if (a.riskClassification === 'HIGH' && complexity === 'SIMPLE') {\n reason = 'Excluded to avoid unnecessary high-risk agent invocation on a simple task.';\n }\n excludedAgents.push({ agentId: a.id, reason });\n }\n }\n\n // 6. Select appropriate skills from registry\n const allSkills = await this.skillRegistry.listAllSkills();\n const selectedSkills: SkillSelection[] = [];\n\n for (const skillId of suggestedSkills) {\n const s = allSkills.find((item) => item.id === skillId);\n if (s) {\n selectedSkills.push({\n skillId: s.id,\n id: s.id,\n name: s.name,\n reason: `Capabilities [${s.capabilities.join(', ')}] directly address task requirements.`,\n });\n }\n }\n\n // Ensure at least basic skill matches task type\n if (selectedSkills.length === 0) {\n const defaultSkillMap: Record<string, string> = {\n FEATURE: 'api-development',\n BUG: 'debugging',\n REFACTOR: 'refactoring',\n DOCUMENTATION: 'documentation',\n TESTING: 'test-driven-development',\n SECURITY: 'security-audit',\n PERFORMANCE: 'performance-optimization',\n };\n const def = defaultSkillMap[taskType] || 'api-development';\n const s = allSkills.find((item) => item.id === def);\n if (s) {\n selectedSkills.push({\n skillId: s.id,\n id: s.id,\n name: s.name,\n reason: `Default foundational skill for ${taskType} tasks.`,\n });\n }\n }\n\n // 7. Calculate estimated resources\n const baseDuration = complexity === 'CRITICAL' ? 400 : complexity === 'COMPLEX' ? 300 : complexity === 'MEDIUM' ? 150 : 60;\n const baseTokens = selectedAgents.length * 25_000;\n const estimatedResources: EstimatedResources = {\n tokensEstimate: baseTokens,\n maxDurationSeconds: baseDuration,\n concurrencyLimit: complexity === 'SIMPLE' ? 1 : 4,\n };\n\n // 8. Required approvals & security implications\n const requiredApprovals: string[] = [];\n const securityImplications: string[] = [];\n\n if (complexity === 'CRITICAL') {\n requiredApprovals.push('Mandatory human sign-off on plan before any mutations occur.');\n securityImplications.push('Request touches sensitive operations, data stores, or credential policies.');\n }\n if (selectedAgents.some((a) => a.agentId === 'database-specialist')) {\n requiredApprovals.push('Review database migration files before execution.');\n securityImplications.push('Database schema alterations can introduce non-reversible table state changes.');\n }\n if (!existingClassification.readOnly) {\n securityImplications.push('Filesystem writes permitted under single-writer policy with rollback checkpoint.');\n }\n\n // 9. Generate transparent explanation\n const agentNames = selectedAgents.map((a) => a.role).join(', ');\n const skillNames = selectedSkills.map((s) => s.name).join(', ');\n const summaryStr =\n `Task classified as ${taskType} (${complexity} complexity, ${strategy.replace(/_/g, ' ')} strategy). ` +\n `Selected ${selectedAgents.length} specialist(s) [${agentNames}] with ${selectedSkills.length} skill(s) [${skillNames}]. ` +\n `Single-writer file boundaries and independent verification enforced.`;\n\n const explanationObj: any = Object.assign(new String(summaryStr), {\n summary: summaryStr,\n whyAgentSelected: `Selected ${selectedAgents.map((a) => `${a.role} (${a.reason})`).join('; ')}`,\n whySkillSelected: `Activated ${selectedSkills.map((s) => `${s.name} (${s.reason})`).join('; ')}`,\n expectedStrategy: `Execution plan under ${strategy} with single-writer lock protection.`,\n approvalRequired: requiredApprovals.length > 0,\n toString() {\n return summaryStr;\n },\n });\n\n const riskTier: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL' =\n complexity === 'CRITICAL' ? 'CRITICAL' : complexity === 'COMPLEX' ? 'HIGH' : complexity === 'MEDIUM' ? 'MEDIUM' : 'LOW';\n\n return {\n request: text,\n taskType,\n complexity,\n strategy,\n executionStrategy: strategy,\n riskTier,\n confidence: existingClassification.confidence === 'high' ? 0.95 : 0.8,\n singleWriterRequired: !existingClassification.readOnly,\n selectedAgents,\n selectedSkills,\n excludedAgents,\n requiredCapabilities: capabilities,\n relevantFiles: context.knownFiles || [],\n explanation: explanationObj,\n estimatedResources,\n requiredApprovals,\n securityImplications,\n };\n }\n}\n"]}
@@ -0,0 +1,64 @@
1
+ import type { TaskType } from '../../tasks/task.js';
2
+ export type ComplexityTier = 'SIMPLE' | 'MEDIUM' | 'COMPLEX' | 'CRITICAL';
3
+ export type ExecutionStrategy = 'SINGLE_AGENT' | 'SPECIALIST_WITH_REVIEWER' | 'SUPERVISOR_SPECIALIST' | 'MULTI_AGENT' | 'MULTI_AGENT_WORKFLOW' | 'APPROVAL_GATED_CRITICAL';
4
+ export interface AgentSelection {
5
+ agentId: string;
6
+ id: string;
7
+ role: string;
8
+ reason: string;
9
+ priority: number;
10
+ }
11
+ export interface SkillSelection {
12
+ skillId: string;
13
+ id: string;
14
+ name: string;
15
+ reason: string;
16
+ }
17
+ export interface ExcludedAgent {
18
+ agentId: string;
19
+ reason: string;
20
+ }
21
+ export interface EstimatedResources {
22
+ tokensEstimate: number;
23
+ maxDurationSeconds: number;
24
+ concurrencyLimit: number;
25
+ }
26
+ export interface RoutingExplanationObject {
27
+ summary: string;
28
+ whyAgentSelected: string;
29
+ whySkillSelected: string;
30
+ expectedStrategy: string;
31
+ approvalRequired?: boolean;
32
+ toString(): string;
33
+ }
34
+ export interface RoutingDecision {
35
+ request: string;
36
+ taskType: TaskType;
37
+ complexity: ComplexityTier;
38
+ strategy: ExecutionStrategy;
39
+ executionStrategy: ExecutionStrategy;
40
+ riskTier: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
41
+ confidence: number;
42
+ singleWriterRequired: boolean;
43
+ selectedAgents: AgentSelection[];
44
+ selectedSkills: SkillSelection[];
45
+ excludedAgents: ExcludedAgent[];
46
+ requiredCapabilities: string[];
47
+ relevantFiles: string[];
48
+ explanation: RoutingExplanationObject & string;
49
+ estimatedResources: EstimatedResources;
50
+ requiredApprovals: string[];
51
+ securityImplications: string[];
52
+ }
53
+ export interface RoutingContext {
54
+ workspaceRoot: string;
55
+ request?: string;
56
+ prompt?: string;
57
+ userPrompt?: string;
58
+ taskType?: TaskType;
59
+ ecosystems?: string[];
60
+ frameworks?: string[];
61
+ hasGraph?: boolean;
62
+ knownFiles?: string[];
63
+ facts?: Record<string, string>;
64
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/intelligence/routing/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TaskType } from '../../tasks/task.js';\n\nexport type ComplexityTier = 'SIMPLE' | 'MEDIUM' | 'COMPLEX' | 'CRITICAL';\n\nexport type ExecutionStrategy =\n | 'SINGLE_AGENT'\n | 'SPECIALIST_WITH_REVIEWER'\n | 'SUPERVISOR_SPECIALIST'\n | 'MULTI_AGENT'\n | 'MULTI_AGENT_WORKFLOW'\n | 'APPROVAL_GATED_CRITICAL';\n\nexport interface AgentSelection {\n agentId: string;\n id: string;\n role: string;\n reason: string;\n priority: number;\n}\n\nexport interface SkillSelection {\n skillId: string;\n id: string;\n name: string;\n reason: string;\n}\n\nexport interface ExcludedAgent {\n agentId: string;\n reason: string;\n}\n\nexport interface EstimatedResources {\n tokensEstimate: number;\n maxDurationSeconds: number;\n concurrencyLimit: number;\n}\n\nexport interface RoutingExplanationObject {\n summary: string;\n whyAgentSelected: string;\n whySkillSelected: string;\n expectedStrategy: string;\n approvalRequired?: boolean;\n toString(): string;\n}\n\nexport interface RoutingDecision {\n request: string;\n taskType: TaskType;\n complexity: ComplexityTier;\n strategy: ExecutionStrategy;\n executionStrategy: ExecutionStrategy;\n riskTier: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';\n confidence: number;\n singleWriterRequired: boolean;\n selectedAgents: AgentSelection[];\n selectedSkills: SkillSelection[];\n excludedAgents: ExcludedAgent[];\n requiredCapabilities: string[];\n relevantFiles: string[];\n explanation: RoutingExplanationObject & string;\n estimatedResources: EstimatedResources;\n requiredApprovals: string[];\n securityImplications: string[];\n}\n\nexport interface RoutingContext {\n workspaceRoot: string;\n request?: string;\n prompt?: string;\n userPrompt?: string;\n taskType?: TaskType;\n ecosystems?: string[];\n frameworks?: string[];\n hasGraph?: boolean;\n knownFiles?: string[];\n facts?: Record<string, string>;\n}\n"]}
@@ -0,0 +1,7 @@
1
+ import type { AgentExecutionRequest, AgentExecutionResponse, AgentRuntimeAdapter, RuntimeAvailability } from '../types.js';
2
+ export declare class GoogleAdkAdapter implements AgentRuntimeAdapter {
3
+ readonly id = "google-adk";
4
+ readonly name = "Google Agent Development Kit (ADK) Adapter";
5
+ checkAvailability(): Promise<RuntimeAvailability>;
6
+ execute(request: AgentExecutionRequest): Promise<AgentExecutionResponse>;
7
+ }
@@ -0,0 +1,49 @@
1
+ import { detectGoogleAdk } from './detector.js';
2
+ import { executeBoundedCommand, nonExecutedResponse } from '../boundary.js';
3
+ export class GoogleAdkAdapter {
4
+ id = 'google-adk';
5
+ name = 'Google Agent Development Kit (ADK) Adapter';
6
+ async checkAvailability() {
7
+ const detection = await detectGoogleAdk();
8
+ const available = detection.isInstalled && detection.hasCredentials;
9
+ return {
10
+ available,
11
+ provider: 'google-adk',
12
+ version: detection.version,
13
+ supportsStreaming: true,
14
+ supportsNativeSubagents: true,
15
+ sandboxed: false,
16
+ sandboxCapability: 'unavailable-cwd-only',
17
+ reason: available ? undefined : detection.reason,
18
+ };
19
+ }
20
+ async execute(request) {
21
+ if (request.isPlaceholder) {
22
+ return nonExecutedResponse('FAILED', {
23
+ executionKind: 'none',
24
+ reason: 'Placeholder runtime cannot return a successful execution.',
25
+ error: 'Placeholder runtime cannot return a successful execution.',
26
+ isPlaceholder: true,
27
+ });
28
+ }
29
+ const avail = await this.checkAvailability();
30
+ if (!avail.available) {
31
+ return nonExecutedResponse('BLOCKED', {
32
+ executionKind: 'none',
33
+ reason: avail.reason || 'Google ADK runtime is unavailable.',
34
+ remediation: 'Install "@google/adk" and configure GEMINI_API_KEY or GOOGLE_API_KEY.',
35
+ cwd: request.cwd,
36
+ });
37
+ }
38
+ if (request.command && request.command.length > 0) {
39
+ return executeBoundedCommand(request, request.command, 'agent', 60_000, true);
40
+ }
41
+ return nonExecutedResponse('UNSUPPORTED', {
42
+ executionKind: 'none',
43
+ reason: 'Google ADK local programmatic workflow invocation is not implemented without an explicit runner command.',
44
+ remediation: 'Provide an explicit executable command or run ADK externally and pass artifacts to IndependentVerificationEngine.',
45
+ cwd: request.cwd,
46
+ });
47
+ }
48
+ }
49
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../../../../src/intelligence/runtime/adk/adapter.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE5E,MAAM,OAAO,gBAAgB;IAClB,EAAE,GAAG,YAAY,CAAC;IAClB,IAAI,GAAG,4CAA4C,CAAC;IAE7D,KAAK,CAAC,iBAAiB;QACrB,MAAM,SAAS,GAAG,MAAM,eAAe,EAAE,CAAC;QAC1C,MAAM,SAAS,GAAG,SAAS,CAAC,WAAW,IAAI,SAAS,CAAC,cAAc,CAAC;QAEpE,OAAO;YACL,SAAS;YACT,QAAQ,EAAE,YAAY;YACtB,OAAO,EAAE,SAAS,CAAC,OAAO;YAC1B,iBAAiB,EAAE,IAAI;YACvB,uBAAuB,EAAE,IAAI;YAC7B,SAAS,EAAE,KAAK;YAChB,iBAAiB,EAAE,sBAAsB;YACzC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM;SACjD,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,OAA8B;QAC1C,IAAI,OAAO,CAAC,aAAa,EAAE,CAAC;YAC1B,OAAO,mBAAmB,CAAC,QAAQ,EAAE;gBACnC,aAAa,EAAE,MAAM;gBACrB,MAAM,EAAE,2DAA2D;gBACnE,KAAK,EAAE,2DAA2D;gBAClE,aAAa,EAAE,IAAI;aACpB,CAAC,CAAC;QACL,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAC7C,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;YACrB,OAAO,mBAAmB,CAAC,SAAS,EAAE;gBACpC,aAAa,EAAE,MAAM;gBACrB,MAAM,EAAE,KAAK,CAAC,MAAM,IAAI,oCAAoC;gBAC5D,WAAW,EAAE,uEAAuE;gBACpF,GAAG,EAAE,OAAO,CAAC,GAAG;aACjB,CAAC,CAAC;QACL,CAAC;QAED,IAAI,OAAO,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAClD,OAAO,qBAAqB,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QAChF,CAAC;QAED,OAAO,mBAAmB,CAAC,aAAa,EAAE;YACxC,aAAa,EAAE,MAAM;YACrB,MAAM,EAAE,0GAA0G;YAClH,WAAW,EAAE,mHAAmH;YAChI,GAAG,EAAE,OAAO,CAAC,GAAG;SACjB,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type {\n AgentExecutionRequest,\n AgentExecutionResponse,\n AgentRuntimeAdapter,\n RuntimeAvailability,\n} from '../types.js';\nimport { detectGoogleAdk } from './detector.js';\nimport { executeBoundedCommand, nonExecutedResponse } from '../boundary.js';\n\nexport class GoogleAdkAdapter implements AgentRuntimeAdapter {\n readonly id = 'google-adk';\n readonly name = 'Google Agent Development Kit (ADK) Adapter';\n\n async checkAvailability(): Promise<RuntimeAvailability> {\n const detection = await detectGoogleAdk();\n const available = detection.isInstalled && detection.hasCredentials;\n\n return {\n available,\n provider: 'google-adk',\n version: detection.version,\n supportsStreaming: true,\n supportsNativeSubagents: true,\n sandboxed: false,\n sandboxCapability: 'unavailable-cwd-only',\n reason: available ? undefined : detection.reason,\n };\n }\n\n async execute(request: AgentExecutionRequest): Promise<AgentExecutionResponse> {\n if (request.isPlaceholder) {\n return nonExecutedResponse('FAILED', {\n executionKind: 'none',\n reason: 'Placeholder runtime cannot return a successful execution.',\n error: 'Placeholder runtime cannot return a successful execution.',\n isPlaceholder: true,\n });\n }\n\n const avail = await this.checkAvailability();\n if (!avail.available) {\n return nonExecutedResponse('BLOCKED', {\n executionKind: 'none',\n reason: avail.reason || 'Google ADK runtime is unavailable.',\n remediation: 'Install \"@google/adk\" and configure GEMINI_API_KEY or GOOGLE_API_KEY.',\n cwd: request.cwd,\n });\n }\n\n if (request.command && request.command.length > 0) {\n return executeBoundedCommand(request, request.command, 'agent', 60_000, true);\n }\n\n return nonExecutedResponse('UNSUPPORTED', {\n executionKind: 'none',\n reason: 'Google ADK local programmatic workflow invocation is not implemented without an explicit runner command.',\n remediation: 'Provide an explicit executable command or run ADK externally and pass artifacts to IndependentVerificationEngine.',\n cwd: request.cwd,\n });\n }\n}\n"]}
@@ -0,0 +1,7 @@
1
+ export interface GoogleAdkDetectionResult {
2
+ isInstalled: boolean;
3
+ hasCredentials: boolean;
4
+ version?: string;
5
+ reason?: string;
6
+ }
7
+ export declare function detectGoogleAdk(): Promise<GoogleAdkDetectionResult>;
@@ -0,0 +1,28 @@
1
+ export async function detectGoogleAdk() {
2
+ const hasCredentials = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);
3
+ let isInstalled;
4
+ let version;
5
+ try {
6
+ // Dynamic import to avoid bundling dependency or crashing when package is absent
7
+ const adkMod = await import('@google/adk');
8
+ isInstalled = true;
9
+ version = adkMod?.version || '0.1.0';
10
+ }
11
+ catch {
12
+ isInstalled = false;
13
+ }
14
+ let reason;
15
+ if (!isInstalled) {
16
+ reason = 'Optional package "@google/adk" is not installed in project dependencies.';
17
+ }
18
+ else if (!hasCredentials) {
19
+ reason = 'Google ADK package is installed, but neither GEMINI_API_KEY nor GOOGLE_API_KEY is configured.';
20
+ }
21
+ return {
22
+ isInstalled,
23
+ hasCredentials,
24
+ version,
25
+ reason,
26
+ };
27
+ }
28
+ //# sourceMappingURL=detector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"detector.js","sourceRoot":"","sources":["../../../../src/intelligence/runtime/adk/detector.ts"],"names":[],"mappings":"AAOA,MAAM,CAAC,KAAK,UAAU,eAAe;IACnC,MAAM,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;IAEzF,IAAI,WAAoB,CAAC;IACzB,IAAI,OAA2B,CAAC;IAEhC,IAAI,CAAC;QACH,iFAAiF;QACjF,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,aAAuB,CAAC,CAAC;QACrD,WAAW,GAAG,IAAI,CAAC;QACnB,OAAO,GAAI,MAAc,EAAE,OAAO,IAAI,OAAO,CAAC;IAChD,CAAC;IAAC,MAAM,CAAC;QACP,WAAW,GAAG,KAAK,CAAC;IACtB,CAAC;IAED,IAAI,MAA0B,CAAC;IAC/B,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,MAAM,GAAG,0EAA0E,CAAC;IACtF,CAAC;SAAM,IAAI,CAAC,cAAc,EAAE,CAAC;QAC3B,MAAM,GAAG,+FAA+F,CAAC;IAC3G,CAAC;IAED,OAAO;QACL,WAAW;QACX,cAAc;QACd,OAAO;QACP,MAAM;KACP,CAAC;AACJ,CAAC","sourcesContent":["export interface GoogleAdkDetectionResult {\n isInstalled: boolean;\n hasCredentials: boolean;\n version?: string;\n reason?: string;\n}\n\nexport async function detectGoogleAdk(): Promise<GoogleAdkDetectionResult> {\n const hasCredentials = Boolean(process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY);\n\n let isInstalled: boolean;\n let version: string | undefined;\n\n try {\n // Dynamic import to avoid bundling dependency or crashing when package is absent\n const adkMod = await import('@google/adk' as string);\n isInstalled = true;\n version = (adkMod as any)?.version || '0.1.0';\n } catch {\n isInstalled = false;\n }\n\n let reason: string | undefined;\n if (!isInstalled) {\n reason = 'Optional package \"@google/adk\" is not installed in project dependencies.';\n } else if (!hasCredentials) {\n reason = 'Google ADK package is installed, but neither GEMINI_API_KEY nor GOOGLE_API_KEY is configured.';\n }\n\n return {\n isInstalled,\n hasCredentials,\n version,\n reason,\n };\n}\n"]}
@@ -0,0 +1,30 @@
1
+ import type { AgentExecutionRequest, AgentExecutionResponse, ExecutionKind, RuntimeExecutionStatus } from './types.js';
2
+ export declare const MAX_RUNTIME_OUTPUT_CHARS = 50000;
3
+ export declare function createExecutionId(prefix?: string): string;
4
+ export declare function nonExecutedResponse(status: Extract<RuntimeExecutionStatus, 'PREPARED' | 'BLOCKED' | 'NOT_EXECUTED' | 'UNSUPPORTED' | 'FAILED'>, opts: {
5
+ executionKind: ExecutionKind;
6
+ output?: string;
7
+ reason: string;
8
+ remediation?: string;
9
+ error?: string;
10
+ cwd?: string;
11
+ isPlaceholder?: boolean;
12
+ durationMs?: number;
13
+ }): AgentExecutionResponse;
14
+ /** Validate working directory containment and symlink safety when workspaceRoot is supplied. */
15
+ export declare function validateExecutionCwd(cwd: string | undefined, workspaceRoot?: string): Promise<{
16
+ ok: true;
17
+ cwd?: string;
18
+ } | {
19
+ ok: false;
20
+ reason: string;
21
+ }>;
22
+ /** Enforce concrete command policy immediately before spawn (binary, shell avoidance, destructive ops). */
23
+ export declare function validateConcreteCommand(cmdArgs: string[], workspaceRoot: string, explicitApproval?: boolean): {
24
+ ok: true;
25
+ } | {
26
+ ok: false;
27
+ reason: string;
28
+ };
29
+ /** Execute a concrete validated command with minimal env, bounded redacted output, and tree cleanup. */
30
+ export declare function executeBoundedCommand(request: AgentExecutionRequest, cmdArgs: string[], executionKind: Extract<ExecutionKind, 'command' | 'agent'>, defaultTimeoutMs: number, untrustedOutput?: boolean): Promise<AgentExecutionResponse>;
@@ -0,0 +1,163 @@
1
+ import crypto from 'node:crypto';
2
+ import { promises as fs } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createMinimalExecutionEnv, run } from '../../utils/proc.js';
5
+ import { assertNoSymlinkEscape, isInside } from '../../utils/paths.js';
6
+ import { redact } from '../../security/redact.js';
7
+ import { SecurityPolicyEvaluator } from '../security/policy.js';
8
+ export const MAX_RUNTIME_OUTPUT_CHARS = 50_000;
9
+ const SHELL_BINARIES = new Set(['sh', 'bash', 'zsh', 'dash', 'cmd', 'cmd.exe', 'powershell', 'powershell.exe', 'pwsh', 'pwsh.exe']);
10
+ const DESTRUCTIVE_EXEC_RE = /\b(?:rm\s+-[a-zA-Z]*[rf][a-zA-Z]*|mkfs|format\s+[a-zA-Z]:|shutdown|reboot|dd\s+if=|del\s+\/[sq])\b/i;
11
+ export function createExecutionId(prefix = 'exec') {
12
+ return `${prefix}-${Date.now().toString(36)}-${crypto.randomBytes(4).toString('hex')}`;
13
+ }
14
+ export function nonExecutedResponse(status, opts) {
15
+ const safeReason = redact(opts.reason);
16
+ const safeOutput = redact(opts.output ?? '');
17
+ return {
18
+ ok: false,
19
+ status,
20
+ executionKind: opts.executionKind,
21
+ executionId: createExecutionId(),
22
+ verificationStatus: 'NOT_TESTED',
23
+ output: safeOutput,
24
+ error: opts.error ? redact(opts.error) : status === 'FAILED' || status === 'BLOCKED' ? safeReason : undefined,
25
+ reason: safeReason,
26
+ remediation: opts.remediation,
27
+ cwd: opts.cwd,
28
+ durationMs: opts.durationMs ?? 0,
29
+ filesModified: [],
30
+ isPlaceholder: opts.isPlaceholder,
31
+ sandboxed: false,
32
+ sandboxCapability: 'unavailable-cwd-only',
33
+ };
34
+ }
35
+ /** Validate working directory containment and symlink safety when workspaceRoot is supplied. */
36
+ export async function validateExecutionCwd(cwd, workspaceRoot) {
37
+ if (!cwd)
38
+ return { ok: true, cwd: undefined };
39
+ const resolvedCwd = path.resolve(cwd);
40
+ try {
41
+ const st = await fs.stat(resolvedCwd);
42
+ if (!st.isDirectory())
43
+ return { ok: false, reason: `Working directory is not a directory: "${cwd}".` };
44
+ }
45
+ catch {
46
+ return { ok: false, reason: `Working directory does not exist: "${cwd}".` };
47
+ }
48
+ if (workspaceRoot) {
49
+ const resolvedRoot = path.resolve(workspaceRoot);
50
+ if (!isInside(resolvedRoot, resolvedCwd)) {
51
+ return { ok: false, reason: `Working directory "${cwd}" escapes workspace root.` };
52
+ }
53
+ try {
54
+ await assertNoSymlinkEscape(resolvedRoot, resolvedCwd);
55
+ }
56
+ catch (e) {
57
+ return { ok: false, reason: e.message };
58
+ }
59
+ }
60
+ return { ok: true, cwd: resolvedCwd };
61
+ }
62
+ /** Enforce concrete command policy immediately before spawn (binary, shell avoidance, destructive ops). */
63
+ export function validateConcreteCommand(cmdArgs, workspaceRoot, explicitApproval = false) {
64
+ const binary = cmdArgs[0];
65
+ if (!binary || !binary.trim()) {
66
+ return { ok: false, reason: 'Empty executable command cannot be invoked.' };
67
+ }
68
+ const base = path.basename(binary).toLowerCase();
69
+ if (SHELL_BINARIES.has(base)) {
70
+ return { ok: false, reason: `Direct shell invocation "${base}" is disallowed; pass an executable with argument array instead.` };
71
+ }
72
+ if (cmdArgs.some((arg) => arg.includes('\0'))) {
73
+ return { ok: false, reason: 'Command arguments contain NUL byte.' };
74
+ }
75
+ if (!explicitApproval) {
76
+ // Only check executable + flag patterns outside quoted payload arguments for shell binaries; block direct destructive commands.
77
+ const headAndFlags = `${base} ${cmdArgs.slice(1).filter((a) => !a.includes(' ')).join(' ')}`;
78
+ if (DESTRUCTIVE_EXEC_RE.test(headAndFlags)) {
79
+ return { ok: false, reason: `Destructive command "${base}" requires explicit developer approval before execution.` };
80
+ }
81
+ const evaluator = new SecurityPolicyEvaluator(workspaceRoot);
82
+ // If invoking an explicit script/command inside an allowlisted tool (node/npm/npx/git) check evaluator on binary; block arbitrary shells/installers.
83
+ const basePolicy = evaluator.checkCommandExec(base);
84
+ const allowedRuntimeBins = new Set(['node', 'node.exe', 'npm', 'npx', 'git', 'vitest', 'tsc', 'claude', 'codex', 'cursor']);
85
+ if (!basePolicy.allowed && !allowedRuntimeBins.has(base) && !path.isAbsolute(binary)) {
86
+ return { ok: false, reason: basePolicy.reason ?? `Executable "${base}" is not permitted by execution policy.` };
87
+ }
88
+ }
89
+ return { ok: true };
90
+ }
91
+ /** Execute a concrete validated command with minimal env, bounded redacted output, and tree cleanup. */
92
+ export async function executeBoundedCommand(request, cmdArgs, executionKind, defaultTimeoutMs, untrustedOutput = false) {
93
+ const executionId = createExecutionId(executionKind);
94
+ const startMs = Date.now();
95
+ const startedAt = new Date(startMs).toISOString();
96
+ const targetCwd = request.sandboxPath ?? request.cwd;
97
+ const cwdCheck = await validateExecutionCwd(targetCwd, request.workspaceRoot);
98
+ if (!cwdCheck.ok) {
99
+ return nonExecutedResponse('BLOCKED', {
100
+ executionKind: 'none',
101
+ reason: cwdCheck.reason,
102
+ remediation: 'Provide an existing working directory inside the workspace root.',
103
+ cwd: targetCwd,
104
+ });
105
+ }
106
+ const cmdCheck = validateConcreteCommand(cmdArgs, request.workspaceRoot ?? targetCwd ?? process.cwd(), request.explicitApproval);
107
+ if (!cmdCheck.ok) {
108
+ return nonExecutedResponse('BLOCKED', {
109
+ executionKind: 'none',
110
+ reason: cmdCheck.reason,
111
+ remediation: 'Approve destructive operations explicitly or use an allowlisted non-shell executable.',
112
+ cwd: cwdCheck.cwd,
113
+ });
114
+ }
115
+ const safeEnv = createMinimalExecutionEnv(process.env, request.allowlistedEnvKeys, request.env);
116
+ const res = await run(cmdArgs[0], cmdArgs.slice(1), {
117
+ cwd: cwdCheck.cwd,
118
+ timeoutMs: request.timeoutMs ?? defaultTimeoutMs,
119
+ signal: request.signal,
120
+ maxBytes: request.maxBytes ?? MAX_RUNTIME_OUTPUT_CHARS,
121
+ env: safeEnv,
122
+ replaceEnv: true,
123
+ });
124
+ const endedAt = new Date().toISOString();
125
+ const durationMs = Date.now() - startMs;
126
+ const boundedStdout = redact(res.stdout.slice(0, MAX_RUNTIME_OUTPUT_CHARS));
127
+ const boundedStderr = redact(res.stderr.slice(0, MAX_RUNTIME_OUTPUT_CHARS));
128
+ const outputText = boundedStdout || boundedStderr;
129
+ let status = 'SUCCEEDED';
130
+ if (res.aborted)
131
+ status = 'CANCELLED';
132
+ else if (res.timedOut)
133
+ status = 'TIMED_OUT';
134
+ else if (!res.ok)
135
+ status = 'FAILED';
136
+ return {
137
+ ok: status === 'SUCCEEDED',
138
+ status,
139
+ executionKind,
140
+ executionId,
141
+ verificationStatus: 'NOT_TESTED',
142
+ output: outputText,
143
+ ...(untrustedOutput ? { untrustedOutput: true } : {}),
144
+ error: status === 'SUCCEEDED'
145
+ ? undefined
146
+ : redact(res.stderr || res.error || (status === 'TIMED_OUT' ? 'Execution timed out' : status === 'CANCELLED' ? 'Execution cancelled' : `Process exited with code ${res.code}`)),
147
+ command: cmdArgs,
148
+ cwd: cwdCheck.cwd,
149
+ startedAt,
150
+ endedAt,
151
+ durationMs,
152
+ tokensUsed: 0,
153
+ filesModified: status === 'SUCCEEDED' ? (request.contextFiles ?? []) : [],
154
+ exitCode: res.code ?? (status === 'SUCCEEDED' ? 0 : 1),
155
+ stdout: boundedStdout,
156
+ stderr: boundedStderr,
157
+ timedOut: res.timedOut,
158
+ aborted: res.aborted,
159
+ sandboxed: false,
160
+ sandboxCapability: 'unavailable-cwd-only',
161
+ };
162
+ }
163
+ //# sourceMappingURL=boundary.js.map