@asterism-app/sdk 2.2.1 → 2.4.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.
- package/README.md +2 -26
- package/docs/data-and-lifecycle.md +18 -40
- package/docs/getting-started.md +20 -28
- package/docs/manual.md +4 -10
- package/docs/resources-and-tools.md +15 -39
- package/docs/views-and-settings.md +3 -3
- package/docs/visual-language.md +2 -2
- package/examples/counter/package.json +1 -1
- package/package.json +1 -1
- package/src/content-runtime.ts +2 -0
- package/src/contracts.ts +1 -0
- package/src/model-catalog.ts +6 -1
- package/src/model-records.ts +7 -2
- package/src/models.ts +22 -12
- package/src/module-contract.ts +44 -12
- package/src/reference-urls.ts +6 -0
- package/src/renderer-content.ts +2 -0
- package/src/renderer-services.ts +2 -2
- package/src/renderer-tools.ts +75 -22
- package/src/runtime-contracts.ts +22 -6
- package/src/runtime-execution.ts +7 -1
- package/src/runtime-resources.ts +44 -17
- package/src/runtime-tools.ts +26 -9
- package/src/tool-validation.ts +40 -8
- package/src/usage-subjects.ts +34 -0
- package/docs/minimal-plugin.md +0 -33
- package/docs/project-structure.md +0 -37
package/src/module-contract.ts
CHANGED
|
@@ -12,12 +12,10 @@ export type ToolInput = JsonObject | null;
|
|
|
12
12
|
/** The transport supplies JSON values; this schema constrains only their root shape. */
|
|
13
13
|
export const toolInputSchema = z.looseObject({}).nullable() as z.ZodType<ToolInput>;
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
interface ToolMetadata extends ContractReference {
|
|
16
16
|
name: string;
|
|
17
17
|
description: string;
|
|
18
18
|
guidelines: readonly string[];
|
|
19
|
-
/** Structured parameters; a tool determines its fields and whether null is accepted. */
|
|
20
|
-
argsSchema: z.ZodType<A>;
|
|
21
19
|
/** Execution requires an endpoint that can receive user interaction. Output rendering alone does not require it. */
|
|
22
20
|
requiresInteraction?: boolean;
|
|
23
21
|
/**
|
|
@@ -27,16 +25,35 @@ export interface ToolContract<A extends ToolInput = ToolInput> extends ContractR
|
|
|
27
25
|
*/
|
|
28
26
|
requiresNotice?: boolean;
|
|
29
27
|
}
|
|
30
|
-
|
|
31
|
-
|
|
28
|
+
export interface StructuredToolContract<A extends ToolInput = ToolInput> extends ToolMetadata {
|
|
29
|
+
kind?: "structured";
|
|
30
|
+
/** Structured parameters; a tool determines its fields and whether null is accepted. */
|
|
31
|
+
argsSchema: z.ZodType<A>;
|
|
32
|
+
}
|
|
33
|
+
export interface FreeformToolContract extends ToolMetadata {
|
|
34
|
+
kind: "freeform";
|
|
35
|
+
argsSchema?: never;
|
|
36
|
+
}
|
|
37
|
+
export type ToolContract<A extends ToolInput = ToolInput> = StructuredToolContract<A> | FreeformToolContract;
|
|
38
|
+
|
|
39
|
+
interface ImplementationMetadata<S extends Json, O extends Json> extends DataContract<O> {
|
|
32
40
|
resource: ResourceContract<S>;
|
|
33
|
-
tool: ToolContract<A>;
|
|
34
|
-
/** Structured selection within the resource; each implementation determines whether null is accepted. */
|
|
35
|
-
targetSchema: z.ZodType<T>;
|
|
36
41
|
effect: "read" | "write";
|
|
37
42
|
/** Sequential operations share submission order; parallel operations can overlap either lane. */
|
|
38
43
|
execution: "parallel" | "sequential";
|
|
39
44
|
}
|
|
45
|
+
/** Implementations of structured tools add a target schema; freeform implementations receive the original text. */
|
|
46
|
+
export interface StructuredImplementationContract<S extends Json, T extends ToolInput, A extends ToolInput, O extends Json> extends ImplementationMetadata<S, O> {
|
|
47
|
+
tool: StructuredToolContract<A>;
|
|
48
|
+
/** Structured selection within the resource; each implementation determines whether null is accepted. */
|
|
49
|
+
targetSchema: z.ZodType<T>;
|
|
50
|
+
}
|
|
51
|
+
export interface FreeformImplementationContract<S extends Json, O extends Json> extends ImplementationMetadata<S, O> {
|
|
52
|
+
tool: FreeformToolContract;
|
|
53
|
+
targetSchema?: never;
|
|
54
|
+
}
|
|
55
|
+
export type ImplementationContract<S extends Json, T extends ToolInput, A extends ToolInput, O extends Json> =
|
|
56
|
+
StructuredImplementationContract<S, T, A, O> | FreeformImplementationContract<S, O>;
|
|
40
57
|
export function defineResource<S extends Json>(kind: string, stateSchema: z.ZodType<S>): ResourceContract<S> {
|
|
41
58
|
return { kind, stateSchema };
|
|
42
59
|
}
|
|
@@ -45,16 +62,31 @@ function requireDescription(schema: z.ZodType, subject: string): void {
|
|
|
45
62
|
if (!schema.description?.trim()) throw new Error(`Missing schema description: ${subject}`);
|
|
46
63
|
try { z.toJSONSchema(schema); } catch (error) { throw new Error(`Schema is not representable as JSON Schema: ${subject}`, { cause: error }); }
|
|
47
64
|
}
|
|
48
|
-
export function defineTool<A extends ToolInput>(definition:
|
|
65
|
+
export function defineTool<A extends ToolInput>(definition: StructuredToolContract<A>): StructuredToolContract<A>;
|
|
66
|
+
export function defineTool(definition: FreeformToolContract): FreeformToolContract;
|
|
67
|
+
export function defineTool(definition: ToolContract): ToolContract;
|
|
68
|
+
export function defineTool(definition: ToolContract): ToolContract {
|
|
49
69
|
if (!definition.name.trim() || !definition.description.trim()) throw new Error("Tool name and description must not be empty.");
|
|
50
70
|
if (definition.guidelines.some(guideline => !guideline.trim())) throw new Error(`Empty tool guideline: ${definition.name}`);
|
|
51
|
-
|
|
71
|
+
if (definition.kind === "freeform") {
|
|
72
|
+
if (/\s/.test(definition.name)) throw new Error(`Freeform tool names must be a single token: ${definition.name}`);
|
|
73
|
+
if ("argsSchema" in definition) throw new Error(`Freeform tools do not declare an args schema: ${definition.name}`);
|
|
74
|
+
} else requireDescription(definition.argsSchema, `${definition.name}.args`);
|
|
52
75
|
return { ...definition, ...contractReferenceSchema.parse({ id: definition.id }), guidelines: [...definition.guidelines] };
|
|
53
76
|
}
|
|
77
|
+
export function defineImplementation<S extends Json, T extends ToolInput, A extends ToolInput, O extends Json>(
|
|
78
|
+
definition: StructuredImplementationContract<S, T, A, O>,
|
|
79
|
+
): StructuredImplementationContract<S, T, A, O>;
|
|
80
|
+
export function defineImplementation<S extends Json, O extends Json>(
|
|
81
|
+
definition: FreeformImplementationContract<S, O>,
|
|
82
|
+
): FreeformImplementationContract<S, O>;
|
|
54
83
|
export function defineImplementation<S extends Json, T extends ToolInput, A extends ToolInput, O extends Json>(
|
|
55
84
|
definition: ImplementationContract<S, T, A, O>,
|
|
56
|
-
): ImplementationContract<S, T, A, O
|
|
57
|
-
|
|
85
|
+
): ImplementationContract<S, T, A, O>;
|
|
86
|
+
export function defineImplementation(definition: ImplementationContract<Json, ToolInput, ToolInput, Json>) {
|
|
87
|
+
if (definition.tool.kind === "freeform") {
|
|
88
|
+
if ("targetSchema" in definition) throw new Error(`Freeform tools do not declare a target schema: ${definition.id}`);
|
|
89
|
+
} else requireDescription(definition.targetSchema!, `${definition.id}.target`);
|
|
58
90
|
requireDescription(definition.schema, `${definition.id}.result`);
|
|
59
91
|
return definition;
|
|
60
92
|
}
|
package/src/reference-urls.ts
CHANGED
|
@@ -58,3 +58,9 @@ export function parseModelUrl(value: string): ModelExpression | null {
|
|
|
58
58
|
export function referenceMarkdown(label: string, url: string): string {
|
|
59
59
|
return `[${label.replace(/[\r\n]+/gu, " ").replace(/[\\[\]]/gu, "\\$&")}](${url})`;
|
|
60
60
|
}
|
|
61
|
+
|
|
62
|
+
/** Markdown links whose destination uses a reference scheme; the label is unescaped. Destinations are not parsed further. */
|
|
63
|
+
export function* referenceLinks(text: string): Generator<{ index: number; length: number; label: string; url: string }> {
|
|
64
|
+
for (const match of text.matchAll(/\[((?:\\[^\r\n]|[^\\\]\r\n])*)\]\(((?:resource|skill|model):[^()\s]+)\)/gu))
|
|
65
|
+
yield { index: match.index, length: match[0].length, label: match[1]!.replace(/\\([\\[\]])/gu, "$1"), url: match[2]! };
|
|
66
|
+
}
|
package/src/renderer-content.ts
CHANGED
|
@@ -4,6 +4,8 @@ import type { ContentReader } from "./content-runtime.ts";
|
|
|
4
4
|
/** The host binds input drafts to contracts; business input carries only ContentRef. The host closes drafts after command success and preserves them for retry after failure. */
|
|
5
5
|
export interface RendererContentInput extends ContentReader {
|
|
6
6
|
stage(source: Blob | Uint8Array, options?: { signal?: AbortSignal; progress?(bytes: number, total: number): void }): Promise<ContentRef>;
|
|
7
|
+
/** Release this draft's hold on the reference. Captured submissions and persistent references are unaffected. */
|
|
8
|
+
release(ref: ContentRef): Promise<void>;
|
|
7
9
|
close(): Promise<void>;
|
|
8
10
|
}
|
|
9
11
|
export interface RendererInputOptions { content?: RendererContentInput }
|
package/src/renderer-services.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { Json } from "./json.ts";
|
|
|
3
3
|
import type { DataContract } from "./presentation.ts";
|
|
4
4
|
import type { ConfigContract } from "./config.ts";
|
|
5
5
|
import type { ModelLiveBlock } from "./models.ts";
|
|
6
|
-
import type {
|
|
6
|
+
import type { AnyToolRenderProps, ToolView } from "./renderer-tools.ts";
|
|
7
7
|
import type { EventSubscriber } from "./events.ts";
|
|
8
8
|
import type { ResourceDescription } from "./renderer.ts";
|
|
9
9
|
import type { UiText } from "./i18n.ts";
|
|
@@ -15,7 +15,7 @@ export interface RendererResources {
|
|
|
15
15
|
}
|
|
16
16
|
export interface RendererCatalogs { get<T extends Json>(contract: DataContract<T>): T | null; error: UiText | null }
|
|
17
17
|
export interface RendererTools {
|
|
18
|
-
resolve(props:
|
|
18
|
+
resolve(props: AnyToolRenderProps): ToolView & { props: AnyToolRenderProps };
|
|
19
19
|
preparation(name: string): string;
|
|
20
20
|
/** Localized name of a tool by its model-facing name and implementation contract; null when no view declares one. */
|
|
21
21
|
label(name: string, implementation: string | null): string | null;
|
package/src/renderer-tools.ts
CHANGED
|
@@ -2,21 +2,25 @@ import { createElement, type ComponentType, type ReactNode } from "react";
|
|
|
2
2
|
import type { z } from "zod";
|
|
3
3
|
import type { UiText } from "./i18n.ts";
|
|
4
4
|
import type { Json } from "./json.ts";
|
|
5
|
+
import type { ToolInputDraft } from "./models.ts";
|
|
5
6
|
import { reference, type ContractReference, type DataContract } from "./presentation.ts";
|
|
6
7
|
import type { ToolCompletion, ToolInvocationInfo, ToolResult } from "./tool-result.ts";
|
|
7
8
|
|
|
8
|
-
interface
|
|
9
|
+
interface ToolIdentityProps {
|
|
9
10
|
name: string;
|
|
11
|
+
invocation: ToolInvocationInfo;
|
|
12
|
+
}
|
|
13
|
+
interface ToolCallProps<T, A> extends ToolIdentityProps {
|
|
14
|
+
kind?: "structured";
|
|
10
15
|
target: T;
|
|
11
16
|
args: A;
|
|
12
|
-
invocation: ToolInvocationInfo;
|
|
13
17
|
}
|
|
14
|
-
/** Partial JSON has not passed the argument contract
|
|
18
|
+
/** Partial JSON has not passed the argument contract. */
|
|
15
19
|
export interface ToolInputRenderProps extends ToolCallProps<Json, Json> {
|
|
16
20
|
phase: "input";
|
|
17
21
|
result: null;
|
|
18
|
-
/** Original unfinished input; the host derives a display-only
|
|
19
|
-
|
|
22
|
+
/** Original unfinished input; the host derives a display-only preview when resolving the view. */
|
|
23
|
+
draft?: ToolInputDraft | null;
|
|
20
24
|
}
|
|
21
25
|
/** Waiting for scheduling and execution share a view; complete arguments have passed contract validation. */
|
|
22
26
|
export interface ToolExecutionRenderProps<D = Json, T = Json, A = Json> extends ToolCallProps<T, A> {
|
|
@@ -30,6 +34,18 @@ export interface ToolResultRenderProps<D = Json, T = Json, A = Json> extends Too
|
|
|
30
34
|
export type ToolRenderProps<D = Json, T = Json, A = Json> =
|
|
31
35
|
| ToolInputRenderProps | ToolExecutionRenderProps<D, T, A> | ToolResultRenderProps<D, T, A>;
|
|
32
36
|
|
|
37
|
+
/** A freeform renderer receives exact text, including an empty string; null means no text was captured. */
|
|
38
|
+
interface FreeformCallProps extends ToolIdentityProps {
|
|
39
|
+
kind: "freeform";
|
|
40
|
+
text: string | null;
|
|
41
|
+
}
|
|
42
|
+
export type FreeformToolInputRenderProps = FreeformCallProps & { phase: "input"; result: null };
|
|
43
|
+
export type FreeformToolExecutionRenderProps<D = Json> = FreeformCallProps & Pick<ToolExecutionRenderProps<D>, "phase" | "result">;
|
|
44
|
+
export type FreeformToolResultRenderProps<D = Json> = FreeformCallProps & Pick<ToolResultRenderProps<D>, "phase" | "result">;
|
|
45
|
+
export type FreeformToolRenderProps<D = Json> = FreeformToolInputRenderProps | FreeformToolExecutionRenderProps<D> | FreeformToolResultRenderProps<D>;
|
|
46
|
+
/** Used by the conversation host before resolving a specific renderer. */
|
|
47
|
+
export type AnyToolRenderProps = ToolRenderProps | FreeformToolRenderProps;
|
|
48
|
+
|
|
33
49
|
/** All three states use the same two independently optional entry points; the same declaration can be reused across phases. */
|
|
34
50
|
export interface ToolPhaseView<P> {
|
|
35
51
|
headerRenderer?: ComponentType<P>;
|
|
@@ -45,15 +61,22 @@ export interface ToolExecutionPhaseView<P> extends ToolStreamingPhaseView<P> {
|
|
|
45
61
|
/** Pure function: returns true when the body requires user attention; the shell immediately expands once on the first match during execution, independently of streaming preferences, and users can still collapse it. */
|
|
46
62
|
attention?: (props: P) => boolean;
|
|
47
63
|
}
|
|
48
|
-
|
|
64
|
+
interface ToolViewOptions {
|
|
49
65
|
label?: UiText;
|
|
50
66
|
icon?: ReactNode;
|
|
51
|
-
/** Whether the conversation shell exposes raw
|
|
67
|
+
/** Whether the conversation shell exposes raw call/result details; defaults to true. */
|
|
52
68
|
details?: boolean;
|
|
69
|
+
}
|
|
70
|
+
export interface ToolRendererDefinition<D = Json, T = Json, A = Json> extends ToolViewOptions {
|
|
53
71
|
input?: ToolStreamingPhaseView<ToolInputRenderProps>;
|
|
54
72
|
execution?: ToolExecutionPhaseView<ToolExecutionRenderProps<D, T, A>>;
|
|
55
73
|
result?: ToolPhaseView<ToolResultRenderProps<D, T, A>>;
|
|
56
74
|
}
|
|
75
|
+
export interface FreeformToolRendererDefinition<D = Json> extends ToolViewOptions {
|
|
76
|
+
input?: ToolStreamingPhaseView<FreeformToolInputRenderProps>;
|
|
77
|
+
execution?: ToolExecutionPhaseView<FreeformToolExecutionRenderProps<D>>;
|
|
78
|
+
result?: ToolPhaseView<FreeformToolResultRenderProps<D>>;
|
|
79
|
+
}
|
|
57
80
|
export interface ToolView {
|
|
58
81
|
label?: UiText;
|
|
59
82
|
icon?: ReactNode;
|
|
@@ -71,7 +94,7 @@ export interface ToolRenderer {
|
|
|
71
94
|
label?: UiText;
|
|
72
95
|
/** Static operation icon, available to call summaries without rendering arguments or results. */
|
|
73
96
|
icon?: ReactNode;
|
|
74
|
-
resolve(props:
|
|
97
|
+
resolve(props: AnyToolRenderProps): ToolView | null;
|
|
75
98
|
}
|
|
76
99
|
|
|
77
100
|
function render<P extends { phase: ToolRenderProps["phase"] }>(
|
|
@@ -87,26 +110,56 @@ function render<P extends { phase: ToolRenderProps["phase"] }>(
|
|
|
87
110
|
};
|
|
88
111
|
}
|
|
89
112
|
|
|
90
|
-
|
|
113
|
+
type StructuredViewContract<D extends Json, T extends Json, A extends Json> = DataContract<D> & {
|
|
114
|
+
kind?: "structured";
|
|
115
|
+
targetSchema?: z.ZodType<T>;
|
|
116
|
+
tool?: { kind?: "structured"; argsSchema: z.ZodType<A> };
|
|
117
|
+
};
|
|
118
|
+
type FreeformViewContract<D extends Json> = (DataContract<D> & { tool: { kind: "freeform" } })
|
|
119
|
+
| (ContractReference & { kind: "freeform"; resultSchema: z.ZodType<D> });
|
|
120
|
+
|
|
121
|
+
/** Structured and freeform views match only their own input kind. Completed result data is decoded in either case. */
|
|
122
|
+
export function toolRenderer<D extends Json>(contract: FreeformViewContract<D>, definition: FreeformToolRendererDefinition<D>): ToolRenderer;
|
|
91
123
|
export function toolRenderer<D extends Json, T extends Json = Json, A extends Json = Json>(
|
|
92
|
-
contract:
|
|
93
|
-
|
|
124
|
+
contract: StructuredViewContract<D, T, A>, definition: ToolRendererDefinition<D, T, A>,
|
|
125
|
+
): ToolRenderer;
|
|
126
|
+
export function toolRenderer<D extends Json, T extends Json, A extends Json>(
|
|
127
|
+
contract: StructuredViewContract<D, T, A> | FreeformViewContract<D>,
|
|
128
|
+
definition: ToolRendererDefinition<D, T, A> | FreeformToolRendererDefinition<D>,
|
|
94
129
|
): ToolRenderer {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
130
|
+
if (isFreeform(contract)) {
|
|
131
|
+
const view = definition as FreeformToolRendererDefinition<D>;
|
|
132
|
+
const schema = "resultSchema" in contract ? contract.resultSchema : contract.schema;
|
|
133
|
+
return { contract: reference(contract), label: view.label, icon: view.icon, resolve(props) {
|
|
134
|
+
if (props.kind !== "freeform") return null;
|
|
135
|
+
if (props.phase === "input") return view.input ? render(view, view.input, props) : null;
|
|
136
|
+
const data = decodeData(schema, props.result?.data);
|
|
137
|
+
if (data === undefined) return null;
|
|
138
|
+
if (props.phase === "settled") return render(view, view.result, { ...props, result: { ...props.result, data } });
|
|
139
|
+
return render(view, view.execution, { ...props, result: props.result ? { ...props.result, data } : null });
|
|
140
|
+
} };
|
|
141
|
+
}
|
|
142
|
+
const view = definition as ToolRendererDefinition<D, T, A>;
|
|
143
|
+
return { contract: reference(contract), label: view.label, icon: view.icon, resolve(props) {
|
|
144
|
+
if (props.kind === "freeform") return null;
|
|
145
|
+
if (props.phase === "input") return view.input ? render(view, view.input, props) : null;
|
|
146
|
+
const data = decodeData(contract.schema, props.result?.data);
|
|
147
|
+
if (data === undefined) return null;
|
|
100
148
|
const target = contract.targetSchema?.safeParse(props.target);
|
|
101
149
|
const args = contract.tool?.argsSchema.safeParse(props.args);
|
|
102
150
|
if (target && !target.success || args && !args.success) return null;
|
|
103
151
|
// Pure data contracts without an argument schema preserve raw JSON; type erasure occurs only at the registration boundary.
|
|
104
152
|
const input = { target: (target ? target.data : props.target) as T, args: (args ? args.data : props.args) as A };
|
|
105
|
-
if (props.phase === "settled") return render(
|
|
106
|
-
|
|
107
|
-
});
|
|
108
|
-
return render(definition, definition.execution, {
|
|
109
|
-
...props, ...input, result: props.result ? { ...props.result, data: parsed?.data ?? null } : null,
|
|
110
|
-
});
|
|
153
|
+
if (props.phase === "settled") return render(view, view.result, { ...props, ...input, result: { ...props.result, data } });
|
|
154
|
+
return render(view, view.execution, { ...props, ...input, result: props.result ? { ...props.result, data } : null });
|
|
111
155
|
} };
|
|
112
156
|
}
|
|
157
|
+
function isFreeform<D extends Json>(contract: StructuredViewContract<D, Json, Json> | FreeformViewContract<D>): contract is FreeformViewContract<D> {
|
|
158
|
+
return ("kind" in contract && contract.kind === "freeform") || ("tool" in contract && contract.tool?.kind === "freeform");
|
|
159
|
+
}
|
|
160
|
+
/** Undefined is reserved for invalid data; null denotes absent data and bypasses the schema. */
|
|
161
|
+
function decodeData<D extends Json>(schema: z.ZodType<D>, data: Json | undefined): D | null | undefined {
|
|
162
|
+
if (data === null || data === undefined) return null;
|
|
163
|
+
const parsed = schema.safeParse(data);
|
|
164
|
+
return parsed.success ? parsed.data : undefined;
|
|
165
|
+
}
|
package/src/runtime-contracts.ts
CHANGED
|
@@ -11,6 +11,7 @@ import type { RecordContract, SessionRecord } from "./records.ts";
|
|
|
11
11
|
import type { EventContract, PluginEvents } from "./events.ts";
|
|
12
12
|
import type { ToolCompletion, ToolInvocationInfo, ToolModelOutput } from "./tool-result.ts";
|
|
13
13
|
import type { PluginConfig, PluginLogger, PluginSecrets, PluginTasks } from "./runtime.ts";
|
|
14
|
+
import type { ModelMediaModality } from "./model-catalog.ts";
|
|
14
15
|
import type { ModelServices } from "./models.ts";
|
|
15
16
|
import type { ResourceRef, ResourceSnapshot, SessionSnapshot, SessionDirectory } from "./workspace.ts";
|
|
16
17
|
import type { ActionContract, CreationContract } from "./commands.ts";
|
|
@@ -50,6 +51,10 @@ export interface PluginContext {
|
|
|
50
51
|
readonly sessions: SessionDirectory;
|
|
51
52
|
readonly createSession: SessionCreation;
|
|
52
53
|
readonly dir: string;
|
|
54
|
+
/** Reconstructible data in the application data root, excluded from recovery points. */
|
|
55
|
+
readonly cacheDir: string;
|
|
56
|
+
/** Plugin-specific system temporary path. Create it as needed; files may disappear and are not backed up. */
|
|
57
|
+
readonly tempDir: string;
|
|
53
58
|
/** Resolve a package-relative asset, independently of writable plugin data. */
|
|
54
59
|
readonly assets: { path(relativePath: string): string };
|
|
55
60
|
readonly agentCatalog: AgentCatalog;
|
|
@@ -162,7 +167,7 @@ export type CallResult<D extends Json = Json> =
|
|
|
162
167
|
| OptionalData<Exclude<ToolCompletion, { kind: "succeeded" | "partial" }>, D>;
|
|
163
168
|
export type PreparedResult = CallResult & ToolInvocationInfo;
|
|
164
169
|
/** Tool caller identity captured at the request boundary; carries neither private resource state nor operation permissions. */
|
|
165
|
-
export type ToolCaller = Readonly<Pick<ResourceSnapshot, "ref" | "title"> & { agent?: string }>;
|
|
170
|
+
export type ToolCaller = Readonly<Pick<ResourceSnapshot, "ref" | "title"> & { agent?: string; modelInputModalities?: readonly ModelMediaModality[] }>;
|
|
166
171
|
export interface ToolInvocation extends ToolInvocationInfo {
|
|
167
172
|
effect: "read" | "write";
|
|
168
173
|
/** Sequential operations share submission order; parallel operations can overlap either lane. */
|
|
@@ -174,7 +179,7 @@ export interface ToolContribution {
|
|
|
174
179
|
readonly contract: ImplementationContract<Json, ToolInput, ToolInput, Json>;
|
|
175
180
|
/** Bind resource-specific access and configuration at the model request boundary. The returned contribution handles that request's calls. */
|
|
176
181
|
capture?(resource: ResourceSnapshot, object: ObjectReader, caller: ToolCaller): ToolContribution;
|
|
177
|
-
/**
|
|
182
|
+
/** Validate raw input before execution. Structured inputs use target and args; freeform uses a null target and the exact text in args. */
|
|
178
183
|
prepare(resource: ResourceSnapshot, object: ObjectExecutor, target: Json, args: Json, caller: ToolCaller, interactive: boolean): ToolInvocation | PreparedResult;
|
|
179
184
|
}
|
|
180
185
|
export interface ModuleContribution {
|
|
@@ -202,8 +207,8 @@ export interface PluginContribution extends ModuleContribution {
|
|
|
202
207
|
modules?: readonly PluginModule[];
|
|
203
208
|
}
|
|
204
209
|
/**
|
|
205
|
-
*
|
|
206
|
-
*
|
|
210
|
+
* Persistent plugin formats. Migration key n means n → n+1.
|
|
211
|
+
* Private files use paths relative to extensions/<pluginId> and store their version in the JSON envelope or SQLite header.
|
|
207
212
|
*/
|
|
208
213
|
export type PluginStorageDeclaration = {
|
|
209
214
|
kind: "json"; path: string; version: number;
|
|
@@ -211,11 +216,22 @@ export type PluginStorageDeclaration = {
|
|
|
211
216
|
} | {
|
|
212
217
|
kind: "sqlite"; path: string; version: number;
|
|
213
218
|
migrations: Readonly<Record<number, (db: DatabaseSync) => void>>;
|
|
214
|
-
};
|
|
219
|
+
} | PluginRecordStorageDeclaration;
|
|
220
|
+
/** A versioned set of owned session record contracts. The host migrates encoded data before plugin setup. */
|
|
221
|
+
export interface PluginRecordStorageDeclaration {
|
|
222
|
+
kind: "records";
|
|
223
|
+
/** Stable identifier within the plugin, independent of display names and file paths. */
|
|
224
|
+
id: string;
|
|
225
|
+
/** Stable, disjoint set of qualified contracts owned by this plugin. Existing untracked history starts at version 1. */
|
|
226
|
+
contracts: readonly string[];
|
|
227
|
+
version: number;
|
|
228
|
+
/** Synchronous transforms of encoded record data. Identity, provenance, and content reference membership stay fixed. */
|
|
229
|
+
migrations: Readonly<Record<number, (contract: string, data: Json) => Json>>;
|
|
230
|
+
}
|
|
215
231
|
/** Default export of the storage entry point (manifest `asterism.storage`); the host imports it separately before the plugin runtime. */
|
|
216
232
|
export function defineStorage(declarations: readonly PluginStorageDeclaration[]): readonly PluginStorageDeclaration[] {
|
|
217
233
|
for (const item of declarations) if (!Number.isSafeInteger(item.version) || item.version < 1)
|
|
218
|
-
throw new Error(`Storage ${item.path} must declare a positive integer version.`);
|
|
234
|
+
throw new Error(`Storage ${item.kind === "records" ? item.id : item.path} must declare a positive integer version.`);
|
|
219
235
|
return Object.freeze([...declarations]);
|
|
220
236
|
}
|
|
221
237
|
export interface PluginDefinition {
|
package/src/runtime-execution.ts
CHANGED
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
import type { ContentReader, RetainedContentScope } from "./content-runtime.ts";
|
|
2
2
|
import type { ModelRunRequest, ModelRunResult, ModelRunObserver, PromptFile, SystemPrompt } from "./models.ts";
|
|
3
|
+
import type { UsageSubject } from "./usage-subjects.ts";
|
|
3
4
|
import type { ResourceRef } from "./workspace.ts";
|
|
4
5
|
|
|
5
|
-
export interface ResourceModelRequest extends Omit<ModelRunRequest, "tools" | "system" | "sessionId"> {
|
|
6
|
+
export interface ResourceModelRequest extends Omit<ModelRunRequest, "tools" | "system" | "sessionId" | "usage"> {
|
|
6
7
|
/** Resource whose current links and tool caller identity supply this request's access. */
|
|
7
8
|
access: ResourceRef;
|
|
8
9
|
/** Paradigm-defined Agent role name, passed to tool implementations as caller identity. */
|
|
9
10
|
agent?: string;
|
|
10
11
|
system: SystemPrompt | ((files: readonly PromptFile[]) => SystemPrompt);
|
|
12
|
+
/**
|
|
13
|
+
* Subjects this request used, recorded with the request when it settles. A function is called once after `system` is prepared,
|
|
14
|
+
* so subjects can describe the prepared prompt. Invalid declarations are logged and omitted.
|
|
15
|
+
*/
|
|
16
|
+
usage?: readonly UsageSubject[] | (() => readonly UsageSubject[]);
|
|
11
17
|
tools?: { allow?: readonly string[]; exclude?: readonly string[] };
|
|
12
18
|
/** Resource type policy for calls; inspection retains information and adds a restriction notice. */
|
|
13
19
|
resources?: { allow?: readonly string[]; exclude?: readonly string[] };
|
package/src/runtime-resources.ts
CHANGED
|
@@ -2,12 +2,12 @@ import type { ActionContract, CreationContract } from "./commands.ts";
|
|
|
2
2
|
import type { z } from "zod";
|
|
3
3
|
import { jsonSchema, type Json } from "./json.ts";
|
|
4
4
|
import { defaultToolModel, type ToolModelOutput } from "./tool-result.ts";
|
|
5
|
-
import type { ResourceContract, ImplementationContract, ToolInput } from "./module-contract.ts";
|
|
5
|
+
import type { ResourceContract, ImplementationContract, StructuredImplementationContract, FreeformImplementationContract, ToolInput } from "./module-contract.ts";
|
|
6
6
|
import type { RecordContract } from "./records.ts";
|
|
7
7
|
import { reference, present, type DataContract } from "./presentation.ts";
|
|
8
8
|
import { PluginApiError } from "./runtime.ts";
|
|
9
9
|
import type { ContextFile, ObjectReader, ObjectExecutor, CreationContribution, ActionContribution, CommandPreparer, CreationPreparation, ActionPreparation, ExternalPreparation, ResourceContribution, ToolContribution, Preparation, CallResult, Lifetime } from "./runtime-contracts.ts";
|
|
10
|
-
import { validationMessage } from "./tool-validation.ts";
|
|
10
|
+
import { resourceValidationMessage, validationMessage } from "./tool-validation.ts";
|
|
11
11
|
import type { ToolCaller } from "./runtime-contracts.ts";
|
|
12
12
|
import { encodeJson } from "./data-encoding.ts";
|
|
13
13
|
import type { ResourceSnapshot } from "./workspace.ts";
|
|
@@ -67,13 +67,29 @@ export function implementResource<S extends Json, V extends Json>(
|
|
|
67
67
|
attach(parse(resource.stateSchema, snapshot.data, "resource"), object, lifetime) } : {}),
|
|
68
68
|
};
|
|
69
69
|
}
|
|
70
|
+
interface ResourceToolContext<D extends Json> {
|
|
71
|
+
object: ObjectExecutor;
|
|
72
|
+
caller: ToolCaller;
|
|
73
|
+
signal: AbortSignal;
|
|
74
|
+
interactive: boolean;
|
|
75
|
+
publish(data: D): void;
|
|
76
|
+
}
|
|
77
|
+
interface StructuredToolHandler<S extends Json, T extends ToolInput, A extends ToolInput, D extends Json> {
|
|
78
|
+
call(data: S, target: T, args: A, context: ResourceToolContext<NoInfer<D>>): Promise<CallResult<NoInfer<D>>>;
|
|
79
|
+
toModel?(data: D): ToolModelOutput;
|
|
80
|
+
}
|
|
81
|
+
interface FreeformToolHandler<S extends Json, D extends Json> {
|
|
82
|
+
call(data: S, input: string, context: ResourceToolContext<NoInfer<D>>): Promise<CallResult<NoInfer<D>>>;
|
|
83
|
+
toModel?(data: D): ToolModelOutput;
|
|
84
|
+
}
|
|
70
85
|
export function implementTool<S extends Json, T extends ToolInput, A extends ToolInput, D extends Json>(
|
|
71
|
-
contract:
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
86
|
+
contract: StructuredImplementationContract<S, T, A, D>, definition: StructuredToolHandler<S, T, A, D>,
|
|
87
|
+
): ToolContribution;
|
|
88
|
+
export function implementTool<S extends Json, D extends Json>(
|
|
89
|
+
contract: FreeformImplementationContract<S, D>, definition: FreeformToolHandler<S, D>,
|
|
90
|
+
): ToolContribution;
|
|
91
|
+
export function implementTool<S extends Json, T extends ToolInput, A extends ToolInput, D extends Json>(
|
|
92
|
+
contract: ImplementationContract<S, T, A, D>, definition: StructuredToolHandler<S, T, A, D> | FreeformToolHandler<S, D>,
|
|
77
93
|
): ToolContribution {
|
|
78
94
|
const identity = reference(contract);
|
|
79
95
|
return {
|
|
@@ -82,14 +98,25 @@ export function implementTool<S extends Json, T extends ToolInput, A extends Too
|
|
|
82
98
|
const state = contract.resource.stateSchema.safeParse(resource.data);
|
|
83
99
|
if (!state.success) return { kind: "failed", implementation: identity,
|
|
84
100
|
error: { code: "invalid_resource", message: "The resource state does not match its backend contract." } };
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
101
|
+
let invoke: (context: ResourceToolContext<D>) => Promise<CallResult<D>>;
|
|
102
|
+
if (contract.tool.kind === "freeform") {
|
|
103
|
+
if (target !== null || typeof args !== "string") return { kind: "rejected", implementation: identity,
|
|
104
|
+
error: { code: "invalid_arguments", message: "This resource tool requires freeform text." } };
|
|
105
|
+
const handler = definition as FreeformToolHandler<S, D>;
|
|
106
|
+
invoke = context => handler.call(state.data, args, context);
|
|
107
|
+
} else {
|
|
108
|
+
const targetSchema = contract.targetSchema!;
|
|
109
|
+
const parsedTarget = targetSchema.safeParse(target, { reportInput: true });
|
|
110
|
+
const parsedArgs = contract.tool.argsSchema.safeParse(args, { reportInput: true });
|
|
111
|
+
if (!parsedTarget.success || !parsedArgs.success) return { kind: "rejected", implementation: identity,
|
|
112
|
+
error: { code: "invalid_arguments", message: [
|
|
113
|
+
`Invalid arguments for ${contract.resource.kind}/${contract.tool.name}.`,
|
|
114
|
+
...(!parsedTarget.success ? [resourceValidationMessage(parsedTarget.error, "target", contract.tool.argsSchema)] : []),
|
|
115
|
+
...(!parsedArgs.success ? [resourceValidationMessage(parsedArgs.error, "args", targetSchema)] : []),
|
|
116
|
+
].join("\n") } };
|
|
117
|
+
const handler = definition as StructuredToolHandler<S, T, A, D>;
|
|
118
|
+
invoke = context => handler.call(state.data, parsedTarget.data, parsedArgs.data, context);
|
|
119
|
+
}
|
|
93
120
|
return {
|
|
94
121
|
effect: contract.effect, execution: contract.execution, implementation: identity,
|
|
95
122
|
// Model projections consume decoded values.
|
|
@@ -106,7 +133,7 @@ export function implementTool<S extends Json, T extends ToolInput, A extends Too
|
|
|
106
133
|
return encoded;
|
|
107
134
|
};
|
|
108
135
|
try {
|
|
109
|
-
const result = await
|
|
136
|
+
const result = await invoke({ object, caller, signal, interactive,
|
|
110
137
|
publish(data) { if (active) publish?.(snapshot(data)); } });
|
|
111
138
|
if (result.kind === "succeeded" || result.kind === "partial") {
|
|
112
139
|
if (result.data === undefined) throw new PluginApiError("invalid_argument", "The tool did not provide final data.");
|
package/src/runtime-tools.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import { defineTool, type
|
|
1
|
+
import { defineTool, type StructuredToolContract, type FreeformToolContract, type ToolInput } from "./module-contract.ts";
|
|
2
2
|
import type { Json } from "./json.ts";
|
|
3
3
|
import type { ObjectReader, ToolSession } from "./objects.ts";
|
|
4
4
|
import type { CallResult, ToolCaller } from "./runtime-contracts.ts";
|
|
5
5
|
import type { ToolModelOutput } from "./tool-result.ts";
|
|
6
|
+
import type { UsageSubject } from "./usage-subjects.ts";
|
|
6
7
|
import type { z } from "zod";
|
|
7
8
|
|
|
8
9
|
export interface TopLevelToolContext<D extends Json = Json> {
|
|
@@ -15,22 +16,38 @@ export interface TopLevelToolContext<D extends Json = Json> {
|
|
|
15
16
|
/** Captured resource-type tool-call restriction, or null when calls are allowed; creation and discovery remain available. */
|
|
16
17
|
resourceToolRestriction(kind: string): string | null;
|
|
17
18
|
publish(data: D): void;
|
|
19
|
+
/**
|
|
20
|
+
* Declare a subject this call used, such as the skill it read. The host records declarations with this call when it settles,
|
|
21
|
+
* attributed to the declaring plugin and the calling request; declarations after the call settles are ignored. Invalid subjects are logged and omitted.
|
|
22
|
+
*/
|
|
23
|
+
recordUsage(subject: UsageSubject): void;
|
|
18
24
|
}
|
|
19
25
|
/** Top-level tools declare their definition and implementation together, independently of resource support relationships. */
|
|
20
|
-
|
|
26
|
+
interface TopLevelExecution<D extends Json> {
|
|
21
27
|
/** Encodes D for progress/history and decodes it for views and model projection. */
|
|
22
28
|
readonly resultSchema: z.ZodType<D>;
|
|
23
29
|
readonly effect: "read" | "write";
|
|
24
30
|
/** Sequential operations share submission order; parallel operations can overlap either lane. */
|
|
25
31
|
readonly execution: "parallel" | "sequential";
|
|
26
|
-
execute(args: A, context: TopLevelToolContext<D>): Promise<CallResult<D>>;
|
|
27
32
|
toModel?(data: D): ToolModelOutput;
|
|
28
33
|
}
|
|
29
|
-
export
|
|
34
|
+
export interface StructuredTopLevelTool<A extends ToolInput, D extends Json> extends StructuredToolContract<A>, TopLevelExecution<D> {
|
|
35
|
+
execute(args: A, context: TopLevelToolContext<D>): Promise<CallResult<D>>;
|
|
36
|
+
}
|
|
37
|
+
export interface FreeformTopLevelTool<D extends Json> extends FreeformToolContract, TopLevelExecution<D> {
|
|
38
|
+
execute(input: string, context: TopLevelToolContext<D>): Promise<CallResult<D>>;
|
|
39
|
+
}
|
|
40
|
+
export type TopLevelTool<A extends ToolInput = ToolInput, D extends Json = Json> = StructuredTopLevelTool<A, D> | FreeformTopLevelTool<D>;
|
|
41
|
+
export function defineTopLevelTool<A extends ToolInput, D extends Json>(definition: StructuredTopLevelTool<A, D>): StructuredTopLevelTool<ToolInput, Json>;
|
|
42
|
+
export function defineTopLevelTool<D extends Json>(definition: FreeformTopLevelTool<D>): FreeformTopLevelTool<Json>;
|
|
43
|
+
export function defineTopLevelTool(definition: TopLevelTool): TopLevelTool {
|
|
30
44
|
if (!definition.resultSchema.description?.trim()) throw new Error(`Missing result schema description: ${definition.id}`);
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
45
|
+
if (definition.kind === "freeform") return { ...definition, ...defineTool(definition),
|
|
46
|
+
execute: (input: string, context: TopLevelToolContext) => definition.execute(input, context),
|
|
47
|
+
...(definition.toModel ? { toModel: data => definition.toModel!(data) } : {}),
|
|
48
|
+
};
|
|
49
|
+
return { ...definition, ...defineTool(definition),
|
|
50
|
+
execute: (args, context) => definition.execute(args, context),
|
|
51
|
+
...(definition.toModel ? { toModel: data => definition.toModel!(data) } : {}),
|
|
52
|
+
};
|
|
36
53
|
}
|
package/src/tool-validation.ts
CHANGED
|
@@ -1,14 +1,46 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
type IssueDetail = (issue: z.core.$ZodIssue, path: readonly PropertyKey[]) => string | undefined;
|
|
4
|
+
|
|
5
|
+
function formatIssues(issues: readonly z.core.$ZodIssue[], parent: readonly PropertyKey[], detail?: IssueDetail): string {
|
|
6
|
+
return issues.map(issue => {
|
|
7
|
+
const path = [...parent, ...issue.path];
|
|
8
|
+
return detail?.(issue, path) ?? (issue.code === "invalid_union"
|
|
9
|
+
? `${path.map(String).join(".")}: must match one of these alternatives: ${issue.errors.map(branch => `(${formatIssues(branch, path, detail)})`).join(" OR ")}`
|
|
10
|
+
: `${path.map(String).join(".")}: ${issue.message}`);
|
|
11
|
+
}).join("; ");
|
|
12
|
+
}
|
|
2
13
|
|
|
3
14
|
/** Preserve field paths and specific validation reasons from union branches so the model can correct the raw JSON arguments. */
|
|
4
15
|
export function validationMessage(error: z.ZodError, field: string): string {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
16
|
+
return formatIssues(error.issues, field ? [field] : []);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function declaresRootField(schema: z.core.$ZodType, key: string): boolean {
|
|
20
|
+
if (schema instanceof z.ZodObject) return Object.hasOwn(schema.shape, key);
|
|
21
|
+
if (schema instanceof z.ZodNullable) return declaresRootField(schema.unwrap(), key);
|
|
22
|
+
if (schema instanceof z.ZodUnion) {
|
|
23
|
+
// A hint must not depend on guessing which object variant the caller intended.
|
|
24
|
+
const variants = schema.options.filter(option => !(option instanceof z.ZodNull));
|
|
25
|
+
return variants.length > 0 && variants.every(option => declaresRootField(option, key));
|
|
26
|
+
}
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Format a resource input error parsed with reportInput, without including raw input values in the hints. */
|
|
31
|
+
export function resourceValidationMessage(error: z.ZodError, field: "args" | "target", otherSchema: z.ZodType): string {
|
|
32
|
+
const other = field === "args" ? "target" : "args";
|
|
33
|
+
return formatIssues(error.issues, [field], (issue, path) => {
|
|
34
|
+
if (issue.code === "unrecognized_keys") return issue.keys.map(key => {
|
|
35
|
+
const at = [...path, key].map(String).join(".");
|
|
36
|
+
return path.length === 1 && declaresRootField(otherSchema, key)
|
|
37
|
+
? `${at}: Not accepted here. This tool implementation declares it as ${other}.${key}.`
|
|
38
|
+
: `${at}: Unknown field at this location for this tool implementation.`;
|
|
39
|
+
}).join("; ");
|
|
40
|
+
if (path.length > 1 && issue.input === undefined &&
|
|
41
|
+
(issue.code === "invalid_type" || issue.code === "invalid_value" || issue.code === "invalid_union"))
|
|
42
|
+
return `${path.map(String).join(".")}: Required field is missing.`;
|
|
43
|
+
});
|
|
12
44
|
}
|
|
13
45
|
|
|
14
46
|
export const jsonArgumentHint = 'target and args are JSON objects or null matching their schemas. Example: target: {"path":"README.md"}, args: {}.';
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
const text = z.string().min(1);
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Something a model request or one of its tool calls used, declared by the plugin that knows the fact. The host records it in the usage
|
|
7
|
+
* ledger with the request or call that is current where it is declared; the declaring plugin, session, and request come from that context.
|
|
8
|
+
* `kind` and `relation` are open identifiers: the host interprets the kinds it owns (`usageSubjectKinds`) and shows other values verbatim.
|
|
9
|
+
*/
|
|
10
|
+
export const usageSubjectSchema = z.strictObject({
|
|
11
|
+
kind: text,
|
|
12
|
+
/** Identity within the kind, such as a skill name. */
|
|
13
|
+
id: text,
|
|
14
|
+
/** Owner scope within the kind, such as the skill source an entry resolved from; null when unresolved. */
|
|
15
|
+
source: text.nullable().optional(),
|
|
16
|
+
/** How the subject was used, such as `read` or `context` (`usageRelations`). */
|
|
17
|
+
relation: text,
|
|
18
|
+
/** Part within the subject, such as a package-relative file. */
|
|
19
|
+
part: text.nullable().optional(),
|
|
20
|
+
/** Non-negative amount in a kind-defined unit, such as prompt characters. */
|
|
21
|
+
quantity: z.number().finite().nonnegative().nullable().optional(),
|
|
22
|
+
});
|
|
23
|
+
export type UsageSubject = z.input<typeof usageSubjectSchema>;
|
|
24
|
+
|
|
25
|
+
/** Kinds whose meaning the host owns. A `skill` subject's id is the skill name and its source the catalog source ID. */
|
|
26
|
+
export const usageSubjectKinds = {
|
|
27
|
+
skill: "skill",
|
|
28
|
+
/** A skill catalog projected into a request; quantity is its prompt characters. */
|
|
29
|
+
skillCatalog: "skill-catalog",
|
|
30
|
+
/** Execution unit context: id is the performer label/key, source its instance scope, and part the unit identity if available. */
|
|
31
|
+
workUnit: "work-unit",
|
|
32
|
+
} as const;
|
|
33
|
+
/** Relations whose meaning the host owns: the model tried to read the subject, or it occupied request context. */
|
|
34
|
+
export const usageRelations = { read: "read", context: "context" } as const;
|