@asterism-app/sdk 1.2.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.
@@ -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,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.
@@ -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.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
@@ -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
 
@@ -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 }
@@ -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;
@@ -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>;
@@ -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,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
+ }
@@ -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[];
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,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>;