@asterism-app/sdk 1.1.0 → 1.3.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,60 @@ 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
+ Use `records.index` when only identity, ancestry, order, contract, or provenance is needed. It returns metadata without reading bodies. Queries can combine contracts, record IDs, and an emitting resource ID. `source: null` selects records without an emitting resource. `from` includes its anchor and `before` excludes its anchor; both anchors must belong to the selected scope before filters are applied. `limit` selects a bounded page, and `edge: "last"` selects the last matches while still returning them in append order. A preceding page ends before the first record of the current page.
74
+
75
+ Query filters intersect, including a typed reader's contract and any supplied contract filter. Repeating a contract or record identity does not duplicate results.
76
+
77
+ Runtime snapshots read synchronously. Renderer snapshots share the same query semantics, with synchronous metadata and asynchronous body and resource reads. Await those reads before decoding or projecting data. React views can use `useSessionRead` with a memoized reader to distinguish loading, ready, and error states. Forward its cancellation signal to reads so closing a view stops further pages without cancelling other readers of the same body. A failed transfer is not an empty result or an unreadable record. Reuse the session snapshot across related queries; finalized bodies are shared across views, while pending bodies retain their original observation.
78
+
79
+ The reading hook supplies `retry()` for rereading the current query. `keepPrevious` retains visible content while the same logical query refreshes along its timeline. A `key` identifies that query when the reader callback also depends on presentation inputs; changing the selected record or query scope uses a different key so content from the previous selection is not shown.
80
+
81
+ 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.
82
+
83
+ 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.
84
+
85
+ Public history contracts provide typed observation. Create, rename, remove, and link resources through the session operations; plugin record writers retain their existing ownership checks.
86
+
53
87
  ## Retain file content
54
88
 
55
89
  Stage immutable bytes through the content service, then store their reference in persistent data or a record that owns them.
56
90
 
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.
91
+ 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
92
 
59
93
  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
94
 
61
95
  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
96
 
97
+ ## Pass resource file references
98
+
99
+ 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.
100
+
101
+ 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.
102
+
103
+ 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.
104
+
105
+ 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.
106
+
63
107
  ## End asynchronous work
64
108
 
65
109
  Bind shared services to the plugin lifetime and object-owned instances to the resource lifetime. Register cleanup when creating the owned work.
@@ -0,0 +1,17 @@
1
+ # Provide and consume messaging
2
+
3
+ Messaging connects plugins to external conversation services through configured identities. A provider contribution declares its display name, settings, and asynchronous instance factory. Return it in a module's `messagingProviders` contribution. The host creates an instance for each enabled connection, supplies resolved settings and a connection identity, and manages receiving work.
4
+
5
+ Settings use the shared provider setting kinds: text, choice, and secret. Secret values are supplied to the backend factory and remain absent from configuration snapshots. Required values are always present in the resolved settings, choices hold a declared option, and unset optional values are absent. A provider type may have several independently configured connections. The plugin owns any platform-specific state or persistent data used by those connections; declare `forget` to release a removed connection's data, which the host calls after that connection's receiver has ended.
6
+
7
+ An instance supplies its external identity, an ongoing receive operation, conversation listing, message reading, and sending. Receive accepts a cancellation signal and a `ready` callback, and publishes typed conversation-discovered and message-received events. Call `ready` once the platform has accepted the receiver; the connection then reports connected and its retry backoff resets. Queries and sends have their own signals. A send carries text, an optional reply target, and file references; text accompanies files as a caption. Resolve each reference with `plugin.files` before contacting the platform, so an unreadable source fails as invalid input without sending anything.
8
+
9
+ The host retries failed creation and receive calls. Throw `MessagingError` with `request_failed` for transient conditions such as network failures, rate limits, and server errors, and set `retryAfterMs` when the platform reports a delay. Errors other than `MessagingError` are also treated as transient. Use `unavailable` for conditions that retrying cannot fix, such as rejected credentials or a conflicting receiver; the connection then stays failed until the user changes its configuration or reconnects. Reject unsupported operations explicitly with `unsupported`.
10
+
11
+ Use opaque strings for platform conversation, topic, and message identities. Give every sender a role relative to the connection: `self` for the connection's own identity, `participant` for another party, and `system` for content the platform produced rather than a party authored. Cursors are opaque, reusable query positions scoped by the provider. A query may compare changes with an earlier cursor, but it must not advance a shared read position. Cursor rejection should explain that the supplied position cannot be used.
12
+
13
+ Consumers access `plugin.messaging`. List connection identities, resolve a specific connection to an operation handle, and subscribe to external events and connection changes. Resolve at the consumer's request boundary when configuration must remain fixed across its operations. Each handle retains its captured instance; operations wait for a connection attempt in progress and fail with the attempt's error otherwise. Current external content remains current at handling time.
14
+
15
+ Provider instances are shared across consumers. A plugin should not create a second receiver for each card or session. Its consumers own their subscriptions and release them with their lifetimes. A listener failure is logged and does not affect other listeners or the provider. Connection removal or provider unavailability prevents new resolutions; provider shutdown cancels its outstanding work.
16
+
17
+ The service has no Agent semantics. A consumer chooses whether an external event updates a view, records a fact, or submits input through a paradigm's public API. Builtin resources use links to select recipients and expose tools. Other plugins may compose the same service differently.
@@ -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
+ }
@@ -21,7 +21,7 @@ function CounterBody({ data }: { data: z.infer<typeof Card.schema> }) {
21
21
  setPending(true);
22
22
  void invoke(ChangeCount, { amount: 1 }).finally(() => setPending(false));
23
23
  },
24
- }, `${data.value} · live ${live ?? "-"} · ${session.snapshot()?.records.all({ scope: "timeline" }).length ?? 0} records`),
24
+ }, `${data.value} · live ${live ?? "-"} · ${session.snapshot()?.records.index({ scope: "timeline" }).length ?? 0} records`),
25
25
  createElement("button", { onClick: () => card.openPanel("details") }, "Details"));
26
26
  }
27
27
  function CounterDetails({ data }: { data: z.infer<typeof Card.schema> }) {
@@ -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
+ });
@@ -5,20 +5,28 @@ import { z } from "zod";
5
5
  const ns = pluginNamespace("example.web");
6
6
  const Metadata = ns.data("metadata", z.object({ sourceId: z.string() }));
7
7
  const responseSchema = z.object({ id: z.string(), title: z.string(), text: z.string() });
8
+ const BASE_URL = "https://api.example.test";
8
9
  const provider: WebProviderDefinition = {
9
10
  id: "example.web/pages", label: "Example pages", search: false, fetch: true,
10
11
  urlPatterns: ["https://docs.example.test/*", "https://help.example.test/*"],
11
- defaultBaseUrl: "https://api.example.test", credential: { kind: "api_key", keyUrl: "https://example.test/api-keys" },
12
- create({ baseUrl, credential }) {
12
+ settings: [
13
+ { kind: "secret", key: "apiKey", label: "API key", required: true, helpUrl: "https://example.test/api-keys" },
14
+ { kind: "choice", key: "format", label: "Page format", default: "markdown", options: [
15
+ { value: "markdown", label: "Markdown" }, { value: "text", label: "Plain text" },
16
+ ] },
17
+ ],
18
+ create({ settings }) {
19
+ // Required secrets are present and choices hold a declared option.
20
+ const format = settings.format as "markdown" | "text";
13
21
  return { async fetch(request, { signal }) {
14
- const response = await fetch(new URL("/read", baseUrl), {
15
- method: "POST", signal, headers: { "Content-Type": "application/json", Authorization: `Bearer ${credential}` },
16
- body: JSON.stringify({ url: request.url }),
22
+ const response = await fetch(new URL("/read", BASE_URL), {
23
+ method: "POST", signal, headers: { "Content-Type": "application/json", Authorization: `Bearer ${settings.apiKey}` },
24
+ body: JSON.stringify({ url: request.url, format }),
17
25
  });
18
26
  if (!response.ok) throw new WebError("request_failed", `Page service returned HTTP ${response.status}.`);
19
27
  const page = responseSchema.parse(await response.json());
20
28
  return webResponseSchema.parse({ documents: [{ url: request.url, title: page.title,
21
- content: [{ kind: "body", format: "markdown", text: page.text }], details: [present(Metadata, { sourceId: page.id })] }],
29
+ content: [{ kind: "body", format, text: page.text }], details: [present(Metadata, { sourceId: page.id })] }],
22
30
  hints: request.query ? [{ code: "unsupported_parameter", parameter: "query", message: "This provider returned the page without query-focused excerpts." }] : [],
23
31
  });
24
32
  } };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asterism-app/sdk",
3
- "version": "1.1.0",
3
+ "version": "1.3.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";
@@ -28,7 +30,9 @@ export * from "./model-cost-estimate.ts";
28
30
  export * from "./model-media.ts";
29
31
  export * from "./model-provider.ts";
30
32
  export * from "./provider-usage.ts";
33
+ export * from "./provider-settings.ts";
31
34
  export * from "./web.ts";
35
+ export * from "./messaging.ts";
32
36
 
33
37
  export * from "./session-title.ts";
34
38
 
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>;
@@ -0,0 +1,73 @@
1
+ import { z } from "zod";
2
+ import { uiTextSchema } from "./i18n.ts";
3
+ import { providerSettingsSchema } from "./provider-settings.ts";
4
+ import { fileReferencePartSchema } from "./files.ts";
5
+
6
+ const id = z.string().min(1);
7
+ export const messagingProviderTypeSchema = z.strictObject({
8
+ id, owner: id, label: uiTextSchema, settings: providerSettingsSchema,
9
+ });
10
+ export const messagingConnectionSchema = z.strictObject({
11
+ id, providerId: id, name: z.string().trim().min(1).max(160), enabled: z.boolean(),
12
+ settings: z.record(z.string(), z.string()),
13
+ });
14
+ /**
15
+ * Connection runtime state. Reconnecting retains the last identity and reports the failure being retried;
16
+ * failed is terminal until the configuration changes or the user reconnects.
17
+ */
18
+ export const messagingConnectionStatusSchema = z.enum(["disabled", "unavailable", "connecting", "connected", "reconnecting", "failed"]);
19
+ export const messagingConnectionInfoSchema = messagingConnectionSchema.omit({ settings: true }).extend({
20
+ status: messagingConnectionStatusSchema,
21
+ identity: z.string().optional(), error: z.string().optional(),
22
+ });
23
+ /** Provider-owned addresses and cursors are opaque to the host. */
24
+ export const conversationAddressSchema = z.strictObject({
25
+ conversationId: id, threadId: id.optional(),
26
+ });
27
+ export const conversationSchema = conversationAddressSchema.extend({
28
+ title: z.string(), kind: z.string(), activity: z.string().optional(),
29
+ change: z.enum(["discovered", "messages"]).optional(),
30
+ });
31
+ /**
32
+ * A sender's relation to the connection: self is the connection's own identity, participant is another party,
33
+ * and system is content produced by the platform rather than authored by a party.
34
+ */
35
+ export const messageSenderRoleSchema = z.enum(["self", "participant", "system"]);
36
+ export const messageSenderSchema = z.strictObject({ id, name: z.string(), role: messageSenderRoleSchema });
37
+ export const messageSchema = z.strictObject({
38
+ id, sender: messageSenderSchema, text: z.string(),
39
+ sentAt: z.string(), replyTo: id.optional(), threadId: id.optional(),
40
+ });
41
+ export const conversationQuerySchema = z.strictObject({ since: id.optional() });
42
+ export const conversationListSchema = z.strictObject({
43
+ conversations: z.array(conversationSchema), cursor: id.optional(), truncated: z.boolean(),
44
+ });
45
+ export const messageQuerySchema = conversationAddressSchema.extend({
46
+ since: id.optional(), limit: z.number().int().positive().optional(),
47
+ });
48
+ export const messageListSchema = z.strictObject({
49
+ messages: z.array(messageSchema), cursor: id.optional(), truncated: z.boolean(),
50
+ });
51
+ /** Files are references resolved by the provider when sending; text accompanies them as a caption. */
52
+ export const sendMessageSchema = conversationAddressSchema.extend({
53
+ text: z.string(), replyTo: id.optional(), files: z.array(fileReferencePartSchema).optional(),
54
+ }).refine(value => !!value.text.trim() || !!value.files?.length, "A message requires text or a file.");
55
+ export const messagingEventSchema = z.discriminatedUnion("kind", [
56
+ z.strictObject({ kind: z.literal("conversation.discovered"), conversation: conversationSchema }),
57
+ z.strictObject({ kind: z.literal("message.received"), conversation: conversationSchema, message: messageSchema }),
58
+ ]);
59
+ export type MessagingProviderType = z.infer<typeof messagingProviderTypeSchema>;
60
+ export type MessagingConnection = z.infer<typeof messagingConnectionSchema>;
61
+ export type MessagingConnectionStatus = z.infer<typeof messagingConnectionStatusSchema>;
62
+ export type MessagingConnectionInfo = z.infer<typeof messagingConnectionInfoSchema>;
63
+ export type ConversationAddress = z.infer<typeof conversationAddressSchema>;
64
+ export type MessagingConversation = z.infer<typeof conversationSchema>;
65
+ export type MessageSenderRole = z.infer<typeof messageSenderRoleSchema>;
66
+ export type MessagingMessage = z.infer<typeof messageSchema>;
67
+ export type ConversationQuery = z.infer<typeof conversationQuerySchema>;
68
+ export type ConversationList = z.infer<typeof conversationListSchema>;
69
+ export type MessageQuery = z.infer<typeof messageQuerySchema>;
70
+ export type MessageList = z.infer<typeof messageListSchema>;
71
+ export type SendMessage = z.infer<typeof sendMessageSchema>;
72
+ export type MessagingEvent = z.infer<typeof messagingEventSchema>;
73
+ export type ConnectionEvent = { connectionId: string; event: MessagingEvent };
@@ -0,0 +1,24 @@
1
+ import { z } from "zod";
2
+ import { uiTextSchema } from "./i18n.ts";
3
+
4
+ const helpUrlSchema = z.string().url().refine(value => ["http:", "https:"].includes(new URL(value).protocol), "An HTTP or HTTPS URL is required.");
5
+ const base = { key: z.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/u), label: uiTextSchema, description: uiTextSchema.optional() };
6
+
7
+ /**
8
+ * Provider settings use a closed set of kinds that the host renders, validates, and stores.
9
+ * Secret values are stored in the credential vault and never appear in configuration snapshots.
10
+ * Text values are saved trimmed; choices always resolve to a declared option.
11
+ */
12
+ export const providerSettingSchema = z.discriminatedUnion("kind", [
13
+ z.strictObject({ ...base, kind: z.literal("secret"), required: z.boolean(), helpUrl: helpUrlSchema.optional() }),
14
+ z.strictObject({ ...base, kind: z.literal("text"), required: z.boolean(), placeholder: uiTextSchema.optional() }),
15
+ z.strictObject({ ...base, kind: z.literal("choice"), default: z.string().min(1),
16
+ options: z.array(z.strictObject({ value: z.string().min(1), label: uiTextSchema, description: uiTextSchema.optional() })).min(1) })
17
+ .refine(setting => new Set(setting.options.map(option => option.value)).size === setting.options.length, "Choice option values are unique.")
18
+ .refine(setting => setting.options.some(option => option.value === setting.default), "The default is one of the options."),
19
+ ]);
20
+ export const providerSettingsSchema = z.array(providerSettingSchema)
21
+ .refine(settings => new Set(settings.map(setting => setting.key)).size === settings.length, "Setting keys are unique.");
22
+ export type ProviderSetting = z.infer<typeof providerSettingSchema>;
23
+ /** Values supplied to provider factories: choices hold a declared option; required values are present; unset optional values are absent. */
24
+ export type ProviderSettingValues = Readonly<Record<string, string | undefined>>;
package/src/records.ts CHANGED
@@ -4,7 +4,7 @@ import type { Source } from "./workspace.ts";
4
4
 
5
5
  /** Public envelope for session records: the host maps its storage format to this envelope, and plugins decode by contract without depending on internal node structure. */
6
6
  export interface RecordRef { readonly id: string }
7
- export interface SessionRecord {
7
+ export interface RecordInfo {
8
8
  readonly id: string;
9
9
  readonly sessionId: string;
10
10
  readonly parentId: string | null;
@@ -14,11 +14,13 @@ export interface SessionRecord {
14
14
  readonly contract: RecordRef;
15
15
  /** Writer; stamped by the host according to the write channel, while the associated object belongs in data. */
16
16
  readonly source: Source;
17
+ /** Present for operations published before completion; false after their one-time result is stored. */
18
+ readonly pending?: boolean;
19
+ }
20
+ export interface SessionRecord extends RecordInfo {
17
21
  /** Model-visible text written by the platform, consumed when executors project context; recipient being null means all executors. */
18
22
  readonly context: { readonly text: string; readonly recipient: string | null } | null;
19
23
  readonly data: Json;
20
- /** Present for operations published before completion; false after their one-time result is stored. */
21
- readonly pending?: boolean;
22
24
  }
23
25
  export type Decoded<D> =
24
26
  | { readonly status: "known"; readonly record: SessionRecord; readonly data: D }
@@ -28,20 +30,28 @@ export interface RecordContract<D extends Json = Json> extends RecordRef {
28
30
  readonly schema: z.ZodType<D>;
29
31
  /** 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
32
  decode(record: SessionRecord): Decoded<D> | null;
33
+ /** Decode a batch in its supplied order, omitting other contracts and retaining unknown matching records. */
34
+ decodeAll(records: readonly SessionRecord[]): Decoded<D>[];
31
35
  }
32
36
  export function defineRecord<D extends Json>(id: string, definition: {
33
37
  schema: z.ZodType<D>;
34
38
  }): RecordContract<D> {
35
39
  const { schema } = definition;
40
+ const decode = (record: SessionRecord): Decoded<D> | null => {
41
+ if (record.contract.id !== id) return null;
42
+ const data = structuredClone(record.data);
43
+ try {
44
+ const parsed = schema.safeParse(data);
45
+ return parsed.success ? { status: "known", record, data: parsed.data } : { status: "unknown", record, reason: "invalid_data" };
46
+ } catch { return { status: "unknown", record, reason: "invalid_data" }; }
47
+ };
36
48
  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" }; }
49
+ id, schema, decode,
50
+ decodeAll(records) {
51
+ return records.flatMap(record => {
52
+ const value = decode(record);
53
+ return value ? [value] : [];
54
+ });
45
55
  },
46
56
  };
47
57
  }
@@ -58,12 +68,26 @@ export function defineOperationRecord<I extends Json, O extends Json>(id: string
58
68
  inputSchema: definition.input, outputSchema: definition.output };
59
69
  }
60
70
  /** timeline reads the complete ancestor path to the snapshot tip; session reads all session records within the snapshot's upper bound in save order. */
61
- export interface RecordQuery { readonly scope: "timeline" | "session" }
71
+ export interface RecordQuery {
72
+ readonly scope: "timeline" | "session";
73
+ /** Inclusive lower and exclusive upper positions in the selected scope, before filtering. */
74
+ readonly from?: string;
75
+ readonly before?: string;
76
+ readonly contracts?: readonly string[];
77
+ readonly ids?: readonly string[];
78
+ /** Emitting resource identity; null selects records without an emitting resource. */
79
+ readonly source?: string | null;
80
+ /** Select the first or last matches in append order; results always retain append order. */
81
+ readonly edge?: "first" | "last";
82
+ readonly limit?: number;
83
+ }
62
84
  /** An observation handle fixed at one read position; reads records on demand and does not switch to the latest state after await. */
63
85
  export interface SessionView {
64
86
  readonly id: string;
65
87
  readonly title: string;
66
88
  readonly records: {
89
+ /** Identities, ancestry, and provenance without materializing record bodies. */
90
+ index(query: RecordQuery): readonly RecordInfo[];
67
91
  all(query: RecordQuery): readonly SessionRecord[];
68
92
  /** The earliest matching record; returns unknown if it cannot be decoded, without skipping it. */
69
93
  first<D extends Json>(contract: RecordContract<D>, query: RecordQuery): Decoded<D> | null;
@@ -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,62 @@
1
+ import { useCallback, useEffect, useState } from "react";
2
+ import type { Decoded, RecordContract, RecordInfo, RecordQuery, SessionRecord } from "./records.ts";
3
+ import type { Json } from "./json.ts";
4
+ import type { SessionSnapshot, ResourceSnapshot, ResourceRef } from "./workspace.ts";
5
+ import type { ResourceContract } from "./module-contract.ts";
6
+ export interface RecordReadOptions { readonly signal?: AbortSignal }
7
+
8
+ /** Remote snapshots share fixed positions and metadata; body reads are explicitly asynchronous. */
9
+ export interface RendererSessionSnapshot extends Omit<SessionSnapshot, "records" | "resources"> {
10
+ readonly resources: {
11
+ all(options?: RecordReadOptions): Promise<readonly ResourceSnapshot[]>;
12
+ linkedTo(receiver: ResourceRef, options?: RecordReadOptions): Promise<readonly ResourceSnapshot[]>;
13
+ get<S extends Json>(contract: ResourceContract<S>, id: string, options?: RecordReadOptions): Promise<
14
+ { status: "known"; resource: ResourceSnapshot<S> } | { status: "unknown"; resource: ResourceSnapshot; reason: "invalid_data" } | null>;
15
+ };
16
+ readonly records: {
17
+ index(query: RecordQuery): readonly RecordInfo[];
18
+ all(query: RecordQuery, options?: RecordReadOptions): Promise<readonly SessionRecord[]>;
19
+ query<D extends Json>(contract: RecordContract<D>, query: RecordQuery, options?: RecordReadOptions): Promise<Decoded<D>[]>;
20
+ first<D extends Json>(contract: RecordContract<D>, query: RecordQuery, options?: RecordReadOptions): Promise<Decoded<D> | null>;
21
+ last<D extends Json>(contract: RecordContract<D>, query: RecordQuery, options?: RecordReadOptions): Promise<Decoded<D> | null>;
22
+ };
23
+ }
24
+
25
+ type SessionReadState<T> =
26
+ | { status: "loading"; data: T | null; error: null }
27
+ | { status: "ready"; data: T; error: null }
28
+ | { status: "error"; data: null; error: Error };
29
+ const loading = { status: "loading", data: null, error: null } as const;
30
+ export type SessionRead<T> = SessionReadState<T> & { retry(): void };
31
+ export interface SessionReadOptions {
32
+ keepPrevious?: boolean;
33
+ /** Identity of the logical query whose content may remain visible during a reread; defaults to the reader function. */
34
+ key?: unknown;
35
+ }
36
+
37
+ /** Memoize read with useCallback. Replacing the snapshot or reader ends the old UI observation. */
38
+ export function useSessionRead<T>(snapshot: RendererSessionSnapshot | null, read: (snapshot: RendererSessionSnapshot, signal: AbortSignal) => Promise<T>,
39
+ options: SessionReadOptions = {}): SessionRead<T> {
40
+ const [attempt, setAttempt] = useState(0);
41
+ const retry = useCallback(() => setAttempt(value => value + 1), []);
42
+ const key = "key" in options ? options.key : read;
43
+ const [value, setValue] = useState<{ snapshot: RendererSessionSnapshot; read: typeof read; attempt: number; key: unknown; result: SessionReadState<T> } | null>(null);
44
+ useEffect(() => {
45
+ if (!snapshot) { setValue(null); return; }
46
+ const controller = new AbortController();
47
+ void Promise.resolve().then(() => read(snapshot, controller.signal)).then(data => {
48
+ if (!controller.signal.aborted) setValue({ snapshot, read, attempt, key, result: { status: "ready", data, error: null } });
49
+ }, error => {
50
+ if (!controller.signal.aborted) setValue({ snapshot, read, attempt, key, result: { status: "error", data: null, error: error instanceof Error ? error : new Error(String(error)) } });
51
+ });
52
+ return () => controller.abort();
53
+ }, [snapshot, read, attempt, key]);
54
+ if (value?.snapshot === snapshot && value?.read === read && value.attempt === attempt && Object.is(value.key, key))
55
+ return { ...value.result, retry };
56
+ let data: T | null = null;
57
+ if (options.keepPrevious && value && snapshot && Object.is(value.key, key) && value.snapshot.id === snapshot.id) {
58
+ const tip = value.snapshot.position.nodeId;
59
+ if (tip === null || snapshot.records.index({ scope: "timeline", ids: [tip] }).length > 0) data = value.result.data;
60
+ }
61
+ return { ...loading, data, retry };
62
+ }
package/src/renderer.ts CHANGED
@@ -7,7 +7,9 @@ export * from "./renderer-i18n.ts";
7
7
  import type { ActionContract, CreationContract } from "./commands.ts";
8
8
  import type { Json } from "./json.ts";
9
9
  import { reference, type ContractReference, type DataContract } from "./presentation.ts";
10
- import type { ResourceRef, SessionSnapshot } from "./workspace.ts";
10
+ import type { ResourceRef } from "./workspace.ts";
11
+ import type { RendererSessionSnapshot } from "./renderer-session.ts";
12
+ export * from "./renderer-session.ts";
11
13
  export * from "./renderer-services.ts";
12
14
  export * from "./renderer-calls.ts";
13
15
  export * from "./renderer-creation.ts";
@@ -60,7 +62,7 @@ export interface RendererObjectContext {
60
62
  error: UiText | null; missing: boolean;
61
63
  };
62
64
  readonly session: {
63
- snapshot(): SessionSnapshot | null;
65
+ snapshot(): RendererSessionSnapshot | null;
64
66
  subscribe(listener: () => void): () => void;
65
67
  create<I, O extends Json>(contract: CreationContract<I, Json, O>, input: NoInfer<I> & Json, position: { x: number; y: number }, options?: RendererInputOptions): Promise<RendererReceipt>;
66
68
  refresh(): Promise<void>;
@@ -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 });
@@ -23,6 +23,7 @@ import type { TopLevelTool } from "./runtime-tools.ts";
23
23
  import type { ModelProviderServices } from "./runtime-model-providers.ts";
24
24
  import type { UsageProviderServices, UsageProvider, UsageServices, ProviderUsage } from "./runtime-usage.ts";
25
25
  import type { WebServices, WebProviderServices, WebProviderDefinition } from "./runtime-web.ts";
26
+ import type { MessagingServices, MessagingProviderDefinition } from "./runtime-messaging.ts";
26
27
  import type { ModelProviderPresetContribution } from "./model-provider.ts";
27
28
  import type { AgentCatalog, AgentSkillDeclaration, AgentInstructionDeclaration } from "./runtime-agent-catalog.ts";
28
29
  import type { SessionCreation } from "./runtime-sessions.ts";
@@ -61,12 +62,14 @@ export interface PluginContext {
61
62
  readonly models: ModelServices;
62
63
  readonly execution: import("./runtime-execution.ts").ExecutionServices;
63
64
  readonly content: import("./content-runtime.ts").ContentServices;
65
+ readonly files: import("./runtime-files.ts").FileServices;
64
66
  readonly modelProviders: ModelProviderServices;
65
67
  readonly usageProviders: UsageProviderServices;
66
68
  readonly usages: UsageServices;
67
69
  readonly providerUsage: ProviderUsage;
68
70
  readonly webProviders: WebProviderServices;
69
71
  readonly web: WebServices;
72
+ readonly messaging: MessagingServices;
70
73
  session(id: string): SessionExecutor;
71
74
  /** Obtain an object handle using a named resource contract; the host validates plugin ownership of the contract, object existence, and matching type, and stamps records accordingly. */
72
75
  object<S extends Json>(sessionId: string, contract: ResourceContract<S>, id: string): ObjectExecutor;
@@ -130,6 +133,8 @@ export interface ResourceContribution {
130
133
  project(resource: ResourceSnapshot, object: ObjectReader): Presentation;
131
134
  inspect(resource: ResourceSnapshot, object: ObjectReader): Promise<Json>;
132
135
  context?(resource: ResourceSnapshot, object: ObjectReader): Promise<ContextFile[]>;
136
+ /** Resolve a file address against this resource at consumption time; consumers need no link or registration of the reference. */
137
+ openFile?(resource: ResourceSnapshot, locator: Json, context: { object: ObjectReader; signal: AbortSignal }): AsyncIterable<Uint8Array>;
133
138
  /** Explanation presented to users before ending the current instance; does not block backend removal or wait for external cleanup. */
134
139
  disposalWarning?(resource: ResourceSnapshot, object: ObjectReader): UiText | null;
135
140
  /**
@@ -147,7 +152,7 @@ export type CallResult<D extends Json = Json> =
147
152
  | OptionalData<Exclude<ToolCompletion, { kind: "succeeded" | "partial" }>, D>;
148
153
  export type PreparedResult = CallResult & ToolInvocationInfo;
149
154
  /** 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">>;
155
+ export type ToolCaller = Readonly<Pick<ResourceSnapshot, "ref" | "title"> & { agent?: string }>;
151
156
  export interface ToolInvocation extends ToolInvocationInfo {
152
157
  effect: "read" | "write";
153
158
  execution: "parallel" | "sequential";
@@ -164,6 +169,7 @@ export interface ModuleContribution {
164
169
  agentSkills?: readonly AgentSkillDeclaration[];
165
170
  agentInstructions?: readonly AgentInstructionDeclaration[];
166
171
  webProviders?: readonly WebProviderDefinition[];
172
+ messagingProviders?: readonly MessagingProviderDefinition[];
167
173
  usageProviders?: readonly UsageProvider[];
168
174
  modelProviderPresets?: readonly ModelProviderPresetContribution[];
169
175
  calls?: readonly CallContribution[];
@@ -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
+ }
@@ -0,0 +1,58 @@
1
+ import type { UiText } from "./i18n.ts";
2
+ import type { ProviderSetting, ProviderSettingValues } from "./provider-settings.ts";
3
+ import type { MessagingProviderType, MessagingConnectionInfo, ConversationQuery, ConversationList,
4
+ MessageQuery, MessageList, SendMessage, MessagingMessage, MessagingEvent, ConnectionEvent } from "./messaging.ts";
5
+
6
+ export interface MessagingInstance {
7
+ readonly identity: string;
8
+ /**
9
+ * Runs until the receiving signal ends. Call ready once the platform has accepted this receiver; the connection then
10
+ * reports connected and its retry backoff resets. A rejection is a connection failure: the host calls receive again on
11
+ * the same instance after a backoff unless the error is a terminal MessagingError. Queries and sends have independent request signals.
12
+ */
13
+ receive(options: { signal: AbortSignal; ready(): void }): Promise<void>;
14
+ listConversations(query: ConversationQuery, options: { signal: AbortSignal }): Promise<ConversationList>;
15
+ readMessages(query: MessageQuery, options: { signal: AbortSignal }): Promise<MessageList>;
16
+ sendMessage(input: SendMessage, options: { signal: AbortSignal }): Promise<MessagingMessage>;
17
+ }
18
+ export interface MessagingProviderDefinition {
19
+ id: string;
20
+ label: UiText;
21
+ /** Settings the user configures for each connection, rendered in declaration order. */
22
+ settings: readonly ProviderSetting[];
23
+ /**
24
+ * One instance per enabled connection; a creation failure is retried like a receive failure.
25
+ * Provider-owned persistence may be shared across its instances.
26
+ */
27
+ create(context: {
28
+ connectionId: string; settings: ProviderSettingValues;
29
+ signal: AbortSignal; publish(event: MessagingEvent): void;
30
+ }): Promise<MessagingInstance>;
31
+ /** Release provider-owned data for a removed connection after its receiver has ended. */
32
+ forget?(connectionId: string): void | Promise<void>;
33
+ }
34
+ export interface MessagingHandle {
35
+ listConversations(query: ConversationQuery, options: { signal: AbortSignal }): Promise<ConversationList>;
36
+ readMessages(query: MessageQuery, options: { signal: AbortSignal }): Promise<MessageList>;
37
+ sendMessage(input: SendMessage, options: { signal: AbortSignal }): Promise<MessagingMessage>;
38
+ }
39
+ export interface MessagingServices {
40
+ types(): readonly MessagingProviderType[];
41
+ connections(): readonly MessagingConnectionInfo[];
42
+ /** Captures a connection handle. Operations await a connection in progress with their own cancellation signals. */
43
+ resolve(connectionId: string, options: { signal: AbortSignal }): Promise<MessagingHandle>;
44
+ subscribe(listener: (event: ConnectionEvent) => void): () => void;
45
+ subscribeConnections(listener: () => void): () => void;
46
+ }
47
+ /**
48
+ * request_failed and errors other than MessagingError are transient and retried with backoff; retryAfterMs overrides the delay.
49
+ * Other codes are terminal for a receiving connection.
50
+ */
51
+ export type MessagingErrorCode = "unavailable" | "unsupported" | "invalid_input" | "invalid_cursor" | "request_failed";
52
+ export class MessagingError extends Error {
53
+ readonly retryAfterMs?: number;
54
+ constructor(readonly code: MessagingErrorCode, message: string, options: { retryAfterMs?: number; cause?: unknown } = {}) {
55
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
56
+ if (options.retryAfterMs !== undefined) this.retryAfterMs = options.retryAfterMs;
57
+ }
58
+ }
@@ -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,4 +1,3 @@
1
- import type { Json } from "./json.ts";
2
1
  import type { CallResult } from "./runtime-contracts.ts";
3
2
  import type { ExecResult, ShellSettings, ShellProfileList } from "./shell.ts";
4
3
  import type { TerminalSessions } from "./runtime-terminal.ts";
@@ -6,7 +5,6 @@ import type { TerminalSessions } from "./runtime-terminal.ts";
6
5
  export interface ShellProfiles { get(): ShellSettings; list(): Promise<ShellProfileList> }
7
6
  /** One noninteractive shell command with piped output and its own process lifetime. */
8
7
  export interface ShellExecution {
9
- inspect(): Promise<Json>;
10
8
  execute(cwd: string, args: { command: string; timeout?: number }, options: {
11
9
  signal: AbortSignal; publish(data: ExecResult): void;
12
10
  }): Promise<CallResult<ExecResult>>;
@@ -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;
@@ -1,5 +1,6 @@
1
1
  import type { UiText } from "./i18n.ts";
2
- import type { WebCredentialDefinition, WebProviderState, WebProviderType, WebSearchRequest, WebFetchRequest, WebResponse, WebSearchResult, WebFetchResult } from "./web.ts";
2
+ import type { ProviderSetting, ProviderSettingValues } from "./provider-settings.ts";
3
+ import type { WebProviderState, WebProviderType, WebSearchRequest, WebFetchRequest, WebResponse, WebSearchResult, WebFetchResult } from "./web.ts";
3
4
 
4
5
  export interface WebProviderInstance {
5
6
  search?(request: WebSearchRequest, options: { signal: AbortSignal }): Promise<WebResponse>;
@@ -12,11 +13,13 @@ export interface WebProviderDefinition {
12
13
  fetch: boolean;
13
14
  /** Glob for the complete URL, with * matching any characters; fetch routing matches in declaration order. */
14
15
  urlPatterns: readonly string[];
15
- defaultBaseUrl: string;
16
- /** Required credential type; null means no credentials are required. */
17
- credential: WebCredentialDefinition | null;
18
- /** Synchronous factory; baseUrl has trailing slashes removed, and credential is null if and only if the credential declaration is null. */
19
- create(context: { baseUrl: string; credential: string | null }): WebProviderInstance;
16
+ /** Settings the user configures for this service, rendered in declaration order. */
17
+ settings: readonly ProviderSetting[];
18
+ /**
19
+ * Synchronous factory called with values captured at the request boundary.
20
+ * Choice settings always hold a declared option; required values are present; unset optional values are absent.
21
+ */
22
+ create(context: { settings: ProviderSettingValues }): WebProviderInstance;
20
23
  }
21
24
  export interface WebProviderServices {
22
25
  types(): readonly WebProviderType[];
package/src/runtime.ts CHANGED
@@ -10,9 +10,11 @@ export * from "./runtime-tools.ts";
10
10
  export type * from "./runtime-model-providers.ts";
11
11
  export * from "./runtime-usage.ts";
12
12
  export * from "./runtime-web.ts";
13
+ export * from "./runtime-messaging.ts";
13
14
  export * from "./runtime-agent-catalog.ts";
14
15
  export * from "./runtime-sessions.ts";
15
16
  export type * from "./content-runtime.ts";
17
+ export type * from "./runtime-files.ts";
16
18
  export type * from "./models.ts";
17
19
  export type * from "./runtime-execution.ts";
18
20
  export { validationMessage, jsonArgumentHint } from "./tool-validation.ts";
package/src/shell.ts CHANGED
@@ -40,6 +40,7 @@ export type ShellSettings = z.infer<typeof shellSettingsSchema>;
40
40
  export const ShellProfilesCatalog = defineData("asterism.shell/profiles", shellSettingsSchema);
41
41
 
42
42
  export const shellProfileListSchema = z.strictObject({
43
+ platform: z.string().describe("Host operating system platform, such as 'darwin', 'linux', or 'win32'."),
43
44
  selected: z.string(),
44
45
  resolvedProfile: z.string().nullable(),
45
46
  profiles: z.array(z.strictObject({
package/src/web.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { presentationSchema } from "./presentation.ts";
3
3
  import { uiTextSchema } from "./i18n.ts";
4
+ import { providerSettingsSchema } from "./provider-settings.ts";
4
5
 
5
6
  export const webUrlSchema = z.string().url().refine(value => {
6
7
  const url = new URL(value);
@@ -45,20 +46,16 @@ export const webFetchRequestSchema = z.object({
45
46
  maxCharacters: z.number().int().positive().optional().describe("Maximum body characters per document, counted as Unicode code points across body parts. Excerpts and metadata are separate. Omitted uses provider defaults."),
46
47
  }).describe("URL, optional additional excerpt focus and body character limit.");
47
48
 
48
- /** Providers declare credential types; the UI renders corresponding inputs by type and does not accept arbitrary JSON. */
49
- export const webCredentialDefinitionSchema = z.object({
50
- kind: z.enum(["api_key"]),
51
- keyUrl: webUrlSchema.optional(),
52
- });
53
- /** At most one configuration per provider type; id equals the type slug. */
49
+ /** At most one configuration per provider type; id equals the type slug. Settings hold saved non-secret values by key. */
54
50
  export const webProviderStateSchema = z.strictObject({
55
51
  id: z.string().trim().min(1),
56
52
  enabled: z.boolean(),
53
+ settings: z.record(z.string(), z.string()),
57
54
  });
58
55
  export const webProviderTypeSchema = z.object({
59
56
  id: z.string().min(1), label: uiTextSchema, owner: z.string(),
60
57
  search: z.boolean(), fetch: z.boolean(), urlPatterns: z.array(z.string().min(1)),
61
- credential: webCredentialDefinitionSchema.nullable(),
58
+ settings: providerSettingsSchema,
62
59
  });
63
60
  /** provider in results is the type slug of the provider that actually handled the request. */
64
61
  export const webSearchResultSchema = webResponseSchema.extend({ query: z.string(), provider: z.string() });
@@ -68,7 +65,6 @@ export type WebDocument = z.infer<typeof webDocumentSchema>;
68
65
  export type WebResponse = z.infer<typeof webResponseSchema>;
69
66
  export type WebSearchRequest = z.infer<typeof webSearchRequestSchema>;
70
67
  export type WebFetchRequest = z.infer<typeof webFetchRequestSchema>;
71
- export type WebCredentialDefinition = z.infer<typeof webCredentialDefinitionSchema>;
72
68
  export type WebProviderState = z.infer<typeof webProviderStateSchema>;
73
69
  export type WebProviderType = z.infer<typeof webProviderTypeSchema>;
74
70
  export type WebSearchResult = z.infer<typeof webSearchResultSchema>;