@asterism-app/sdk 2.3.0 → 2.5.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/src/models.ts CHANGED
@@ -19,10 +19,18 @@ export interface SystemPrompt { blocks: readonly PromptBlock[] }
19
19
  /** Reasoning text is the plaintext delivered by the protocol, and summary is an independent summary; both can coexist or be empty, and neither fills the other.
20
20
  * continuation carries only native data such as signatures/ciphertext, shaped by the producing protocol; target projection determines whether it can be reused.
21
21
  */
22
+ /** Completed tool input in Asterism's vocabulary, independent of provider wire encoding. */
23
+ export type ToolCallInput = { kind: "structured"; value: Json } | { kind: "freeform"; text: string };
24
+ /** Unfinished generation for display and recording, never for execution. */
25
+ export interface ToolInputDraft { kind: ToolCallInput["kind"]; text: string }
26
+ export type ModelToolDeclaration = { name: string; description: string } & (
27
+ { kind: "structured"; parameters: Json } | { kind: "freeform" }
28
+ );
29
+
22
30
  export type ModelPart =
23
31
  | { kind: "thinking"; text: string; summary: string; continuation: Json }
24
32
  | { kind: "text"; text: string; continuation: Json }
25
- | { kind: "toolcall"; callId: string; name: string; arguments: Json; continuation: Json };
33
+ | { kind: "toolcall"; callId: string; name: string; input: ToolCallInput; continuation: Json };
26
34
  export type ModelItem =
27
35
  | { kind: "input" | "context"; parts: readonly ModelInputPart[] }
28
36
  // scope and adapter (the producing protocol's continuation format) constrain native data; they do not gate public content in cross-model requests.
@@ -34,11 +42,11 @@ export interface Usage {
34
42
  }
35
43
  export type StreamPart =
36
44
  | { id: string; kind: "text" | "thinking" }
37
- | { id: string; kind: "toolcall"; callId: string; name: string };
45
+ | { id: string; kind: "toolcall"; callId: string; name: string; inputKind: ToolCallInput["kind"] };
38
46
  export type ModelEvent =
39
47
  | { type: "part.start"; part: StreamPart }
40
48
  | { type: "part.delta"; partId: string; delta: string; channel?: "summary" }
41
- | { type: "part.end"; partId: string; arguments?: Json; continuation?: Json }
49
+ | { type: "part.end"; partId: string; input?: ToolCallInput; continuation?: Json }
42
50
  | { type: "finish"; reason: string; usage: Usage | null; responseId?: string; rawFinishReason?: string; source?: ModelSource; timing?: RequestTiming; response?: ModelResponse | null };
43
51
  export type ModelSource = { model: string; adapter: string; scope: string };
44
52
  /** Failure message is a standalone English summary; details preserve original diagnostic text and response data. */
@@ -66,15 +74,14 @@ export type ModelBlock = {
66
74
  } & (
67
75
  | { kind: "thinking"; text: string; summary: string }
68
76
  | { kind: "text"; text: string }
69
- | { kind: "toolcall"; callId: string; name: string; argumentsText: string | null; arguments: Json; outcome: ToolOutcome | null;
77
+ | { kind: "toolcall"; callId: string; name: string; input: ToolCallInput | null; draft: ToolInputDraft | null; outcome: ToolOutcome | null;
70
78
  /** Original input preview identity; available even when execution never produced an outcome. */
71
79
  invocation?: ToolInvocationInfo }
72
80
  );
73
81
  export type ModelLiveBlock = { id: string; responseId: string; ordinal: number } & (
74
82
  | { kind: "text"; text: string; endedAt: number | null }
75
83
  | { kind: "thinking"; text: string; startedAt: number; endedAt: number | null }
76
- /** During the input phase, arguments is a display preview parsed tolerantly and cannot be used for execution; other phases contain complete arguments. */
77
- | { kind: "toolcall"; name: string; argumentsText: string; arguments: Json; state: "input" | "ready" | "executing";
84
+ | { kind: "toolcall"; name: string; input: ToolCallInput | null; draft: ToolInputDraft | null; state: "input" | "ready" | "executing";
78
85
  invocation: ToolInvocationInfo | null; result: Extract<ToolResult, { kind: "running" }> | null;
79
86
  /** One-shot attention time, present only in live execution; history does not replay notices. */
80
87
  noticeAt?: number }
@@ -107,7 +114,7 @@ export interface ModelResponse {
107
114
  receivedAt: number;
108
115
  headers: Readonly<Record<string, string>>;
109
116
  }
110
- export interface ModelToolCall { callId: string; name: string; arguments: Json }
117
+ export interface ModelToolCall { callId: string; name: string; input: ToolCallInput }
111
118
  export interface ModelToolObserver {
112
119
  prepared?(call: ModelToolCall, info: ToolInvocationInfo): void;
113
120
  started?(call: ModelToolCall, info: ToolInvocationInfo): void;
@@ -117,8 +124,8 @@ export interface ModelToolObserver {
117
124
  }
118
125
  /** Executable tools supplied by the requesting paradigm or a host-bound request environment. */
119
126
  export interface ModelTools {
120
- readonly declarations: readonly { name: string; description: string; parameters: Json }[];
121
- preview?(name: string, args: Json): ToolInvocationInfo;
127
+ readonly declarations: readonly ModelToolDeclaration[];
128
+ preview?(name: string, input: ToolCallInput | null): ToolInvocationInfo;
122
129
  execute(calls: readonly ModelToolCall[], signal: AbortSignal,
123
130
  settle: (call: ModelToolCall, outcome: ToolOutcome) => void, observer: ModelToolObserver): Promise<void>;
124
131
  }
@@ -144,7 +151,7 @@ export type ModelRunResult = {
144
151
  /** The final request's input context; an independent copy for domain extension producers to read. */
145
152
  export interface ModelRequestContext {
146
153
  system: SystemPrompt;
147
- tools: readonly { name: string; description: string; parameters: Json }[];
154
+ tools: readonly ModelToolDeclaration[];
148
155
  }
149
156
  export interface StreamRequest extends ModelRequestIdentity {
150
157
  target: ModelTarget;
@@ -152,7 +159,7 @@ export interface StreamRequest extends ModelRequestIdentity {
152
159
  messages: ModelItem[];
153
160
  /** The output limit for this completion; uses the smaller of this value and the model's configured limit. */
154
161
  maxOutputTokens?: number;
155
- tools?: { name: string; description: string; parameters: Json }[];
162
+ tools?: ModelToolDeclaration[];
156
163
  signal: AbortSignal;
157
164
  }
158
165
  export interface ModelInputOptions { content?: ContentReader }
@@ -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
- export interface ToolContract<A extends ToolInput = ToolInput> extends ContractReference {
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
- /** Tool definitions fix selection descriptions, usage guidance, and args; implementations add only target/result and execution information. */
31
- export interface ImplementationContract<S extends Json, T extends ToolInput, A extends ToolInput, O extends Json> extends DataContract<O> {
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: ToolContract<A>): ToolContract<A> {
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
- requireDescription(definition.argsSchema, `${definition.name}.args`);
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
- requireDescription(definition.targetSchema, `${definition.id}.target`);
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
  }
@@ -7,17 +7,18 @@ import { parseModelExpression, type ModelExpression } from "./model-selection.ts
7
7
  * name something that does not exist; parsing checks only the format.
8
8
  */
9
9
 
10
- /** `resource:<resourceId>/<location>`: the authority is the resource ID and the resource interprets the location. */
11
- export interface ResourceUrl { readonly resourceId: string; readonly location: string }
10
+ /** `resource:<resourceId>/<location>[#<fragment>]`: the resource interprets the location and optional navigation fragment. */
11
+ export interface ResourceUrl { readonly resourceId: string; readonly location: string; readonly fragment?: string }
12
12
  /** `skill:<name>[/<path>]`: the skill name and an optional package-relative file; undefined means SKILL.md. */
13
13
  export interface SkillUrl { readonly name: string; readonly path: string | undefined }
14
14
 
15
15
  const encodePath = (path: string) => path.split("/").map(encodeURIComponent).join("/");
16
16
  const decodePath = (path: string) => path.split("/").map(decodeURIComponent).join("/");
17
17
 
18
- export function resourceUrl(resourceId: string, location: string): string {
18
+ export function resourceUrl(resourceId: string, location: string, fragment?: string): string {
19
+ const suffix = fragment === undefined ? "" : `#${encodeURIComponent(fragment)}`;
19
20
  // Parentheses are URI-safe but delimit the Markdown destination used by references.
20
- return `resource:${encodeURIComponent(resourceId)}/${encodePath(location)}`.replaceAll("(", "%28").replaceAll(")", "%29");
21
+ return `resource:${encodeURIComponent(resourceId)}/${encodePath(location)}${suffix}`.replaceAll("(", "%28").replaceAll(")", "%29");
21
22
  }
22
23
 
23
24
  export function parseResourceUrl(value: string): ResourceUrl | null {
@@ -25,7 +26,14 @@ export function parseResourceUrl(value: string): ResourceUrl | null {
25
26
  if (!match) return null;
26
27
  try {
27
28
  const resourceId = decodeURIComponent(match[1]!);
28
- return resourceId ? { resourceId, location: decodePath(match[2]!) } : null;
29
+ if (!resourceId) return null;
30
+ const address = match[2]!;
31
+ const hash = address.indexOf("#");
32
+ if (hash < 0) return { resourceId, location: decodePath(address) };
33
+ const location = decodePath(address.slice(0, hash));
34
+ // A malformed navigation hint does not invalidate the resource location.
35
+ try { return { resourceId, location, fragment: decodeURIComponent(address.slice(hash + 1)) }; }
36
+ catch { return { resourceId, location }; }
29
37
  } catch { return null; }
30
38
  }
31
39
 
@@ -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 }
@@ -14,7 +14,14 @@ export interface RendererIslandSpec {
14
14
  origin?: HTMLElement | null;
15
15
  /** Content surfaces grow wider than the default form panel. */
16
16
  size?: "panel" | "content";
17
- render: () => ReactNode;
17
+ /** Receives the latest navigation for this live instance, including when its key is reused. Consume it once per request object. */
18
+ render: (navigation?: RendererIslandNavigation) => ReactNode;
19
+ }
20
+ /** An in-memory navigation request. Only the owning plugin interprets its target. */
21
+ export interface RendererIslandNavigation { readonly target: unknown }
22
+ export interface RendererIslandOpenOptions {
23
+ /** When supplied, send a fresh request to the shown island without replacing its content. */
24
+ readonly navigation?: unknown;
18
25
  }
19
26
  /** Explicit cancellation action of an island; cancellation may close it through the usual close guards. */
20
27
  export type RendererIslandCancel = () => void | Promise<void>;
@@ -28,7 +35,7 @@ export interface RendererIsland {
28
35
  */
29
36
  bindKey(key: string): boolean;
30
37
  /** Open an island owned by this one at the right end of the screen, or locate the open island with the same key. Resolves to whether it is shown. */
31
- open(spec: RendererIslandSpec): Promise<boolean>;
38
+ open(spec: RendererIslandSpec, options?: RendererIslandOpenOptions): Promise<boolean>;
32
39
  /** Close this island and the islands it opened; has no effect on host-managed islands such as the one containing a plugin settings page. force skips guards. */
33
40
  close(options?: { force?: boolean }): Promise<boolean>;
34
41
  /** Close the islands this island opened, transitively. */
@@ -5,7 +5,11 @@ import type { ResourceRef } from "./workspace.ts";
5
5
  import type { RendererCalls } from "./renderer-calls.ts";
6
6
  import type { RendererIsland } from "./renderer-island.ts";
7
7
 
8
- export interface RendererResourceOpenOptions { readonly origin?: HTMLElement | null }
8
+ export interface RendererResourceOpenOptions {
9
+ readonly origin?: HTMLElement | null;
10
+ /** A decoded URL fragment for in-app navigation, separate from the resource location. */
11
+ readonly fragment?: string;
12
+ }
9
13
 
10
14
  /** The resource interprets location and chooses its operation or view. Islands belong to the target plugin. */
11
15
  export interface RendererResourceOpenContext extends RendererResourceOpenOptions {
@@ -38,7 +42,7 @@ export interface RendererResourceNavigation {
38
42
  /** Read the resource's current identity and title at call time; null when the session or resource is absent. Other failures reject. */
39
43
  resolve(resource: Pick<ResourceRef, "sessionId" | "id">): Promise<RendererResourceIdentity | null>;
40
44
  /** Resolve current presence and available location actions. The host supplies "open" when an in-app opener exists; resource actions retain their declared IDs. Lookup failures reject; action execution reports failures through the host. */
41
- actions(resource: Pick<ResourceRef, "sessionId" | "id">, location: string): Promise<readonly RendererResourceLocationAction[]>;
45
+ actions(resource: Pick<ResourceRef, "sessionId" | "id">, location: string, options?: Pick<RendererResourceOpenOptions, "fragment">): Promise<readonly RendererResourceLocationAction[]>;
42
46
  /** Resolve current presence without model-request authorization. Failures are shown by the host; a cancelled open returns false. */
43
47
  open(resource: Pick<ResourceRef, "sessionId" | "id">, location: string, options?: RendererResourceOpenOptions): Promise<boolean>;
44
48
  }
@@ -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 { ToolRenderProps, ToolView } from "./renderer-tools.ts";
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: ToolRenderProps): ToolView & { props: ToolRenderProps };
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;
@@ -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 ToolCallProps<T, A> {
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; fields may be missing, incomplete, or of the wrong type. */
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 argument preview when resolving the view. */
19
- argumentsText?: string;
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
- export interface ToolRendererDefinition<D = Json, T = Json, A = Json> {
64
+ interface ToolViewOptions {
49
65
  label?: UiText;
50
66
  icon?: ReactNode;
51
- /** Whether the conversation shell exposes raw argument/result details; defaults to true. */
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: ToolRenderProps): ToolView | null;
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
- /** Dispatch by phase; streaming input is not treated as valid arguments, while execution and results share complete argument and output validation. */
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: DataContract<D> & { targetSchema?: z.ZodType<T>; tool?: { argsSchema: z.ZodType<A> } },
93
- definition: ToolRendererDefinition<D, T, A>,
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
- return { contract: reference(contract), label: definition.label, icon: definition.icon, resolve(props) {
96
- if (props.phase === "input") return definition.input ? render(definition, definition.input, props) : null;
97
- const data = props.result?.data;
98
- const parsed = data === null || data === undefined ? null : contract.schema.safeParse(data);
99
- if (parsed && !parsed.success) return null;
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(definition, definition.result, {
106
- ...props, ...input, result: { ...props.result, data: parsed?.data ?? null },
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
+ }
@@ -1,4 +1,5 @@
1
1
  import { createContext, createElement, useContext, type ComponentType, type ReactNode } from "react";
2
+ import type { ToolInvocationInfo } from "./tool-result.ts";
2
3
 
3
4
  export interface HeaderExcerptProps {
4
5
  /** Full value. Only a bounded, single-line prefix is rendered; keep the full value in the body. */
@@ -17,9 +18,49 @@ export interface StreamingScrollAreaProps {
17
18
  initialScrollPosition?: "start" | "end";
18
19
  }
19
20
 
21
+ /** One-line tool title: the operation name, then an optional subject badge, a summary that yields space first, and trailing metadata. */
22
+ export interface ToolHeaderProps {
23
+ /** Localized operation name. */
24
+ label: string;
25
+ /** The operation's focus, such as a `ToolResourceSubject`; omit it when there is none. */
26
+ subject?: ReactNode;
27
+ /** Muted details such as a path or query; ellipsized as the width shrinks. */
28
+ summary?: ReactNode;
29
+ /** Short trailing facts such as counts; stays visible. */
30
+ meta?: ReactNode;
31
+ }
32
+
33
+ export interface ToolResourceSubjectProps {
34
+ /** The resource recorded with the call, from `invocation.resource`. */
35
+ resource: NonNullable<ToolInvocationInfo["resource"]>;
36
+ }
37
+
38
+ export interface ToolScrollAreaProps {
39
+ children: ReactNode;
40
+ /** Localized accessible name for the scrolling region. */
41
+ label: string;
42
+ }
43
+
44
+ export interface DiffProps {
45
+ /** Unified diff text of one file, with `---`/`+++` headers and `@@` hunks. */
46
+ diff: string;
47
+ /** Wrap long lines instead of scrolling horizontally. Defaults to true. */
48
+ wrap?: boolean;
49
+ /** Emphasize changed words within changed lines, in addition to marking the lines themselves. Defaults to "none". */
50
+ highlightChanges?: "none" | "word";
51
+ /** Infer syntax highlighting from the filename, or render hunk contents as plain text. Defaults to "auto". */
52
+ syntax?: "auto" | "plain";
53
+ /** Show old and new line numbers; defaults to true. Turn them off when the hunk positions are not real file positions. */
54
+ lineNumbers?: boolean;
55
+ }
56
+
20
57
  interface RendererUi {
21
58
  HeaderExcerpt: ComponentType<HeaderExcerptProps>;
22
59
  StreamingScrollArea: ComponentType<StreamingScrollAreaProps>;
60
+ ToolHeader: ComponentType<ToolHeaderProps>;
61
+ ToolResourceSubject: ComponentType<ToolResourceSubjectProps>;
62
+ ToolScrollArea: ComponentType<ToolScrollAreaProps>;
63
+ Diff: ComponentType<DiffProps>;
23
64
  }
24
65
 
25
66
  const Ui = createContext<RendererUi | null>(null);
@@ -40,3 +81,23 @@ export function HeaderExcerpt(props: HeaderExcerptProps) {
40
81
  export function StreamingScrollArea(props: StreamingScrollAreaProps) {
41
82
  return createElement(useRendererUi().StreamingScrollArea, props);
42
83
  }
84
+
85
+ /** The shared tool title layout. Use `HeaderExcerpt` in the summary for unbounded inputs. */
86
+ export function ToolHeader(props: ToolHeaderProps) {
87
+ return createElement(useRendererUi().ToolHeader, props);
88
+ }
89
+
90
+ /** The recorded name and kind icon of the resource a call operated on, for a tool header's subject slot. */
91
+ export function ToolResourceSubject(props: ToolResourceSubjectProps) {
92
+ return createElement(useRendererUi().ToolResourceSubject, props);
93
+ }
94
+
95
+ /** The default bounded reading region for settled tool content. Use your own layout when it doesn't fit the view. */
96
+ export function ToolScrollArea(props: ToolScrollAreaProps) {
97
+ return createElement(useRendererUi().ToolScrollArea, props);
98
+ }
99
+
100
+ /** Optional single-file diff viewer. The caller owns its controls and layout. Patches without renderable hunks display as diff text. */
101
+ export function Diff(props: DiffProps) {
102
+ return createElement(useRendererUi().Diff, props);
103
+ }
@@ -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
- /** Raw model inputs are validated against the target and argument contracts before execution. */
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
- * Format declarations for persistent plugin files; paths are relative to extensions/<pluginId>, and migration key n means n → n+1.
206
- * Versions are stamped by the writer: JSON uses a `{ version, data }` envelope, and SQLite uses `PRAGMA user_version`.
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 {