@moldea.ai/adapter-eve 1.0.0

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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +42 -0
  3. package/cover.png +0 -0
  4. package/dist/adapter/index.d.ts +3 -0
  5. package/dist/adapter/index.d.ts.map +1 -0
  6. package/dist/constants/index.d.ts +11 -0
  7. package/dist/constants/index.d.ts.map +1 -0
  8. package/dist/contracts/index.d.ts +127 -0
  9. package/dist/contracts/index.d.ts.map +1 -0
  10. package/dist/diagnostics/index.d.ts +38 -0
  11. package/dist/diagnostics/index.d.ts.map +1 -0
  12. package/dist/index.d.ts +2 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +1831 -0
  15. package/dist/inspection/agent-inspection.d.ts +6 -0
  16. package/dist/inspection/agent-inspection.d.ts.map +1 -0
  17. package/dist/inspection/common.d.ts +16 -0
  18. package/dist/inspection/common.d.ts.map +1 -0
  19. package/dist/inspection/index.d.ts +2 -0
  20. package/dist/inspection/index.d.ts.map +1 -0
  21. package/dist/inspection/inspection.d.ts +19 -0
  22. package/dist/inspection/inspection.d.ts.map +1 -0
  23. package/dist/inspection/instruction-inspection.d.ts +6 -0
  24. package/dist/inspection/instruction-inspection.d.ts.map +1 -0
  25. package/dist/inspection/package-inspection.d.ts +7 -0
  26. package/dist/inspection/package-inspection.d.ts.map +1 -0
  27. package/dist/inspection/relationships.d.ts +9 -0
  28. package/dist/inspection/relationships.d.ts.map +1 -0
  29. package/dist/inspection/session.d.ts +5 -0
  30. package/dist/inspection/session.d.ts.map +1 -0
  31. package/dist/inspection/skill-inspection.d.ts +6 -0
  32. package/dist/inspection/skill-inspection.d.ts.map +1 -0
  33. package/dist/inspection/subagent-inspection.d.ts +6 -0
  34. package/dist/inspection/subagent-inspection.d.ts.map +1 -0
  35. package/dist/inspection/tool-inspection.d.ts +6 -0
  36. package/dist/inspection/tool-inspection.d.ts.map +1 -0
  37. package/dist/package-discovery/index.d.ts +5 -0
  38. package/dist/package-discovery/index.d.ts.map +1 -0
  39. package/dist/repository-discovery/agent-roots.d.ts +5 -0
  40. package/dist/repository-discovery/agent-roots.d.ts.map +1 -0
  41. package/dist/repository-discovery/candidate-index.d.ts +5 -0
  42. package/dist/repository-discovery/candidate-index.d.ts.map +1 -0
  43. package/dist/repository-discovery/index.d.ts +3 -0
  44. package/dist/repository-discovery/index.d.ts.map +1 -0
  45. package/dist/source-analysis/functions.d.ts +9 -0
  46. package/dist/source-analysis/functions.d.ts.map +1 -0
  47. package/dist/source-analysis/helper-imports.d.ts +5 -0
  48. package/dist/source-analysis/helper-imports.d.ts.map +1 -0
  49. package/dist/source-analysis/index.d.ts +6 -0
  50. package/dist/source-analysis/index.d.ts.map +1 -0
  51. package/dist/source-analysis/object-definitions.d.ts +11 -0
  52. package/dist/source-analysis/object-definitions.d.ts.map +1 -0
  53. package/dist/source-analysis/source-analysis.d.ts +5 -0
  54. package/dist/source-analysis/source-analysis.d.ts.map +1 -0
  55. package/dist/source-analysis/static-values.d.ts +7 -0
  56. package/dist/source-analysis/static-values.d.ts.map +1 -0
  57. package/package.json +60 -0
package/dist/index.js ADDED
@@ -0,0 +1,1831 @@
1
+ import ts from "typescript";
2
+ import { posix } from "node:path";
3
+ import { parseRepositoryPath } from "@moldea.ai/repository";
4
+ import { intersects, subset, validRange } from "semver";
5
+ //#region src/constants/index.ts
6
+ var EVE_SUPPORTED_PACKAGE_RANGE = ">=0.39.1 <0.40.0";
7
+ var EVE_TARGET_ID = "typescript-filesystem-agent-0-39";
8
+ var EVE_SUPPORTED_REPOSITORY_FORMAT_VERSIONS = Object.freeze([1]);
9
+ var EVE_AUTHORED_MODULE_EXTENSIONS = Object.freeze([
10
+ ".cts",
11
+ ".mts",
12
+ ".cjs",
13
+ ".mjs",
14
+ ".ts",
15
+ ".js"
16
+ ]);
17
+ var EVE_TOOL_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/u;
18
+ var EVE_RESERVED_TOOL_NAME = "Workflow";
19
+ var EVE_FRAMEWORK_TOOL_NAMES = Object.freeze([
20
+ "ask_question",
21
+ "bash",
22
+ "glob",
23
+ "grep",
24
+ "read_file",
25
+ "write_file",
26
+ "todo",
27
+ "web_fetch",
28
+ "web_search",
29
+ "agent",
30
+ "connection_search",
31
+ "load_skill"
32
+ ]);
33
+ //#endregion
34
+ //#region src/repository-discovery/agent-roots.ts
35
+ var isSafeRuntimeName = (runtimeName) => runtimeName.length > 0 && !runtimeName.includes("\0") && !runtimeName.includes("\n") && !runtimeName.includes("\r") && runtimeName === runtimeName.trim();
36
+ var getPackageRuntimeName = (packageName) => {
37
+ if (packageName === null || packageName.length === 0) return null;
38
+ const runtimeName = packageName.slice(packageName.lastIndexOf("/") + 1);
39
+ return isSafeRuntimeName(runtimeName) ? runtimeName : null;
40
+ };
41
+ var getLocalRoot = (path, baseRoot, layout) => {
42
+ const prefix = `${baseRoot === "/" ? "" : baseRoot}/subagents/`;
43
+ if (!path.startsWith(prefix) || !path.endsWith("/agent.ts")) return null;
44
+ const segments = path.slice(prefix.length, -9).split("/");
45
+ if (segments.length === 0 || segments.some((segment) => segment.length === 0)) return null;
46
+ if (segments.length % 2 === 0) return null;
47
+ for (let index = 1; index < segments.length; index += 2) if (segments[index] !== "subagents") return null;
48
+ const agentRoot = posix.dirname(path);
49
+ const parentRoot = posix.dirname(posix.dirname(agentRoot));
50
+ const runtimeName = segments.at(-1) ?? "";
51
+ return Object.freeze({
52
+ agentKind: "local-subagent",
53
+ agentRoot,
54
+ layout,
55
+ parentRoot,
56
+ runtimeName: isSafeRuntimeName(runtimeName) ? runtimeName : null
57
+ });
58
+ };
59
+ /** Resolves one bound `agent.ts` into an exact Eve root or local-subagent layout. */
60
+ var resolveEveAgentRoot = (path, packageObservation) => {
61
+ if (posix.basename(path) !== "agent.ts") return null;
62
+ const packageRoot = parseRepositoryPath(posix.dirname(packageObservation.path));
63
+ const flatPath = parseRepositoryPath(posix.join(packageRoot, "agent.ts"));
64
+ const nestedRoot = parseRepositoryPath(posix.join(packageRoot, "agent"));
65
+ const nestedPath = parseRepositoryPath(posix.join(nestedRoot, "agent.ts"));
66
+ if (path === flatPath) return Object.freeze({
67
+ agentKind: "root",
68
+ agentRoot: packageRoot,
69
+ layout: "flat",
70
+ parentRoot: null,
71
+ runtimeName: getPackageRuntimeName(packageObservation.manifestPackageName)
72
+ });
73
+ if (path === nestedPath) return Object.freeze({
74
+ agentKind: "root",
75
+ agentRoot: nestedRoot,
76
+ layout: "nested",
77
+ parentRoot: null,
78
+ runtimeName: getPackageRuntimeName(packageObservation.manifestPackageName)
79
+ });
80
+ return getLocalRoot(path, packageRoot, "flat") ?? getLocalRoot(path, nestedRoot, "nested");
81
+ };
82
+ //#endregion
83
+ //#region src/repository-discovery/candidate-index.ts
84
+ var compareStrings = (left, right) => left < right ? -1 : left > right ? 1 : 0;
85
+ var getAuthoredExtension = (path) => EVE_AUTHORED_MODULE_EXTENSIONS.find((extension) => path.endsWith(extension)) ?? null;
86
+ var removeExtension = (path, extension) => path.slice(0, -extension.length);
87
+ var getDirectRelativePath = (root, path) => {
88
+ const prefix = root === "/" ? "/" : `${root}/`;
89
+ return path.startsWith(prefix) ? path.slice(prefix.length) : null;
90
+ };
91
+ var indexExtensionNamespaces = (root, entries) => {
92
+ const namespaces = /* @__PURE__ */ new Set();
93
+ for (const entry of entries) {
94
+ if (entry.type !== "file") continue;
95
+ const relative = getDirectRelativePath(root, entry.path);
96
+ if (relative === null || !relative.startsWith("extensions/")) continue;
97
+ const extensionRelative = relative.slice(11);
98
+ const segments = extensionRelative.split("/");
99
+ const extension = getAuthoredExtension(extensionRelative);
100
+ const firstSegment = segments[0];
101
+ const secondSegment = segments[1];
102
+ let namespace = null;
103
+ if (extension !== null && segments.length === 1 && firstSegment !== void 0) namespace = removeExtension(firstSegment, extension);
104
+ else if (extension !== null && segments.length === 2 && firstSegment !== void 0 && secondSegment !== void 0 && removeExtension(secondSegment, extension) === "extension") namespace = firstSegment;
105
+ if (namespace !== null && EVE_TOOL_NAME_PATTERN.test(namespace)) namespaces.add(namespace);
106
+ }
107
+ return namespaces;
108
+ };
109
+ var isExtensionReserved = (name, namespaces) => [...namespaces].some((namespace) => name.startsWith(`${namespace}__`));
110
+ var indexTools = (root, entries, namespaces) => {
111
+ const raw = entries.flatMap((entry) => {
112
+ if (entry.type !== "file") return [];
113
+ const relative = getDirectRelativePath(root, entry.path);
114
+ if (relative === null || !relative.startsWith("tools/")) return [];
115
+ const toolRelative = relative.slice(6);
116
+ const extension = getAuthoredExtension(toolRelative);
117
+ if (extension === null) return [];
118
+ const withoutExtension = removeExtension(toolRelative, extension);
119
+ return [{
120
+ entry,
121
+ extension,
122
+ relativePath: withoutExtension,
123
+ segments: withoutExtension.split("/")
124
+ }];
125
+ });
126
+ const slots = /* @__PURE__ */ new Map();
127
+ for (const candidate of raw) slots.set(candidate.relativePath, (slots.get(candidate.relativePath) ?? 0) + 1);
128
+ return Object.freeze(raw.map(({ entry, extension, relativePath, segments }) => {
129
+ const runtimeName = segments.join("-");
130
+ return Object.freeze({
131
+ isCollidedSlot: (slots.get(relativePath) ?? 0) > 1,
132
+ isExtensionReserved: isExtensionReserved(segments[0] ?? "", namespaces),
133
+ isSupportedSource: extension === ".ts",
134
+ path: entry.path,
135
+ relativePath,
136
+ runtimeName,
137
+ segments: Object.freeze(segments)
138
+ });
139
+ }));
140
+ };
141
+ var indexSkills = (root, entries) => {
142
+ const raw = [];
143
+ for (const entry of entries) {
144
+ if (entry.type !== "file") continue;
145
+ const relative = getDirectRelativePath(root, entry.path);
146
+ if (relative === null || !relative.startsWith("skills/")) continue;
147
+ const segments = relative.slice(7).split("/");
148
+ const firstSegment = segments[0];
149
+ const secondSegment = segments[1];
150
+ if (segments.length === 2 && firstSegment !== void 0 && secondSegment === "SKILL.md") {
151
+ raw.push({
152
+ identity: firstSegment,
153
+ kind: "packaged",
154
+ path: entry.path
155
+ });
156
+ continue;
157
+ }
158
+ if (segments.length !== 1) continue;
159
+ if (firstSegment === void 0) continue;
160
+ if (/\.md$/iu.test(firstSegment)) {
161
+ raw.push({
162
+ identity: firstSegment.slice(0, -3),
163
+ kind: "markdown",
164
+ path: entry.path
165
+ });
166
+ continue;
167
+ }
168
+ const extension = getAuthoredExtension(firstSegment);
169
+ if (extension !== null) raw.push({
170
+ identity: removeExtension(firstSegment, extension),
171
+ kind: extension === ".ts" ? "typescript" : "markdown",
172
+ path: entry.path
173
+ });
174
+ }
175
+ const identities = /* @__PURE__ */ new Map();
176
+ for (const candidate of raw) identities.set(candidate.identity, (identities.get(candidate.identity) ?? 0) + 1);
177
+ return Object.freeze(raw.map((candidate) => Object.freeze({
178
+ ...candidate,
179
+ isCollidedSlot: (identities.get(candidate.identity) ?? 0) > 1
180
+ })));
181
+ };
182
+ var indexSubagents = (root, entries, namespaces) => {
183
+ const raw = [];
184
+ for (const entry of entries) {
185
+ if (entry.type !== "file") continue;
186
+ const relative = getDirectRelativePath(root, entry.path);
187
+ if (relative === null || !relative.startsWith("subagents/")) continue;
188
+ const segments = relative.slice(10).split("/");
189
+ const firstSegment = segments[0];
190
+ const secondSegment = segments[1];
191
+ if (segments.length === 2 && firstSegment !== void 0 && secondSegment !== void 0) {
192
+ const extension = getAuthoredExtension(secondSegment);
193
+ if (extension !== null && removeExtension(secondSegment, extension) === "agent") raw.push({
194
+ agentPath: entry.path,
195
+ kind: "directory",
196
+ runtimeName: firstSegment
197
+ });
198
+ continue;
199
+ }
200
+ if (segments.length === 1 && firstSegment !== void 0) {
201
+ const extension = getAuthoredExtension(firstSegment);
202
+ if (extension !== null) raw.push({
203
+ agentPath: entry.path,
204
+ kind: "file",
205
+ runtimeName: removeExtension(firstSegment, extension)
206
+ });
207
+ }
208
+ }
209
+ const identities = /* @__PURE__ */ new Map();
210
+ for (const candidate of raw) identities.set(candidate.runtimeName, (identities.get(candidate.runtimeName) ?? 0) + 1);
211
+ return Object.freeze(raw.map((candidate) => Object.freeze({
212
+ agentPath: candidate.agentPath,
213
+ isDirectoryBacked: candidate.kind === "directory" && candidate.agentPath.endsWith("/agent.ts") && (identities.get(candidate.runtimeName) ?? 0) === 1,
214
+ isExtensionReserved: isExtensionReserved(candidate.runtimeName, namespaces),
215
+ runtimeName: candidate.runtimeName
216
+ })));
217
+ };
218
+ /** Creates the deterministic candidate index for one selected Eve agent root. */
219
+ var createEveAgentRootIndex = (root, sourceEntries) => {
220
+ const entries = [...sourceEntries].sort((left, right) => compareStrings(left.path, right.path));
221
+ const namespaces = indexExtensionNamespaces(root, entries);
222
+ const agentCandidates = entries.filter((entry) => {
223
+ const relative = getDirectRelativePath(root, entry.path);
224
+ return relative !== null && !relative.includes("/");
225
+ }).filter((entry) => {
226
+ const extension = getAuthoredExtension(entry.path);
227
+ return entry.type === "file" && extension !== null && posix.basename(entry.path, extension) === "agent";
228
+ });
229
+ const instructionEntries = entries.filter((entry) => {
230
+ const relative = getDirectRelativePath(root, entry.path);
231
+ return relative !== null && (relative === "instructions" || !relative.includes("/") && (/^instructions\.md$/iu.test(relative) || /^system\.md$/iu.test(relative) || getAuthoredExtension(relative) !== null && ["instructions", "system"].includes(removeExtension(relative, getAuthoredExtension(relative) ?? ""))));
232
+ });
233
+ return Object.freeze({
234
+ extensionNamespaces: namespaces,
235
+ instructionEntries: Object.freeze(instructionEntries),
236
+ isAgentSlotCollided: agentCandidates.length > 1,
237
+ skillCandidates: indexSkills(root, entries),
238
+ subagentCandidates: indexSubagents(root, entries, namespaces),
239
+ toolCandidates: indexTools(root, entries, namespaces)
240
+ });
241
+ };
242
+ //#endregion
243
+ //#region ../../packages/adapter-static-analysis/dist/index.js
244
+ /**
245
+ * Creates an operation-local inspection session with deterministic promise caches.
246
+ * @param options Provider callbacks and the optional operation signal.
247
+ * @returns Cached source, package, and entry inspection functions.
248
+ * @throws If the inspection is aborted.
249
+ */
250
+ var createInspectionSession = (options) => {
251
+ const sourceCache = /* @__PURE__ */ new Map();
252
+ const packageCache = /* @__PURE__ */ new Map();
253
+ const entryCache = /* @__PURE__ */ new Map();
254
+ const analyzeSource = (path) => {
255
+ options.signal?.throwIfAborted();
256
+ const existing = sourceCache.get(path);
257
+ if (existing !== void 0) return existing;
258
+ const analysis = (async () => {
259
+ options.signal?.throwIfAborted();
260
+ const bytes = await options.readFile(path, options.signal);
261
+ options.signal?.throwIfAborted();
262
+ const result = await options.analyzeSource(path, bytes, options.signal);
263
+ options.signal?.throwIfAborted();
264
+ return result;
265
+ })();
266
+ sourceCache.set(path, analysis);
267
+ return analysis;
268
+ };
269
+ const discoverPackage = (path) => {
270
+ options.signal?.throwIfAborted();
271
+ const existing = packageCache.get(path);
272
+ if (existing !== void 0) return existing;
273
+ const discovery = options.discoverPackage(path, options.signal);
274
+ packageCache.set(path, discovery);
275
+ return discovery;
276
+ };
277
+ const getEntry = (path) => {
278
+ options.signal?.throwIfAborted();
279
+ const existing = entryCache.get(path);
280
+ if (existing !== void 0) return existing;
281
+ const entry = options.getEntry(path, options.signal);
282
+ entryCache.set(path, entry);
283
+ return entry;
284
+ };
285
+ return Object.freeze({
286
+ analyzeSource,
287
+ discoverPackage,
288
+ getEntry,
289
+ ...options.signal === void 0 ? {} : { signal: options.signal }
290
+ });
291
+ };
292
+ var decoder = new TextDecoder("utf-8", {
293
+ fatal: true,
294
+ ignoreBOM: true
295
+ });
296
+ var findLineIndex = (lineStarts, offset) => {
297
+ let lower = 0;
298
+ let upper = lineStarts.length - 1;
299
+ while (lower < upper) {
300
+ const middle = Math.ceil((lower + upper) / 2);
301
+ if ((lineStarts[middle] ?? 0) <= offset) lower = middle;
302
+ else upper = middle - 1;
303
+ }
304
+ return lower;
305
+ };
306
+ /**
307
+ * Creates a TypeScript UTF-16-offset to Unicode-scalar source locator.
308
+ * @param value The normalized valid Unicode-scalar text.
309
+ * @returns The scalar-aware source locator.
310
+ */
311
+ var createSourceLocator = (value) => {
312
+ const scalarOffsets = new Uint32Array(value.length + 1);
313
+ const lineStarts = [0];
314
+ let scalarOffset = 0;
315
+ for (let codeUnitOffset = 0; codeUnitOffset < value.length;) {
316
+ const codePoint = value.codePointAt(codeUnitOffset);
317
+ const width = codePoint !== void 0 && codePoint > 65535 ? 2 : 1;
318
+ scalarOffsets[codeUnitOffset] = scalarOffset;
319
+ for (let interiorOffset = 1; interiorOffset < width; interiorOffset += 1) scalarOffsets[codeUnitOffset + interiorOffset] = scalarOffset;
320
+ codeUnitOffset += width;
321
+ scalarOffset += 1;
322
+ scalarOffsets[codeUnitOffset] = scalarOffset;
323
+ if (codePoint === 10) lineStarts.push(codeUnitOffset);
324
+ }
325
+ const locatePosition = (candidateOffset) => {
326
+ const codeUnitOffset = Math.max(0, Math.min(value.length, candidateOffset));
327
+ const lineIndex = findLineIndex(lineStarts, codeUnitOffset);
328
+ const lineStart = lineStarts[lineIndex] ?? 0;
329
+ const positionScalarOffset = scalarOffsets[codeUnitOffset] ?? 0;
330
+ return {
331
+ column: positionScalarOffset - (scalarOffsets[lineStart] ?? 0) + 1,
332
+ line: lineIndex + 1,
333
+ offset: positionScalarOffset
334
+ };
335
+ };
336
+ return Object.freeze({ locateRange: (startOffset, endOffset) => ({
337
+ end: locatePosition(endOffset),
338
+ start: locatePosition(startOffset)
339
+ }) });
340
+ };
341
+ /**
342
+ * Decodes and normalizes source bytes through the runtime-adapter text contract.
343
+ * @param bytes The exact reader-owned source bytes.
344
+ * @returns The normalized text and locator or an invalid-text result.
345
+ */
346
+ var normalizeText = (bytes) => {
347
+ let decoded;
348
+ try {
349
+ decoded = decoder.decode(bytes);
350
+ } catch {
351
+ return Object.freeze({ valid: false });
352
+ }
353
+ const value = (decoded.startsWith("") ? decoded.slice(1) : decoded).replace(/\r\n?/gu, "\n");
354
+ if (value.includes("\0")) return Object.freeze({ valid: false });
355
+ return Object.freeze({
356
+ locator: createSourceLocator(value),
357
+ valid: true,
358
+ value
359
+ });
360
+ };
361
+ var PACKAGE_DEPENDENCY_FIELDS = Object.freeze([
362
+ "dependencies",
363
+ "optionalDependencies",
364
+ "peerDependencies",
365
+ "devDependencies"
366
+ ]);
367
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
368
+ /**
369
+ * Creates nearest-to-root package-manifest candidates for one source path.
370
+ * @param sourcePath The normalized source path.
371
+ * @returns Deterministically ordered manifest paths.
372
+ */
373
+ var createPackageManifestCandidatePaths = (sourcePath) => {
374
+ const candidates = [];
375
+ let directory = posix.dirname(sourcePath);
376
+ while (true) {
377
+ candidates.push(posix.join(directory, "package.json"));
378
+ if (directory === "/") break;
379
+ directory = posix.dirname(directory);
380
+ }
381
+ return Object.freeze(candidates);
382
+ };
383
+ var extractPackageDeclarations = (manifest, packageName) => {
384
+ const declarations = [];
385
+ for (const field of PACKAGE_DEPENDENCY_FIELDS) {
386
+ const dependencies = manifest[field];
387
+ if (dependencies === void 0) continue;
388
+ if (!isRecord(dependencies)) return null;
389
+ const declaration = dependencies[packageName];
390
+ if (declaration === void 0) continue;
391
+ if (typeof declaration !== "string" || declaration.trim().length === 0) return null;
392
+ declarations.push(Object.freeze({
393
+ declaredRange: declaration,
394
+ dependencyKind: field
395
+ }));
396
+ }
397
+ return declarations;
398
+ };
399
+ var classifyPackageDeclarations = (declarations, supportedRange) => {
400
+ const classifications = declarations.map(({ declaredRange }) => {
401
+ const normalizedRange = validRange(declaredRange, {
402
+ loose: false,
403
+ includePrerelease: false
404
+ });
405
+ if (normalizedRange === null) return "ambiguous";
406
+ if (subset(normalizedRange, supportedRange, {
407
+ loose: false,
408
+ includePrerelease: false
409
+ })) return "supported";
410
+ if (!intersects(normalizedRange, supportedRange, {
411
+ loose: false,
412
+ includePrerelease: false
413
+ })) return "unsupported";
414
+ return "ambiguous";
415
+ });
416
+ if (classifications.every((classification) => classification === "supported")) return "supported";
417
+ if (classifications.every((classification) => classification === "unsupported")) return "unsupported";
418
+ return "ambiguous";
419
+ };
420
+ /**
421
+ * Discovers the nearest package declaration without repository enumeration.
422
+ * @param options The package target, repository callbacks, path, range, and signal.
423
+ * @returns The first observed declaration, invalid manifest, or absence result.
424
+ * @throws If repository reading or the active inspection is aborted.
425
+ */
426
+ var discoverPackage = async (options) => {
427
+ const { includeManifestPackageName, packageName, reader, signal, sourcePath, supportedRange } = options;
428
+ for (const manifestPath of createPackageManifestCandidatePaths(sourcePath)) {
429
+ signal?.throwIfAborted();
430
+ const entry = await reader.getEntry(manifestPath);
431
+ signal?.throwIfAborted();
432
+ if (entry === null) continue;
433
+ if (entry.type !== "file") return Object.freeze({
434
+ kind: "invalid",
435
+ path: manifestPath
436
+ });
437
+ const bytes = await reader.readFile(manifestPath);
438
+ signal?.throwIfAborted();
439
+ const text = normalizeText(bytes);
440
+ signal?.throwIfAborted();
441
+ if (!text.valid) return Object.freeze({
442
+ kind: "invalid",
443
+ path: manifestPath
444
+ });
445
+ let parsed;
446
+ try {
447
+ parsed = JSON.parse(text.value);
448
+ } catch {
449
+ return Object.freeze({
450
+ kind: "invalid",
451
+ path: manifestPath
452
+ });
453
+ }
454
+ signal?.throwIfAborted();
455
+ if (!isRecord(parsed)) return Object.freeze({
456
+ kind: "invalid",
457
+ path: manifestPath
458
+ });
459
+ const declarations = extractPackageDeclarations(parsed, packageName);
460
+ if (declarations === null) return Object.freeze({
461
+ kind: "invalid",
462
+ path: manifestPath
463
+ });
464
+ if (declarations.length === 0) return Object.freeze({ kind: "absent" });
465
+ return Object.freeze({
466
+ kind: "observed",
467
+ observation: Object.freeze({
468
+ compatibility: classifyPackageDeclarations(declarations, supportedRange),
469
+ declarations: Object.freeze(declarations),
470
+ ...includeManifestPackageName === true ? { manifestPackageName: typeof parsed["name"] === "string" ? parsed["name"] : null } : {},
471
+ path: manifestPath
472
+ })
473
+ });
474
+ }
475
+ return Object.freeze({ kind: "absent" });
476
+ };
477
+ /**
478
+ * Removes the transparent expression wrappers supported by runtime adapters.
479
+ * @param expression The expression to normalize.
480
+ * @returns The underlying expression used by static matching.
481
+ */
482
+ var unwrapExpression = (expression) => {
483
+ let current = expression;
484
+ while (ts.isAsExpression(current) || ts.isParenthesizedExpression(current) || ts.isSatisfiesExpression(current)) current = current.expression;
485
+ return current;
486
+ };
487
+ /**
488
+ * Reads an exact static string literal from one expression.
489
+ * @param expression The candidate string expression.
490
+ * @returns Its exact value or `null` when dynamic.
491
+ */
492
+ var getStaticString = (expression) => {
493
+ if (expression === null || expression === void 0) return null;
494
+ const candidate = unwrapExpression(expression);
495
+ return ts.isStringLiteral(candidate) || ts.isNoSubstitutionTemplateLiteral(candidate) ? candidate.text : null;
496
+ };
497
+ var hasModifier = (node, kind) => ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some((modifier) => modifier.kind === kind) ?? false);
498
+ var isConstDeclarationList = (declarationList) => (declarationList.flags & ts.NodeFlags.Const) !== 0;
499
+ /**
500
+ * Indexes static value imports and supported SDK constructor imports.
501
+ * @param sourceFile The parsed TypeScript source.
502
+ * @param config The provider package and constructor import forms.
503
+ * @returns Module-owned import bindings needed by static checks.
504
+ */
505
+ var indexImports = (sourceFile, config) => {
506
+ const constructorNames = /* @__PURE__ */ new Set();
507
+ const namedImports = /* @__PURE__ */ new Map();
508
+ const supportedNamedImports = new Set(config.namedConstructorImports);
509
+ for (const statement of sourceFile.statements) {
510
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
511
+ const importClause = statement.importClause;
512
+ if (importClause?.isTypeOnly === true) continue;
513
+ const moduleSpecifier = statement.moduleSpecifier.text;
514
+ if (moduleSpecifier === config.packageName && config.supportsDefaultConstructorImport && importClause?.name !== void 0) constructorNames.add(importClause.name.text);
515
+ if (moduleSpecifier === config.packageName && importClause?.namedBindings !== void 0 && ts.isNamedImports(importClause.namedBindings)) for (const element of importClause.namedBindings.elements) {
516
+ const importedName = element.propertyName?.text ?? element.name.text;
517
+ if (!element.isTypeOnly && supportedNamedImports.has(importedName)) constructorNames.add(element.name.text);
518
+ }
519
+ if (!moduleSpecifier.startsWith(".") || importClause?.namedBindings === void 0 || !ts.isNamedImports(importClause.namedBindings)) continue;
520
+ for (const element of importClause.namedBindings.elements) {
521
+ if (element.isTypeOnly) continue;
522
+ namedImports.set(element.name.text, Object.freeze({
523
+ importedName: element.propertyName?.text ?? element.name.text,
524
+ moduleSpecifier
525
+ }));
526
+ }
527
+ }
528
+ return {
529
+ constructorNames,
530
+ namedImports
531
+ };
532
+ };
533
+ /**
534
+ * Indexes direct exports, module-level SDK clients, and constant arrays.
535
+ * @param sourceFile The parsed TypeScript source.
536
+ * @param constructorNames The supported constructor bindings.
537
+ * @returns Static module declarations used by adapter inspection.
538
+ */
539
+ var indexModuleDeclarations = (sourceFile, constructorNames) => {
540
+ const clientNames = /* @__PURE__ */ new Set();
541
+ const exports = /* @__PURE__ */ new Map();
542
+ const moduleArrays = /* @__PURE__ */ new Map();
543
+ const moduleConstDeclarations = /* @__PURE__ */ new Map();
544
+ for (const statement of sourceFile.statements) {
545
+ if (ts.isFunctionDeclaration(statement) && statement.name !== void 0) {
546
+ if (hasModifier(statement, ts.SyntaxKind.ExportKeyword)) exports.set(statement.name.text, Object.freeze({
547
+ declaration: statement,
548
+ kind: statement.body === void 0 || hasModifier(statement, ts.SyntaxKind.DefaultKeyword) ? "present-unsupported" : "present-supported"
549
+ }));
550
+ continue;
551
+ }
552
+ if (ts.isExportDeclaration(statement) && statement.exportClause !== void 0) {
553
+ if (!ts.isNamedExports(statement.exportClause) || statement.isTypeOnly) continue;
554
+ for (const element of statement.exportClause.elements) if (!element.isTypeOnly) exports.set(element.name.text, Object.freeze({
555
+ declaration: element,
556
+ kind: "present-unsupported"
557
+ }));
558
+ continue;
559
+ }
560
+ if (!ts.isVariableStatement(statement)) {
561
+ if (hasModifier(statement, ts.SyntaxKind.ExportKeyword) && (ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement) || ts.isModuleDeclaration(statement)) && statement.name !== void 0 && ts.isIdentifier(statement.name)) exports.set(statement.name.text, Object.freeze({
562
+ declaration: statement,
563
+ kind: "present-unsupported"
564
+ }));
565
+ continue;
566
+ }
567
+ const isConst = isConstDeclarationList(statement.declarationList);
568
+ const isExported = hasModifier(statement, ts.SyntaxKind.ExportKeyword);
569
+ for (const declaration of statement.declarationList.declarations) {
570
+ if (!ts.isIdentifier(declaration.name)) continue;
571
+ if (isExported) exports.set(declaration.name.text, Object.freeze({
572
+ declaration,
573
+ kind: isConst && declaration.initializer !== void 0 ? "present-supported" : "present-unsupported"
574
+ }));
575
+ if (!isConst || declaration.initializer === void 0) continue;
576
+ moduleConstDeclarations.set(declaration.name.text, declaration);
577
+ const initializer = unwrapExpression(declaration.initializer);
578
+ if (ts.isNewExpression(initializer)) {
579
+ const constructor = unwrapExpression(initializer.expression);
580
+ if (ts.isIdentifier(constructor) && constructorNames.has(constructor.text)) clientNames.add(declaration.name.text);
581
+ }
582
+ if (ts.isArrayLiteralExpression(initializer)) moduleArrays.set(declaration.name.text, Object.freeze({
583
+ declaration,
584
+ expression: initializer
585
+ }));
586
+ }
587
+ }
588
+ return {
589
+ clientNames,
590
+ exports,
591
+ moduleArrays,
592
+ moduleConstDeclarations
593
+ };
594
+ };
595
+ var addBindingNames = (names, bindingName) => {
596
+ if (ts.isIdentifier(bindingName)) {
597
+ names.add(bindingName.text);
598
+ return;
599
+ }
600
+ for (const element of bindingName.elements) if (!ts.isOmittedExpression(element)) addBindingNames(names, element.name);
601
+ };
602
+ var addVariableDeclarationListBindings = (names, declarationList) => {
603
+ for (const declaration of declarationList.declarations) addBindingNames(names, declaration.name);
604
+ };
605
+ var addStatementBindings = (names, statement) => {
606
+ if (ts.isVariableStatement(statement)) {
607
+ addVariableDeclarationListBindings(names, statement.declarationList);
608
+ return;
609
+ }
610
+ if (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement) || ts.isModuleDeclaration(statement)) {
611
+ if (statement.name !== void 0 && ts.isIdentifier(statement.name)) names.add(statement.name.text);
612
+ }
613
+ };
614
+ var isFunctionScope = (node) => ts.isArrowFunction(node) || ts.isConstructorDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isGetAccessorDeclaration(node) || ts.isMethodDeclaration(node) || ts.isSetAccessorDeclaration(node);
615
+ var getLocalBindingNames = (bindings, scope) => {
616
+ const existingNames = bindings.get(scope);
617
+ if (existingNames !== void 0) return existingNames;
618
+ const names = /* @__PURE__ */ new Set();
619
+ bindings.set(scope, names);
620
+ return names;
621
+ };
622
+ /**
623
+ * Indexes local runtime bindings that can shadow module-owned identifiers.
624
+ * @param sourceFile The parsed TypeScript source.
625
+ * @returns Local binding names keyed by lexical or function scope.
626
+ */
627
+ var indexLocalBindingNames = (sourceFile) => {
628
+ const bindings = /* @__PURE__ */ new Map();
629
+ const visit = (node, functionScope) => {
630
+ let childFunctionScope = functionScope;
631
+ if (isFunctionScope(node)) {
632
+ const names = getLocalBindingNames(bindings, node);
633
+ for (const parameter of node.parameters) addBindingNames(names, parameter.name);
634
+ if (node.name !== void 0 && ts.isIdentifier(node.name)) names.add(node.name.text);
635
+ childFunctionScope = node;
636
+ }
637
+ if (ts.isBlock(node) || ts.isModuleBlock(node)) {
638
+ const names = getLocalBindingNames(bindings, node);
639
+ for (const statement of node.statements) addStatementBindings(names, statement);
640
+ } else if (ts.isCaseBlock(node)) {
641
+ const names = getLocalBindingNames(bindings, node);
642
+ for (const clause of node.clauses) for (const statement of clause.statements) addStatementBindings(names, statement);
643
+ } else if (ts.isCatchClause(node) && node.variableDeclaration !== void 0) addBindingNames(getLocalBindingNames(bindings, node), node.variableDeclaration.name);
644
+ else if ((ts.isForStatement(node) || ts.isForInStatement(node) || ts.isForOfStatement(node)) && node.initializer !== void 0 && ts.isVariableDeclarationList(node.initializer)) addVariableDeclarationListBindings(getLocalBindingNames(bindings, node), node.initializer);
645
+ else if (ts.isClassExpression(node) && node.name !== void 0) getLocalBindingNames(bindings, node).add(node.name.text);
646
+ if (childFunctionScope !== null && ts.isVariableDeclarationList(node) && (node.flags & ts.NodeFlags.BlockScoped) === 0) addVariableDeclarationListBindings(getLocalBindingNames(bindings, childFunctionScope), node);
647
+ ts.forEachChild(node, (child) => visit(child, childFunctionScope));
648
+ };
649
+ visit(sourceFile, null);
650
+ return bindings;
651
+ };
652
+ /**
653
+ * Indexes identifier occurrences once for binding-specific safety analysis.
654
+ * @param sourceFile The parsed TypeScript source.
655
+ * @returns Identifier occurrences grouped by exact source spelling.
656
+ */
657
+ var indexIdentifierUses = (sourceFile) => {
658
+ const identifierUses = /* @__PURE__ */ new Map();
659
+ const visit = (node) => {
660
+ if (ts.isIdentifier(node)) {
661
+ const uses = identifierUses.get(node.text) ?? [];
662
+ uses.push(node);
663
+ identifierUses.set(node.text, uses);
664
+ }
665
+ ts.forEachChild(node, visit);
666
+ };
667
+ visit(sourceFile);
668
+ return new Map([...identifierUses].map(([name, uses]) => [name, Object.freeze(uses)]));
669
+ };
670
+ /**
671
+ * Determines whether a module-bound name is visible at one identifier use.
672
+ * @param identifier The identifier whose lexical environment is inspected.
673
+ * @param analysis The indexed source containing the identifier.
674
+ * @returns Whether no parameter or local declaration shadows the module binding.
675
+ */
676
+ var isModuleBindingVisible = (identifier, analysis) => {
677
+ let current = identifier.parent;
678
+ while (current !== void 0 && !ts.isSourceFile(current)) {
679
+ if (analysis.localBindingNames.get(current)?.has(identifier.text) === true) return false;
680
+ current = current.parent;
681
+ }
682
+ return true;
683
+ };
684
+ /**
685
+ * Resolves TypeScript source candidates for a supported relative ESM specifier.
686
+ * @param containingPath The importing source path.
687
+ * @param moduleSpecifier The exact relative ESM specifier.
688
+ * @returns Supported logical source candidates in deterministic order.
689
+ */
690
+ var resolveImportCandidatePaths = (containingPath, moduleSpecifier) => {
691
+ const resolved = posix.resolve(posix.dirname(containingPath), moduleSpecifier);
692
+ if (resolved.endsWith(".js")) return [`${resolved.slice(0, -3)}.ts`, `${resolved.slice(0, -3)}.tsx`];
693
+ if (resolved.endsWith(".mjs")) return [`${resolved.slice(0, -4)}.mts`];
694
+ return [
695
+ ".ts",
696
+ ".tsx",
697
+ ".mts"
698
+ ].some((extension) => resolved.endsWith(extension)) ? [resolved] : [];
699
+ };
700
+ var getScriptKind = (path) => path.endsWith(".tsx") ? ts.ScriptKind.TSX : ts.ScriptKind.TS;
701
+ var createSyntaxProgram = (sourceFile, text) => {
702
+ return ts.createProgram({
703
+ host: {
704
+ fileExists: (fileName) => fileName === sourceFile.fileName,
705
+ getCanonicalFileName: (fileName) => fileName,
706
+ getCurrentDirectory: () => "/",
707
+ getDefaultLibFileName: () => "/lib.d.ts",
708
+ getDirectories: () => [],
709
+ getNewLine: () => "\n",
710
+ getSourceFile: (fileName) => fileName === sourceFile.fileName ? sourceFile : void 0,
711
+ readFile: (fileName) => fileName === sourceFile.fileName ? text : void 0,
712
+ useCaseSensitiveFileNames: () => true,
713
+ writeFile: () => void 0
714
+ },
715
+ options: {
716
+ jsx: ts.JsxEmit.Preserve,
717
+ module: ts.ModuleKind.ESNext,
718
+ noLib: true,
719
+ noResolve: true,
720
+ target: ts.ScriptTarget.ES2023
721
+ },
722
+ rootNames: [sourceFile.fileName]
723
+ });
724
+ };
725
+ /**
726
+ * Parses and indexes one TypeScript module without provider request assumptions.
727
+ * @param path The normalized logical source path.
728
+ * @param bytes The exact source bytes returned by the adapter reader.
729
+ * @param importConfig The provider constructor-import contract.
730
+ * @param signal The active inspection signal.
731
+ * @returns A source analysis or stable invalid-text or invalid-syntax result.
732
+ * @throws If source analysis is aborted.
733
+ */
734
+ var analyzeTypeScriptModule = (path, bytes, importConfig, signal) => {
735
+ signal?.throwIfAborted();
736
+ const text = normalizeText(bytes);
737
+ if (!text.valid) return Object.freeze({ kind: "invalid-text" });
738
+ signal?.throwIfAborted();
739
+ const sourceFile = ts.createSourceFile(path, text.value, ts.ScriptTarget.ES2023, true, getScriptKind(path));
740
+ const syntaxDiagnostic = createSyntaxProgram(sourceFile, text.value).getSyntacticDiagnostics(sourceFile).filter(({ category }) => category === ts.DiagnosticCategory.Error).sort((left, right) => (left.start ?? 0) - (right.start ?? 0))[0];
741
+ signal?.throwIfAborted();
742
+ if (syntaxDiagnostic !== void 0) {
743
+ const start = syntaxDiagnostic.start;
744
+ return Object.freeze({
745
+ kind: "invalid-syntax",
746
+ range: start === void 0 ? null : text.locator.locateRange(start, start + (syntaxDiagnostic.length ?? 0))
747
+ });
748
+ }
749
+ const { constructorNames, namedImports } = indexImports(sourceFile, importConfig);
750
+ signal?.throwIfAborted();
751
+ const { clientNames, exports, moduleArrays, moduleConstDeclarations } = indexModuleDeclarations(sourceFile, constructorNames);
752
+ signal?.throwIfAborted();
753
+ const identifierUses = indexIdentifierUses(sourceFile);
754
+ signal?.throwIfAborted();
755
+ const localBindingNames = indexLocalBindingNames(sourceFile);
756
+ signal?.throwIfAborted();
757
+ const analysis = Object.freeze({
758
+ clientNames,
759
+ constructorNames,
760
+ exports,
761
+ identifierUses,
762
+ localBindingNames,
763
+ moduleArrays,
764
+ moduleConstDeclarations,
765
+ namedImports,
766
+ path,
767
+ safeModuleArrayNames: /* @__PURE__ */ new Set(),
768
+ sourceFile,
769
+ text
770
+ });
771
+ signal?.throwIfAborted();
772
+ return Object.freeze({
773
+ analysis,
774
+ kind: "valid"
775
+ });
776
+ };
777
+ /**
778
+ * Classifies a directly exported constant and returns its static initializer.
779
+ * @param analysis The indexed source.
780
+ * @param symbol The exact bound symbol.
781
+ * @returns The symbol state and initializer when supported.
782
+ */
783
+ var getConstExport = (analysis, symbol) => {
784
+ const exported = analysis.exports.get(symbol);
785
+ if (exported === void 0) return Object.freeze({ kind: "absent" });
786
+ if (exported.kind === "present-supported" && ts.isVariableDeclaration(exported.declaration) && exported.declaration.initializer !== void 0) return Object.freeze({
787
+ declaration: exported.declaration,
788
+ expression: unwrapExpression(exported.declaration.initializer),
789
+ kind: "present-supported"
790
+ });
791
+ return Object.freeze({
792
+ declaration: exported.declaration,
793
+ kind: "present-unsupported"
794
+ });
795
+ };
796
+ var resolveCandidatePath = async (options, containingPath, moduleSpecifier) => {
797
+ const matchingPaths = [];
798
+ for (const candidate of resolveImportCandidatePaths(containingPath, moduleSpecifier)) {
799
+ const path = options.parsePath(candidate);
800
+ if ((await options.getEntry(path))?.type === "file") matchingPaths.push(path);
801
+ }
802
+ return matchingPaths.length === 1 ? matchingPaths[0] : null;
803
+ };
804
+ var resolveStaticStringExpression = async (options, analysis, expression, visited) => {
805
+ options.signal?.throwIfAborted();
806
+ const candidate = unwrapExpression(expression);
807
+ const literal = getStaticString(candidate);
808
+ if (literal !== null) return Object.freeze({
809
+ expression: candidate,
810
+ kind: "supported",
811
+ value: literal
812
+ });
813
+ if (!ts.isIdentifier(candidate) || !isModuleBindingVisible(candidate, analysis)) return Object.freeze({ kind: "unsupported" });
814
+ const localDeclaration = analysis.moduleConstDeclarations.get(candidate.text);
815
+ if (localDeclaration?.initializer !== void 0) {
816
+ const key = `${analysis.path}\0local\0${candidate.text}`;
817
+ if (visited.has(key)) return Object.freeze({ kind: "unsupported" });
818
+ visited.add(key);
819
+ const result = await resolveStaticStringExpression(options, analysis, localDeclaration.initializer, visited);
820
+ visited.delete(key);
821
+ return result;
822
+ }
823
+ const namedImport = analysis.namedImports.get(candidate.text);
824
+ if (namedImport === void 0) return Object.freeze({ kind: "unsupported" });
825
+ const importedPath = await resolveCandidatePath(options, analysis.path, namedImport.moduleSpecifier);
826
+ if (importedPath === null) return Object.freeze({ kind: "unsupported" });
827
+ const key = `${importedPath}\0export\0${namedImport.importedName}`;
828
+ if (visited.has(key)) return Object.freeze({ kind: "unsupported" });
829
+ visited.add(key);
830
+ const importedResult = await options.analyzeSource(importedPath);
831
+ if (importedResult.kind !== "valid") {
832
+ visited.delete(key);
833
+ return Object.freeze({ kind: "unsupported" });
834
+ }
835
+ const exported = getConstExport(importedResult.analysis, namedImport.importedName);
836
+ if (exported.kind !== "present-supported" || exported.expression === void 0) {
837
+ visited.delete(key);
838
+ return Object.freeze({ kind: "unsupported" });
839
+ }
840
+ const result = await resolveStaticStringExpression(options, importedResult.analysis, exported.expression, visited);
841
+ visited.delete(key);
842
+ return result;
843
+ };
844
+ /**
845
+ * Resolves one exact supported static string without normalization or execution.
846
+ * @param options The source, expression, repository callbacks, and parser for the relationship.
847
+ * @returns The exact compiler-parsed string or an unsupported state.
848
+ */
849
+ var resolveStaticString = (options) => resolveStaticStringExpression(options, options.analysis, options.expression, /* @__PURE__ */ new Set());
850
+ //#endregion
851
+ //#region src/source-analysis/helper-imports.ts
852
+ var HELPER_IMPORTS = Object.freeze({
853
+ eve: Object.freeze({ defineAgent: "defineAgent" }),
854
+ "eve/instructions": Object.freeze({ defineInstructions: "defineInstructions" }),
855
+ "eve/skills": Object.freeze({ defineSkill: "defineSkill" }),
856
+ "eve/tools": Object.freeze({ defineTool: "defineTool" })
857
+ });
858
+ /** Indexes exact Eve helper runtime imports by lexical local binding. */
859
+ var indexEveHelperImports = (sourceFile) => {
860
+ const defineAgent = /* @__PURE__ */ new Set();
861
+ const defineInstructions = /* @__PURE__ */ new Set();
862
+ const defineSkill = /* @__PURE__ */ new Set();
863
+ const defineTool = /* @__PURE__ */ new Set();
864
+ const sets = {
865
+ defineAgent,
866
+ defineInstructions,
867
+ defineSkill,
868
+ defineTool
869
+ };
870
+ for (const statement of sourceFile.statements) {
871
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) continue;
872
+ const importClause = statement.importClause;
873
+ const expected = HELPER_IMPORTS[statement.moduleSpecifier.text];
874
+ if (expected === void 0 || importClause?.isTypeOnly === true || importClause?.namedBindings === void 0 || !ts.isNamedImports(importClause.namedBindings)) continue;
875
+ for (const element of importClause.namedBindings.elements) {
876
+ const importedName = element.propertyName?.text ?? element.name.text;
877
+ if (!element.isTypeOnly && importedName in expected) sets[importedName].add(element.name.text);
878
+ }
879
+ }
880
+ return Object.freeze({
881
+ defineAgent,
882
+ defineInstructions,
883
+ defineSkill,
884
+ defineTool
885
+ });
886
+ };
887
+ //#endregion
888
+ //#region src/source-analysis/source-analysis.ts
889
+ var indexRuntimeSymbols = (sourceFile) => {
890
+ const symbols = /* @__PURE__ */ new Map();
891
+ for (const statement of sourceFile.statements) {
892
+ if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement) || ts.isEnumDeclaration(statement)) && statement.name !== void 0) {
893
+ symbols.set(statement.name.text, statement);
894
+ continue;
895
+ }
896
+ if (!ts.isVariableStatement(statement)) continue;
897
+ for (const declaration of statement.declarationList.declarations) if (ts.isIdentifier(declaration.name)) symbols.set(declaration.name.text, declaration);
898
+ }
899
+ return symbols;
900
+ };
901
+ /** Parses one supported Eve TypeScript module without executing or resolving it. */
902
+ var analyzeEveSource = (path, bytes, signal) => {
903
+ const result = analyzeTypeScriptModule(path, bytes, {
904
+ namedConstructorImports: [],
905
+ packageName: "eve",
906
+ supportsDefaultConstructorImport: false
907
+ }, signal);
908
+ if (result.kind !== "valid") return result;
909
+ const analysis = Object.freeze({
910
+ ...result.analysis,
911
+ defaultExports: Object.freeze(result.analysis.sourceFile.statements.filter((statement) => ts.isExportAssignment(statement) && !statement.isExportEquals)),
912
+ helperImports: indexEveHelperImports(result.analysis.sourceFile),
913
+ path,
914
+ runtimeSymbols: indexRuntimeSymbols(result.analysis.sourceFile)
915
+ });
916
+ return Object.freeze({
917
+ analysis,
918
+ kind: "valid"
919
+ });
920
+ };
921
+ //#endregion
922
+ //#region src/source-analysis/object-definitions.ts
923
+ var DEFINITION_HELPER_KEYS = Object.freeze({
924
+ agent: "defineAgent",
925
+ instructions: "defineInstructions",
926
+ skill: "defineSkill",
927
+ tool: "defineTool"
928
+ });
929
+ /** Returns the exact static name of an ordinary Eve object member. */
930
+ var getEveObjectMemberName = (member) => {
931
+ if (!ts.isPropertyAssignment(member) && !ts.isMethodDeclaration(member) && !ts.isGetAccessorDeclaration(member) && !ts.isSetAccessorDeclaration(member) && !ts.isShorthandPropertyAssignment(member)) return null;
932
+ return ts.isIdentifier(member.name) || ts.isStringLiteral(member.name) ? member.name.text : null;
933
+ };
934
+ /** Indexes unique ordinary members without accepting spreads or prototype setters. */
935
+ var getEveObjectMembers = (object) => {
936
+ const members = /* @__PURE__ */ new Map();
937
+ for (const member of object.properties) {
938
+ const name = getEveObjectMemberName(member);
939
+ if (name === null || name === "__proto__" || members.has(name) || ts.isShorthandPropertyAssignment(member) || ts.isGetAccessorDeclaration(member) || ts.isSetAccessorDeclaration(member)) return null;
940
+ members.set(name, member);
941
+ }
942
+ return members;
943
+ };
944
+ /** Returns an ordinary property-assignment expression from a closed definition. */
945
+ var getEvePropertyExpression = (properties, name) => {
946
+ const property = properties.get(name);
947
+ return property !== void 0 && ts.isPropertyAssignment(property) ? unwrapExpression(property.initializer) : null;
948
+ };
949
+ /** Classifies one exact direct default-exported Eve helper definition. */
950
+ var getEveDefinition = (analysis, kind) => {
951
+ if (analysis.defaultExports.length === 0) return Object.freeze({
952
+ hasDefaultExport: false,
953
+ kind: "absent"
954
+ });
955
+ if (analysis.defaultExports.length !== 1) return Object.freeze({
956
+ hasDefaultExport: true,
957
+ kind: "present-unsupported"
958
+ });
959
+ const declaration = analysis.defaultExports[0];
960
+ if (declaration === void 0) return Object.freeze({
961
+ hasDefaultExport: false,
962
+ kind: "absent"
963
+ });
964
+ const expression = unwrapExpression(declaration.expression);
965
+ if (!ts.isCallExpression(expression) || expression.arguments.length !== 1) return Object.freeze({
966
+ hasDefaultExport: true,
967
+ kind: "present-unsupported"
968
+ });
969
+ const callee = unwrapExpression(expression.expression);
970
+ const helperKey = DEFINITION_HELPER_KEYS[kind];
971
+ if (!ts.isIdentifier(callee) || !analysis.helperImports[helperKey].has(callee.text)) return Object.freeze({
972
+ hasDefaultExport: true,
973
+ kind: "present-unsupported"
974
+ });
975
+ const argument = expression.arguments[0];
976
+ if (argument === void 0) return Object.freeze({
977
+ hasDefaultExport: true,
978
+ kind: "present-unsupported"
979
+ });
980
+ const object = unwrapExpression(argument);
981
+ if (!ts.isObjectLiteralExpression(object)) return Object.freeze({
982
+ hasDefaultExport: true,
983
+ kind: "present-unsupported"
984
+ });
985
+ const properties = getEveObjectMembers(object);
986
+ return properties === null ? Object.freeze({
987
+ hasDefaultExport: true,
988
+ kind: "present-unsupported"
989
+ }) : Object.freeze({
990
+ call: expression,
991
+ declaration,
992
+ kind: "present-supported",
993
+ object,
994
+ properties
995
+ });
996
+ };
997
+ //#endregion
998
+ //#region src/source-analysis/functions.ts
999
+ /** Determines whether a declaration is one supported runtime function value. */
1000
+ var isEveFunctionDeclaration = (declaration) => {
1001
+ if (declaration === void 0) return false;
1002
+ if (ts.isFunctionDeclaration(declaration)) return declaration.body !== void 0;
1003
+ if (!ts.isVariableDeclaration(declaration) || declaration.initializer === void 0) return false;
1004
+ const initializer = unwrapExpression(declaration.initializer);
1005
+ return ts.isArrowFunction(initializer) || ts.isFunctionExpression(initializer);
1006
+ };
1007
+ /** Classifies an inline or module-local direct runtime function expression. */
1008
+ var isEveFunctionValue = (analysis, expression) => {
1009
+ const candidate = unwrapExpression(expression);
1010
+ return ts.isArrowFunction(candidate) || ts.isFunctionExpression(candidate) || ts.isIdentifier(candidate) && isEveFunctionDeclaration(analysis.runtimeSymbols.get(candidate.text));
1011
+ };
1012
+ /** Resolves an inline, module-local, or exact relative-imported runtime function. */
1013
+ var isEveResolvedFunctionValue = async (session, analysis, expression) => {
1014
+ if (isEveFunctionValue(analysis, expression)) return true;
1015
+ const candidate = unwrapExpression(expression);
1016
+ if (!ts.isIdentifier(candidate)) return false;
1017
+ const imported = analysis.namedImports.get(candidate.text);
1018
+ if (imported === void 0 || !imported.moduleSpecifier.startsWith(".")) return false;
1019
+ const resolved = posix.resolve(posix.dirname(analysis.path), imported.moduleSpecifier);
1020
+ const path = parseRepositoryPath(resolved.endsWith(".js") ? `${resolved.slice(0, -3)}.ts` : resolved);
1021
+ if ((await session.getEntry(path))?.type !== "file" || !path.endsWith(".ts")) return false;
1022
+ const result = await session.analyzeSource(path);
1023
+ const exported = result.kind === "valid" ? result.analysis.exports.get(imported.importedName) : void 0;
1024
+ return result.kind === "valid" && exported?.kind === "present-supported" && isEveFunctionDeclaration(result.analysis.runtimeSymbols.get(imported.importedName));
1025
+ };
1026
+ //#endregion
1027
+ //#region src/source-analysis/static-values.ts
1028
+ /** Resolves one exact Eve static string through supported local and relative bindings. */
1029
+ var resolveEveStaticString = (session, analysis, expression) => resolveStaticString({
1030
+ analysis,
1031
+ analyzeSource: (path) => session.analyzeSource(parseRepositoryPath(path)),
1032
+ expression: unwrapExpression(expression),
1033
+ getEntry: (path) => session.getEntry(parseRepositoryPath(path)),
1034
+ parsePath: (path) => parseRepositoryPath(path),
1035
+ ...session.signal === void 0 ? {} : { signal: session.signal }
1036
+ });
1037
+ /** Resolves a closed object whose keys and values are exact static strings. */
1038
+ var isEveStaticStringRecord = async (session, analysis, expression) => {
1039
+ const candidate = unwrapExpression(expression);
1040
+ if (!ts.isObjectLiteralExpression(candidate)) return false;
1041
+ const names = /* @__PURE__ */ new Set();
1042
+ for (const property of candidate.properties) {
1043
+ if (!ts.isPropertyAssignment(property) || !ts.isIdentifier(property.name) && !ts.isStringLiteral(property.name) || property.name.text === "__proto__" || names.has(property.name.text)) return false;
1044
+ names.add(property.name.text);
1045
+ if ((await resolveEveStaticString(session, analysis, property.initializer)).kind !== "supported") return false;
1046
+ }
1047
+ return true;
1048
+ };
1049
+ //#endregion
1050
+ //#region src/diagnostics/index.ts
1051
+ var EVE_ADAPTER_DIAGNOSTICS = Object.freeze({
1052
+ EVE_PACKAGE_MANIFEST_INVALID: "The owning package manifest is invalid for Eve dependency detection.",
1053
+ EVE_SDK_VERSION_UNSUPPORTED: "The observed Eve dependency range is disjoint from the supported range.",
1054
+ EVE_SOURCE_TEXT_INVALID: "The referenced Eve source file is not valid normalized text.",
1055
+ EVE_SOURCE_SYNTAX_INVALID: "The referenced Eve source file contains invalid TypeScript syntax.",
1056
+ EVE_RUNTIME_AGENT_SYMBOL_NOT_FOUND: "The declared Eve runtime-agent symbol was not found.",
1057
+ EVE_INSTRUCTION_LOADER_SYMBOL_NOT_FOUND: "The declared Eve instruction-loader symbol was not found.",
1058
+ EVE_AGENT_OUTPUT_SCHEMA_SYMBOL_NOT_FOUND: "The declared Eve agent output-schema symbol was not found.",
1059
+ EVE_TOOL_IMPLEMENTATION_SYMBOL_NOT_FOUND: "The declared Eve tool implementation symbol was not found.",
1060
+ EVE_TOOL_REGISTRATION_SYMBOL_NOT_FOUND: "The declared Eve tool registration symbol was not found.",
1061
+ EVE_TOOL_INPUT_SCHEMA_SYMBOL_NOT_FOUND: "The declared Eve tool input-schema symbol was not found.",
1062
+ EVE_TOOL_OUTPUT_SCHEMA_SYMBOL_NOT_FOUND: "The declared Eve tool output-schema symbol was not found.",
1063
+ EVE_SKILL_IMPLEMENTATION_SYMBOL_NOT_FOUND: "The declared Eve skill implementation symbol was not found.",
1064
+ EVE_SKILL_REGISTRATION_SYMBOL_NOT_FOUND: "The declared Eve skill registration symbol was not found.",
1065
+ EVE_INSTRUCTION_ROOT_CONFLICT: "The Eve instruction slot contains conflicting authored sources.",
1066
+ EVE_INSTRUCTION_LOADER_NOT_WIRED: "The declared instruction loader is not wired to the supported Eve instruction surface.",
1067
+ EVE_AGENT_OUTPUT_SCHEMA_NOT_WIRED: "The declared agent output schema is not wired to the Eve agent definition.",
1068
+ EVE_TOOL_IMPLEMENTATION_NOT_WIRED: "The declared tool implementation is not wired to the Eve tool definition.",
1069
+ EVE_TOOL_REGISTRATION_NOT_WIRED: "The declared tool registration is not wired to the owning Eve agent.",
1070
+ EVE_TOOL_NAME_INVALID: "The Eve filesystem tool name is invalid.",
1071
+ EVE_TOOL_NAME_RESERVED: "The Eve filesystem tool name is reserved by the runtime.",
1072
+ EVE_TOOL_RUNTIME_NAME_COLLISION: "Multiple Eve tool sources resolve to the same runtime tool name.",
1073
+ EVE_TOOL_NAME_MISMATCH: "The declared tool name does not match the Eve path-derived runtime name.",
1074
+ EVE_TOOL_INPUT_SCHEMA_NOT_WIRED: "The declared tool input schema is not wired to the Eve tool definition.",
1075
+ EVE_TOOL_OUTPUT_SCHEMA_NOT_WIRED: "The declared tool output schema is not wired to the Eve tool definition.",
1076
+ EVE_SKILL_IMPLEMENTATION_NOT_WIRED: "The declared skill implementation is not the discovered Eve skill artifact.",
1077
+ EVE_SKILL_REGISTRATION_NOT_WIRED: "The declared skill registration is not wired to the owning Eve agent.",
1078
+ EVE_SKILL_NAME_MISMATCH: "The declared skill name does not match the Eve path-derived runtime name.",
1079
+ EVE_TOOL_SUBAGENT_NAME_COLLISION: "The Eve tool and local subagent use the same runtime tool name.",
1080
+ EVE_SUBAGENT_PARENT_AMBIGUOUS: "Multiple registered Eve agents map to the local subagent's immediate parent root.",
1081
+ EVE_ROUTING_DESCRIPTION_MISSING: "The supported Eve local subagent definition is missing its routing description.",
1082
+ EVE_ROUTING_DESCRIPTION_NOT_WIRED: "The Eve local subagent description does not use the target effective routing description."
1083
+ });
1084
+ /** Creates one frozen, safely namespaced Eve adapter diagnostic. */
1085
+ var createEveDiagnostic = (input) => Object.freeze({
1086
+ ...input,
1087
+ details: Object.freeze({ ...input.details }),
1088
+ entity: input.entity === null ? null : Object.freeze({ ...input.entity }),
1089
+ message: EVE_ADAPTER_DIAGNOSTICS[input.code],
1090
+ source: "eve"
1091
+ });
1092
+ //#endregion
1093
+ //#region src/inspection/common.ts
1094
+ /** Compares exact strings without locale-sensitive behavior. */
1095
+ var compareEveStrings = (left, right) => left < right ? -1 : left > right ? 1 : 0;
1096
+ var freezeReference = (reference) => Object.freeze({
1097
+ path: reference.path,
1098
+ ...reference.symbol === void 0 ? {} : { symbol: reference.symbol }
1099
+ });
1100
+ /** Creates one deeply immutable Eve evidence record. */
1101
+ var createEveEvidence = (evidence) => Object.freeze({
1102
+ ...evidence,
1103
+ details: Object.freeze({ ...evidence.details }),
1104
+ references: Object.freeze(evidence.references.map(freezeReference))
1105
+ });
1106
+ var createEntity = (agentId, capabilityKind, capabilityId) => Object.freeze({
1107
+ adapterId: "eve",
1108
+ agentId,
1109
+ ...capabilityKind === void 0 || capabilityId === void 0 ? {} : {
1110
+ capabilityId,
1111
+ capabilityKind
1112
+ }
1113
+ });
1114
+ /** Appends one stable package-owned Eve diagnostic. */
1115
+ var addEveDiagnostic = (diagnostics, code, path, agentId, range = null, capabilityKind, capabilityId, details = {}) => {
1116
+ diagnostics.push(createEveDiagnostic({
1117
+ code,
1118
+ details,
1119
+ entity: createEntity(agentId, capabilityKind, capabilityId),
1120
+ path,
1121
+ pointer: null,
1122
+ range
1123
+ }));
1124
+ };
1125
+ /** Adds the sole permitted diagnostic for invalid referenced TypeScript source. */
1126
+ var addEveSourceFailureDiagnostic = (diagnostics, result, path, agentId, capabilityKind, capabilityId) => {
1127
+ const hasMatchingDiagnostic = (code) => diagnostics.some((diagnostic) => diagnostic.code === code && diagnostic.path === path && diagnostic.entity?.agentId === agentId && diagnostic.entity.capabilityKind === capabilityKind && diagnostic.entity.capabilityId === capabilityId);
1128
+ if (result.kind === "invalid-text") {
1129
+ if (!hasMatchingDiagnostic("EVE_SOURCE_TEXT_INVALID")) addEveDiagnostic(diagnostics, "EVE_SOURCE_TEXT_INVALID", path, agentId, null, capabilityKind, capabilityId);
1130
+ return true;
1131
+ }
1132
+ if (result.kind === "invalid-syntax") {
1133
+ if (!hasMatchingDiagnostic("EVE_SOURCE_SYNTAX_INVALID")) addEveDiagnostic(diagnostics, "EVE_SOURCE_SYNTAX_INVALID", path, agentId, result.range, capabilityKind, capabilityId);
1134
+ return true;
1135
+ }
1136
+ return false;
1137
+ };
1138
+ /** Returns the Core scalar range for one Eve source node. */
1139
+ var locateEveNode = (analysis, node) => analysis.text.locator.locateRange(node.getStart(analysis.sourceFile), node.getEnd());
1140
+ //#endregion
1141
+ //#region src/inspection/package-inspection.ts
1142
+ /** Inspects one scoped agent's nearest Eve package declaration. */
1143
+ var inspectEvePackage = async (session, agent, sourcePath, evidence, diagnostics) => {
1144
+ const result = await session.discoverPackage(sourcePath);
1145
+ if (result.kind === "absent") return null;
1146
+ if (result.kind === "invalid") {
1147
+ addEveDiagnostic(diagnostics, "EVE_PACKAGE_MANIFEST_INVALID", result.path, agent.id);
1148
+ return null;
1149
+ }
1150
+ const { observation } = result;
1151
+ if (observation.compatibility === "unsupported") {
1152
+ addEveDiagnostic(diagnostics, "EVE_SDK_VERSION_UNSUPPORTED", observation.path, agent.id);
1153
+ return null;
1154
+ }
1155
+ for (const declaration of observation.declarations) {
1156
+ const isSemver = validRange(declaration.declaredRange, {
1157
+ includePrerelease: false,
1158
+ loose: false
1159
+ }) !== null;
1160
+ evidence.push(createEveEvidence({
1161
+ agentId: agent.id,
1162
+ capabilityId: null,
1163
+ capabilityKind: null,
1164
+ details: {
1165
+ dependencyKind: declaration.dependencyKind,
1166
+ ...isSemver ? { declaredRange: declaration.declaredRange } : {},
1167
+ packageClassification: observation.compatibility,
1168
+ targetId: EVE_TARGET_ID
1169
+ },
1170
+ kind: "runtime-package",
1171
+ references: [{ path: observation.path }],
1172
+ runtimeName: null,
1173
+ source: "eve"
1174
+ }));
1175
+ }
1176
+ return observation;
1177
+ };
1178
+ //#endregion
1179
+ //#region src/inspection/relationships.ts
1180
+ var resolveRelativeImportPath = (containingPath, moduleSpecifier) => {
1181
+ if (!moduleSpecifier.startsWith(".")) return null;
1182
+ const resolved = posix.resolve(posix.dirname(containingPath), moduleSpecifier);
1183
+ if (resolved.endsWith(".js")) return parseRepositoryPath(`${resolved.slice(0, -3)}.ts`);
1184
+ return resolved.endsWith(".ts") ? parseRepositoryPath(resolved) : null;
1185
+ };
1186
+ var isSupportedRuntimeSymbol = (analysis, symbol, requiresFunction) => {
1187
+ const declaration = analysis.runtimeSymbols.get(symbol);
1188
+ if (declaration === void 0) return false;
1189
+ return !requiresFunction || isEveFunctionDeclaration(declaration);
1190
+ };
1191
+ /** Classifies whether one direct expression uses the exact manifest-bound runtime value. */
1192
+ var classifyEveBoundExpression = async (session, analysis, expression, reference, requiresFunction = false) => {
1193
+ if (reference.symbol === void 0 || reference.symbol === "default") return "unresolved";
1194
+ const boundResult = await session.analyzeSource(reference.path);
1195
+ if (boundResult.kind !== "valid") return "unresolved";
1196
+ if (analysis.path === reference.path) {
1197
+ if (!boundResult.analysis.runtimeSymbols.has(reference.symbol)) return boundResult.analysis.exports.has(reference.symbol) ? "unresolved" : "missing";
1198
+ if (!isSupportedRuntimeSymbol(boundResult.analysis, reference.symbol, requiresFunction)) return "unresolved";
1199
+ } else {
1200
+ const exported = boundResult.analysis.exports.get(reference.symbol);
1201
+ if (exported === void 0) return "missing";
1202
+ if (exported.kind !== "present-supported" || !isSupportedRuntimeSymbol(boundResult.analysis, reference.symbol, requiresFunction)) return "unresolved";
1203
+ }
1204
+ if (expression === null) return "different";
1205
+ const candidate = unwrapExpression(expression);
1206
+ if (!ts.isIdentifier(candidate)) return "unresolved";
1207
+ if (analysis.path === reference.path && candidate.text === reference.symbol && isSupportedRuntimeSymbol(analysis, candidate.text, requiresFunction)) return "wired";
1208
+ const imported = analysis.namedImports.get(candidate.text);
1209
+ if (imported === void 0) return analysis.runtimeSymbols.has(candidate.text) ? "different" : "unresolved";
1210
+ return resolveRelativeImportPath(analysis.path, imported.moduleSpecifier) === reference.path && imported.importedName === reference.symbol ? "wired" : "different";
1211
+ };
1212
+ /** Classifies one direct call to an exact manifest-bound function. */
1213
+ var classifyEveBoundCall = async (session, analysis, expression, reference) => {
1214
+ if (expression === null) return classifyEveBoundExpression(session, analysis, null, reference, true);
1215
+ const candidate = unwrapExpression(expression);
1216
+ return ts.isCallExpression(candidate) ? classifyEveBoundExpression(session, analysis, candidate.expression, reference, true) : "unresolved";
1217
+ };
1218
+ //#endregion
1219
+ //#region src/inspection/agent-inspection.ts
1220
+ var POSITIVE_AGENT_KEYS = /* @__PURE__ */ new Set([
1221
+ "description",
1222
+ "model",
1223
+ "outputSchema"
1224
+ ]);
1225
+ /** Inspects one exact manifest-bound Eve agent definition and its output schema. */
1226
+ var inspectEveAgent = async (session, agent, evidence, diagnostics) => {
1227
+ const runtimeAgent = agent.declaration.bindings?.runtimeAgent;
1228
+ if (runtimeAgent === void 0 || !runtimeAgent.path.endsWith("/agent.ts")) return null;
1229
+ const packageObservation = await inspectEvePackage(session, agent, runtimeAgent.path, evidence, diagnostics);
1230
+ if (packageObservation === null) return null;
1231
+ const root = resolveEveAgentRoot(runtimeAgent.path, packageObservation);
1232
+ if (root === null) return null;
1233
+ const rootIndex = await session.indexAgentRoot(root.agentRoot);
1234
+ if (rootIndex.isAgentSlotCollided) return null;
1235
+ const result = await session.analyzeSource(runtimeAgent.path);
1236
+ if (addEveSourceFailureDiagnostic(diagnostics, result, runtimeAgent.path, agent.id)) return null;
1237
+ if (result.kind !== "valid") return null;
1238
+ evidence.push(createEveEvidence({
1239
+ agentId: agent.id,
1240
+ capabilityId: null,
1241
+ capabilityKind: null,
1242
+ details: { language: "typescript" },
1243
+ kind: "language",
1244
+ references: [runtimeAgent],
1245
+ runtimeName: null,
1246
+ source: "eve"
1247
+ }));
1248
+ if (runtimeAgent.symbol !== void 0 && runtimeAgent.symbol !== "default") return null;
1249
+ const definition = getEveDefinition(result.analysis, "agent");
1250
+ if (definition.kind === "absent") {
1251
+ if (runtimeAgent.symbol === "default") addEveDiagnostic(diagnostics, "EVE_RUNTIME_AGENT_SYMBOL_NOT_FOUND", runtimeAgent.path, agent.id);
1252
+ return null;
1253
+ }
1254
+ if (definition.kind !== "present-supported" || [...definition.properties].some(([key, property]) => !POSITIVE_AGENT_KEYS.has(key) || !ts.isPropertyAssignment(property))) return null;
1255
+ const model = getEvePropertyExpression(definition.properties, "model");
1256
+ if (model === null || (await resolveEveStaticString(session, result.analysis, model)).kind !== "supported") return null;
1257
+ evidence.push(createEveEvidence({
1258
+ agentId: agent.id,
1259
+ capabilityId: null,
1260
+ capabilityKind: null,
1261
+ details: {
1262
+ agentKind: root.agentKind,
1263
+ agentRoot: root.agentRoot,
1264
+ layout: root.layout,
1265
+ targetId: EVE_TARGET_ID
1266
+ },
1267
+ kind: "agent-definition",
1268
+ references: [runtimeAgent],
1269
+ runtimeName: root.runtimeName,
1270
+ source: "eve"
1271
+ }));
1272
+ const outputSchema = agent.declaration.bindings?.outputSchema;
1273
+ if (outputSchema !== void 0 && outputSchema.symbol !== void 0) {
1274
+ if (!addEveSourceFailureDiagnostic(diagnostics, await session.analyzeSource(outputSchema.path), outputSchema.path, agent.id)) {
1275
+ const state = await classifyEveBoundExpression(session, result.analysis, getEvePropertyExpression(definition.properties, "outputSchema"), outputSchema);
1276
+ if (state === "missing") addEveDiagnostic(diagnostics, "EVE_AGENT_OUTPUT_SCHEMA_SYMBOL_NOT_FOUND", outputSchema.path, agent.id);
1277
+ else if (state === "wired") evidence.push(createEveEvidence({
1278
+ agentId: agent.id,
1279
+ capabilityId: null,
1280
+ capabilityKind: null,
1281
+ details: { schemaRole: "agent-output" },
1282
+ kind: "schema",
1283
+ references: [outputSchema],
1284
+ runtimeName: outputSchema.symbol,
1285
+ source: "eve"
1286
+ }));
1287
+ else if (state === "different") addEveDiagnostic(diagnostics, "EVE_AGENT_OUTPUT_SCHEMA_NOT_WIRED", runtimeAgent.path, agent.id);
1288
+ }
1289
+ }
1290
+ const descriptionProperty = definition.properties.get("description");
1291
+ const descriptionExpression = getEvePropertyExpression(definition.properties, "description");
1292
+ let routingDescription;
1293
+ if (descriptionProperty === void 0) routingDescription = Object.freeze({
1294
+ kind: "absent",
1295
+ range: null
1296
+ });
1297
+ else if (descriptionExpression === null) routingDescription = Object.freeze({
1298
+ kind: "unsupported",
1299
+ range: locateEveNode(result.analysis, descriptionProperty)
1300
+ });
1301
+ else {
1302
+ const staticDescription = await resolveEveStaticString(session, result.analysis, descriptionExpression);
1303
+ const range = locateEveNode(result.analysis, descriptionProperty);
1304
+ routingDescription = staticDescription.kind === "supported" ? Object.freeze({
1305
+ kind: "supported",
1306
+ range,
1307
+ value: staticDescription.value
1308
+ }) : Object.freeze({
1309
+ kind: "unsupported",
1310
+ range
1311
+ });
1312
+ }
1313
+ return Object.freeze({
1314
+ agent,
1315
+ analysis: result.analysis,
1316
+ definition,
1317
+ packageObservation,
1318
+ root,
1319
+ rootIndex,
1320
+ routingDescription
1321
+ });
1322
+ };
1323
+ //#endregion
1324
+ //#region src/inspection/instruction-inspection.ts
1325
+ var getDirectName = (root, entry) => {
1326
+ const prefix = root === "/" ? "/" : `${root}/`;
1327
+ return entry.path.slice(prefix.length);
1328
+ };
1329
+ var isModernMarkdown = (name) => /^instructions\.md$/iu.test(name);
1330
+ var isLegacyMarkdown = (name) => /^system\.md$/iu.test(name);
1331
+ var isModernModule = (name) => /^instructions\.(?:cts|mts|cjs|mjs|ts|js)$/u.test(name);
1332
+ var isLegacyModule = (name) => /^system\.(?:cts|mts|cjs|mjs|ts|js)$/u.test(name);
1333
+ var addInstructionConflicts = (diagnostics, agentId, candidates) => {
1334
+ const sorted = [...candidates].sort((left, right) => compareEveStrings(left.path, right.path));
1335
+ const primary = sorted[0];
1336
+ if (primary === void 0) return;
1337
+ for (const conflicting of sorted.slice(1)) addEveDiagnostic(diagnostics, "EVE_INSTRUCTION_ROOT_CONFLICT", primary.path, agentId, null, void 0, void 0, { conflictingPath: conflicting.path });
1338
+ };
1339
+ var inspectMarkdown = async (session, definition, path, evidence, diagnostics) => {
1340
+ const binding = definition.agent.declaration.bindings?.instructionLoader;
1341
+ if (binding === void 0) return;
1342
+ if (!normalizeText(await session.reader.readFile(path, session.signal === void 0 ? void 0 : { signal: session.signal })).valid) {
1343
+ addEveDiagnostic(diagnostics, "EVE_SOURCE_TEXT_INVALID", path, definition.agent.id);
1344
+ return;
1345
+ }
1346
+ if (binding.path === path && binding.symbol === void 0) {
1347
+ evidence.push(createEveEvidence({
1348
+ agentId: definition.agent.id,
1349
+ capabilityId: null,
1350
+ capabilityKind: null,
1351
+ details: {},
1352
+ kind: "instruction-loader",
1353
+ references: [binding],
1354
+ runtimeName: null,
1355
+ source: "eve"
1356
+ }));
1357
+ return;
1358
+ }
1359
+ if (binding.symbol === void 0) addEveDiagnostic(diagnostics, "EVE_INSTRUCTION_LOADER_NOT_WIRED", path, definition.agent.id);
1360
+ };
1361
+ var inspectTypeScriptInstructions = async (session, definition, path, evidence, diagnostics) => {
1362
+ const binding = definition.agent.declaration.bindings?.instructionLoader;
1363
+ if (binding === void 0) return;
1364
+ const result = await session.analyzeSource(path);
1365
+ if (addEveSourceFailureDiagnostic(diagnostics, result, path, definition.agent.id)) return;
1366
+ if (result.kind !== "valid") return;
1367
+ const instructions = getEveDefinition(result.analysis, "instructions");
1368
+ if (instructions.kind !== "present-supported" || instructions.properties.size < 1 || instructions.properties.size > 2 || !instructions.properties.has("content") || [...instructions.properties].some(([key, property]) => !["content", "role"].includes(key) || !ts.isPropertyAssignment(property))) return;
1369
+ const role = getEvePropertyExpression(instructions.properties, "role");
1370
+ if (role !== null && getStaticString(role) !== "system") {
1371
+ if (getStaticString(role) === "user") addEveDiagnostic(diagnostics, "EVE_INSTRUCTION_LOADER_NOT_WIRED", path, definition.agent.id);
1372
+ return;
1373
+ }
1374
+ if (addEveSourceFailureDiagnostic(diagnostics, await session.analyzeSource(binding.path), binding.path, definition.agent.id)) return;
1375
+ const state = await classifyEveBoundCall(session, result.analysis, getEvePropertyExpression(instructions.properties, "content"), binding);
1376
+ if (state === "missing") addEveDiagnostic(diagnostics, "EVE_INSTRUCTION_LOADER_SYMBOL_NOT_FOUND", binding.path, definition.agent.id);
1377
+ else if (state === "wired") evidence.push(createEveEvidence({
1378
+ agentId: definition.agent.id,
1379
+ capabilityId: null,
1380
+ capabilityKind: null,
1381
+ details: {},
1382
+ kind: "instruction-loader",
1383
+ references: [binding],
1384
+ runtimeName: binding.symbol ?? null,
1385
+ source: "eve"
1386
+ }));
1387
+ else if (state === "different") addEveDiagnostic(diagnostics, "EVE_INSTRUCTION_LOADER_NOT_WIRED", path, definition.agent.id);
1388
+ };
1389
+ /** Inspects the exclusive modern instruction surface for one supported Eve agent. */
1390
+ var inspectEveInstructions = async (session, definition, evidence, diagnostics) => {
1391
+ const named = definition.rootIndex.instructionEntries.map((entry) => ({
1392
+ entry,
1393
+ name: getDirectName(definition.root.agentRoot, entry)
1394
+ }));
1395
+ if (named.find(({ entry, name }) => entry.type === "directory" && name === "instructions") !== void 0) return;
1396
+ const modern = named.filter(({ entry, name }) => entry.type === "file" && (isModernMarkdown(name) || isModernModule(name)));
1397
+ if (modern.length > 1) {
1398
+ if (!modern.every(({ name }) => isModernMarkdown(name))) addInstructionConflicts(diagnostics, definition.agent.id, modern.map(({ entry }) => entry));
1399
+ return;
1400
+ }
1401
+ if (modern.length === 1) {
1402
+ const modernSource = modern[0];
1403
+ if (modernSource === void 0) return;
1404
+ const { entry, name } = modernSource;
1405
+ if (name === "instructions.md") await inspectMarkdown(session, definition, entry.path, evidence, diagnostics);
1406
+ else if (name === "instructions.ts") await inspectTypeScriptInstructions(session, definition, entry.path, evidence, diagnostics);
1407
+ return;
1408
+ }
1409
+ const legacy = named.filter(({ entry, name }) => entry.type === "file" && (isLegacyMarkdown(name) || isLegacyModule(name)));
1410
+ if (legacy.length > 1 && !legacy.every(({ name }) => isLegacyMarkdown(name))) {
1411
+ addInstructionConflicts(diagnostics, definition.agent.id, legacy.map(({ entry }) => entry));
1412
+ return;
1413
+ }
1414
+ if (legacy.length === 0 && definition.agent.declaration.bindings?.instructionLoader !== void 0) addEveDiagnostic(diagnostics, "EVE_INSTRUCTION_LOADER_NOT_WIRED", definition.analysis.path, definition.agent.id);
1415
+ };
1416
+ //#endregion
1417
+ //#region src/package-discovery/index.ts
1418
+ /** Discovers the nearest owning Eve package and its safe root identity. */
1419
+ var discoverEvePackage = async (reader, sourcePath, signal) => {
1420
+ const result = await discoverPackage({
1421
+ includeManifestPackageName: true,
1422
+ packageName: "eve",
1423
+ reader: {
1424
+ getEntry: (path) => reader.getEntry(path, signal === void 0 ? void 0 : { signal }),
1425
+ readFile: (path) => reader.readFile(path, signal === void 0 ? void 0 : { signal })
1426
+ },
1427
+ ...signal === void 0 ? {} : { signal },
1428
+ sourcePath,
1429
+ supportedRange: EVE_SUPPORTED_PACKAGE_RANGE
1430
+ });
1431
+ if (result.kind !== "observed") return result;
1432
+ return Object.freeze({
1433
+ kind: "observed",
1434
+ observation: Object.freeze({
1435
+ ...result.observation,
1436
+ manifestPackageName: result.observation.manifestPackageName ?? null,
1437
+ path: result.observation.path
1438
+ })
1439
+ });
1440
+ };
1441
+ //#endregion
1442
+ //#region src/inspection/session.ts
1443
+ /** Creates one operation-local Eve inspection session with source and listing caches. */
1444
+ var createEveInspectionSession = (context) => {
1445
+ const base = createInspectionSession({
1446
+ analyzeSource: analyzeEveSource,
1447
+ discoverPackage: (path, signal) => discoverEvePackage(context.repository, path, signal),
1448
+ getEntry: (path, signal) => context.repository.getEntry(path, signal === void 0 ? void 0 : { signal }),
1449
+ readFile: (path, signal) => context.repository.readFile(path, signal === void 0 ? void 0 : { signal }),
1450
+ ...context.signal === void 0 ? {} : { signal: context.signal }
1451
+ });
1452
+ const rootCache = /* @__PURE__ */ new Map();
1453
+ const indexAgentRoot = (path) => {
1454
+ context.signal?.throwIfAborted();
1455
+ const existing = rootCache.get(path);
1456
+ if (existing !== void 0) return existing;
1457
+ const indexed = (async () => {
1458
+ const entries = [];
1459
+ for await (const entry of context.repository.listEntries({
1460
+ prefix: path,
1461
+ ...context.signal === void 0 ? {} : { signal: context.signal }
1462
+ })) {
1463
+ context.signal?.throwIfAborted();
1464
+ entries.push(entry);
1465
+ }
1466
+ return createEveAgentRootIndex(path, entries);
1467
+ })();
1468
+ rootCache.set(path, indexed);
1469
+ return indexed;
1470
+ };
1471
+ return Object.freeze({
1472
+ ...base,
1473
+ indexAgentRoot,
1474
+ reader: context.repository
1475
+ });
1476
+ };
1477
+ //#endregion
1478
+ //#region src/inspection/skill-inspection.ts
1479
+ var ALLOWED_SKILL_KEYS = /* @__PURE__ */ new Set([
1480
+ "description",
1481
+ "files",
1482
+ "license",
1483
+ "markdown",
1484
+ "metadata"
1485
+ ]);
1486
+ var prepareSkill = async (session, candidate) => {
1487
+ if (candidate.kind !== "typescript" || candidate.isCollidedSlot) return null;
1488
+ const result = await session.analyzeSource(candidate.path);
1489
+ if (result.kind !== "valid") return null;
1490
+ const definition = getEveDefinition(result.analysis, "skill");
1491
+ if (definition.kind !== "present-supported" || [...definition.properties].some(([key, property]) => !ALLOWED_SKILL_KEYS.has(key) || !ts.isPropertyAssignment(property))) return null;
1492
+ const description = getEvePropertyExpression(definition.properties, "description");
1493
+ const markdown = getEvePropertyExpression(definition.properties, "markdown");
1494
+ const license = getEvePropertyExpression(definition.properties, "license");
1495
+ const metadata = getEvePropertyExpression(definition.properties, "metadata");
1496
+ const files = getEvePropertyExpression(definition.properties, "files");
1497
+ const isRegistrationEligible = description !== null && markdown !== null && (await resolveEveStaticString(session, result.analysis, description)).kind === "supported" && (await resolveEveStaticString(session, result.analysis, markdown)).kind === "supported" && (license === null || (await resolveEveStaticString(session, result.analysis, license)).kind === "supported") && (metadata === null || await isEveStaticStringRecord(session, result.analysis, metadata)) && (files === null || await isEveStaticStringRecord(session, result.analysis, files));
1498
+ return Object.freeze({
1499
+ analysis: result.analysis,
1500
+ candidate,
1501
+ definition,
1502
+ isRegistrationEligible
1503
+ });
1504
+ };
1505
+ var selectSkill = (candidates, skill) => {
1506
+ const implementationMatches = candidates.filter(({ path }) => path === skill.implementation.path);
1507
+ if (implementationMatches.length === 1) return implementationMatches[0] ?? null;
1508
+ const nameMatches = candidates.filter(({ identity }) => identity === skill.name);
1509
+ return nameMatches.length === 1 ? nameMatches[0] ?? null : null;
1510
+ };
1511
+ /** Inspects flat, packaged, and TypeScript Eve skills for one scoped agent. */
1512
+ var inspectEveSkills = async (session, definition, evidence, diagnostics) => {
1513
+ for (const [capabilityId, skill] of Object.entries(definition.agent.declaration.skills ?? {})) {
1514
+ const candidate = selectSkill(definition.rootIndex.skillCandidates, skill);
1515
+ if (candidate === null || candidate.isCollidedSlot) continue;
1516
+ const supportsImplementationSymbol = candidate.kind === "typescript" ? skill.implementation.symbol === void 0 || skill.implementation.symbol === "default" : skill.implementation.symbol === void 0;
1517
+ if (skill.implementation.path !== candidate.path || !supportsImplementationSymbol) {
1518
+ if (supportsImplementationSymbol) addEveDiagnostic(diagnostics, "EVE_SKILL_IMPLEMENTATION_NOT_WIRED", candidate.path, definition.agent.id, null, "skill", capabilityId);
1519
+ continue;
1520
+ }
1521
+ if (candidate.kind !== "typescript") continue;
1522
+ const prepared = await prepareSkill(session, candidate);
1523
+ if (prepared === null) {
1524
+ const result = await session.analyzeSource(candidate.path);
1525
+ if (addEveSourceFailureDiagnostic(diagnostics, result, candidate.path, definition.agent.id, "skill", capabilityId)) continue;
1526
+ if (skill.implementation.symbol === "default") {
1527
+ if (result.kind === "valid" && getEveDefinition(result.analysis, "skill").kind === "absent") addEveDiagnostic(diagnostics, "EVE_SKILL_IMPLEMENTATION_SYMBOL_NOT_FOUND", candidate.path, definition.agent.id, null, "skill", capabilityId);
1528
+ }
1529
+ continue;
1530
+ }
1531
+ const registration = skill.registration;
1532
+ let isRegistrationWired = registration === void 0;
1533
+ if (registration !== void 0) {
1534
+ if (registration.path === candidate.path && (registration.symbol === void 0 || registration.symbol === "default")) isRegistrationWired = true;
1535
+ else if (registration.symbol === "default") {
1536
+ const result = await session.analyzeSource(registration.path);
1537
+ if (addEveSourceFailureDiagnostic(diagnostics, result, registration.path, definition.agent.id, "skill", capabilityId)) continue;
1538
+ const registrationDefinition = result.kind === "valid" ? getEveDefinition(result.analysis, "skill") : null;
1539
+ if (registrationDefinition?.kind === "absent") addEveDiagnostic(diagnostics, "EVE_SKILL_REGISTRATION_SYMBOL_NOT_FOUND", registration.path, definition.agent.id, null, "skill", capabilityId);
1540
+ else if (registrationDefinition?.kind === "present-supported") addEveDiagnostic(diagnostics, "EVE_SKILL_REGISTRATION_NOT_WIRED", candidate.path, definition.agent.id, null, "skill", capabilityId);
1541
+ } else if (registration.symbol === void 0) addEveDiagnostic(diagnostics, "EVE_SKILL_REGISTRATION_NOT_WIRED", candidate.path, definition.agent.id, null, "skill", capabilityId);
1542
+ }
1543
+ if (!prepared.isRegistrationEligible || !isRegistrationWired) continue;
1544
+ if (skill.name !== candidate.identity) {
1545
+ addEveDiagnostic(diagnostics, "EVE_SKILL_NAME_MISMATCH", candidate.path, definition.agent.id, null, "skill", capabilityId);
1546
+ continue;
1547
+ }
1548
+ evidence.push(createEveEvidence({
1549
+ agentId: definition.agent.id,
1550
+ capabilityId,
1551
+ capabilityKind: "skill",
1552
+ details: { registrationKind: "typescript" },
1553
+ kind: "skill-registration",
1554
+ references: [{ path: candidate.path }],
1555
+ runtimeName: candidate.identity,
1556
+ source: "eve"
1557
+ }));
1558
+ }
1559
+ };
1560
+ //#endregion
1561
+ //#region src/inspection/subagent-inspection.ts
1562
+ /** Inspects exact immediate directory-backed local-subagent registrations. */
1563
+ var inspectEveSubagents = (definitions, preparedToolNames, evidence, diagnostics) => {
1564
+ for (const target of definitions) {
1565
+ if (target.root.agentKind !== "local-subagent" || target.root.parentRoot === null || target.root.runtimeName === null) continue;
1566
+ const parents = definitions.filter(({ root }) => root.agentRoot === target.root.parentRoot).sort((left, right) => compareEveStrings(left.agent.id, right.agent.id));
1567
+ if (parents.length > 1) {
1568
+ addEveDiagnostic(diagnostics, "EVE_SUBAGENT_PARENT_AMBIGUOUS", target.agent.declaration.bindings?.runtimeAgent?.path ?? null, target.agent.id, null, void 0, void 0, { candidateAgentIds: parents.map(({ agent }) => agent.id).join(",") });
1569
+ continue;
1570
+ }
1571
+ const parent = parents[0];
1572
+ if (parent === void 0) continue;
1573
+ const candidates = parent.rootIndex.subagentCandidates.filter(({ runtimeName }) => runtimeName === target.root.runtimeName);
1574
+ const candidate = candidates.find(({ agentPath, isDirectoryBacked }) => isDirectoryBacked && agentPath === target.agent.declaration.bindings?.runtimeAgent?.path);
1575
+ if (candidates.length !== 1 || candidate === void 0 || candidate.isExtensionReserved) continue;
1576
+ if ((preparedToolNames.get(parent.agent.id) ?? /* @__PURE__ */ new Set()).has(target.root.runtimeName) || EVE_FRAMEWORK_TOOL_NAMES.includes(target.root.runtimeName) || target.root.runtimeName === "load_skill") {
1577
+ addEveDiagnostic(diagnostics, "EVE_TOOL_SUBAGENT_NAME_COLLISION", target.agent.declaration.bindings?.runtimeAgent?.path ?? null, target.agent.id, null, void 0, void 0, { collisionKind: "runtime-tool" });
1578
+ continue;
1579
+ }
1580
+ if (target.routingDescription.kind === "absent" || target.routingDescription.kind === "supported" && target.routingDescription.value === "") {
1581
+ addEveDiagnostic(diagnostics, "EVE_ROUTING_DESCRIPTION_MISSING", target.agent.declaration.bindings?.runtimeAgent?.path ?? null, target.agent.id, target.routingDescription.range);
1582
+ continue;
1583
+ }
1584
+ if (target.routingDescription.kind !== "supported") continue;
1585
+ const routingDescriptionSource = target.agent.handoffDescription === null ? "agent-description" : "handoff-description";
1586
+ const effectiveDescription = target.agent.handoffDescription?.value ?? target.agent.description.value;
1587
+ const isWired = target.routingDescription.value === effectiveDescription;
1588
+ if (!isWired) addEveDiagnostic(diagnostics, "EVE_ROUTING_DESCRIPTION_NOT_WIRED", target.agent.declaration.bindings?.runtimeAgent?.path ?? null, target.agent.id, target.routingDescription.range);
1589
+ const parentReference = parent.agent.declaration.bindings?.runtimeAgent;
1590
+ const targetReference = target.agent.declaration.bindings?.runtimeAgent;
1591
+ if (parentReference === void 0 || targetReference === void 0) continue;
1592
+ evidence.push(createEveEvidence({
1593
+ agentId: parent.agent.id,
1594
+ capabilityId: null,
1595
+ capabilityKind: null,
1596
+ details: {
1597
+ registrationKind: "local-subagent-package",
1598
+ routingDescriptionSource,
1599
+ routingDescriptionWired: isWired,
1600
+ targetAgentId: target.agent.id,
1601
+ targetRuntimeName: target.root.runtimeName
1602
+ },
1603
+ kind: "handoff-registration",
1604
+ references: [parentReference, targetReference],
1605
+ runtimeName: target.root.runtimeName,
1606
+ source: "eve"
1607
+ }));
1608
+ }
1609
+ };
1610
+ //#endregion
1611
+ //#region src/inspection/tool-inspection.ts
1612
+ var ALLOWED_TOOL_KEYS = /* @__PURE__ */ new Set([
1613
+ "approval",
1614
+ "description",
1615
+ "execute",
1616
+ "inputSchema",
1617
+ "outputSchema",
1618
+ "toModelOutput"
1619
+ ]);
1620
+ var isApprovalSupported = async (session, analysis, property) => {
1621
+ if (property === void 0) return true;
1622
+ if (!ts.isPropertyAssignment(property)) return false;
1623
+ if (await isEveResolvedFunctionValue(session, analysis, property.initializer)) return true;
1624
+ const expression = property.initializer;
1625
+ if (!ts.isObjectLiteralExpression(expression)) return false;
1626
+ const members = getEveObjectMembers(expression);
1627
+ if (members === null || !members.has("request") || [...members.keys()].some((key) => !["request", "response"].includes(key))) return false;
1628
+ for (const [name, member] of members) {
1629
+ if (!ts.isMethodDeclaration(member) && (!ts.isPropertyAssignment(member) || !await isEveResolvedFunctionValue(session, analysis, member.initializer))) return false;
1630
+ if (!["request", "response"].includes(name)) return false;
1631
+ }
1632
+ return true;
1633
+ };
1634
+ var prepareTool = async (session, candidate) => {
1635
+ if (!candidate.isSupportedSource || candidate.isCollidedSlot || candidate.isExtensionReserved) return null;
1636
+ const result = await session.analyzeSource(candidate.path);
1637
+ if (result.kind !== "valid") return null;
1638
+ const definition = getEveDefinition(result.analysis, "tool");
1639
+ if (definition.kind !== "present-supported") return null;
1640
+ const description = getEvePropertyExpression(definition.properties, "description");
1641
+ const inputSchema = getEvePropertyExpression(definition.properties, "inputSchema");
1642
+ const executeMember = definition.properties.get("execute");
1643
+ const toModelOutput = definition.properties.get("toModelOutput");
1644
+ const hasSupportedMembers = [...definition.properties].every(([key, member]) => {
1645
+ if (!ALLOWED_TOOL_KEYS.has(key)) return false;
1646
+ return ts.isPropertyAssignment(member) || (key === "execute" || key === "toModelOutput") && ts.isMethodDeclaration(member);
1647
+ });
1648
+ const executeSupported = executeMember !== void 0 && (ts.isMethodDeclaration(executeMember) || ts.isPropertyAssignment(executeMember) && await isEveResolvedFunctionValue(session, result.analysis, executeMember.initializer));
1649
+ const toModelOutputSupported = toModelOutput === void 0 || ts.isMethodDeclaration(toModelOutput) || ts.isPropertyAssignment(toModelOutput) && await isEveResolvedFunctionValue(session, result.analysis, toModelOutput.initializer);
1650
+ const isRegistrationEligible = hasSupportedMembers && description !== null && inputSchema !== null && executeSupported && toModelOutputSupported && await isApprovalSupported(session, result.analysis, definition.properties.get("approval")) && (await resolveEveStaticString(session, result.analysis, description)).kind === "supported";
1651
+ return Object.freeze({
1652
+ analysis: result.analysis,
1653
+ candidate,
1654
+ definition,
1655
+ isRegistrationEligible
1656
+ });
1657
+ };
1658
+ var selectTool = (prepared, tool) => {
1659
+ const nameMatches = prepared.filter(({ candidate }) => candidate.runtimeName === tool.name);
1660
+ if (nameMatches.length === 1) return nameMatches[0] ?? null;
1661
+ const implementationMatches = prepared.filter(({ candidate }) => candidate.path === tool.implementation.path);
1662
+ if (implementationMatches.length === 1) return implementationMatches[0] ?? null;
1663
+ const registrationMatches = prepared.filter(({ candidate }) => candidate.path === tool.registration?.path);
1664
+ return registrationMatches.length === 1 ? registrationMatches[0] ?? null : null;
1665
+ };
1666
+ var selectToolCandidate = (candidates, tool) => {
1667
+ const nameMatches = candidates.filter(({ runtimeName }) => runtimeName === tool.name);
1668
+ if (nameMatches.length === 1) return nameMatches[0] ?? null;
1669
+ const implementationMatches = candidates.filter(({ path }) => path === tool.implementation.path);
1670
+ if (implementationMatches.length === 1) return implementationMatches[0] ?? null;
1671
+ const registrationMatches = candidates.filter(({ path }) => path === tool.registration?.path);
1672
+ return registrationMatches.length === 1 ? registrationMatches[0] ?? null : null;
1673
+ };
1674
+ var inspectToolSchema = async (session, definition, prepared, capabilityId, role, tool, evidence, diagnostics) => {
1675
+ const reference = role === "input" ? tool.inputSchema : tool.outputSchema;
1676
+ if (reference?.symbol === void 0) return;
1677
+ if (addEveSourceFailureDiagnostic(diagnostics, await session.analyzeSource(reference.path), reference.path, definition.agent.id, "tool", capabilityId)) return;
1678
+ const propertyName = role === "input" ? "inputSchema" : "outputSchema";
1679
+ const state = await classifyEveBoundExpression(session, prepared.analysis, getEvePropertyExpression(prepared.definition.properties, propertyName), reference);
1680
+ const prefix = role === "input" ? "INPUT" : "OUTPUT";
1681
+ if (state === "missing") addEveDiagnostic(diagnostics, `EVE_TOOL_${prefix}_SCHEMA_SYMBOL_NOT_FOUND`, reference.path, definition.agent.id, null, "tool", capabilityId);
1682
+ else if (state === "wired") evidence.push(createEveEvidence({
1683
+ agentId: definition.agent.id,
1684
+ capabilityId,
1685
+ capabilityKind: "tool",
1686
+ details: { schemaRole: `tool-${role}` },
1687
+ kind: "schema",
1688
+ references: [reference],
1689
+ runtimeName: reference.symbol,
1690
+ source: "eve"
1691
+ }));
1692
+ else if (state === "different") addEveDiagnostic(diagnostics, `EVE_TOOL_${prefix}_SCHEMA_NOT_WIRED`, prepared.candidate.path, definition.agent.id, null, "tool", capabilityId);
1693
+ };
1694
+ /** Inspects recursive static Eve tools declared by one scoped agent. */
1695
+ var inspectEveTools = async (session, definition, evidence, diagnostics) => {
1696
+ const prepared = (await Promise.all(definition.rootIndex.toolCandidates.map((candidate) => prepareTool(session, candidate)))).filter((candidate) => candidate !== null);
1697
+ const runtimeGroups = /* @__PURE__ */ new Map();
1698
+ for (const candidate of definition.rootIndex.toolCandidates) {
1699
+ if (!candidate.isSupportedSource || candidate.isCollidedSlot || candidate.isExtensionReserved || candidate.runtimeName === "Workflow" || candidate.segments.some((segment) => !EVE_TOOL_NAME_PATTERN.test(segment))) continue;
1700
+ const group = runtimeGroups.get(candidate.runtimeName) ?? [];
1701
+ group.push(candidate);
1702
+ runtimeGroups.set(candidate.runtimeName, group);
1703
+ }
1704
+ const collidedNames = /* @__PURE__ */ new Set();
1705
+ for (const [runtimeName, candidates] of runtimeGroups) {
1706
+ if (candidates.length < 2) continue;
1707
+ collidedNames.add(runtimeName);
1708
+ const sorted = candidates.map(({ path }) => path).sort(compareEveStrings);
1709
+ addEveDiagnostic(diagnostics, "EVE_TOOL_RUNTIME_NAME_COLLISION", sorted[0] ?? null, definition.agent.id, null, void 0, void 0, { conflictingPaths: sorted.join(",") });
1710
+ }
1711
+ for (const [capabilityId, tool] of Object.entries(definition.agent.declaration.tools ?? {})) {
1712
+ const selected = selectTool(prepared, tool);
1713
+ if (selected === null) {
1714
+ const candidate = selectToolCandidate(definition.rootIndex.toolCandidates, tool);
1715
+ if (candidate !== null && candidate.isSupportedSource && !candidate.isCollidedSlot && !candidate.isExtensionReserved) addEveSourceFailureDiagnostic(diagnostics, await session.analyzeSource(candidate.path), candidate.path, definition.agent.id, "tool", capabilityId);
1716
+ continue;
1717
+ }
1718
+ const { candidate } = selected;
1719
+ const invalidSegmentIndex = candidate.segments.findIndex((segment) => !EVE_TOOL_NAME_PATTERN.test(segment));
1720
+ const isReserved = candidate.runtimeName === EVE_RESERVED_TOOL_NAME;
1721
+ const canDiagnoseRegistration = invalidSegmentIndex < 0 && !isReserved && !collidedNames.has(candidate.runtimeName);
1722
+ if (invalidSegmentIndex >= 0) addEveDiagnostic(diagnostics, "EVE_TOOL_NAME_INVALID", candidate.path, definition.agent.id, null, "tool", capabilityId, { segmentIndex: invalidSegmentIndex });
1723
+ else if (isReserved) addEveDiagnostic(diagnostics, "EVE_TOOL_NAME_RESERVED", candidate.path, definition.agent.id, null, "tool", capabilityId);
1724
+ let implementationKind = null;
1725
+ if (tool.implementation.path === candidate.path && (tool.implementation.symbol === void 0 || tool.implementation.symbol === "default")) implementationKind = "inline";
1726
+ else if (tool.implementation.symbol !== void 0) {
1727
+ if (!addEveSourceFailureDiagnostic(diagnostics, await session.analyzeSource(tool.implementation.path), tool.implementation.path, definition.agent.id, "tool", capabilityId)) {
1728
+ const execute = selected.definition.properties.get("execute");
1729
+ const state = await classifyEveBoundExpression(session, selected.analysis, execute !== void 0 && ts.isPropertyAssignment(execute) ? execute.initializer : null, tool.implementation, true);
1730
+ if (state === "missing") addEveDiagnostic(diagnostics, "EVE_TOOL_IMPLEMENTATION_SYMBOL_NOT_FOUND", tool.implementation.path, definition.agent.id, null, "tool", capabilityId);
1731
+ else if (state === "wired") implementationKind = "bound-function";
1732
+ else if (state === "different") addEveDiagnostic(diagnostics, "EVE_TOOL_IMPLEMENTATION_NOT_WIRED", candidate.path, definition.agent.id, null, "tool", capabilityId);
1733
+ }
1734
+ }
1735
+ await inspectToolSchema(session, definition, selected, capabilityId, "input", tool, evidence, diagnostics);
1736
+ await inspectToolSchema(session, definition, selected, capabilityId, "output", tool, evidence, diagnostics);
1737
+ const registration = tool.registration;
1738
+ let isRegistrationWired = registration === void 0;
1739
+ let isRegistrationResolved = true;
1740
+ if (registration !== void 0) {
1741
+ if (registration.path === candidate.path && (registration.symbol === void 0 || registration.symbol === "default")) isRegistrationWired = true;
1742
+ else if (registration.symbol === "default") {
1743
+ const registrationResult = await session.analyzeSource(registration.path);
1744
+ if (addEveSourceFailureDiagnostic(diagnostics, registrationResult, registration.path, definition.agent.id, "tool", capabilityId)) isRegistrationResolved = false;
1745
+ const registrationDefinition = registrationResult.kind === "valid" ? getEveDefinition(registrationResult.analysis, "tool") : null;
1746
+ if (registrationDefinition?.kind === "absent") {
1747
+ if (canDiagnoseRegistration) addEveDiagnostic(diagnostics, "EVE_TOOL_REGISTRATION_SYMBOL_NOT_FOUND", registration.path, definition.agent.id, null, "tool", capabilityId);
1748
+ isRegistrationResolved = false;
1749
+ } else if (registrationDefinition?.kind === "present-supported") {
1750
+ if (canDiagnoseRegistration) addEveDiagnostic(diagnostics, "EVE_TOOL_REGISTRATION_NOT_WIRED", selected.candidate.path, definition.agent.id, null, "tool", capabilityId);
1751
+ } else isRegistrationResolved = false;
1752
+ } else if (registration.symbol === void 0) {
1753
+ if (canDiagnoseRegistration) addEveDiagnostic(diagnostics, "EVE_TOOL_REGISTRATION_NOT_WIRED", candidate.path, definition.agent.id, null, "tool", capabilityId);
1754
+ }
1755
+ }
1756
+ if (!(selected.isRegistrationEligible && implementationKind !== null && isRegistrationWired && isRegistrationResolved && invalidSegmentIndex < 0 && !isReserved && !collidedNames.has(candidate.runtimeName))) continue;
1757
+ if (tool.name !== candidate.runtimeName) {
1758
+ addEveDiagnostic(diagnostics, "EVE_TOOL_NAME_MISMATCH", candidate.path, definition.agent.id, null, "tool", capabilityId);
1759
+ continue;
1760
+ }
1761
+ const references = [{ path: candidate.path }, ...tool.implementation.path === candidate.path ? [] : [tool.implementation]];
1762
+ evidence.push(createEveEvidence({
1763
+ agentId: definition.agent.id,
1764
+ capabilityId,
1765
+ capabilityKind: "tool",
1766
+ details: {
1767
+ implementationKind,
1768
+ pathDepth: candidate.segments.length,
1769
+ registrationKind: "filesystem-tool"
1770
+ },
1771
+ kind: "tool-registration",
1772
+ references,
1773
+ runtimeName: candidate.runtimeName,
1774
+ source: "eve"
1775
+ }));
1776
+ }
1777
+ return new Set(prepared.filter(({ candidate, isRegistrationEligible }) => isRegistrationEligible && !collidedNames.has(candidate.runtimeName) && candidate.runtimeName !== "Workflow" && candidate.segments.every((segment) => EVE_TOOL_NAME_PATTERN.test(segment))).map(({ candidate }) => candidate.runtimeName));
1778
+ };
1779
+ //#endregion
1780
+ //#region src/inspection/inspection.ts
1781
+ /**
1782
+ * Inspects all scoped Eve agents through one deterministic read-only session.
1783
+ * @param context The Core-provided immutable adapter context.
1784
+ * @returns A promise resolving to source-grounded evidence and diagnostics.
1785
+ * @throws
1786
+ * - INVALID_REPOSITORY_PATH: The repository path is invalid.
1787
+ * - ENTRY_NOT_FOUND: The requested repository entry was not found.
1788
+ * - ENTRY_NOT_FILE: The requested repository entry is not a file.
1789
+ * - ENTRY_NOT_DIRECTORY: The requested repository entry is not a directory.
1790
+ * - ACCESS_DENIED: Access to the repository source was denied.
1791
+ * - SOURCE_UNAVAILABLE: The repository source is unavailable.
1792
+ * - SNAPSHOT_CHANGED: The repository snapshot changed during the operation.
1793
+ * - INVALID_SOURCE_DATA: The repository source returned invalid data.
1794
+ * - RESOURCE_LIMIT_EXCEEDED: A repository reading resource limit was exceeded.
1795
+ * - ABORTED: The repository operation or inspection signal was aborted.
1796
+ */
1797
+ var inspectEve = async (context) => {
1798
+ context.signal?.throwIfAborted();
1799
+ const session = createEveInspectionSession(context);
1800
+ const evidence = [];
1801
+ const diagnostics = [];
1802
+ const definitions = [];
1803
+ const agents = [...context.agents].sort((left, right) => compareEveStrings(left.id, right.id));
1804
+ for (const agent of agents) {
1805
+ context.signal?.throwIfAborted();
1806
+ const definition = await inspectEveAgent(session, agent, evidence, diagnostics);
1807
+ if (definition !== null) definitions.push(definition);
1808
+ }
1809
+ const preparedToolNames = /* @__PURE__ */ new Map();
1810
+ for (const definition of definitions) {
1811
+ context.signal?.throwIfAborted();
1812
+ await inspectEveInstructions(session, definition, evidence, diagnostics);
1813
+ preparedToolNames.set(definition.agent.id, await inspectEveTools(session, definition, evidence, diagnostics));
1814
+ await inspectEveSkills(session, definition, evidence, diagnostics);
1815
+ }
1816
+ context.signal?.throwIfAborted();
1817
+ inspectEveSubagents(definitions, preparedToolNames, evidence, diagnostics);
1818
+ return Object.freeze({
1819
+ diagnostics: Object.freeze(diagnostics),
1820
+ evidence: Object.freeze(evidence)
1821
+ });
1822
+ };
1823
+ //#endregion
1824
+ //#region src/adapter/index.ts
1825
+ var eveAdapter = Object.freeze({
1826
+ id: "eve",
1827
+ inspect: inspectEve,
1828
+ supportedRepositoryFormatVersions: EVE_SUPPORTED_REPOSITORY_FORMAT_VERSIONS
1829
+ });
1830
+ //#endregion
1831
+ export { eveAdapter };