@asterism-app/sdk 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -70,6 +70,14 @@ for (const created of ResourceCreated.decodeAll(records)) {
70
70
 
71
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
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
+
73
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.
74
82
 
75
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.
@@ -0,0 +1,19 @@
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 connection-state callbacks, 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. A transport that restores its own protocol session calls `reconnecting(error)` during the interruption and `ready()` after recovery, preserving its active receiver. Queries and sends have their own signals. A send carries ordered text and file-reference parts plus an optional reply target. Platforms with a caption field combine the text and deliver the files in order. Resolve each reference with `plugin.files` before contacting the platform, so an unreadable source fails as invalid input without sending anything.
8
+
9
+ Received messages also have ordered text and file parts. File parts identify a platform attachment and describe its MIME type, filename, and known size. An instance's optional `openFile` operation streams the bytes selected by conversation, message, and file IDs. Verify that the selected file belongs to that address, refresh temporary platform URLs as needed, and preserve cancellation and download errors. Resource consumers create FileRefs with their own source identity; provider messages do not depend on a particular card or session.
10
+
11
+ 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`.
12
+
13
+ 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.
14
+
15
+ 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.
16
+
17
+ 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.
18
+
19
+ 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.
@@ -16,6 +16,8 @@ Resource titles belong to session history. Use the session's rename operation wi
16
16
 
17
17
  Declare `links: { receive: true }` in the backend resource implementation when the object can receive directed links. The host supplies this capability to the workbench's connection controls and authorization panel. Renderer resource descriptions supply labels, icons, and card geometry; link reception needs no frontend declaration.
18
18
 
19
+ Within a tool, `session.link(receiverId)` exposes the bound caller to a recipient in the request's captured resource scope, and `session.unlink(receiverId)` withdraws that exposure. The host supplies the caller identity. These operations preserve the recipient's link to the caller and cannot authorize additional resources for the caller. Subsequent requests capture the updated relationships; active requests retain their captured access.
20
+
19
21
  Use a session snapshot to query the resources directly linked to a receiver. Results contain resource references, titles, and public data on that snapshot's timeline path. Reverse links and links through another resource are independent. For external event handling, such as forwarding network messages to linked agents, read a fresh snapshot for each event. Session observers can also query their supplied snapshot after commits or cursor changes. The query exposes relationships without granting access to private state or expanding a model request's operation scope.
20
22
 
21
23
  ## Add a model operation
@@ -44,6 +46,8 @@ Resource holds do not block history movement. Use an object busy scope for work
44
46
 
45
47
  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.
46
48
 
49
+ Tool input events arrive in model order before the batch executes. A consumer can begin an operation record for each input, then fill that record when its tool completion event arrives. Progress remains transient. Response termination metadata describes model generation independently of tool outcomes, including available diagnostics after a failed stream. The caller owns retry policy and can use the returned failure's retryability without interpreting provider error strings.
50
+
47
51
  For a temporary conversation, use a content scope to retain generated attachments across requests. Pass it as the input reader and output owner for session-bound execution. Persistent records or a longer-lived scope must retain any surviving results before the temporary scope closes.
48
52
 
49
53
  ## Connect other interactions
@@ -2,6 +2,8 @@
2
2
 
3
3
  Views present state and accept input. Backend services own the work, results, and resource lifetime.
4
4
 
5
+ Application file services let views open resource FileRefs as byte streams and save a stream through the native Save As dialog. Pass a suggested filename and a lazy stream from the object's content reader or a file reference. Cancelling the dialog returns without reading the stream; ending the stream early abandons the transfer. Transfer failures preserve the old destination and surface as errors; views own their pending indicator and feedback. Previews and exports of captured content read the same immutable bytes.
6
+
5
7
  ## Present objects and operations
6
8
 
7
9
  A resource card shows the object's content. A tool view shows one operation, including generated input, execution progress, and the final outcome.
@@ -1,7 +1,8 @@
1
1
  import { sample, Counter, Count, CounterView, CountChanged, CreateCounter, ChangeCount, CounterUpdates, counterCard } from "./counter-contract.ts";
2
2
  /** Independent examples of session records, resource behavior, and model execution. */
3
3
  import { z } from "zod";
4
- import { pluginNamespace, defineAction, resourceCall, defineRecord, defineTool, defineImplementation, modelRunRecordSchema, type ModelItem } from "@asterism-app/sdk/contracts";
4
+ import { pluginNamespace, defineAction, resourceCall, defineRecord, defineOperationRecord, defineTool, defineImplementation,
5
+ modelRunRecordSchema, modelBlockSchema, toolOutcomeSchema, type ModelItem } from "@asterism-app/sdk/contracts";
5
6
  import {
6
7
  defineModule, definePlugin, implementCreation, implementAction, implementPreparer, implementResource, implementTool, implementChannel,
7
8
  type PluginContext, type ObjectReader, type ObjectExecutor, type SessionObserver, type SessionSnapshot, type ResourceRef,
@@ -121,19 +122,25 @@ export const counterPlugin = definePlugin({
121
122
  /** Scenario three: the plugin's own Agent drives the loop, with context projected from the timeline each time. */
122
123
  const research = pluginNamespace("example.research");
123
124
  const Execution = defineRecord(research.name("execution"), { schema: modelRunRecordSchema });
124
- export const modelRecordsModule = defineModule(() => ({ records: [Execution] }));
125
+ const ToolExecution = defineOperationRecord(research.name("tool-execution"), { input: modelBlockSchema, output: toolOutcomeSchema });
126
+ export const modelRecordsModule = defineModule(() => ({ records: [Execution, ToolExecution] }));
125
127
  /** The domain plugin constructs the projection from its own input/execution events; it is not stored in Agent or run. */
126
128
  export async function modelWork(plugin: PluginContext, object: ObjectExecutor, signal: AbortSignal,
127
129
  projectOwnContext: (snapshot: SessionSnapshot, object: ResourceRef) => ModelItem[]) {
128
130
  for (let request = 0; request < 8; request++) {
129
131
  const snapshot = object.session.snapshot();
132
+ const calls = new Map<string, string>();
130
133
  const result = await plugin.execution.run({
131
134
  access: object.ref, interactive: false, requestParentId: snapshot.position.nodeId, target: { provider: "configured-provider", model: "configured-model" },
132
135
  system: { blocks: [{ id: research.name("instruction"), text: "Inspect linked materials and report findings." }] },
133
136
  messages: projectOwnContext(snapshot, object.ref), cache: { expectHit: request > 0 }, signal,
134
137
  observer: { event(event) {
135
138
  if (event.type === "progress") return;
136
- object.commit(writer => { writer.append(Execution, modelRunRecordSchema.parse(event)); });
139
+ object.commit(writer => {
140
+ if (event.type === "tool.begin") calls.set(event.block.callId, writer.begin(ToolExecution, event.block));
141
+ else if (event.type === "tool.complete") writer.complete(ToolExecution, calls.get(event.block.callId)!, event.block.outcome!);
142
+ else writer.append(Execution, modelRunRecordSchema.parse(event));
143
+ });
137
144
  } },
138
145
  });
139
146
  if (result.reason !== "completed" || result.tools.length === 0) return result;
@@ -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> }) {
@@ -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.2.0",
3
+ "version": "1.4.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
@@ -30,7 +30,9 @@ export * from "./model-cost-estimate.ts";
30
30
  export * from "./model-media.ts";
31
31
  export * from "./model-provider.ts";
32
32
  export * from "./provider-usage.ts";
33
+ export * from "./provider-settings.ts";
33
34
  export * from "./web.ts";
35
+ export * from "./messaging.ts";
34
36
 
35
37
  export * from "./session-title.ts";
36
38
 
package/src/files.ts CHANGED
@@ -15,5 +15,6 @@ export const fileReferencePartSchema = z.strictObject({
15
15
  ref: fileRefSchema,
16
16
  filename: z.string().min(1).max(255).optional().describe("Name used for delivery."),
17
17
  mediaType: z.string().optional().describe("Descriptive MIME type; the reference does not freeze the source content."),
18
+ size: z.number().int().nonnegative().optional().describe("Byte size observed when the reference was described."),
18
19
  }).describe("A FileRef with optional delivery metadata.");
19
20
  export type FileReferencePart = z.infer<typeof fileReferencePartSchema>;
@@ -0,0 +1,88 @@
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 messagingFilePartSchema = z.strictObject({
38
+ kind: z.literal("file"), id,
39
+ filename: z.string().optional(), mediaType: z.string(),
40
+ size: z.number().int().nonnegative().optional(),
41
+ });
42
+ export const messagingTextPartSchema = z.strictObject({ kind: z.literal("text"), text: z.string() });
43
+ export const messagingPartSchema = z.discriminatedUnion("kind", [messagingTextPartSchema, messagingFilePartSchema]);
44
+ export const messageSchema = z.strictObject({
45
+ id, sender: messageSenderSchema, parts: z.array(messagingPartSchema),
46
+ sentAt: z.string(), replyTo: id.optional(), threadId: id.optional(),
47
+ });
48
+ export const messagingFileQuerySchema = conversationAddressSchema.extend({ messageId: id, fileId: id });
49
+ export const conversationQuerySchema = z.strictObject({ since: id.optional() });
50
+ export const conversationListSchema = z.strictObject({
51
+ conversations: z.array(conversationSchema), cursor: id.optional(), truncated: z.boolean(),
52
+ });
53
+ export const messageQuerySchema = conversationAddressSchema.extend({
54
+ since: id.optional(), limit: z.number().int().positive().optional(),
55
+ });
56
+ export const messageListSchema = z.strictObject({
57
+ messages: z.array(messageSchema), cursor: id.optional(), truncated: z.boolean(),
58
+ });
59
+ /** Files are references resolved by the provider when sending; text accompanies them as a caption. */
60
+ export const sendMessageSchema = conversationAddressSchema.extend({
61
+ parts: z.array(z.union([messagingTextPartSchema, fileReferencePartSchema])).min(1),
62
+ replyTo: id.optional(),
63
+ }).refine(value => value.parts.some(part => part.kind === "file-reference" || part.text.trim()), "A message requires text or a file.");
64
+ export const messagingEventSchema = z.discriminatedUnion("kind", [
65
+ z.strictObject({ kind: z.literal("conversation.discovered"), conversation: conversationSchema }),
66
+ z.strictObject({ kind: z.literal("message.received"), conversation: conversationSchema, message: messageSchema }),
67
+ ]);
68
+ export type MessagingProviderType = z.infer<typeof messagingProviderTypeSchema>;
69
+ export type MessagingConnection = z.infer<typeof messagingConnectionSchema>;
70
+ export type MessagingConnectionStatus = z.infer<typeof messagingConnectionStatusSchema>;
71
+ export type MessagingConnectionInfo = z.infer<typeof messagingConnectionInfoSchema>;
72
+ export type ConversationAddress = z.infer<typeof conversationAddressSchema>;
73
+ export type MessagingConversation = z.infer<typeof conversationSchema>;
74
+ export type MessageSenderRole = z.infer<typeof messageSenderRoleSchema>;
75
+ export type MessagingMessage = z.infer<typeof messageSchema>;
76
+ export type MessagingFilePart = z.infer<typeof messagingFilePartSchema>;
77
+ export type MessagingPart = z.infer<typeof messagingPartSchema>;
78
+ export type MessagingFileQuery = z.infer<typeof messagingFileQuerySchema>;
79
+ export function messagingText(message: { parts: readonly MessagingPart[] }): string {
80
+ return message.parts.map(part => part.kind === "text" ? part.text : `[File: ${part.filename ?? part.id}]`).join("\n");
81
+ }
82
+ export type ConversationQuery = z.infer<typeof conversationQuerySchema>;
83
+ export type ConversationList = z.infer<typeof conversationListSchema>;
84
+ export type MessageQuery = z.infer<typeof messageQuerySchema>;
85
+ export type MessageList = z.infer<typeof messageListSchema>;
86
+ export type SendMessage = z.infer<typeof sendMessageSchema>;
87
+ export type MessagingEvent = z.infer<typeof messagingEventSchema>;
88
+ export type ConnectionEvent = { connectionId: string; event: MessagingEvent };
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { contentRefSchema } from "./content.ts";
3
+ import { fileRefSchema } from "./files.ts";
3
4
 
4
5
  /** mediaType is the MIME type truthfully identified by the client and sent with the bytes; the client does not infer model capabilities from it, and acceptance is determined by server feedback. */
5
6
  export const mediaTypeSchema = z.string().regex(/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/);
@@ -8,7 +9,9 @@ export const mediaTypeSchema = z.string().regex(/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$
8
9
  export const modelInputPartSchema = z.discriminatedUnion("kind", [
9
10
  z.strictObject({ kind: z.literal("text"), text: z.string() }),
10
11
  z.strictObject({ kind: z.literal("file"), file: contentRefSchema,
11
- mediaType: mediaTypeSchema, filename: z.string().min(1).max(255).optional() }),
12
+ mediaType: mediaTypeSchema, filename: z.string().min(1).max(255).optional(),
13
+ size: z.number().int().nonnegative().optional(),
14
+ ref: fileRefSchema.optional().describe("Resource address for saving or forwarding the captured file.") }),
12
15
  ]);
13
16
  export type ModelInputPart = z.infer<typeof modelInputPartSchema>;
14
17
  export type ModelFilePart = Extract<ModelInputPart, { kind: "file" }>;
@@ -1,7 +1,7 @@
1
1
  /** Shared payloads for model execution; consuming plugins declare RecordContract identities, and the SDK does not create a separate history. */
2
2
  import { z } from "zod";
3
3
  import { jsonSchema, type Json } from "./json.ts";
4
- import { toolOutcomeSchema } from "./tool-result.ts";
4
+ import { toolOutcomeSchema, toolInvocationSchema } from "./tool-result.ts";
5
5
  import { presentationSchema, type DataContract } from "./presentation.ts";
6
6
  import type { ModelCompletion } from "./models.ts";
7
7
  import { errorDetailsSchema } from "./error-details.ts";
@@ -27,9 +27,16 @@ export const requestTimingSchema = z.strictObject({
27
27
  export type RequestTiming = z.infer<typeof requestTimingSchema>;
28
28
 
29
29
  export const modelSourceSchema = z.strictObject({ model: z.string(), adapter: z.string(), scope: z.string() });
30
- export const modelCompletionSchema = z.strictObject({ usage: modelUsageSchema.nullable(), finishReason: z.string(),
30
+ export const modelTerminationSchema = z.discriminatedUnion("reason", [
31
+ z.strictObject({ reason: z.literal("completed") }),
32
+ z.strictObject({ reason: z.literal("cancelled") }),
33
+ z.strictObject({ reason: z.literal("failed"), origin: z.enum(["model", "software"]), code: z.string(), message: z.string(),
34
+ retryable: z.boolean(), details: errorDetailsSchema.optional() }),
35
+ ]);
36
+ /** finishReason is the provider-reported reason; it is null when generation ended before the provider reported one. */
37
+ export const modelCompletionSchema = z.strictObject({ usage: modelUsageSchema.nullable(), finishReason: z.string().nullable(),
31
38
  rawFinishReason: z.string().nullable(), providerResponseId: z.string().nullable(), timing: requestTimingSchema.optional(),
32
- extensions: z.array(presentationSchema).optional() });
39
+ termination: modelTerminationSchema.optional(), extensions: z.array(presentationSchema).optional() });
33
40
  /** Decode only domain extensions known to the caller; unknown or undecodable extensions do not affect the public terminal state. */
34
41
  export function completionData<T extends Json>(completion: ModelCompletion | null | undefined, contract: DataContract<T>): T | null {
35
42
  const extension = completion?.extensions?.find(value => value.contract.id === contract.id);
@@ -41,16 +48,19 @@ const block = { responseId: id, requestParentId: id.nullable(), ordinal: z.numbe
41
48
  complete: z.boolean(), continuation: jsonSchema, source: modelSourceSchema, completion: modelCompletionSchema.nullable().optional(),
42
49
  /** Block generation start and end times (millisecond timestamps); blocks finalized before generation ends have a null end time, and unrecorded times are omitted. See outcome for tool execution times. */
43
50
  startedAt: z.number().nonnegative().optional(), endedAt: z.number().nonnegative().nullable().optional() };
51
+ /** Tool call block shape without the completion invariant, for contracts that store input and outcome separately. */
52
+ export const modelToolCallBlockSchema = z.strictObject({ ...block, kind: z.literal("toolcall"), callId: id, name: id,
53
+ /** Original model text; retained only when parsed arguments are unavailable (the call is incomplete), otherwise arguments is authoritative. */
54
+ argumentsText: z.string().nullable(), arguments: jsonSchema, outcome: toolOutcomeSchema.nullable(), invocation: toolInvocationSchema.optional() });
44
55
  export const modelBlockSchema = z.discriminatedUnion("kind", [
45
56
  z.strictObject({ ...block, kind: z.literal("thinking"), text: z.string(), summary: z.string() }),
46
57
  z.strictObject({ ...block, kind: z.literal("text"), text: z.string() }),
47
- z.strictObject({ ...block, kind: z.literal("toolcall"), callId: id, name: id,
48
- /** Original model text; retained only when parsed arguments are unavailable (the call is incomplete), otherwise arguments is authoritative. */
49
- argumentsText: z.string().nullable(), arguments: jsonSchema, outcome: toolOutcomeSchema.nullable() })
50
- .refine(data => data.complete === (data.outcome !== null), "Complete tool calls must have an outcome."),
58
+ modelToolCallBlockSchema.refine(data => data.complete === (data.outcome !== null), "Complete tool calls must have an outcome."),
51
59
  ]);
52
- /** Terminal state is embedded in finalized blocks; execution notifications carry only feedback, not response identity or measurements. */
60
+ /** Generation termination is embedded in blocks; tool publication and completion preserve a fixed input position. */
53
61
  export const modelRunRecordSchema = z.discriminatedUnion("type", [
54
62
  z.strictObject({ type: z.literal("block"), block: modelBlockSchema }),
55
- z.strictObject({ type: z.literal("diagnostic"), origin: z.enum(["model", "software"]), code: z.string(), message: z.string(), level: z.enum(["error", "warning"]), details: errorDetailsSchema.optional() }),
63
+ z.strictObject({ type: z.literal("tool.begin"), block: modelBlockSchema }),
64
+ z.strictObject({ type: z.literal("tool.complete"), block: modelBlockSchema }),
65
+ z.strictObject({ type: z.literal("diagnostic"), origin: z.enum(["model", "software"]), code: z.string(), message: z.string(), level: z.enum(["error", "warning"]), details: errorDetailsSchema.optional(), responseId: id.optional() }),
56
66
  ]);
package/src/models.ts CHANGED
@@ -39,13 +39,21 @@ export type ModelEvent =
39
39
  | { type: "part.end"; partId: string; arguments?: Json; continuation?: Json }
40
40
  | { type: "finish"; reason: string; usage: Usage | null; responseId?: string; rawFinishReason?: string; source?: ModelSource; timing?: RequestTiming; response?: ModelResponse | null };
41
41
  export type ModelSource = { model: string; adapter: string; scope: string };
42
+ export type ModelTermination =
43
+ | { reason: "completed" }
44
+ | { reason: "cancelled" }
45
+ | { reason: "failed"; origin: "model" | "software"; code: string; message: string; retryable: boolean; details?: ErrorDetails };
42
46
  export type ModelCompletion = {
43
- usage: Usage | null; finishReason: string; rawFinishReason: string | null; providerResponseId: string | null;
47
+ usage: Usage | null;
48
+ /** Provider-reported finish reason; null when generation ended before the provider reported one. */
49
+ finishReason: string | null; rawFinishReason: string | null; providerResponseId: string | null;
44
50
  timing?: RequestTiming;
51
+ /** How model generation ended, independently of subsequent tool execution. Omitted in older history. */
52
+ termination?: ModelTermination;
45
53
  /** Typed data declared and consumed by the domain; the public layer preserves unknown contracts. */
46
54
  extensions?: Presentation[];
47
55
  };
48
- /** Finalized response blocks; these are not session nodes, and the consumer provides timeline identity and persistence. */
56
+ /** Response blocks, including published tool inputs; consumers own timeline identity and one-time outcome persistence. */
49
57
  export type ModelBlock = {
50
58
  responseId: string; requestParentId: string | null; ordinal: number; complete: boolean; continuation: Json; source: ModelSource;
51
59
  /** Terminal state is delivered once with the actual response block having the highest ordinal; null for all other blocks. */
@@ -55,7 +63,9 @@ export type ModelBlock = {
55
63
  } & (
56
64
  | { kind: "thinking"; text: string; summary: string }
57
65
  | { kind: "text"; text: string }
58
- | { kind: "toolcall"; callId: string; name: string; argumentsText: string | null; arguments: Json; outcome: ToolOutcome | null }
66
+ | { kind: "toolcall"; callId: string; name: string; argumentsText: string | null; arguments: Json; outcome: ToolOutcome | null;
67
+ /** Original input preview identity; available even when execution never produced an outcome. */
68
+ invocation?: ToolInvocationInfo }
59
69
  );
60
70
  export type ModelLiveBlock = { id: string; responseId: string; ordinal: number } & (
61
71
  | { kind: "text"; text: string; endedAt: number | null }
@@ -66,8 +76,10 @@ export type ModelLiveBlock = { id: string; responseId: string; ordinal: number }
66
76
  );
67
77
  export type ModelRunEvent =
68
78
  | { type: "block"; block: ModelBlock }
79
+ | { type: "tool.begin"; block: Extract<ModelBlock, { kind: "toolcall" }> }
80
+ | { type: "tool.complete"; block: Extract<ModelBlock, { kind: "toolcall" }> }
69
81
  | { type: "progress"; blocks: readonly ModelLiveBlock[] }
70
- | { type: "diagnostic"; origin: "model" | "software"; code: string; message: string; level: "error" | "warning"; details?: ErrorDetails };
82
+ | { type: "diagnostic"; origin: "model" | "software"; code: string; message: string; level: "error" | "warning"; details?: ErrorDetails; responseId?: string };
71
83
  /** Deliver execution events synchronously; consumers save finalized records, exceptions stop execution, and no further events are delivered after returning. */
72
84
  export interface ModelRunObserver { event(event: ModelRunEvent): undefined }
73
85
  /** Used only for HTTP request identity; does not enter model messages, history, or resource authorization. */
@@ -117,7 +129,7 @@ export type ModelRunResult = {
117
129
  response: ModelResponse | null;
118
130
  /** Measured timing for this call; still available for transient feedback when no terminal state was obtained. */
119
131
  timing: RequestTiming | null;
120
- } & ({ reason: "completed" } | { reason: "cancelled" } | { reason: "failed"; code: string; details?: ErrorDetails });
132
+ } & ({ reason: "completed" } | { reason: "cancelled" } | { reason: "failed"; code: string; details?: ErrorDetails; retryable?: boolean });
121
133
  /** The final request's input context; an independent copy for domain extension producers to read. */
122
134
  export interface ModelRequestContext {
123
135
  system: SystemPrompt;
package/src/objects.ts CHANGED
@@ -60,6 +60,7 @@ export interface SessionExecutor extends SessionReader {
60
60
  * An operation facade for the same session from the perspective of the tool caller and this request.
61
61
  * The host binds the originating resource, the effective link scope at request start, and the tool execution scope, handling identity and execution validation consistently.
62
62
  * Operations originate from the initiating resource: newly created resources link to it, while removal and rename targets resolve within this request's effective link scope.
63
+ * Link operations expose the initiator to a recipient within that same scope; the initiator is always the resource being shared.
63
64
  * New operations use this perspective, explicitly defining implicitly bound endpoints, the operable resource scope, and the execution scope.
64
65
  */
65
66
  export interface ToolSession extends SessionReader {
@@ -68,6 +69,10 @@ export interface ToolSession extends SessionReader {
68
69
  /** Link the bound initiator to the new resource, committed atomically with creation; defaults to false when omitted. */
69
70
  exposeSelf?: boolean;
70
71
  }): Promise<ResourceCreationResult>;
72
+ /** Expose the bound initiator to a recipient in this request's effective link scope. The recipient must support receiving links. */
73
+ link(receiverId: string): void;
74
+ /** Withdraw the bound initiator's exposure to a recipient in this request's effective link scope; preserve the reverse link. */
75
+ unlink(receiverId: string): void;
71
76
  remove(resourceId: string): void;
72
77
  rename(resourceId: string, title: string): string;
73
78
  }
@@ -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 }
@@ -66,12 +68,26 @@ export function defineOperationRecord<I extends Json, O extends Json>(id: string
66
68
  inputSchema: definition.input, outputSchema: definition.output };
67
69
  }
68
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. */
69
- 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
+ }
70
84
  /** An observation handle fixed at one read position; reads records on demand and does not switch to the latest state after await. */
71
85
  export interface SessionView {
72
86
  readonly id: string;
73
87
  readonly title: string;
74
88
  readonly records: {
89
+ /** Identities, ancestry, and provenance without materializing record bodies. */
90
+ index(query: RecordQuery): readonly RecordInfo[];
75
91
  all(query: RecordQuery): readonly SessionRecord[];
76
92
  /** The earliest matching record; returns unknown if it cannot be decoded, without skipping it. */
77
93
  first<D extends Json>(contract: RecordContract<D>, query: RecordQuery): Decoded<D> | null;
@@ -85,6 +85,11 @@ export interface RendererApplicationServices {
85
85
  preferences(pluginId: string): import("./renderer-creation.ts").RendererPreferences;
86
86
  pickDirectory(initialPath?: string): Promise<string | null>;
87
87
  openLocalFile(path: string): Promise<void>;
88
+ readonly files: {
89
+ open(ref: import("./files.ts").FileRef): AsyncIterable<Uint8Array>;
90
+ /** Show the system Save As dialog, then consume the stream. Returns false when the user cancels. */
91
+ save(filename: string, source: AsyncIterable<Uint8Array>): Promise<boolean>;
92
+ };
88
93
  }
89
94
  const Application = createContext<RendererApplicationServices | null>(null);
90
95
  export const RendererApplicationProvider = Application.Provider;
@@ -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
+ }
@@ -15,6 +15,8 @@ interface ToolCallProps<T, A> {
15
15
  export interface ToolInputRenderProps extends ToolCallProps<Json, Json> {
16
16
  phase: "input";
17
17
  result: null;
18
+ /** Original unfinished input; the host derives a display-only argument preview when resolving the view. */
19
+ argumentsText?: string;
18
20
  }
19
21
  /** Waiting for scheduling and execution share a view; complete arguments have passed contract validation. */
20
22
  export interface ToolExecutionRenderProps<D = Json, T = Json, A = Json> extends ToolCallProps<T, A> {
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>;
@@ -117,10 +119,18 @@ export interface PluginSettingsPage {
117
119
  locations?: readonly string[];
118
120
  Body: ComponentType<{ location?: string }>;
119
121
  }
122
+ /** Host folder selection for the next session started from the entry. */
123
+ export interface SessionEntryFolder {
124
+ /** Selected folder identity, or null for no folder; pass it as the `folderId` session creation option. */
125
+ readonly id: string | null;
126
+ /** Host-rendered folder control for the entry's own toolbar; selection and folder creation stay with the host. */
127
+ readonly Picker: ComponentType<{ disabled?: boolean }>;
128
+ }
120
129
  export interface SessionEntryProps {
121
130
  active: boolean;
122
131
  ready: boolean;
123
132
  open(sessionId: string): void;
133
+ folder: SessionEntryFolder;
124
134
  }
125
135
  export interface PluginSessionEntry {
126
136
  id: string;
@@ -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";
@@ -68,6 +69,7 @@ export interface PluginContext {
68
69
  readonly providerUsage: ProviderUsage;
69
70
  readonly webProviders: WebProviderServices;
70
71
  readonly web: WebServices;
72
+ readonly messaging: MessagingServices;
71
73
  session(id: string): SessionExecutor;
72
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. */
73
75
  object<S extends Json>(sessionId: string, contract: ResourceContract<S>, id: string): ObjectExecutor;
@@ -167,6 +169,7 @@ export interface ModuleContribution {
167
169
  agentSkills?: readonly AgentSkillDeclaration[];
168
170
  agentInstructions?: readonly AgentInstructionDeclaration[];
169
171
  webProviders?: readonly WebProviderDefinition[];
172
+ messagingProviders?: readonly MessagingProviderDefinition[];
170
173
  usageProviders?: readonly UsageProvider[];
171
174
  modelProviderPresets?: readonly ModelProviderPresetContribution[];
172
175
  calls?: readonly CallContribution[];
@@ -0,0 +1,61 @@
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, MessagingFileQuery } 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 transport that restores its own protocol session reports
11
+ * reconnecting(error), then ready() after recovery. A rejection is a connection failure: the host calls receive again
12
+ * on the same instance after a backoff unless the error is terminal. Queries and sends have independent request signals.
13
+ */
14
+ receive(options: { signal: AbortSignal; ready(): void; reconnecting(error: unknown): void }): Promise<void>;
15
+ listConversations(query: ConversationQuery, options: { signal: AbortSignal }): Promise<ConversationList>;
16
+ readMessages(query: MessageQuery, options: { signal: AbortSignal }): Promise<MessageList>;
17
+ sendMessage(input: SendMessage, options: { signal: AbortSignal }): Promise<MessagingMessage>;
18
+ openFile?(query: MessagingFileQuery, options: { signal: AbortSignal }): AsyncIterable<Uint8Array>;
19
+ }
20
+ export interface MessagingProviderDefinition {
21
+ id: string;
22
+ label: UiText;
23
+ /** Settings the user configures for each connection, rendered in declaration order. */
24
+ settings: readonly ProviderSetting[];
25
+ /**
26
+ * One instance per enabled connection; a creation failure is retried like a receive failure.
27
+ * Provider-owned persistence may be shared across its instances.
28
+ */
29
+ create(context: {
30
+ connectionId: string; settings: ProviderSettingValues;
31
+ signal: AbortSignal; publish(event: MessagingEvent): void;
32
+ }): Promise<MessagingInstance>;
33
+ /** Release provider-owned data for a removed connection after its receiver has ended. */
34
+ forget?(connectionId: string): void | Promise<void>;
35
+ }
36
+ export interface MessagingHandle {
37
+ listConversations(query: ConversationQuery, options: { signal: AbortSignal }): Promise<ConversationList>;
38
+ readMessages(query: MessageQuery, options: { signal: AbortSignal }): Promise<MessageList>;
39
+ sendMessage(input: SendMessage, options: { signal: AbortSignal }): Promise<MessagingMessage>;
40
+ openFile(query: MessagingFileQuery, options: { signal: AbortSignal }): AsyncIterable<Uint8Array>;
41
+ }
42
+ export interface MessagingServices {
43
+ types(): readonly MessagingProviderType[];
44
+ connections(): readonly MessagingConnectionInfo[];
45
+ /** Captures a connection handle. Operations await a connection in progress with their own cancellation signals. */
46
+ resolve(connectionId: string, options: { signal: AbortSignal }): Promise<MessagingHandle>;
47
+ subscribe(listener: (event: ConnectionEvent) => void): () => void;
48
+ subscribeConnections(listener: () => void): () => void;
49
+ }
50
+ /**
51
+ * request_failed and errors other than MessagingError are transient and retried with backoff; retryAfterMs overrides the delay.
52
+ * Other codes are terminal for a receiving connection.
53
+ */
54
+ export type MessagingErrorCode = "unavailable" | "unsupported" | "invalid_input" | "invalid_cursor" | "request_failed";
55
+ export class MessagingError extends Error {
56
+ readonly retryAfterMs?: number;
57
+ constructor(readonly code: MessagingErrorCode, message: string, options: { retryAfterMs?: number; cause?: unknown } = {}) {
58
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
59
+ if (options.retryAfterMs !== undefined) this.retryAfterMs = options.retryAfterMs;
60
+ }
61
+ }
@@ -32,5 +32,7 @@ export interface SessionCreation {
32
32
  (key: string, prepare: (context: SessionPreparation) => Promise<SessionInitialization>, options?: {
33
33
  signal?: AbortSignal;
34
34
  content?: ContentReader;
35
+ /** Host folder that receives the session; omitted or null leaves it without a folder. A named folder must still exist when the session commits. */
36
+ folderId?: string | null;
35
37
  }): Promise<string>;
36
38
  }
@@ -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,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[];
@@ -32,5 +35,6 @@ export interface WebServices {
32
35
  }
33
36
  export type WebErrorCode = "provider_unavailable" | "credential_unavailable" | "unsupported" | "invalid_request" | "protocol" | "request_failed";
34
37
  export class WebError extends Error {
35
- constructor(readonly code: WebErrorCode, message: string) { super(message); }
38
+ /** sourceStatus identifies an HTTP failure of the requested page, never the provider API. */
39
+ constructor(readonly code: WebErrorCode, message: string, readonly sourceStatus?: number) { super(message); }
36
40
  }
package/src/runtime.ts CHANGED
@@ -10,6 +10,7 @@ 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";
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,10 +1,11 @@
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
- const url = new URL(value);
7
- return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password;
7
+ const url = URL.parse(value);
8
+ return url !== null && ["http:", "https:"].includes(url.protocol) && !url.username && !url.password;
8
9
  }, "An HTTP or HTTPS URL without embedded credentials is required.");
9
10
  export const webHintSchema = z.object({ code: z.string(), message: z.string(), parameter: z.string().optional() });
10
11
  export const webContentPartSchema = z.object({
@@ -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>;