@theoremjs/agents 0.3.5-next.902.g334d23a → 0.3.5-next.904.g8358918
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/esm/src/kernel/registry/kernel-registry.js +2 -2
- package/esm/src/kernel/registry/profiles.d.ts +3 -1
- package/esm/src/kernel/registry/profiles.js +10 -1
- package/esm/src/kernel/registry/resolve.js +6 -1
- package/esm/src/kernel/registry/schemas.js +2 -0
- package/esm/src/kernel/tools/execute.js +9 -6
- package/esm/src/kernel/tools/model-view.d.ts +18 -0
- package/esm/src/kernel/tools/model-view.js +204 -0
- package/esm/src/kernel/tools/registry.d.ts +4 -1
- package/esm/src/kernel/tools/registry.js +5 -1
- package/esm/src/kernel/tools/remote.d.ts +6 -2
- package/esm/src/kernel/tools/remote.js +16 -11
- package/package.json +1 -1
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { createProviderRegistry } from '../protocols/provider.js';
|
|
2
2
|
import { createToolRegistry } from '../tools/registry.js';
|
|
3
|
-
import { createProfileRegistry } from './profiles.js';
|
|
3
|
+
import { createProfileRegistry, structuredReplySchemas } from './profiles.js';
|
|
4
4
|
import { createSchemaRegistry } from './schemas.js';
|
|
5
5
|
/** Creates an empty registry of tools, profiles, and schemas, wired so a tool that names a profile can find it. */
|
|
6
6
|
function createKernelRegistry() {
|
|
7
7
|
// why: An agent tool names a profile, and a profile allows tools: each registry reads
|
|
8
8
|
// the other. Tools look profiles up only when one registers, after both exist.
|
|
9
|
-
const tools = createToolRegistry((id) => profiles.find(id));
|
|
10
9
|
const schemas = createSchemaRegistry();
|
|
10
|
+
const tools = createToolRegistry((id) => profiles.find(id), (id) => structuredReplySchemas(schemas, profiles.find(id)));
|
|
11
11
|
const providers = createProviderRegistry();
|
|
12
12
|
const profiles = createProfileRegistry(tools, schemas, providers);
|
|
13
13
|
return { tools, profiles, schemas, providers };
|
|
@@ -258,6 +258,8 @@ declare function defineProfile(input: EmbeddingProfileDefinition): EmbeddingProf
|
|
|
258
258
|
declare function defineProfile(input: Exclude<ProfileDefinition, LiveProfileDefinition | HostProfileDefinition>): Exclude<Profile, LiveProfile | HostProfile>;
|
|
259
259
|
/** Validate any definition and return the profile. */
|
|
260
260
|
declare function defineProfile(input: ProfileDefinition): Profile;
|
|
261
|
+
/** The reply schemas a profile can give, for the agent tools that call it. */
|
|
262
|
+
declare function structuredReplySchemas(schemas: SchemaRegistry, profile: Profile | undefined): Record<string, unknown>[];
|
|
261
263
|
/** A set of registered profiles, kept by id. */
|
|
262
264
|
interface ProfileRegistry {
|
|
263
265
|
register(profileInput: Profile | ProfileDefinition): void;
|
|
@@ -272,4 +274,4 @@ interface ProfileRegistry {
|
|
|
272
274
|
/** Profiles are checked against `tools` and `schemas`, so register a scope's tools and schemas before its profiles. */
|
|
273
275
|
declare function createProfileRegistry(tools: ToolRegistry, schemas: SchemaRegistry, providers?: ProviderRegistry): ProfileRegistry;
|
|
274
276
|
export type { ProfileRegistry };
|
|
275
|
-
export { createProfileRegistry, defineProfile };
|
|
277
|
+
export { createProfileRegistry, defineProfile, structuredReplySchemas };
|
|
@@ -699,6 +699,15 @@ function structuredIds(profile) {
|
|
|
699
699
|
return [structured];
|
|
700
700
|
return [...new Set([...Object.values(structured.map), structured.fallback])];
|
|
701
701
|
}
|
|
702
|
+
/** The reply schemas a profile can give, for the agent tools that call it. */
|
|
703
|
+
function structuredReplySchemas(schemas, profile) {
|
|
704
|
+
if (profile?.type !== 'text')
|
|
705
|
+
return [];
|
|
706
|
+
return structuredIds(profile).flatMap((id) => {
|
|
707
|
+
const spec = schemas.find(id);
|
|
708
|
+
return spec ? [spec.jsonSchema] : [];
|
|
709
|
+
});
|
|
710
|
+
}
|
|
702
711
|
/**
|
|
703
712
|
* Every schema `outputs.structured` names is registered, and every
|
|
704
713
|
* `outputs.validation.fields` path reaches a property of one of them.
|
|
@@ -808,4 +817,4 @@ function createProfileRegistry(tools, schemas, providers) {
|
|
|
808
817
|
clear: () => profiles.clear(),
|
|
809
818
|
};
|
|
810
819
|
}
|
|
811
|
-
export { createProfileRegistry, defineProfile };
|
|
820
|
+
export { createProfileRegistry, defineProfile, structuredReplySchemas };
|
|
@@ -8,6 +8,7 @@ import { ANSWER_TOOL } from '../answer-tool.js';
|
|
|
8
8
|
import { DEFAULT_MAX_STEPS } from '../profile-presence.js';
|
|
9
9
|
import { operationNameOf } from '../protocols/binding.js';
|
|
10
10
|
import { profileTurnResumption } from '../stop.js';
|
|
11
|
+
import { withoutModelMarks } from '../tools/model-view.js';
|
|
11
12
|
import { projectTools } from '../tools/project.js';
|
|
12
13
|
import { resolveTurnTools } from '../tools/resolve.js';
|
|
13
14
|
import { profileInputs, requireModelBinding } from './catalog.js';
|
|
@@ -207,7 +208,11 @@ function resolveTurnInRegistry(registry, req, model) {
|
|
|
207
208
|
history: input.history,
|
|
208
209
|
maxSteps: profile.maxSteps ?? DEFAULT_MAX_STEPS,
|
|
209
210
|
structured: structuredId
|
|
210
|
-
? {
|
|
211
|
+
? {
|
|
212
|
+
id: structuredId,
|
|
213
|
+
// why: The mark is for the agent tools that read this reply; the provider never sees it.
|
|
214
|
+
jsonSchema: withoutModelMarks(registry.schemas.get(structuredId).jsonSchema),
|
|
215
|
+
}
|
|
211
216
|
: null,
|
|
212
217
|
image: resolveImageFormat(profile),
|
|
213
218
|
speech: resolveSpeech(profile, safe),
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { TheoremError } from '../../guardrails/error.js';
|
|
2
|
+
import { assertModelMarks } from '../tools/model-view.js';
|
|
2
3
|
/** Creates an empty schema registry; `register` rejects a spec that still carries the removed `enforced` field. */
|
|
3
4
|
function createSchemaRegistry() {
|
|
4
5
|
const schemas = new Map();
|
|
@@ -12,6 +13,7 @@ function createSchemaRegistry() {
|
|
|
12
13
|
Array.isArray(spec.jsonSchema)) {
|
|
13
14
|
throw new TheoremError('config', `registerStructured '${id}': jsonSchema must be a JSON Schema object`);
|
|
14
15
|
}
|
|
16
|
+
assertModelMarks(spec.jsonSchema, `registerStructured '${id}'`, 'output');
|
|
15
17
|
schemas.set(id, spec);
|
|
16
18
|
},
|
|
17
19
|
get(id) {
|
|
@@ -18,6 +18,7 @@ import { dispatchToolBody, failedActivity, failedActivityOf, failureEvent, messa
|
|
|
18
18
|
import { HandlerEvents } from './handler-events.js';
|
|
19
19
|
import { fetchToolImages } from './image-fetch.js';
|
|
20
20
|
import { formatToolFailureForModel, formatToolResult, frameToolFailure } from './model-text.js';
|
|
21
|
+
import { agentOutputSchema, outputForModel } from './model-view.js';
|
|
21
22
|
import { operationBroken, operationWireValue } from './operation.js';
|
|
22
23
|
import { checkPermission, gateDetails, isGateResumeDenied, isGateResumeGranted, isResumeContinuation, } from './permission.js';
|
|
23
24
|
import { executeHttpTool, executeMcpTool, failureWithoutSecret, modelResultFromOutput, omitSecret, outcomeFromUnauth, parseToolOutput, refusedCredentialOutcome, resolveToolAuth, withMedia, } from './remote.js';
|
|
@@ -117,14 +118,15 @@ export function projectForModel(tool, output, labels) {
|
|
|
117
118
|
if (tool.exposeToModel === false) {
|
|
118
119
|
return { finding: labelText('tool.completed_hidden', {}, labels) };
|
|
119
120
|
}
|
|
121
|
+
const seen = outputForModel(tool.outputSchema, output);
|
|
120
122
|
if (isAwaitingUserInput(output)) {
|
|
121
123
|
return {
|
|
122
124
|
finding: labelText('tool.awaiting_user', { kind: output.kind, prompt: output.prompt }, labels),
|
|
123
|
-
data: leanToolResultData(
|
|
125
|
+
data: leanToolResultData(seen),
|
|
124
126
|
};
|
|
125
127
|
}
|
|
126
|
-
const parts = isRecord(
|
|
127
|
-
const lean = leanToolResultData(
|
|
128
|
+
const parts = isRecord(seen) && 'parts' in seen ? coerceToolResultParts(seen.parts) : undefined;
|
|
129
|
+
const lean = leanToolResultData(seen);
|
|
128
130
|
const summarized = isRecord(lean) && 'finding' in lean;
|
|
129
131
|
const { finding: summary, ...rest } = summarized ? lean : {};
|
|
130
132
|
const result = summarized
|
|
@@ -132,7 +134,7 @@ export function projectForModel(tool, output, labels) {
|
|
|
132
134
|
finding: String(summary),
|
|
133
135
|
...(Object.keys(rest).length > 0 ? { data: rest } : {}),
|
|
134
136
|
}
|
|
135
|
-
: modelResultFromOutput(lean);
|
|
137
|
+
: modelResultFromOutput(lean, undefined);
|
|
136
138
|
return { ...result, ...(parts ? { parts } : {}) };
|
|
137
139
|
}
|
|
138
140
|
function loadsT2(tool, ctx) {
|
|
@@ -754,7 +756,7 @@ async function* settleBodyOutcome(args) {
|
|
|
754
756
|
labels: tool.labels,
|
|
755
757
|
reproject: makeReproject((v) => parseToolOutput(tool.output, v),
|
|
756
758
|
// why: A hook's edit replaces the value; the media the tool returned stays.
|
|
757
|
-
(data) => withMedia(modelResultFromOutput(data), outcome.modelResult.parts), labels),
|
|
759
|
+
(data) => withMedia(modelResultFromOutput(data, tool.outputSchema), outcome.modelResult.parts), labels),
|
|
758
760
|
});
|
|
759
761
|
}
|
|
760
762
|
function turnReadBack({ modelResult }) {
|
|
@@ -1129,7 +1131,8 @@ async function* executeAgentTool(args) {
|
|
|
1129
1131
|
}
|
|
1130
1132
|
};
|
|
1131
1133
|
// why: Its hooks take `AgentToolInput`, which the input schema has already checked.
|
|
1132
|
-
const
|
|
1134
|
+
const outputSchema = agentOutputSchema(tool.outputSchema, args.tools.structuredReplies(tool.profile));
|
|
1135
|
+
const asFunction = { ...tool, type: 'function', handler, outputSchema };
|
|
1133
1136
|
const exec = executeFunction(args.tools, asFunction, args.safeInput, ctx, base, args.snapshot, args.stages, tool, args.beginBody);
|
|
1134
1137
|
for (;;) {
|
|
1135
1138
|
const next = await exec.next();
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { JsonSchema } from './schema.js';
|
|
2
|
+
/** The schema with the mark taken off every field: the mark is Theorem's, never a provider's. */
|
|
3
|
+
export declare function withoutModelMarks(schema: JsonSchema): JsonSchema;
|
|
4
|
+
/**
|
|
5
|
+
* Refuses a mark the kernel cannot honour: one that is not `false`, one on the whole output,
|
|
6
|
+
* and any on an input, which the model fills itself.
|
|
7
|
+
*/
|
|
8
|
+
export declare function assertModelMarks(schema: JsonSchema, where: string, io: 'input' | 'output'): void;
|
|
9
|
+
/**
|
|
10
|
+
* The output as the model reads it: every field whose schema says `exposeToModel: false` is left
|
|
11
|
+
* out, at any depth. The output itself is not changed.
|
|
12
|
+
*/
|
|
13
|
+
export declare function outputForModel(schema: JsonSchema | undefined, output: unknown): unknown;
|
|
14
|
+
/**
|
|
15
|
+
* An agent tool's output schema with `structured` read as any reply schema the called agent can
|
|
16
|
+
* give, so a field one of them marks is kept from the calling model.
|
|
17
|
+
*/
|
|
18
|
+
export declare function agentOutputSchema(outputSchema: JsonSchema, structured: readonly JsonSchema[]): JsonSchema;
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { TheoremError } from '../../guardrails/error.js';
|
|
2
|
+
/** The keyword on an output field's schema that keeps the field from the model. */
|
|
3
|
+
const MODEL_MARK = 'exposeToModel';
|
|
4
|
+
const SCHEMA_MAPS = ['properties', 'patternProperties', '$defs', 'definitions'];
|
|
5
|
+
const SCHEMA_LISTS = ['allOf', 'anyOf', 'oneOf', 'prefixItems'];
|
|
6
|
+
const SCHEMA_ONE = [
|
|
7
|
+
'items',
|
|
8
|
+
'additionalProperties',
|
|
9
|
+
'additionalItems',
|
|
10
|
+
'not',
|
|
11
|
+
'contains',
|
|
12
|
+
'propertyNames',
|
|
13
|
+
'if',
|
|
14
|
+
'then',
|
|
15
|
+
'else',
|
|
16
|
+
];
|
|
17
|
+
function isSchema(value) {
|
|
18
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
19
|
+
}
|
|
20
|
+
/** Every schema inside `schema`, itself first, with its JSON Pointer from the root. */
|
|
21
|
+
function* eachSchema(schema, at = '#') {
|
|
22
|
+
if (!isSchema(schema))
|
|
23
|
+
return;
|
|
24
|
+
yield [schema, at];
|
|
25
|
+
for (const key of SCHEMA_MAPS) {
|
|
26
|
+
const map = schema[key];
|
|
27
|
+
if (!isSchema(map))
|
|
28
|
+
continue;
|
|
29
|
+
for (const [name, child] of Object.entries(map))
|
|
30
|
+
yield* eachSchema(child, `${at}/${key}/${name}`);
|
|
31
|
+
}
|
|
32
|
+
for (const key of [...SCHEMA_LISTS, ...SCHEMA_ONE]) {
|
|
33
|
+
const child = schema[key];
|
|
34
|
+
if (Array.isArray(child)) {
|
|
35
|
+
for (const [index, entry] of child.entries())
|
|
36
|
+
yield* eachSchema(entry, `${at}/${key}/${index}`);
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
yield* eachSchema(child, `${at}/${key}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Whether any field of the schema carries the mark. */
|
|
44
|
+
function hasModelMark(schema) {
|
|
45
|
+
for (const [node] of eachSchema(schema)) {
|
|
46
|
+
if (Object.hasOwn(node, MODEL_MARK))
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
/** The schema with the mark taken off every field: the mark is Theorem's, never a provider's. */
|
|
52
|
+
export function withoutModelMarks(schema) {
|
|
53
|
+
if (!hasModelMark(schema))
|
|
54
|
+
return schema;
|
|
55
|
+
const copy = structuredClone(schema);
|
|
56
|
+
for (const [node] of eachSchema(copy))
|
|
57
|
+
delete node[MODEL_MARK];
|
|
58
|
+
return copy;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Refuses a mark the kernel cannot honour: one that is not `false`, one on the whole output,
|
|
62
|
+
* and any on an input, which the model fills itself.
|
|
63
|
+
*/
|
|
64
|
+
export function assertModelMarks(schema, where, io) {
|
|
65
|
+
const refuse = (at, problem) => {
|
|
66
|
+
throw new TheoremError('config', `${where} at ${at}: ${problem}`); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
|
|
67
|
+
};
|
|
68
|
+
for (const [node, at] of eachSchema(schema)) {
|
|
69
|
+
if (!Object.hasOwn(node, MODEL_MARK))
|
|
70
|
+
continue;
|
|
71
|
+
if (io === 'input') {
|
|
72
|
+
// labels-exempt: developer contract — a registration error, not end-user or model copy
|
|
73
|
+
refuse(at, `${MODEL_MARK} marks output fields only; the model fills every input field`);
|
|
74
|
+
}
|
|
75
|
+
if (node[MODEL_MARK] !== false) {
|
|
76
|
+
// labels-exempt: developer contract — a registration error, not end-user or model copy
|
|
77
|
+
refuse(at, `${MODEL_MARK} takes false only`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (io === 'output' && hidden(nodesAt(schema, schema))) {
|
|
81
|
+
refuse('#',
|
|
82
|
+
// labels-exempt: developer contract — a registration error, not end-user or model copy
|
|
83
|
+
`${MODEL_MARK}: false on the whole output hides every field; set exposeToModel: false on the tool instead`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function resolvePointer(root, ref) {
|
|
87
|
+
if (!ref.startsWith('#'))
|
|
88
|
+
return undefined;
|
|
89
|
+
let node = root;
|
|
90
|
+
for (const raw of ref.slice(1).split('/').slice(1)) {
|
|
91
|
+
const key = decodeURIComponent(raw).replaceAll('~1', '/').replaceAll('~0', '~');
|
|
92
|
+
node =
|
|
93
|
+
isSchema(node) || Array.isArray(node) ? node[key] : undefined;
|
|
94
|
+
}
|
|
95
|
+
return isSchema(node) ? node : undefined;
|
|
96
|
+
}
|
|
97
|
+
/** The schemas that apply to one value: a reference followed, every branch of a combinator opened. */
|
|
98
|
+
function nodesAt(schema, root, seen = new Set()) {
|
|
99
|
+
if (!isSchema(schema) || seen.has(schema))
|
|
100
|
+
return [];
|
|
101
|
+
seen.add(schema);
|
|
102
|
+
const nodes = [{ schema, root }];
|
|
103
|
+
if (typeof schema.$ref === 'string') {
|
|
104
|
+
nodes.push(...nodesAt(resolvePointer(root, schema.$ref), root, seen));
|
|
105
|
+
}
|
|
106
|
+
for (const key of ['allOf', 'anyOf', 'oneOf']) {
|
|
107
|
+
const branches = schema[key];
|
|
108
|
+
if (Array.isArray(branches)) {
|
|
109
|
+
for (const branch of branches)
|
|
110
|
+
nodes.push(...nodesAt(branch, root, seen));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return nodes;
|
|
114
|
+
}
|
|
115
|
+
/** invariant: A field one branch of a union marks is kept from the model in every branch. */
|
|
116
|
+
function hidden(nodes) {
|
|
117
|
+
return nodes.some((node) => node.schema[MODEL_MARK] === false);
|
|
118
|
+
}
|
|
119
|
+
function childNodes(nodes, pick) {
|
|
120
|
+
return nodes.flatMap((node) => nodesAt(pick(node.schema), node.root));
|
|
121
|
+
}
|
|
122
|
+
function propertyNodes(nodes, key) {
|
|
123
|
+
return childNodes(nodes, (schema) => {
|
|
124
|
+
const props = schema.properties;
|
|
125
|
+
if (isSchema(props) && Object.hasOwn(props, key))
|
|
126
|
+
return props[key];
|
|
127
|
+
const patterns = schema.patternProperties;
|
|
128
|
+
if (isSchema(patterns)) {
|
|
129
|
+
const match = Object.entries(patterns).find(([pattern]) => new RegExp(pattern, 'u').test(key));
|
|
130
|
+
if (match)
|
|
131
|
+
return match[1];
|
|
132
|
+
}
|
|
133
|
+
return schema.additionalProperties;
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
function itemNodes(nodes, index) {
|
|
137
|
+
return childNodes(nodes, (schema) => {
|
|
138
|
+
const tuple = Array.isArray(schema.prefixItems)
|
|
139
|
+
? schema.prefixItems
|
|
140
|
+
: Array.isArray(schema.items)
|
|
141
|
+
? schema.items
|
|
142
|
+
: undefined;
|
|
143
|
+
if (tuple)
|
|
144
|
+
return index < tuple.length ? tuple[index] : (schema.additionalItems ?? schema.items);
|
|
145
|
+
return schema.items;
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
function cut(value, nodes) {
|
|
149
|
+
if (nodes.length === 0)
|
|
150
|
+
return value;
|
|
151
|
+
if (Array.isArray(value)) {
|
|
152
|
+
return value.flatMap((item, index) => {
|
|
153
|
+
const children = itemNodes(nodes, index);
|
|
154
|
+
return hidden(children) ? [] : [cut(item, children)];
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
if (isSchema(value)) {
|
|
158
|
+
const kept = {};
|
|
159
|
+
for (const [key, child] of Object.entries(value)) {
|
|
160
|
+
const children = propertyNodes(nodes, key);
|
|
161
|
+
if (!hidden(children))
|
|
162
|
+
kept[key] = cut(child, children);
|
|
163
|
+
}
|
|
164
|
+
return kept;
|
|
165
|
+
}
|
|
166
|
+
return value;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* The output as the model reads it: every field whose schema says `exposeToModel: false` is left
|
|
170
|
+
* out, at any depth. The output itself is not changed.
|
|
171
|
+
*/
|
|
172
|
+
export function outputForModel(schema, output) {
|
|
173
|
+
if (!schema || !hasModelMark(schema))
|
|
174
|
+
return output;
|
|
175
|
+
return cut(output, nodesAt(schema, schema));
|
|
176
|
+
}
|
|
177
|
+
function prefixRefs(schema, base) {
|
|
178
|
+
const copy = structuredClone(schema);
|
|
179
|
+
for (const [node] of eachSchema(copy)) {
|
|
180
|
+
if (typeof node.$ref === 'string' && node.$ref.startsWith('#')) {
|
|
181
|
+
node.$ref = `${base}${node.$ref.slice(1)}`;
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return copy;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* An agent tool's output schema with `structured` read as any reply schema the called agent can
|
|
188
|
+
* give, so a field one of them marks is kept from the calling model.
|
|
189
|
+
*/
|
|
190
|
+
export function agentOutputSchema(outputSchema, structured) {
|
|
191
|
+
const marked = structured.filter(hasModelMark);
|
|
192
|
+
if (marked.length === 0)
|
|
193
|
+
return outputSchema;
|
|
194
|
+
const defs = Object.fromEntries(marked.map((spec, index) => [`reply${index}`, prefixRefs(spec, `#/$defs/reply${index}`)]));
|
|
195
|
+
const properties = isSchema(outputSchema.properties) ? outputSchema.properties : {};
|
|
196
|
+
return {
|
|
197
|
+
...outputSchema,
|
|
198
|
+
properties: {
|
|
199
|
+
...properties,
|
|
200
|
+
structured: { anyOf: marked.map((_, index) => ({ $ref: `#/$defs/reply${index}` })) },
|
|
201
|
+
},
|
|
202
|
+
$defs: { ...(isSchema(outputSchema.$defs) ? outputSchema.$defs : {}), ...defs },
|
|
203
|
+
};
|
|
204
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Profile, ProfileId } from '../types.js';
|
|
2
2
|
import { type ToolBackground } from './background.js';
|
|
3
3
|
import { type McpSessionCache } from './mcp-sessions.js';
|
|
4
|
+
import { type JsonSchema } from './schema.js';
|
|
4
5
|
import type { FunctionToolDef, HttpToolDef, McpToolDef, RegisteredTool, ToolDefinitionInput } from './types.js';
|
|
5
6
|
/** The settings of a tool's definition that are plain values: every check `register` makes without running or converting anything. */
|
|
6
7
|
declare function assertToolSettings(def: Pick<HttpToolDef, 'name'> & Partial<Pick<HttpToolDef, 'endpoint' | 'auth' | 'mapping' | 'limit' | 'timeoutMs'> & Pick<HttpToolDef, 'maxResponseBytes' | 'imageLimits'> & Pick<McpToolDef, 'session'> & Pick<FunctionToolDef, 'answeredBy'>> & {
|
|
@@ -19,6 +20,8 @@ interface ToolRegistry {
|
|
|
19
20
|
list(): RegisteredTool[];
|
|
20
21
|
/** A profile in this scope, for the agent tools that run one. */
|
|
21
22
|
findProfile(id: ProfileId): Profile | undefined;
|
|
23
|
+
/** The reply schemas a profile in this scope can give, read when an agent tool's call settles. */
|
|
24
|
+
structuredReplies(id: ProfileId): JsonSchema[];
|
|
22
25
|
/** Also forgets the MCP sessions. */
|
|
23
26
|
reset(): void;
|
|
24
27
|
/** Sessions for this scope's MCP servers that require one; never shared across scopes. */
|
|
@@ -28,6 +31,6 @@ interface ToolRegistry {
|
|
|
28
31
|
* Registration is not synchronized: register a scope's tools before its turns or invokes run.
|
|
29
32
|
* `findProfile` is the scope's profiles, which an agent tool names; without it none registers.
|
|
30
33
|
*/
|
|
31
|
-
declare function createToolRegistry(findProfile?: (id: ProfileId) => Profile | undefined): ToolRegistry;
|
|
34
|
+
declare function createToolRegistry(findProfile?: (id: ProfileId) => Profile | undefined, structuredReplies?: (id: ProfileId) => JsonSchema[]): ToolRegistry;
|
|
32
35
|
export type { ToolRegistry };
|
|
33
36
|
export { assertToolSettings, createToolRegistry };
|
|
@@ -6,6 +6,7 @@ import { agentToolInputFor, agentToolOutput, agentToolProfile, normalizeAgent }
|
|
|
6
6
|
import { assertBackgroundSetting, backgroundField } from './background.js';
|
|
7
7
|
import { withCallOrder, withModelField } from './call-order.js';
|
|
8
8
|
import { createMcpSessionCache } from './mcp-sessions.js';
|
|
9
|
+
import { assertModelMarks } from './model-view.js';
|
|
9
10
|
import { pageAnswerHandler } from './page-answer.js';
|
|
10
11
|
import { assertFixedEndpointOrigin, jsonSchemaFromZod, validateToolSchema, } from './schema.js';
|
|
11
12
|
/** Each zod pair's JSON Schemas, as converted and checked: a zod schema is never changed. */
|
|
@@ -31,6 +32,8 @@ function checkedSchemas(input, output) {
|
|
|
31
32
|
function schemasFromZod(def) {
|
|
32
33
|
// why: A studio compile registers each tool once for every agent that uses it, again on each edit that settles.
|
|
33
34
|
const { inputSchema, outputSchema } = checkedSchemas(def.input, def.output);
|
|
35
|
+
assertModelMarks(inputSchema, `Tool "${def.name}" input`, 'input');
|
|
36
|
+
assertModelMarks(outputSchema, `Tool "${def.name}" output`, 'output');
|
|
34
37
|
const labels = {
|
|
35
38
|
activity: { input: inputSchema },
|
|
36
39
|
activityPast: { input: inputSchema, output: outputSchema },
|
|
@@ -188,7 +191,7 @@ function normalizeDefinition(def, findProfile, findTool) {
|
|
|
188
191
|
* Registration is not synchronized: register a scope's tools before its turns or invokes run.
|
|
189
192
|
* `findProfile` is the scope's profiles, which an agent tool names; without it none registers.
|
|
190
193
|
*/
|
|
191
|
-
function createToolRegistry(findProfile = () => undefined) {
|
|
194
|
+
function createToolRegistry(findProfile = () => undefined, structuredReplies = () => []) {
|
|
192
195
|
const tools = new Map();
|
|
193
196
|
const mcpSessions = createMcpSessionCache();
|
|
194
197
|
const get = (name) => tools.get(name);
|
|
@@ -211,6 +214,7 @@ function createToolRegistry(findProfile = () => undefined) {
|
|
|
211
214
|
has: (name) => tools.has(name),
|
|
212
215
|
list: () => [...tools.values()],
|
|
213
216
|
findProfile,
|
|
217
|
+
structuredReplies,
|
|
214
218
|
reset: () => {
|
|
215
219
|
tools.clear();
|
|
216
220
|
mcpSessions.clear();
|
|
@@ -5,6 +5,7 @@ import { type ToolCallBase } from './events.js';
|
|
|
5
5
|
import type { HandlerEvents } from './handler-events.js';
|
|
6
6
|
import { type McpSessionCache } from './mcp-sessions.js';
|
|
7
7
|
import type { ToolOperationClaim } from './operation.js';
|
|
8
|
+
import { type JsonSchema } from './schema.js';
|
|
8
9
|
import { type ToolStageSupport } from './stage-run.js';
|
|
9
10
|
import type { HttpToolDef, McpToolDef, ModelToolResult, ToolAuthConfig, ToolBodyOutcome, ToolContext, ToolFailure, ToolGate } from './types.js';
|
|
10
11
|
export type AuthResolveResult = {
|
|
@@ -65,8 +66,11 @@ export declare function parseToolOutput<T>(schema: {
|
|
|
65
66
|
flatten: () => unknown;
|
|
66
67
|
};
|
|
67
68
|
};
|
|
68
|
-
/**
|
|
69
|
-
|
|
69
|
+
/**
|
|
70
|
+
* Not repeated as `data`, which `composeToolText` would append a second time. A field the tool's
|
|
71
|
+
* output schema marks `exposeToModel: false` is left out.
|
|
72
|
+
*/
|
|
73
|
+
export declare function modelResultFromOutput(data: unknown, outputSchema: JsonSchema | undefined): ModelToolResult;
|
|
70
74
|
/** The result with the media a tool returned beside its value, when it returned any. */
|
|
71
75
|
export declare function withMedia(result: ModelToolResult, parts: InteractionPart[] | undefined): ModelToolResult;
|
|
72
76
|
/** `sent`: the service refused a request the call already sent, so the call has started. */
|
|
@@ -7,6 +7,7 @@ import { mapStrings } from '../engine/tree.js';
|
|
|
7
7
|
import { dispatchToolBody, guardToolTarget, messageOf, networkBlocked, networkBlockedEvent, requestChecks, startToolExecution, toolEvent, toolNetworkPolicy, } from './events.js';
|
|
8
8
|
import { answeredIn, takeLimitPlace } from './http-limit.js';
|
|
9
9
|
import { createMcpSessionCache, isMcpSessionId, mcpSessionKey, } from './mcp-sessions.js';
|
|
10
|
+
import { outputForModel } from './model-view.js';
|
|
10
11
|
import { checkPermission, gateDetails } from './permission.js';
|
|
11
12
|
import { assertFixedEndpointOrigin } from './schema.js';
|
|
12
13
|
import { runPreToolPipeline } from './stage-run.js';
|
|
@@ -250,9 +251,13 @@ export function parseToolOutput(schema, responseData) {
|
|
|
250
251
|
}
|
|
251
252
|
return checked;
|
|
252
253
|
}
|
|
253
|
-
/**
|
|
254
|
-
|
|
255
|
-
|
|
254
|
+
/**
|
|
255
|
+
* Not repeated as `data`, which `composeToolText` would append a second time. A field the tool's
|
|
256
|
+
* output schema marks `exposeToModel: false` is left out.
|
|
257
|
+
*/
|
|
258
|
+
export function modelResultFromOutput(data, outputSchema) {
|
|
259
|
+
const seen = outputForModel(outputSchema, data);
|
|
260
|
+
return { finding: typeof seen === 'string' ? seen : JSON.stringify(seen) };
|
|
256
261
|
}
|
|
257
262
|
/** The result with the media a tool returned beside its value, when it returned any. */
|
|
258
263
|
export function withMedia(result, parts) {
|
|
@@ -501,7 +506,7 @@ export function failureWithoutSecret(failure, secret) {
|
|
|
501
506
|
};
|
|
502
507
|
}
|
|
503
508
|
/** An echo endpoint or debug page can repeat the credential; it must never reach the model, trace, or client. */
|
|
504
|
-
function withoutSecret(outcome, secret) {
|
|
509
|
+
function withoutSecret(outcome, secret, outputSchema) {
|
|
505
510
|
if (!secret)
|
|
506
511
|
return outcome;
|
|
507
512
|
if (outcome.kind === 'ok') {
|
|
@@ -509,7 +514,7 @@ function withoutSecret(outcome, secret) {
|
|
|
509
514
|
return {
|
|
510
515
|
kind: 'ok',
|
|
511
516
|
outputRaw,
|
|
512
|
-
modelResult: withMedia(modelResultFromOutput(outputRaw), outcome.modelResult.parts),
|
|
517
|
+
modelResult: withMedia(modelResultFromOutput(outputRaw, outputSchema), outcome.modelResult.parts),
|
|
513
518
|
};
|
|
514
519
|
}
|
|
515
520
|
if (outcome.kind === 'failed') {
|
|
@@ -527,12 +532,12 @@ export function audienceMismatch(audience, url) {
|
|
|
527
532
|
* An OAuth token goes only to the resource it was issued for (RFC 8707); any other target gets no
|
|
528
533
|
* request. `send` gets the URL with any key the tool puts in the query, after the target's checks.
|
|
529
534
|
*/
|
|
530
|
-
async function* sendWithCredential(prepared, url, send) {
|
|
535
|
+
async function* sendWithCredential(prepared, outputSchema, url, send) {
|
|
531
536
|
const mismatch = audienceMismatch(prepared.audience, url);
|
|
532
537
|
if (mismatch) {
|
|
533
538
|
return failureOutcome({ code: 'credential_audience_mismatch', kind: 'config', message: mismatch }, true);
|
|
534
539
|
}
|
|
535
|
-
return withoutSecret(yield* send(withCredentialQuery(url, prepared.query)), prepared.secret);
|
|
540
|
+
return withoutSecret(yield* send(withCredentialQuery(url, prepared.query)), prepared.secret, outputSchema);
|
|
536
541
|
}
|
|
537
542
|
/**
|
|
538
543
|
* Order: schema → permission → auth → preTool/host stages → body. `shown` takes the body while it
|
|
@@ -563,7 +568,7 @@ export async function* executeHttpTool(tool, rawInput, ctx, base, stages, beginB
|
|
|
563
568
|
if (!guarded.ok)
|
|
564
569
|
return failureOutcome(guarded.failure, true);
|
|
565
570
|
const handOff = yield* dispatchToolBody(tool, input, ctx, base, beginBody);
|
|
566
|
-
return yield* sendWithCredential(prepared, guarded.url, (url) => sendHttpRequest(tool, url, target.body, prepared, ctx, base, stages?.span, shown, handOff));
|
|
571
|
+
return yield* sendWithCredential(prepared, tool.outputSchema, guarded.url, (url) => sendHttpRequest(tool, url, target.body, prepared, ctx, base, stages?.span, shown, handOff));
|
|
567
572
|
}
|
|
568
573
|
/** A body that is text, read so far: what a successful call's drafts show. */
|
|
569
574
|
function isDraftable(response) {
|
|
@@ -633,7 +638,7 @@ async function* sendHttpRequest(tool, targetUrl, body, { authHeaders, secret },
|
|
|
633
638
|
}
|
|
634
639
|
return {
|
|
635
640
|
kind: 'ok',
|
|
636
|
-
modelResult: modelResultFromOutput(checked.data),
|
|
641
|
+
modelResult: modelResultFromOutput(checked.data, tool.outputSchema),
|
|
637
642
|
outputRaw: checked.data,
|
|
638
643
|
};
|
|
639
644
|
}
|
|
@@ -1089,7 +1094,7 @@ sessions = createMcpSessionCache(), beginBody) {
|
|
|
1089
1094
|
if (!('ok' in prepared))
|
|
1090
1095
|
return prepared;
|
|
1091
1096
|
const handOff = yield* dispatchToolBody(tool, prepared.input, ctx, base, beginBody);
|
|
1092
|
-
return yield* sendWithCredential(prepared, guarded.url, (url) => sendMcpRequest(tool, url, prepared.input, prepared, ctx, base, stages?.span, sessions, handOff));
|
|
1097
|
+
return yield* sendWithCredential(prepared, tool.outputSchema, guarded.url, (url) => sendMcpRequest(tool, url, prepared.input, prepared, ctx, base, stages?.span, sessions, handOff));
|
|
1093
1098
|
}
|
|
1094
1099
|
async function* sendMcpRequest(tool, url, input, { authHeaders, secret }, ctx, base, span, sessions, handOff) {
|
|
1095
1100
|
const checks = requestChecks(span);
|
|
@@ -1141,7 +1146,7 @@ async function* sendMcpRequest(tool, url, input, { authHeaders, secret }, ctx, b
|
|
|
1141
1146
|
}
|
|
1142
1147
|
return {
|
|
1143
1148
|
kind: 'ok',
|
|
1144
|
-
modelResult: withMedia(modelResultFromOutput(interpreted.data), interpreted.parts),
|
|
1149
|
+
modelResult: withMedia(modelResultFromOutput(interpreted.data, tool.outputSchema), interpreted.parts),
|
|
1145
1150
|
outputRaw: interpreted.data,
|
|
1146
1151
|
};
|
|
1147
1152
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theoremjs/agents",
|
|
3
|
-
"version": "0.3.5-next.
|
|
3
|
+
"version": "0.3.5-next.904.g8358918",
|
|
4
4
|
"description": "A flat TypeScript agent kernel for typed profiles, deterministic turn execution, registered tools, provider adapters, guardrails, and host-injected traces.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent",
|