@asterism-app/sdk 1.1.0 → 1.2.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.
@@ -50,16 +50,52 @@ Transient events announce change. A consumer needing current state establishes i
50
50
 
51
51
  Typed calls describe request and response values with ordinary Zod schemas. The caller supplies the input schema's input; the implementation receives its parsed output, including defaults. The implementation returns JSON accepted by the output schema, and the caller receives that schema's parsed output. These types are inferred from the shared declaration, so a conversion such as string to number does not require separate type annotations.
52
52
 
53
+ ## Read typed history
54
+
55
+ Public record contracts belong to the package that owns their meaning. The SDK exposes host resource creation, renaming, removal, and link changes. A paradigm's public API supplies its conversation records; a plugin's public package supplies its business records. Import the original contract to decode a record rather than interpreting its JSON fields yourself.
56
+
57
+ Use `contract.decode(record)` for a single record and `contract.decodeAll(records)` for a commit batch. Batch decoding preserves the supplied order and omits records belonging to other contracts. A matching record returns either `known` with typed `data`, or `unknown` with the original `record` and an invalid-data reason. An unreadable matching record remains visible for reporting and recovery decisions.
58
+
59
+ ```ts
60
+ import { ResourceCreated } from "@asterism-app/sdk/contracts";
61
+
62
+ for (const created of ResourceCreated.decodeAll(records)) {
63
+ if (created.status === "unknown") {
64
+ reportUnreadable(created.record);
65
+ continue;
66
+ }
67
+ handleCreation(created.data, created.record.sessionId);
68
+ }
69
+ ```
70
+
71
+ For stored history, use `snapshot.records.query(ResourceCreated, { scope: "timeline" })`; it returns the same decoded result shape. `first` and `last` select the earliest or latest matching record and preserve `unknown` when that selected record is unreadable. `timeline` selects the snapshot's ancestor path; `session` includes other branches within its captured append bound. These reads retain original record identity and do not rewrite stored data.
72
+
73
+ A creation record separates resource identity, type, title, and encoded resource state. Its `type` is the resource kind. The nested `data` remains JSON because resource kinds have different state contracts; match the resource kind and decode that state with its resource contract when needed. To read a resource present in a snapshot, use `snapshot.resources.get(resourceContract, id)`. Private current-data entries remain owned by their declaring plugin.
74
+
75
+ Creation records include new identities instantiated from templates. Moving through history may make an existing resource appear again without creating a new record. Record observers report committed facts; presence events and attachment lifetimes describe membership in the current resource set. A host-created resource record has a null source, with the associated resource identity in its payload.
76
+
77
+ Public history contracts provide typed observation. Create, rename, remove, and link resources through the session operations; plugin record writers retain their existing ownership checks.
78
+
53
79
  ## Retain file content
54
80
 
55
81
  Stage immutable bytes through the content service, then store their reference in persistent data or a record that owns them.
56
82
 
57
- A reference identifies content. Copying its identifier does not by itself grant access or retain the bytes. Pass it through the supported operation scope so ownership remains explicit.
83
+ A `ContentRef` identifies stored immutable content. Copying its identifier does not by itself grant access or retain the bytes. Pass it through the supported operation scope so ownership remains explicit.
58
84
 
59
85
  Retention follows references in the JSON actually saved. Preserve content references in that encoding when their bytes must remain available; synthesizing a reference during decoding does not retain content or grant access.
60
86
 
61
87
  When completing an operation with attachments from an independent temporary scope, supply that scope's content reader. The host validates access and retains those result references in the same transaction as completion. Input references remain retained. Close the temporary scope after completion has committed.
62
88
 
89
+ ## Pass resource file references
90
+
91
+ Use a `FileRef` to pass an address without reading or retaining content. It contains the full source resource identity and a JSON locator interpreted by that resource. Construct it directly and include it in tool results, typed calls, events, or saved state. No registration, content scope, or consumer link is required.
92
+
93
+ The source resource implements `openFile` to interpret its locator and produce an asynchronous byte stream. A consumer uses `plugin.files.open(ref, { signal })` and processes chunks as they arrive. Breaking iteration closes the stream. Forward an operation's cancellation signal so its consumption stops with that operation.
94
+
95
+ Reuse `fileRefSchema` in contracts that return or accept these addresses. Its description supplies the shared meaning. Describe each operation's own use of the reference without coupling its instructions to particular producer or consumer resource types.
96
+
97
+ Discovery returns addresses and descriptive metadata; it need not open files. Each consumption resolves the source anew across sessions, independently of open UI surfaces. The host does not cache bytes or freeze external files. Changed content is read as it exists at consumption, and missing resources, unavailable providers, or failed reads surface as errors. Persisting a file reference preserves its address, not the bytes it once identified. Use immutable content storage when a business operation needs to preserve a particular version.
98
+
63
99
  ## End asynchronous work
64
100
 
65
101
  Bind shared services to the plugin lifetime and object-owned instances to the resource lifetime. Register cleanup when creating the owned work.
@@ -28,6 +28,8 @@ For model calls, `resource_id` selects the resource, `args` supplies the operati
28
28
 
29
29
  Use a top-level tool for operations on the execution context or shared resource lifecycle, such as creation and renaming. The host supplies caller identity and execution scope.
30
30
 
31
+ Both resource tools and top-level tools receive `caller`, containing the access owner's resource reference and title. When the executing paradigm supplies an Agent role name, it is available as `caller.agent`. The role identifies the executing configuration independently of the access owner; several roles can execute through one shared resource. Role identity carries no configuration object or additional resource access.
32
+
31
33
  Describe the operation's purpose and observable behavior. Parameters should explain business meaning that names and types alone do not express. Results should distinguish known success, failure, cancellation, partial output, and uncertain effects.
32
34
 
33
35
  A tool contribution can capture resource-specific configuration and access at the start of each model request. Return a bound contribution using the same implementation contract; the host uses it for that request's tool batch. This is useful for a resource whose selected network or reachable objects can change while a model is responding. Capture addressing and authorization facts, while reading ordinary mutable content when the operation runs.
@@ -36,6 +38,8 @@ Declare `requiresInteraction: true` when a tool cannot complete without user int
36
38
 
37
39
  Use `plugin.execution.run` to execute one model request with tools bound to a resource's current links and the real session. Supply that resource as the access owner and select the interaction capability. The execution holds captured relationships through the tool batch; subsequent calls capture current links again. Calls sharing an access owner keep independent message inputs and can run concurrently.
38
40
 
41
+ Supply the executing role's name through `agent` and any resource type allowlist or denylist through `resources`. The host captures these inputs with the request. Resource policy is enforced by the shared dispatcher: inspection retains resource state and tool schemas with a notice naming a denied role, and calls on restricted types are rejected before the implementation runs. Listing and linked context remain available. Individual resource tools need no role-policy checks.
42
+
39
43
  Resource holds do not block history movement. Use an object busy scope for work that depends on the timeline, such as a conversation writing its responses there. Object-bound managed tasks protect history by default; use `affectsHistory: false` for external runtime tasks that should still stop when their owning resource leaves the session.
40
44
 
41
45
  Use `plugin.models.run` when supplying messages and executable tools directly. It needs no workbench resource or timeline. Both forms deliver execution records to the observer you provide. `plugin.execution.withProgress` supplies an optional workbench observer for the events you choose to display.
@@ -10,6 +10,14 @@ Input previews can be incomplete. Displaying arguments does not establish that e
10
10
 
11
11
  Use host presentation facilities for the surrounding card or operation. Keep domain content within the view rather than rebuilding application navigation and containment.
12
12
 
13
+ ## Open expanded content
14
+
15
+ Resource card views can use the renderer island capability to open plugin content beside the workbench. The same entry works from a focused resource. Settings pages and expanded views open additional islands to their own right. Opening another island from the same source level replaces deeper content, subject to close guards.
16
+
17
+ Supply a plugin-local identity, accessible label, opening element, and content renderer. Choose a content surface for an editor or another view that needs more width. The host manages layout and focus. The opened view has an independent plugin region; pass its resource reference and other domain inputs explicitly rather than relying on the source component's React context or mount lifetime.
18
+
19
+ Use the island panel for its title, actions, and close control. Its fill layout lets an editor own scrolling. Mark unsaved content as dirty so closing, replacement, session navigation, and application exit ask before discarding it. A close guard can also retain a view while a save is pending. Closing the island releases its view calls without ending independent backend services.
20
+
13
21
  ## Style plugin views
14
22
 
15
23
  Import CSS from the renderer entry or its components. Asterism builds the imported styles and loads them before frontend preparation and view registration. CSS references to bundled images and fonts keep their relative paths. Style loading failures appear as frontend plugin failures.
@@ -0,0 +1,39 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { z } from "zod";
4
+ import { defineCreation, defineEvent, fileRefSchema, pluginNamespace, type FileRef } from "@asterism-app/sdk/contracts";
5
+ import { defineModule, definePlugin, implementCreation, implementResource, type PluginContext } from "@asterism-app/sdk/runtime";
6
+
7
+ const namespace = pluginNamespace("example.file-source");
8
+ const Folder = namespace.resource("folder", z.object({ path: z.string() }));
9
+ const CreateFolder = defineCreation(Folder, { id: namespace.name("create"), schema: Folder.stateSchema });
10
+ const FolderView = namespace.data("view", Folder.stateSchema);
11
+ export const FileOffered = defineEvent(namespace.name("file-offered"), {
12
+ schema: z.object({ file: fileRefSchema, filename: z.string() }),
13
+ source: "plugin", semantics: { kind: "occurrence" },
14
+ });
15
+
16
+ export default definePlugin({ namespace, modules: [defineModule(() => ({
17
+ events: [FileOffered],
18
+ resources: [implementResource(Folder, FolderView, {
19
+ creation: implementCreation(CreateFolder, { create: data => ({ title: "Files", data }) }),
20
+ project: data => data,
21
+ inspect: async data => data,
22
+ async *openFile(data, locator, { signal }) {
23
+ const { path } = z.object({ path: z.string() }).parse(locator);
24
+ yield* createReadStream(join(data.path, path), { signal });
25
+ },
26
+ })],
27
+ }))] });
28
+
29
+ /** Called with the source plugin's context. Publishing does not check the file or read its bytes. */
30
+ export function offerFile(plugin: PluginContext, file: FileRef, filename: string) {
31
+ plugin.ipc.events.publish(FileOffered, { file, filename });
32
+ }
33
+
34
+ /** A consuming plugin subscribes to the shared event contract and streams bytes into its own operation. */
35
+ export function receiveFiles(plugin: PluginContext, consume: (chunks: AsyncIterable<Uint8Array>, filename: string, signal: AbortSignal) => Promise<void>) {
36
+ return plugin.ipc.events.subscribe(FileOffered, { signal: plugin.lifetime.signal }, async ({ data }, { signal }) => {
37
+ await consume(plugin.files.open(data.file, { signal }), data.filename, signal);
38
+ });
39
+ }
@@ -0,0 +1,29 @@
1
+ import { ResourceCreated, ResourceRemoved, pluginNamespace } from "@asterism-app/sdk/contracts";
2
+ import { defineModule, definePlugin } from "@asterism-app/sdk/runtime";
3
+
4
+ /** Observe public resource facts independently of any resource implementation or Agent paradigm. */
5
+ export default definePlugin({
6
+ namespace: pluginNamespace("example.resource-history"),
7
+ modules: [defineModule(plugin => ({
8
+ observers: [{
9
+ id: "resource-history",
10
+ committed({ records }) {
11
+ for (const created of ResourceCreated.decodeAll(records)) {
12
+ if (created.status === "unknown") {
13
+ plugin.log.error(`Cannot decode creation record ${created.record.id}.`);
14
+ continue;
15
+ }
16
+ const { id, type, title } = created.data;
17
+ plugin.log.info(`Created ${type} resource ${id} in session ${created.record.sessionId}: ${title}`);
18
+ }
19
+ for (const removed of ResourceRemoved.decodeAll(records)) {
20
+ if (removed.status === "unknown") {
21
+ plugin.log.error(`Cannot decode removal record ${removed.record.id}.`);
22
+ continue;
23
+ }
24
+ plugin.log.info(`Removed resource ${removed.data.id} from the current path.`);
25
+ }
26
+ },
27
+ }],
28
+ }))],
29
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asterism-app/sdk",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Public contracts and host capabilities for Asterism plugins",
5
5
  "license": "MIT",
6
6
  "author": "Chien Zhang",
package/src/contracts.ts CHANGED
@@ -6,6 +6,7 @@ export * from "./module-contract.ts";
6
6
  export type { CardAppearance } from "./card.ts";
7
7
  export * from "./plugin.ts";
8
8
  export * from "./records.ts";
9
+ export * from "./resource-records.ts";
9
10
  export * from "./events.ts";
10
11
  export * from "./calls.ts";
11
12
  export * from "./channels.ts";
@@ -19,6 +20,7 @@ export * from "./commands.ts";
19
20
  export * from "./i18n.ts";
20
21
  export * from "./config.ts";
21
22
  export * from "./content.ts";
23
+ export * from "./files.ts";
22
24
  export * from "./model-input.ts";
23
25
 
24
26
  export * from "./model-selection.ts";
package/src/files.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { z } from "zod";
2
+ import { jsonSchema } from "./json.ts";
3
+
4
+ /** A self-contained address resolved by its source resource when consumed. References are ordinary, freely constructible JSON. */
5
+ export const fileRefSchema = z.strictObject({
6
+ source: z.strictObject({ sessionId: z.string().min(1), id: z.string().min(1), kind: z.string().min(1) })
7
+ .describe("Full identity of the resource providing the content, including its session."),
8
+ locator: jsonSchema.describe("Location interpreted by the source resource's file provider."),
9
+ }).describe("FileRef: a source resource and a provider-defined locator identifying content fetched when consumed.");
10
+ export type FileRef = z.infer<typeof fileRefSchema>;
11
+
12
+ /** Descriptive metadata travels with a reference; it does not freeze the source content. */
13
+ export const fileReferencePartSchema = z.strictObject({
14
+ kind: z.literal("file-reference"),
15
+ ref: fileRefSchema,
16
+ filename: z.string().min(1).max(255).optional().describe("Name used for delivery."),
17
+ mediaType: z.string().optional().describe("Descriptive MIME type; the reference does not freeze the source content."),
18
+ }).describe("A FileRef with optional delivery metadata.");
19
+ export type FileReferencePart = z.infer<typeof fileReferencePartSchema>;
package/src/records.ts CHANGED
@@ -28,20 +28,28 @@ export interface RecordContract<D extends Json = Json> extends RecordRef {
28
28
  readonly schema: z.ZodType<D>;
29
29
  /** Return null when the record does not belong to this contract; compatibility and transformations are determined by the schema, and failure preserves the raw record. */
30
30
  decode(record: SessionRecord): Decoded<D> | null;
31
+ /** Decode a batch in its supplied order, omitting other contracts and retaining unknown matching records. */
32
+ decodeAll(records: readonly SessionRecord[]): Decoded<D>[];
31
33
  }
32
34
  export function defineRecord<D extends Json>(id: string, definition: {
33
35
  schema: z.ZodType<D>;
34
36
  }): RecordContract<D> {
35
37
  const { schema } = definition;
38
+ const decode = (record: SessionRecord): Decoded<D> | null => {
39
+ if (record.contract.id !== id) return null;
40
+ const data = structuredClone(record.data);
41
+ try {
42
+ const parsed = schema.safeParse(data);
43
+ return parsed.success ? { status: "known", record, data: parsed.data } : { status: "unknown", record, reason: "invalid_data" };
44
+ } catch { return { status: "unknown", record, reason: "invalid_data" }; }
45
+ };
36
46
  return {
37
- id, schema,
38
- decode(record) {
39
- if (record.contract.id !== id) return null;
40
- const data = structuredClone(record.data);
41
- try {
42
- const parsed = schema.safeParse(data);
43
- return parsed.success ? { status: "known", record, data: parsed.data } : { status: "unknown", record, reason: "invalid_data" };
44
- } catch { return { status: "unknown", record, reason: "invalid_data" }; }
47
+ id, schema, decode,
48
+ decodeAll(records) {
49
+ return records.flatMap(record => {
50
+ const value = decode(record);
51
+ return value ? [value] : [];
52
+ });
45
53
  },
46
54
  };
47
55
  }
@@ -2,7 +2,7 @@ import { createContext, createElement, useContext, useEffect, useRef, type Compo
2
2
  import type { UiText } from "./i18n.ts";
3
3
 
4
4
  /**
5
- * Island: an independent surface column within the host screen; opening one places it to the right of the current island and replaces existing deeper islands.
5
+ * Island: an independent surface column within the host screen. Resource cards open beside the workbench, including when focused; other islands open to their own right.
6
6
  * The host uniformly manages width, position, motion, and focus; plugins provide only identity, an accessible name, and content.
7
7
  */
8
8
  export interface RendererIslandSpec {
@@ -12,6 +12,8 @@ export interface RendererIslandSpec {
12
12
  label: UiText;
13
13
  /** The element that opened it: used for the expansion animation and receives focus again after closing. */
14
14
  origin?: HTMLElement | null;
15
+ /** Content surfaces grow wider than the default form panel. */
16
+ size?: "panel" | "content";
15
17
  render: () => ReactNode;
16
18
  }
17
19
  /** Close guard: returning false (or resolving to false) aborts closing; may asynchronously wait for user confirmation. */
@@ -40,6 +42,8 @@ export interface RendererIslandPanelProps {
40
42
  /** Fixed toolbar below the title bar, such as search. */
41
43
  toolbar?: ReactNode;
42
44
  dirty?: boolean;
45
+ /** Fill the available area without padding; the content owns scrolling. */
46
+ layout?: "padded" | "fill";
43
47
  children: ReactNode;
44
48
  }
45
49
 
@@ -51,7 +55,7 @@ function required<T>(value: T | null, name: string): T {
51
55
  if (value === null) throw new Error(`Renderer ${name} must be provided by the host.`);
52
56
  return value;
53
57
  }
54
- /** The containing island; available within plugin settings pages and islands they open. */
58
+ /** Available within resource cards, plugin settings pages, and islands they open. Opened content has its own region; pass domain inputs explicitly. */
55
59
  export function useRendererIsland(): RendererIsland { return required(useContext(Island), "island"); }
56
60
  /** Register a close guard for the containing island; null guard permits closing, and the guard always uses the latest callback. */
57
61
  export function useRendererCloseGuard(guard: RendererCloseGuard | null) {
@@ -0,0 +1,28 @@
1
+ import { z } from "zod";
2
+ import { defineRecord } from "./records.ts";
3
+ import { jsonSchema } from "./json.ts";
4
+
5
+ /** A new resource identity, including template instances. data is the resource's encoded creation state. */
6
+ export const ResourceCreated = defineRecord("resource_created", {
7
+ schema: z.object({
8
+ id: z.string(),
9
+ type: z.string().min(1),
10
+ title: z.string(),
11
+ data: jsonSchema,
12
+ }),
13
+ });
14
+
15
+ /** A title assignment on the resource's history path. */
16
+ export const ResourceRenamed = defineRecord("resource_renamed", {
17
+ schema: z.object({ id: z.string(), title: z.string() }),
18
+ });
19
+
20
+ /** Removal from the current history path; the resource identity and earlier records remain in history. */
21
+ export const ResourceRemoved = defineRecord("object_removed", {
22
+ schema: z.object({ id: z.string() }),
23
+ });
24
+
25
+ /** id is the resource made available to receiverId; both endpoints are resource identities. */
26
+ const linkSchema = z.object({ id: z.string(), receiverId: z.string() });
27
+ export const ResourceAttached = defineRecord("resource_attached", { schema: linkSchema });
28
+ export const ResourceDetached = defineRecord("resource_detached", { schema: linkSchema });
@@ -61,6 +61,7 @@ export interface PluginContext {
61
61
  readonly models: ModelServices;
62
62
  readonly execution: import("./runtime-execution.ts").ExecutionServices;
63
63
  readonly content: import("./content-runtime.ts").ContentServices;
64
+ readonly files: import("./runtime-files.ts").FileServices;
64
65
  readonly modelProviders: ModelProviderServices;
65
66
  readonly usageProviders: UsageProviderServices;
66
67
  readonly usages: UsageServices;
@@ -130,6 +131,8 @@ export interface ResourceContribution {
130
131
  project(resource: ResourceSnapshot, object: ObjectReader): Presentation;
131
132
  inspect(resource: ResourceSnapshot, object: ObjectReader): Promise<Json>;
132
133
  context?(resource: ResourceSnapshot, object: ObjectReader): Promise<ContextFile[]>;
134
+ /** Resolve a file address against this resource at consumption time; consumers need no link or registration of the reference. */
135
+ openFile?(resource: ResourceSnapshot, locator: Json, context: { object: ObjectReader; signal: AbortSignal }): AsyncIterable<Uint8Array>;
133
136
  /** Explanation presented to users before ending the current instance; does not block backend removal or wait for external cleanup. */
134
137
  disposalWarning?(resource: ResourceSnapshot, object: ObjectReader): UiText | null;
135
138
  /**
@@ -147,7 +150,7 @@ export type CallResult<D extends Json = Json> =
147
150
  | OptionalData<Exclude<ToolCompletion, { kind: "succeeded" | "partial" }>, D>;
148
151
  export type PreparedResult = CallResult & ToolInvocationInfo;
149
152
  /** Tool caller identity captured at the request boundary; carries neither private resource state nor operation permissions. */
150
- export type ToolCaller = Readonly<Pick<ResourceSnapshot, "ref" | "title">>;
153
+ export type ToolCaller = Readonly<Pick<ResourceSnapshot, "ref" | "title"> & { agent?: string }>;
151
154
  export interface ToolInvocation extends ToolInvocationInfo {
152
155
  effect: "read" | "write";
153
156
  execution: "parallel" | "sequential";
@@ -5,8 +5,12 @@ import type { ResourceRef } from "./workspace.ts";
5
5
  export interface ResourceModelRequest extends Omit<ModelRunRequest, "tools" | "system" | "sessionId"> {
6
6
  /** Resource whose current links and tool caller identity supply this request's access. */
7
7
  access: ResourceRef;
8
+ /** Paradigm-defined Agent role name, passed to tool implementations as caller identity. */
9
+ agent?: string;
8
10
  system: SystemPrompt | ((files: readonly PromptFile[]) => SystemPrompt);
9
11
  tools?: { allow?: readonly string[]; exclude?: readonly string[] };
12
+ /** Resource type policy for calls; inspection retains information and adds a restriction notice. */
13
+ resources?: { allow?: readonly string[]; exclude?: readonly string[] };
10
14
  /** Whether this execution has a user interaction endpoint. */
11
15
  interactive: boolean;
12
16
  }
@@ -0,0 +1,7 @@
1
+ import type { FileRef } from "./files.ts";
2
+
3
+ /** Each consumption resolves the source anew. Passing or storing a reference performs no I/O and retains no bytes. */
4
+ export interface FileServices {
5
+ /** Pull bytes from the source resource. Breaking iteration closes the stream; cancellation rejects further pulls. Provider errors propagate to the consumer. */
6
+ open(ref: FileRef, options?: { signal?: AbortSignal }): AsyncIterable<Uint8Array>;
7
+ }
@@ -10,6 +10,7 @@ import type { ContextFile, ObjectReader, ObjectExecutor, CreationContribution, A
10
10
  import { validationMessage, jsonArgumentHint } from "./tool-validation.ts";
11
11
  import type { ToolCaller } from "./runtime-contracts.ts";
12
12
  import { encodeJson } from "./data-encoding.ts";
13
+ import type { ResourceSnapshot } from "./workspace.ts";
13
14
 
14
15
  function parse<T>(schema: z.ZodType<T>, input: unknown, subject: string): T {
15
16
  const result = schema.safeParse(input);
@@ -46,18 +47,21 @@ export function implementResource<S extends Json, V extends Json>(
46
47
  project(data: NoInfer<S>, object: ObjectReader): NoInfer<V>;
47
48
  inspect(data: NoInfer<S>, object: ObjectReader): Promise<Json>;
48
49
  context?(data: NoInfer<S>, object: ObjectReader): Promise<ContextFile[]>;
50
+ openFile?(data: NoInfer<S>, locator: Json, context: { object: ObjectReader; signal: AbortSignal }): AsyncIterable<Uint8Array>;
49
51
  disposalWarning?(data: NoInfer<S>, object: ObjectReader): import("./i18n.ts").UiText | null;
50
52
  /** Called when an object enters the current set; external instances owned exclusively by the object register cleanup with lifetime. */
51
53
  attach?(data: NoInfer<S>, object: ObjectReader, lifetime: Lifetime): void;
52
54
  },
53
55
  ): ResourceContribution {
54
- const attach = definition.attach;
56
+ const { attach, openFile } = definition;
55
57
  return {
56
58
  resource, card: definition.card, records: [...definition.records ?? []], links: definition.links, template: definition.template,
57
59
  creation: definition.creation, actions: definition.actions,
58
60
  project: (snapshot, object) => present(view, definition.project(parse(resource.stateSchema, snapshot.data, "resource"), object)),
59
61
  inspect: async (snapshot, object) => jsonSchema.parse(await definition.inspect(parse(resource.stateSchema, snapshot.data, "resource"), object)),
60
62
  context: async (snapshot, object) => definition.context?.(parse(resource.stateSchema, snapshot.data, "resource"), object) ?? [],
63
+ ...(openFile ? { openFile: (snapshot: ResourceSnapshot, locator: Json, context: { object: ObjectReader; signal: AbortSignal }) =>
64
+ openFile(parse(resource.stateSchema, snapshot.data, "resource"), locator, context) } : {}),
61
65
  disposalWarning: (snapshot, object) => definition.disposalWarning?.(parse(resource.stateSchema, snapshot.data, "resource"), object) ?? null,
62
66
  ...(attach ? { attach: (snapshot: Parameters<NonNullable<ResourceContribution["attach"]>>[0], object: ObjectReader, lifetime: Lifetime) =>
63
67
  attach(parse(resource.stateSchema, snapshot.data, "resource"), object, lifetime) } : {}),
@@ -1,12 +1,13 @@
1
1
  import { defineTool, type ToolContract } from "./module-contract.ts";
2
2
  import type { Json } from "./json.ts";
3
3
  import type { ObjectReader, ToolSession } from "./objects.ts";
4
- import type { CallResult } from "./runtime-contracts.ts";
4
+ import type { CallResult, ToolCaller } from "./runtime-contracts.ts";
5
5
  import type { ToolModelOutput } from "./tool-result.ts";
6
6
  import type { z } from "zod";
7
7
 
8
8
  export interface TopLevelToolContext<D extends Json = Json> {
9
9
  readonly object: ObjectReader;
10
+ readonly caller: ToolCaller;
10
11
  readonly session: ToolSession;
11
12
  readonly callId: string;
12
13
  readonly signal: AbortSignal;
package/src/runtime.ts CHANGED
@@ -13,6 +13,7 @@ export * from "./runtime-web.ts";
13
13
  export * from "./runtime-agent-catalog.ts";
14
14
  export * from "./runtime-sessions.ts";
15
15
  export type * from "./content-runtime.ts";
16
+ export type * from "./runtime-files.ts";
16
17
  export type * from "./models.ts";
17
18
  export type * from "./runtime-execution.ts";
18
19
  export { validationMessage, jsonArgumentHint } from "./tool-validation.ts";