@beehexa/hexasync-template-validate 2610.4.6 → 2610.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- package/dist/index.js.map +1 -1
- package/dist/validate/agentAnswers.d.ts +12 -2
- package/dist/validate/agentAnswers.d.ts.map +1 -1
- package/dist/validate/agentAnswers.js +36 -9
- package/dist/validate/agentAnswers.js.map +1 -1
- package/dist/validate/agentTools.d.ts +30 -22
- package/dist/validate/agentTools.d.ts.map +1 -1
- package/dist/validate/agentTools.js +74 -37
- package/dist/validate/agentTools.js.map +1 -1
- package/dist/validate/answerAgentTool.d.ts +150 -42
- package/dist/validate/answerAgentTool.d.ts.map +1 -1
- package/dist/validate/answerAgentTool.js +377 -163
- package/dist/validate/answerAgentTool.js.map +1 -1
- package/dist/validate/boundedAgentTool.d.ts +94 -0
- package/dist/validate/boundedAgentTool.d.ts.map +1 -0
- package/dist/validate/boundedAgentTool.js +136 -0
- package/dist/validate/boundedAgentTool.js.map +1 -0
- package/dist/validate/buildValidationModel.d.ts +19 -3
- package/dist/validate/buildValidationModel.d.ts.map +1 -1
- package/dist/validate/buildValidationModel.js +14 -3
- package/dist/validate/buildValidationModel.js.map +1 -1
- package/dist/validate/contextFromGraph.d.ts +1 -1
- package/dist/validate/knowledgeDocs.d.ts +76 -0
- package/dist/validate/knowledgeDocs.d.ts.map +1 -0
- package/dist/validate/knowledgeDocs.js +261 -0
- package/dist/validate/knowledgeDocs.js.map +1 -0
- package/dist/validate/registry.d.ts +2 -3
- package/dist/validate/registry.d.ts.map +1 -1
- package/dist/validate/registry.js +4 -3
- package/dist/validate/registry.js.map +1 -1
- package/dist/validate/retrieve.d.ts +10 -0
- package/dist/validate/retrieve.d.ts.map +1 -1
- package/dist/validate/retrieve.js +34 -11
- package/dist/validate/retrieve.js.map +1 -1
- package/dist/validate/ruleCatalog.d.ts.map +1 -1
- package/dist/validate/ruleCatalog.js +19 -11
- package/dist/validate/ruleCatalog.js.map +1 -1
- package/dist/validate/rules/connectorIdentity.js +1 -1
- package/dist/validate/rules/flow.d.ts +1 -1
- package/dist/validate/rules/flow.d.ts.map +1 -1
- package/dist/validate/rules/flow.js +32 -22
- package/dist/validate/rules/flow.js.map +1 -1
- package/dist/validate/rules/stepData.d.ts +2 -2
- package/dist/validate/rules/stepData.js +2 -2
- package/dist/validate/rules/tables.js +5 -5
- package/dist/validate/rules/tables.js.map +1 -1
- package/dist/validate/rules/unimplementedStep.d.ts +3 -0
- package/dist/validate/rules/unimplementedStep.d.ts.map +1 -0
- package/dist/validate/rules/unimplementedStep.js +94 -0
- package/dist/validate/rules/unimplementedStep.js.map +1 -0
- package/dist/validate/sourceLocator.d.ts +25 -2
- package/dist/validate/sourceLocator.d.ts.map +1 -1
- package/dist/validate/sourceLocator.js +126 -21
- package/dist/validate/sourceLocator.js.map +1 -1
- package/dist/validate/typeKnowledge.d.ts +63 -0
- package/dist/validate/typeKnowledge.d.ts.map +1 -0
- package/dist/validate/typeKnowledge.js +350 -0
- package/dist/validate/typeKnowledge.js.map +1 -0
- package/package.json +6 -6
|
@@ -1,217 +1,431 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* How every surface ANSWERS a tool call — one implementation, injected host I/O.
|
|
3
|
-
*
|
|
4
|
-
* ⛔ `agentTools.ts` next door holds the tool *list* and says, in its own header, that two lists cannot stay in
|
|
5
|
-
* agreement: *"they agree the day they are written and drift afterwards"*. The same is true of two **bodies**, and
|
|
6
|
-
* until this file existed there were two: `src/adapters/agentTools.ts` in the extension read the surface through
|
|
7
|
-
* `vscode.workspace.fs`, and `apps/cli/src/commands/mcpCommand.ts` in the sibling CLI read it through `node:fs`,
|
|
8
|
-
* each re-deriving the bounds, the refusal text and the JSON tail. Story 7.6 AC-1 asks for the same tool set *"by
|
|
9
|
-
* name and behaviour"* — the list gave us the names, and this gives us the behaviour.
|
|
10
|
-
*
|
|
11
|
-
* ### What is injected, and why only this much
|
|
12
|
-
*
|
|
13
|
-
* Two things differ between an editor and a stdio server, and nothing else does:
|
|
14
|
-
*
|
|
15
|
-
* - **reading a file.** A web extension host has no `node:fs` and a server has no `vscode.workspace.fs`.
|
|
16
|
-
* - **validating.** The editor has already run the rules over the effective graph and holds the findings as
|
|
17
|
-
* diagnostics; a server must run them on demand. That is a real difference in *where the answer comes from*, so
|
|
18
|
-
* it is a host method rather than something faked here.
|
|
19
|
-
*
|
|
20
|
-
* Everything else — which file answers which tool, every bound, every refusal — is here, once.
|
|
21
|
-
*
|
|
22
|
-
* ⚠️ This module stays pure: it takes I/O as an argument and imports none. That is what keeps it in the `core`
|
|
23
|
-
* layer alongside the rules, reachable from a browser bundle and a Node server alike.
|
|
24
|
-
*/
|
|
1
|
+
/** One host-neutral invocation authority. Hosts prepare facts; this service validates and renders them. */
|
|
25
2
|
import { POSITIONS, resolveEnvironment } from '@beehexa/hexasync-template-context';
|
|
26
3
|
import { AGENT_TOOLS } from './agentTools.js';
|
|
27
4
|
import { z } from 'zod';
|
|
28
|
-
import { explainRule, explainType, positionAnswer, searchExamples
|
|
29
|
-
import { connectorAnswer, orientationOpening, typeAnswers
|
|
30
|
-
|
|
5
|
+
import { explainRule, explainType, findingsTouching, positionAnswer, searchExamples } from './retrieve.js';
|
|
6
|
+
import { connectorAnswer, orientationOpening, typeAnswers } from './agentAnswers.js';
|
|
7
|
+
import { encodeWorkspaceReference, isWorkspaceSourcedAnswer } from './boundedAgentTool.js';
|
|
8
|
+
import { conceptHeadings, formatKnowledgeLinks, headingLink, markdownKnowledgeLink, mentioningSections, typePage, } from './knowledgeDocs.js';
|
|
9
|
+
import { fieldReference, matchName, normalizedPath, renderFieldDetail, renderFieldLine, renderNameMatches, renderTypeDocs, suggestNames, typeFields, } from './typeKnowledge.js';
|
|
10
|
+
/**
|
|
11
|
+
* Closed Tool failure vocabulary (not documentation Resource codes).
|
|
12
|
+
* Input/catalog branches map to argument/unknown-subject codes; Host Root/discovery/selection branches map to
|
|
13
|
+
* preparation codes; selected Knowledge reads, JSON/schema/index/manifest and checksum branches stay distinct.
|
|
14
|
+
* Expected handler preconditions are values; unexpected faults are mapped only by the composition boundary.
|
|
15
|
+
*/
|
|
16
|
+
export const AGENT_TOOL_FAILURE_CODES = Object.freeze({
|
|
17
|
+
argumentInvalid: 'ARGUMENT_INVALID',
|
|
18
|
+
toolUnknown: 'TOOL_UNKNOWN',
|
|
19
|
+
ruleUnknown: 'RULE_UNKNOWN',
|
|
20
|
+
typeUnknown: 'TYPE_UNKNOWN',
|
|
21
|
+
connectorUnknown: 'CONNECTOR_UNKNOWN',
|
|
22
|
+
positionUnknown: 'POSITION_UNKNOWN',
|
|
23
|
+
exampleNoMatch: 'EXAMPLE_NO_MATCH',
|
|
24
|
+
rootUnavailable: 'ROOT_UNAVAILABLE',
|
|
25
|
+
rootUnsupported: 'ROOT_UNSUPPORTED',
|
|
26
|
+
rootConflict: 'ROOT_CONFLICT',
|
|
27
|
+
discoveryUnavailable: 'DISCOVERY_UNAVAILABLE',
|
|
28
|
+
discoveryCancelled: 'DISCOVERY_CANCELLED',
|
|
29
|
+
projectNotFound: 'PROJECT_NOT_FOUND',
|
|
30
|
+
projectSelectorInvalid: 'PROJECT_SELECTOR_INVALID',
|
|
31
|
+
projectUnknown: 'PROJECT_UNKNOWN',
|
|
32
|
+
projectAmbiguous: 'PROJECT_AMBIGUOUS',
|
|
33
|
+
knowledgeAbsent: 'KNOWLEDGE_ABSENT',
|
|
34
|
+
knowledgeFileMissing: 'KNOWLEDGE_FILE_MISSING',
|
|
35
|
+
knowledgeUnreadable: 'KNOWLEDGE_UNREADABLE',
|
|
36
|
+
knowledgeMalformedJson: 'KNOWLEDGE_MALFORMED_JSON',
|
|
37
|
+
knowledgeMalformedSurface: 'KNOWLEDGE_MALFORMED_SURFACE',
|
|
38
|
+
knowledgeMalformedIndex: 'KNOWLEDGE_MALFORMED_INDEX',
|
|
39
|
+
knowledgeMalformedManifest: 'KNOWLEDGE_MALFORMED_MANIFEST',
|
|
40
|
+
knowledgeIntegrityFailed: 'KNOWLEDGE_INTEGRITY_FAILED',
|
|
41
|
+
preparationIncomplete: 'PREPARATION_INCOMPLETE',
|
|
42
|
+
handlerPrecondition: 'HANDLER_PRECONDITION',
|
|
43
|
+
unexpectedFault: 'UNEXPECTED_FAULT',
|
|
44
|
+
});
|
|
45
|
+
/** Scope meaning shared by every Host that validates the selected Project as one composed profile. */
|
|
46
|
+
export const AGENT_COMPOSED_PROJECT_SCOPE_DESCRIPTION = 'The selected Project composed from its main.yaml through partials, includes, inheritance and variable substitution, then validated as one composed profile.';
|
|
47
|
+
/** A typed expected host/handler precondition, never an unexpected implementation exception. */
|
|
31
48
|
export class AgentToolPreconditionError extends Error {
|
|
49
|
+
failure;
|
|
50
|
+
code;
|
|
51
|
+
constructor(failure) {
|
|
52
|
+
super(failure.message);
|
|
53
|
+
this.failure = failure;
|
|
54
|
+
this.name = 'AgentToolPreconditionError';
|
|
55
|
+
this.code = failure.code;
|
|
56
|
+
}
|
|
32
57
|
}
|
|
33
|
-
export const NOT_INSTALLED = 'No HexaSync knowledge is available for this question. Run **HexaSync: Install IntelliSense** or use a product ' +
|
|
58
|
+
export const NOT_INSTALLED = 'No HexaSync knowledge is available for this question. Run **HexaSync IDE: Install IntelliSense** or use a product ' +
|
|
34
59
|
'distribution with bundled knowledge. Do not guess at identifiers meanwhile.';
|
|
35
|
-
export const MALFORMED_SURFACE = 'The selected HexaSync knowledge surface is malformed
|
|
60
|
+
export const MALFORMED_SURFACE = 'The selected HexaSync knowledge surface is malformed. Repair the selected installation or product ' +
|
|
36
61
|
'distribution, and do not guess at identifiers meanwhile.';
|
|
37
62
|
export const MALFORMED_INDEX = 'The selected HexaSync index is malformed — it has no `## Collections` section. Repair the knowledge surface.';
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
63
|
+
export function agentToolFailure(failure) {
|
|
64
|
+
const candidates = failure.candidates?.slice(0, 20);
|
|
65
|
+
const suffix = candidates === undefined || candidates.length === 0 ? '' :
|
|
66
|
+
'\n' + candidates.map((project) => `- ${project.name}: \`${project.id}\` (\`${project.root}\`)`).join('\n');
|
|
67
|
+
return { text: failure.message + suffix, isError: true, code: failure.code,
|
|
68
|
+
state: failure.code === AGENT_TOOL_FAILURE_CODES.preparationIncomplete ? 'Incomplete' : 'Unavailable',
|
|
69
|
+
...(candidates === undefined ? {} : { candidates }) };
|
|
70
|
+
}
|
|
71
|
+
const success = (text, provenance) => ({ text, isError: false, ...(provenance === undefined ? {} : { provenance }) });
|
|
72
|
+
const failed = (code, message) => agentToolFailure({ code, message });
|
|
73
|
+
function parseJson(raw, code = AGENT_TOOL_FAILURE_CODES.knowledgeMalformedJson) {
|
|
45
74
|
try {
|
|
46
75
|
return JSON.parse(raw);
|
|
47
76
|
}
|
|
48
77
|
catch {
|
|
49
|
-
|
|
78
|
+
throw new AgentToolPreconditionError({ code, message: 'The selected HexaSync knowledge JSON is malformed. Repair the selected surface.' });
|
|
50
79
|
}
|
|
51
80
|
}
|
|
52
81
|
const InstalledBundleStamp = z.object({ assetBundleVersion: z.number().int().positive() });
|
|
53
|
-
|
|
54
|
-
* The footer that tells an agent WHERE the answer came from, so that "read more" means reading this copy.
|
|
55
|
-
*
|
|
56
|
-
* The bundle number comes from the install manifest, read through the same host, so it is the installed copy's
|
|
57
|
-
* stamp and not the running extension's.
|
|
58
|
-
*/
|
|
59
|
-
export async function installedLocationFooter(host) {
|
|
82
|
+
async function installedEvidence(host) {
|
|
60
83
|
const location = host.installedLocation?.();
|
|
61
84
|
if (location === undefined)
|
|
62
|
-
return '';
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
})
|
|
85
|
+
return { footer: '' };
|
|
86
|
+
const raw = await host.readInstalled('.install-manifest.json');
|
|
87
|
+
if (raw === undefined)
|
|
88
|
+
return {
|
|
89
|
+
provenance: { source: 'installed', location },
|
|
90
|
+
footer: `\n\nKnowledge source: local workspace \`${location}\`; no content version declared.`,
|
|
91
|
+
};
|
|
92
|
+
const manifest = InstalledBundleStamp.safeParse(parseJson(raw, AGENT_TOOL_FAILURE_CODES.knowledgeMalformedManifest));
|
|
93
|
+
if (!manifest.success)
|
|
94
|
+
throw new AgentToolPreconditionError({
|
|
95
|
+
code: AGENT_TOOL_FAILURE_CODES.knowledgeMalformedManifest,
|
|
96
|
+
message: 'The selected install manifest is malformed. Its asset bundle version cannot be verified.',
|
|
97
|
+
});
|
|
98
|
+
const version = `asset bundle ${manifest.data.assetBundleVersion}`;
|
|
99
|
+
return {
|
|
100
|
+
provenance: { source: 'installed', location, version },
|
|
101
|
+
footer: `\n\n---\nInstalled knowledge surface (${version}): \`${location}\`\n` +
|
|
102
|
+
'Worker step schema: `steps/step.json` · frontend step schema: `frontend/steps/step.json` · ' +
|
|
103
|
+
'step contracts: `steps/inputs.json` · docs: `docs/`.\n' +
|
|
104
|
+
'When you need more than this answer, read the files HERE — never the extension\'s source or its `assets/`, ' +
|
|
105
|
+
'and never a `.hexasync/` belonging to another workspace.',
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/** Also used by non-Tool consumers; provenance rendering remains service-owned. */
|
|
109
|
+
export async function installedLocationFooter(host) {
|
|
110
|
+
return (await installedEvidence(host)).footer;
|
|
111
|
+
}
|
|
112
|
+
const StepInputs = z.object({ contracts: z.record(z.object({
|
|
113
|
+
fields: z.record(z.string()).optional(), argumentFields: z.record(z.string()).optional(), note: z.string().optional(),
|
|
114
|
+
rules: z.array(z.object({ whenBoth: z.string().optional(), whenNeither: z.string().optional(), note: z.string().optional() })).optional(),
|
|
115
|
+
})) });
|
|
79
116
|
const ConnectorRow = z.object({
|
|
80
|
-
systemCode: z.string().optional(),
|
|
81
|
-
|
|
82
|
-
systemId: z.string().optional(),
|
|
83
|
-
generation: z.unknown().optional(),
|
|
84
|
-
status: z.string().optional(),
|
|
117
|
+
systemCode: z.string().optional(), name: z.string().optional(), systemId: z.string().optional(),
|
|
118
|
+
generation: z.unknown().optional(), status: z.string().optional(),
|
|
85
119
|
}).refine((row) => row.systemCode !== undefined || row.name !== undefined);
|
|
86
|
-
const ConnectorCatalog = z.union([
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
features: z.array(z.string()),
|
|
96
|
-
connectors: z.array(z.string()),
|
|
97
|
-
entities: z.array(z.string()).optional(),
|
|
98
|
-
})),
|
|
99
|
-
});
|
|
120
|
+
const ConnectorCatalog = z.union([z.array(ConnectorRow), z.object({ connectors: z.array(ConnectorRow) })])
|
|
121
|
+
.transform((catalog) => Array.isArray(catalog) ? catalog : catalog.connectors);
|
|
122
|
+
const ExampleCatalog = z.object({ entries: z.array(z.object({
|
|
123
|
+
id: z.string(), kind: z.string(), summary: z.string(), features: z.array(z.string()),
|
|
124
|
+
connectors: z.array(z.string()), entities: z.array(z.string()).optional(),
|
|
125
|
+
path: z.string().min(1), body: z.string().min(1),
|
|
126
|
+
partials: z.array(z.object({ path: z.string().min(1), body: z.string().min(1) })),
|
|
127
|
+
context: z.string().min(1),
|
|
128
|
+
})) });
|
|
100
129
|
async function readKnowledge(host, relative) {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
130
|
+
let fallbackReason;
|
|
131
|
+
try {
|
|
132
|
+
const installed = await host.readInstalled(relative);
|
|
133
|
+
if (installed !== undefined) {
|
|
134
|
+
const compatible = relative === 'docs/AI-INDEX.md' ? orientationOpening(installed) !== undefined
|
|
135
|
+
: relative === 'steps/inputs.json' ? StepInputs.safeParse(parseJson(installed)).success
|
|
136
|
+
: relative === 'connectors/catalog.json' ? ConnectorCatalog.safeParse(parseJson(installed)).success
|
|
137
|
+
: relative === 'docs/examples.json' ? ExampleCatalog.safeParse(parseJson(installed)).success : true;
|
|
138
|
+
if (!compatible)
|
|
139
|
+
throw new AgentToolPreconditionError({
|
|
140
|
+
code: relative === 'docs/AI-INDEX.md' ? AGENT_TOOL_FAILURE_CODES.knowledgeMalformedIndex : AGENT_TOOL_FAILURE_CODES.knowledgeMalformedSurface,
|
|
141
|
+
message: relative === 'docs/AI-INDEX.md' ? MALFORMED_INDEX : MALFORMED_SURFACE,
|
|
142
|
+
});
|
|
143
|
+
return { text: installed, ...await installedEvidence(host) };
|
|
144
|
+
}
|
|
145
|
+
if (host.installedLocation?.() !== undefined)
|
|
146
|
+
fallbackReason = AGENT_TOOL_FAILURE_CODES.knowledgeFileMissing;
|
|
104
147
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
148
|
+
catch (error) {
|
|
149
|
+
if (!(error instanceof AgentToolPreconditionError))
|
|
150
|
+
throw error;
|
|
151
|
+
fallbackReason = error.code;
|
|
152
|
+
if (host.readBundled === undefined)
|
|
153
|
+
throw error;
|
|
108
154
|
}
|
|
109
155
|
const bundled = await host.readBundled?.(relative);
|
|
110
156
|
if (bundled === undefined)
|
|
111
|
-
throw new AgentToolPreconditionError(
|
|
157
|
+
throw new AgentToolPreconditionError({
|
|
158
|
+
code: fallbackReason ?? AGENT_TOOL_FAILURE_CODES.knowledgeAbsent,
|
|
159
|
+
message: fallbackReason === undefined ? NOT_INSTALLED : 'The selected workspace knowledge cannot answer this question and no compatible bundled reference is available.',
|
|
160
|
+
});
|
|
112
161
|
return {
|
|
113
162
|
text: bundled.text,
|
|
163
|
+
provenance: { source: 'bundled', location: bundled.uri, version: bundled.version, ...(fallbackReason === undefined ? {} : { fallbackReason }) },
|
|
114
164
|
footer: `\n\n---\nBundled product knowledge (${bundled.version}): \`${bundled.uri}\`.\n` +
|
|
115
165
|
'This is an embedded MCP resource, not a workspace installation. Read that resource for the full reference.',
|
|
116
166
|
};
|
|
117
167
|
}
|
|
118
|
-
/**
|
|
168
|
+
/** Validate from the very schema advertised by callers, then invoke the definition's actual semantic binding. */
|
|
119
169
|
export async function answerAgentTool(name, args, host) {
|
|
170
|
+
const rootAuthority = host.rootAuthority?.();
|
|
171
|
+
const withRoots = (answer) => rootAuthority === undefined ? answer : { ...answer, rootAuthority };
|
|
120
172
|
const tool = AGENT_TOOLS.find((entry) => entry.name === name);
|
|
121
173
|
if (tool === undefined)
|
|
122
|
-
return
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
174
|
+
return withRoots(failed(AGENT_TOOL_FAILURE_CODES.toolUnknown, `No tool named \`${name}\`.`));
|
|
175
|
+
if (args === null || typeof args !== 'object' || Array.isArray(args)) {
|
|
176
|
+
return withRoots(failed(AGENT_TOOL_FAILURE_CODES.argumentInvalid, 'Tool arguments must be an object.'));
|
|
177
|
+
}
|
|
178
|
+
for (const [key, property] of Object.entries(tool.inputSchema.properties)) {
|
|
179
|
+
const value = args[key];
|
|
180
|
+
const required = tool.inputSchema.required.includes(key);
|
|
181
|
+
if (value === undefined && !required)
|
|
126
182
|
continue;
|
|
127
|
-
const valid =
|
|
128
|
-
:
|
|
129
|
-
:
|
|
183
|
+
const valid = property.type === 'boolean' ? typeof value === 'boolean'
|
|
184
|
+
: property.type === 'integer' ? typeof value === 'number' && Number.isSafeInteger(value) && value >= property.minimum && value <= property.maximum
|
|
185
|
+
: property.type === 'array' ? Array.isArray(value) && value.every((entry) => typeof entry === 'string')
|
|
186
|
+
: typeof value === 'string' && /\S/.test(value);
|
|
130
187
|
if (!valid)
|
|
131
|
-
return
|
|
188
|
+
return withRoots(failed(AGENT_TOOL_FAILURE_CODES.argumentInvalid, `Invalid \`${key}\`: expected ${property.type === 'array' ? 'string[]' : property.type}${required ? ' (required)' : ''}.`));
|
|
132
189
|
}
|
|
190
|
+
let answer;
|
|
133
191
|
try {
|
|
134
|
-
|
|
192
|
+
answer = await tool.handler(args, host);
|
|
135
193
|
}
|
|
136
194
|
catch (error) {
|
|
137
|
-
if (error instanceof AgentToolPreconditionError)
|
|
138
|
-
|
|
195
|
+
if (!(error instanceof AgentToolPreconditionError))
|
|
196
|
+
throw error;
|
|
197
|
+
answer = agentToolFailure(error.failure);
|
|
198
|
+
}
|
|
199
|
+
const workspaceSourced = isWorkspaceSourcedAnswer(answer, name);
|
|
200
|
+
const result = withRoots({ ...answer, text: workspaceSourced ? encodeWorkspaceReference(answer.text)
|
|
201
|
+
: formatKnowledgeLinks(answer.text, host.knowledgeDocs?.()),
|
|
202
|
+
state: answer.state ?? (answer.isError ? answer.code === AGENT_TOOL_FAILURE_CODES.preparationIncomplete ? 'Incomplete' : 'Unavailable' : 'Complete') });
|
|
203
|
+
const textOffset = args['textOffset'];
|
|
204
|
+
if (typeof textOffset === 'number' && (textOffset > result.text.length ||
|
|
205
|
+
(textOffset > 0 && textOffset === result.text.length) ||
|
|
206
|
+
(textOffset > 0 && result.text.charCodeAt(textOffset - 1) >= 0xD800 && result.text.charCodeAt(textOffset - 1) <= 0xDBFF &&
|
|
207
|
+
result.text.charCodeAt(textOffset) >= 0xDC00 && result.text.charCodeAt(textOffset) <= 0xDFFF))) {
|
|
208
|
+
return withRoots(failed(AGENT_TOOL_FAILURE_CODES.argumentInvalid, 'Invalid `textOffset`: expected an offset within the answer at a Unicode boundary.'));
|
|
209
|
+
}
|
|
210
|
+
return result;
|
|
211
|
+
}
|
|
212
|
+
function pageOptions(args) {
|
|
213
|
+
return { offset: typeof args['offset'] === 'number' ? args['offset'] : 0,
|
|
214
|
+
limit: typeof args['limit'] === 'number' ? args['limit'] : args['full'] === true ? 500 : 50 };
|
|
215
|
+
}
|
|
216
|
+
function pageEvidence(offset, count, total, limit) {
|
|
217
|
+
return offset + count < total ? { state: 'Incomplete',
|
|
218
|
+
continuation: { offset: offset + count, limit, action: 'Repeat this Tool with the same filters and the supplied offset/limit.' } } : {};
|
|
219
|
+
}
|
|
220
|
+
// Callable definition bindings. Retrieval semantics remain in their existing owner modules.
|
|
221
|
+
const AI_INDEX_URI = 'hexasync://docs/AI-INDEX';
|
|
222
|
+
/** One `Documentation:` line from resolvable links; empty without a documentation index. */
|
|
223
|
+
function documentationLine(docs, uris) {
|
|
224
|
+
const unique = [...new Set(uris)];
|
|
225
|
+
return docs === undefined || unique.length === 0 ? '' : `Documentation: ${unique.map((uri) => markdownKnowledgeLink(uri, docs)).join(', ')}`;
|
|
226
|
+
}
|
|
227
|
+
/** The leading sections about a concept: its pages first, then its shallowest headings. */
|
|
228
|
+
const conceptLinks = (term, docs, limit) => docs === undefined ? [] : conceptHeadings(term, docs).slice(0, limit).map(headingLink);
|
|
229
|
+
export async function answerPosition(args, host) {
|
|
230
|
+
const docs = host.knowledgeDocs?.();
|
|
231
|
+
const known = POSITIONS;
|
|
232
|
+
const documentation = documentationLine(docs, conceptLinks('position', docs, 2));
|
|
233
|
+
if (args['position'] === undefined) {
|
|
234
|
+
const answers = known.map((each) => positionAnswer(resolveEnvironment({ position: each })));
|
|
235
|
+
return success([`${known.length} authoring positions. Ask again with \`position\` for the roots one of them has.`,
|
|
236
|
+
...answers.map((answer) => `- \`${answer.position}\` — ${answer.note.split('\n')[0]}`), documentation].filter(Boolean).join('\n\n'));
|
|
237
|
+
}
|
|
238
|
+
const position = String(args['position']);
|
|
239
|
+
if (!known.includes(position))
|
|
240
|
+
return failed(AGENT_TOOL_FAILURE_CODES.positionUnknown, `There is no position \`${position}\`. There are ${known.length}: ${known.map((each) => `\`${each}\``).join(', ')}.`);
|
|
241
|
+
const answer = positionAnswer(resolveEnvironment({ position: position }));
|
|
242
|
+
return { ...success([`${answer.position}\n\n${answer.note}`, documentation, JSON.stringify(answer, null, 2)].filter(Boolean).join('\n\n')),
|
|
243
|
+
position: answer };
|
|
244
|
+
}
|
|
245
|
+
export async function answerOrientation(_args, host) {
|
|
246
|
+
const knowledge = await readKnowledge(host, 'docs/AI-INDEX.md');
|
|
247
|
+
const opening = orientationOpening(knowledge.text);
|
|
248
|
+
return opening == null ? { ...failed(AGENT_TOOL_FAILURE_CODES.knowledgeMalformedIndex, MALFORMED_INDEX), provenance: knowledge.provenance }
|
|
249
|
+
: success(opening + knowledge.footer, knowledge.provenance);
|
|
250
|
+
}
|
|
251
|
+
/** Sections that cite a rule id, then the index's rule list — so every rule answer names somewhere to read on. */
|
|
252
|
+
function ruleDocumentation(id, docs) {
|
|
253
|
+
if (docs === undefined)
|
|
254
|
+
return '';
|
|
255
|
+
const mentions = id === undefined ? []
|
|
256
|
+
: mentioningSections(id, docs, (uri) => uri === AI_INDEX_URI || uri.startsWith(`${AI_INDEX_URI}/`)).slice(0, 3);
|
|
257
|
+
const list = docs.headings.find((heading) => heading.page === AI_INDEX_URI && /\brule ids?\b/iu.test(heading.text));
|
|
258
|
+
return documentationLine(docs, [...mentions, ...(list === undefined ? docs.text(AI_INDEX_URI) === undefined ? [] : [AI_INDEX_URI] : [headingLink(list)])]);
|
|
259
|
+
}
|
|
260
|
+
export async function answerRule(args, host) {
|
|
261
|
+
const id = String(args['id']).toUpperCase();
|
|
262
|
+
const answer = explainRule(id, { full: args['full'] === true });
|
|
263
|
+
const documentation = ruleDocumentation(answer.found ? id : undefined, host.knowledgeDocs?.());
|
|
264
|
+
const text = [`${answer.title}\n\n${answer.text}`, answer.more ?? '', documentation].filter(Boolean).join('\n\n');
|
|
265
|
+
return answer.found ? { ...success(text), ...(answer.more === undefined ? {} : {
|
|
266
|
+
state: 'Incomplete',
|
|
267
|
+
continuation: { action: 'Repeat this Tool with full: true for the complete entry. The 64 KiB response cap still applies.' },
|
|
268
|
+
}) } : failed(AGENT_TOOL_FAILURE_CODES.ruleUnknown, text);
|
|
269
|
+
}
|
|
270
|
+
/** The step schema from the same source as the contracts; a field's grammar links are an addition, never a failure. */
|
|
271
|
+
async function stepSchema(host, provenance) {
|
|
272
|
+
try {
|
|
273
|
+
const text = provenance?.source === 'installed' ? await host.readInstalled('steps/step.json')
|
|
274
|
+
: (await host.readBundled?.('steps/step.json'))?.text;
|
|
275
|
+
return text === undefined ? undefined : JSON.parse(text);
|
|
276
|
+
}
|
|
277
|
+
catch (error) {
|
|
278
|
+
if (error instanceof AgentToolPreconditionError || error instanceof SyntaxError)
|
|
279
|
+
return undefined;
|
|
139
280
|
throw error;
|
|
140
281
|
}
|
|
141
282
|
}
|
|
142
|
-
|
|
283
|
+
const FULL_CONTINUATION = {
|
|
284
|
+
state: 'Incomplete',
|
|
285
|
+
continuation: { action: 'Repeat this Tool with full: true for the complete entry. The 64 KiB response cap still applies.' },
|
|
286
|
+
};
|
|
287
|
+
/**
|
|
288
|
+
* A type, one of its fields (`QUERY_SINGLE.where`, `QUERY_SINGLE.data.where`), or a bare field or concept (`where`,
|
|
289
|
+
* `pagination`) across every type and documentation page. Unknown only when nothing of that name exists.
|
|
290
|
+
*/
|
|
291
|
+
export async function answerType(args, host) {
|
|
292
|
+
const knowledge = await readKnowledge(host, 'steps/inputs.json');
|
|
293
|
+
const asset = StepInputs.safeParse(parseJson(knowledge.text));
|
|
294
|
+
if (!asset.success)
|
|
295
|
+
return { ...failed(AGENT_TOOL_FAILURE_CODES.knowledgeMalformedSurface, MALFORMED_SURFACE), provenance: knowledge.provenance };
|
|
296
|
+
const contracts = asset.data.contracts;
|
|
297
|
+
const name = String(args['name']).trim();
|
|
143
298
|
const full = args['full'] === true;
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
const
|
|
164
|
-
const
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
if (name === 'hexasync_list_connectors') {
|
|
171
|
-
const knowledge = await readKnowledge(host, 'connectors/catalog.json');
|
|
172
|
-
const catalog = ConnectorCatalog.safeParse(parseJson(knowledge.text));
|
|
173
|
-
if (!catalog.success)
|
|
174
|
-
return result(MALFORMED_SURFACE, true);
|
|
175
|
-
const answer = connectorAnswer(catalog.data, {
|
|
176
|
-
...(args['code'] === undefined ? {} : { code: String(args['code']) }),
|
|
177
|
-
full,
|
|
299
|
+
const docs = host.knowledgeDocs?.();
|
|
300
|
+
const types = typeAnswers(contracts);
|
|
301
|
+
const found = (text, more) => ({ ...success(`${text}${knowledge.footer}`, knowledge.provenance), ...(more ? FULL_CONTINUATION : {}) });
|
|
302
|
+
const typed = explainType(name, types, { full });
|
|
303
|
+
if (typed.found) {
|
|
304
|
+
const schema = await stepSchema(host, knowledge.provenance);
|
|
305
|
+
return found([`${typed.title}\n\n${typed.text}`, typed.more ?? '', renderTypeDocs(typed.id, contracts[typed.id], schema, docs)]
|
|
306
|
+
.filter(Boolean).join('\n\n'), typed.more !== undefined);
|
|
307
|
+
}
|
|
308
|
+
const dot = name.indexOf('.');
|
|
309
|
+
const owner = dot > 0 ? explainType(name.slice(0, dot), types) : undefined;
|
|
310
|
+
if (owner?.found === true) {
|
|
311
|
+
const type = owner.id;
|
|
312
|
+
const contract = contracts[type];
|
|
313
|
+
const rest = name.slice(dot + 1);
|
|
314
|
+
const key = normalizedPath(rest);
|
|
315
|
+
const pick = (entries) => Object.entries(entries ?? {}).find(([field]) => field.toLowerCase() === key);
|
|
316
|
+
const data = /^arguments\./u.test(rest) ? undefined : pick(contract.fields);
|
|
317
|
+
const argument = data === undefined && !/^(?:data|input)\./u.test(rest) ? pick(contract.argumentFields) : undefined;
|
|
318
|
+
const schema = await stepSchema(host, knowledge.provenance);
|
|
319
|
+
const page = docs === undefined ? undefined : typePage(type, docs)?.page;
|
|
320
|
+
const path = argument !== undefined ? `arguments.${argument[0]}` : /^(?:data|input|arguments)\./u.test(rest) ? rest
|
|
321
|
+
: `data.${data?.[0] ?? rest}`;
|
|
322
|
+
const reference = fieldReference(type, path, {
|
|
323
|
+
...(data !== undefined ? { contract: data[1] } : argument !== undefined ? { contract: argument[1], argument: true } : {}),
|
|
324
|
+
...(page === undefined ? {} : { page }), schema, ...(docs === undefined ? {} : { docs }),
|
|
178
325
|
});
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
const
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
326
|
+
if (reference.contract !== undefined || reference.heading !== undefined) {
|
|
327
|
+
return found(`${type}.${normalizedPath(reference.path)}\n\n${renderFieldDetail(reference, docs)}`, false);
|
|
328
|
+
}
|
|
329
|
+
const fields = typeFields(type, contract, schema, docs);
|
|
330
|
+
return { ...failed(AGENT_TOOL_FAILURE_CODES.typeUnknown, [`No field ${name}`,
|
|
331
|
+
`**${type}** has no field \`${rest}\`. Its fields:`, ...fields.map((field) => renderFieldLine(field, docs)),
|
|
332
|
+
].join('\n\n')), provenance: knowledge.provenance };
|
|
333
|
+
}
|
|
334
|
+
const schema = await stepSchema(host, knowledge.provenance);
|
|
335
|
+
const matches = matchName(name, contracts, schema, docs);
|
|
336
|
+
if (matches.fields.length + matches.concepts.length > 0) {
|
|
337
|
+
const rendered = renderNameMatches(name, matches, docs, { full, detailLimit: 3, listLimit: 40 });
|
|
338
|
+
return found([`${name} — ${matches.fields.length} field${matches.fields.length === 1 ? '' : 's'}, ` +
|
|
339
|
+
`${matches.concepts.length} section${matches.concepts.length === 1 ? '' : 's'}`, rendered.text, rendered.more ?? '']
|
|
340
|
+
.filter(Boolean).join('\n\n'), rendered.more !== undefined);
|
|
341
|
+
}
|
|
342
|
+
const suggestions = suggestNames(name, contracts, docs);
|
|
343
|
+
return { ...failed(AGENT_TOOL_FAILURE_CODES.typeUnknown, [`No type ${name}`,
|
|
344
|
+
`There is no type, field or documented property \`${name}\`.` +
|
|
345
|
+
(suggestions.length === 0 ? '' : ` Closest: ${suggestions.map((each) => `\`${each}\``).join(', ')}.`),
|
|
346
|
+
`Every type, collection and page is listed in ${docs === undefined ? `<${AI_INDEX_URI}>` : markdownKnowledgeLink(AI_INDEX_URI, docs)}.`,
|
|
347
|
+
].join('\n\n')), provenance: knowledge.provenance };
|
|
348
|
+
}
|
|
349
|
+
export async function answerConnectors(args, host) {
|
|
350
|
+
const knowledge = await readKnowledge(host, 'connectors/catalog.json');
|
|
351
|
+
const catalog = ConnectorCatalog.safeParse(parseJson(knowledge.text));
|
|
352
|
+
if (!catalog.success)
|
|
353
|
+
return { ...failed(AGENT_TOOL_FAILURE_CODES.knowledgeMalformedSurface, MALFORMED_SURFACE), provenance: knowledge.provenance };
|
|
354
|
+
const page = pageOptions(args);
|
|
355
|
+
const supported = catalog.data.filter((row) => row.systemCode);
|
|
356
|
+
const shown = supported.slice(page.offset, page.offset + page.limit);
|
|
357
|
+
const answer = connectorAnswer(args['code'] === undefined ? shown : catalog.data, { ...(args['code'] === undefined ? {} : { code: String(args['code']) }), full: true });
|
|
358
|
+
const title = args['code'] === undefined ? `${supported.length} connectors; showing ${shown.length} at offset ${page.offset}` : answer.title;
|
|
359
|
+
const documentation = documentationLine(host.knowledgeDocs?.(), conceptLinks('connector', host.knowledgeDocs?.(), 2));
|
|
360
|
+
const text = [`${title}\n\n${answer.text}`, answer.more ?? '', documentation].filter(Boolean).join('\n\n') + knowledge.footer;
|
|
361
|
+
return answer.found ? { ...success(text, knowledge.provenance),
|
|
362
|
+
...(args['code'] === undefined ? pageEvidence(page.offset, shown.length, supported.length, page.limit) : {}) }
|
|
363
|
+
: { ...failed(AGENT_TOOL_FAILURE_CODES.connectorUnknown, text), provenance: knowledge.provenance };
|
|
364
|
+
}
|
|
365
|
+
export async function answerExamples(args, host) {
|
|
366
|
+
const knowledge = await readKnowledge(host, 'docs/examples.json');
|
|
367
|
+
const catalog = ExampleCatalog.safeParse(parseJson(knowledge.text));
|
|
368
|
+
if (!catalog.success)
|
|
369
|
+
return { ...failed(AGENT_TOOL_FAILURE_CODES.knowledgeMalformedSurface, MALFORMED_SURFACE), provenance: knowledge.provenance };
|
|
370
|
+
const answer = searchExamples({
|
|
371
|
+
...(args['kind'] === undefined ? {} : { kind: String(args['kind']) }),
|
|
372
|
+
...(args['feature'] === undefined ? {} : { feature: String(args['feature']) }),
|
|
373
|
+
...(args['connector'] === undefined ? {} : { connector: String(args['connector']) }),
|
|
374
|
+
...(args['entity'] === undefined ? {} : { entity: String(args['entity']) }),
|
|
375
|
+
}, catalog.data.entries, { full: args['full'] === true, ...pageOptions(args) });
|
|
376
|
+
const text = `${answer.title}\n\n${answer.text}${answer.more ? `\n\n${answer.more}` : ''}${knowledge.footer}`;
|
|
377
|
+
return answer.found ? { ...success(text, knowledge.provenance),
|
|
378
|
+
...(answer.more === undefined ? {} : { state: 'Incomplete',
|
|
379
|
+
continuation: { offset: pageOptions(args).offset + (answer.returnedItems ?? 0), limit: pageOptions(args).limit, action: 'Repeat this Tool with the same filters and the supplied offset/limit.' } }) }
|
|
380
|
+
: { ...failed(AGENT_TOOL_FAILURE_CODES.exampleNoMatch, text), provenance: knowledge.provenance };
|
|
381
|
+
}
|
|
382
|
+
export async function answerValidation(args, host) {
|
|
383
|
+
const preparation = await host.prepareProject(args['project'] === undefined ? {} : { project: String(args['project']) });
|
|
384
|
+
if (preparation.status === 'failed')
|
|
385
|
+
return agentToolFailure(preparation.failure);
|
|
386
|
+
const found = findingsTouching(preparation.findings, args['changedFiles'] ?? []);
|
|
387
|
+
const page = pageOptions(args);
|
|
388
|
+
const shown = found.slice(page.offset, page.offset + page.limit);
|
|
389
|
+
const unavailableFiles = preparation.unavailableFiles ?? [];
|
|
390
|
+
const discoveryIncomplete = preparation.discoveryIncomplete === true;
|
|
391
|
+
const scope = discoveryIncomplete || unavailableFiles.length > 0
|
|
392
|
+
? { ...preparation.scope, completeness: 'incomplete' } : preparation.scope;
|
|
393
|
+
const incomplete = scope.completeness === 'incomplete';
|
|
394
|
+
const preparationNote = [
|
|
395
|
+
discoveryIncomplete ? 'Project discovery is incomplete: some descriptors could not be read.' : '',
|
|
396
|
+
unavailableFiles.length > 0 ? `Documents unavailable for validation: ${unavailableFiles.slice(0, 20).map(({ file, reason, detail }) => `${file} (${reason}${detail === undefined ? '' : `: ${detail}`})`).join('; ')}.` : '',
|
|
397
|
+
preparation.scope.kind === 'indexed-diagnostics'
|
|
398
|
+
? 'Run `hexasync.composeProject` (HexaSync IDE: Compose Current Project) or `hexasync.composeAndPreview` (HexaSync IDE: Compose and Preview) for the whole project, then run `hexasync_validate`; read the report, fix every issue, and re-validate before reporting success. A template that composes is not necessarily correct; never claim success without validation.' : '',
|
|
399
|
+
].filter(Boolean).join(' ');
|
|
400
|
+
const text = `Project: ${preparation.project.name} (\`${preparation.project.id}\`)\n` +
|
|
401
|
+
`Scope: ${scope.kind}; ${scope.completeness}. ${scope.description}\n\n` +
|
|
402
|
+
renderFindings(shown, { full: true, total: found.length, offset: page.offset, emptyNote: incomplete
|
|
403
|
+
? 'Incomplete: no findings in the prepared scope. This is not proof that the whole project has no findings.'
|
|
404
|
+
: 'No findings in the validated scope.' }) + (preparationNote === '' ? '' : `\n\n${preparationNote}`);
|
|
405
|
+
const evidence = {
|
|
406
|
+
project: preparation.project, scope, findings: shown, totalFindings: found.length,
|
|
407
|
+
...pageEvidence(page.offset, shown.length, found.length, page.limit),
|
|
408
|
+
unavailableFiles, discoveryIncomplete,
|
|
409
|
+
};
|
|
410
|
+
return incomplete ? { text, isError: true, code: AGENT_TOOL_FAILURE_CODES.preparationIncomplete, ...evidence }
|
|
411
|
+
: { text, isError: false, ...evidence };
|
|
199
412
|
}
|
|
200
413
|
export const VALIDATE_PAGE = 50;
|
|
414
|
+
/** Kept for existing non-Tool consumers; the Tool orchestration now calls this itself. */
|
|
201
415
|
export function renderFindings(found, options) {
|
|
202
|
-
|
|
416
|
+
const total = options.total ?? found.length;
|
|
417
|
+
if (total === 0)
|
|
203
418
|
return options.emptyNote;
|
|
204
419
|
const shown = options.full ? found : found.slice(0, VALIDATE_PAGE);
|
|
420
|
+
const offset = options.offset ?? 0;
|
|
205
421
|
return [
|
|
206
|
-
`${
|
|
422
|
+
`${total} finding${total === 1 ? '' : 's'} in the validated scope:`,
|
|
423
|
+
...(shown.length === 0 ? [`No findings on this page (offset ${offset}); choose an offset below ${total}.`] : []),
|
|
207
424
|
...shown.map((finding) => `- [${finding.ruleId}] ${finding.message} (${finding.sourceFile}:${finding.line})`),
|
|
208
|
-
...(shown.length <
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
'',
|
|
212
|
-
'Fix these, run this again, and only then report success.',
|
|
213
|
-
'',
|
|
214
|
-
JSON.stringify({ findings: shown, total: found.length }, null, 2),
|
|
425
|
+
...(shown.length < total ? [options.total === undefined
|
|
426
|
+
? `Showing ${shown.length} of ${total}. Ask again with \`full: true\` for the rest.`
|
|
427
|
+
: `Showing ${shown.length} of ${total} at offset ${offset}.`] : []),
|
|
428
|
+
'', 'Fix these, run this again, and only then report success.', '', JSON.stringify({ findings: shown, total }, null, 2),
|
|
215
429
|
].join('\n');
|
|
216
430
|
}
|
|
217
431
|
//# sourceMappingURL=answerAgentTool.js.map
|