@asterism-app/sdk 2.1.1 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/manual.md CHANGED
@@ -16,6 +16,12 @@ An example is worth discussing when the explanation helps an author adapt it. Ex
16
16
 
17
17
  Write each article with enough context to stand alone. Organize it around an author or user question, not a tour of every available method. A reading sequence should not be necessary to understand a capability's purpose.
18
18
 
19
+ ## Document shortcuts where they work
20
+
21
+ If your plugin provides keyboard shortcuts, publish a **Keyboard shortcuts** topic or section in its own manual. Group shortcuts by view or dialog. Say where focus must be, what the shortcut does, and which keys differ by platform. Include a command or button alternative when it helps users find the action.
22
+
23
+ The application manual covers shortcuts owned by the host. A plugin topic covers the plugin’s shortcuts, including any context that determines when they are available. Declare the containing directory in `asterism.manual` in `package.json` and ship it with the plugin. This publishes the documentation through the Manual resource without changing how shortcuts are handled.
24
+
19
25
  ## Keep runtime guidance with tools
20
26
 
21
27
  Models consult the manual when helping with software use or plugin development. Ordinary tool use should not depend on reading it.
@@ -8,6 +8,14 @@ A resource card presents an object; an operation view explains one attempt to do
8
8
 
9
9
  Use host presentation for containment and navigation. Keep the plugin's domain content within it instead of rebuilding the surrounding application. Localize the view's styling so one plugin does not redefine another's interface.
10
10
 
11
+ ## Carry a tool view from input to result
12
+
13
+ A tool title should identify the work before it produces output. Give long questions, commands, and other unbounded inputs a short, single-line excerpt. Use the SDK renderer’s `HeaderExcerpt` in a shrinkable title slot so the input yields space to a distinct status label, and make the complete input available in the expanded view rather than embedding it in the title.
14
+
15
+ During argument generation, an input preview can follow the tail of the whole draft. Once the tool begins, its arguments are stable: put the context and controls that users still need outside any live-output viewport. A tool that only needs to show status or ask for input does not need a streaming region.
16
+
17
+ If a tool emits a growing report or log, use the SDK renderer’s `StreamingScrollArea` to bound that section’s height so updates cannot push its context away. Follow new content at the end, but let readers move away without losing their place. When the operation settles, keep the input and report in the same places and update the status or add outcome details in place. The renderer owns these choices; a streaming declaration tells the host when a body is available for automatic disclosure, not how to lay it out or scroll it.
18
+
11
19
  ## Give expanded views a meaningful identity
12
20
 
13
21
  An island is an expanded plugin surface with its own view lifetime. Choose its identity according to what users consider the same open work. A shared settings editor may need one instance; editors for different resources or sessions need distinct identities.
@@ -0,0 +1,57 @@
1
+ # Fit plugin views into the workbench
2
+
3
+ A plugin's views appear beside the host's own and other plugins' views. Users read them as one application when they share its layering, the meaning of its lines and motion, and its controls for each kind of choice. This guide explains that visual language and the choices it implies for plugin authors. The shared controls carry the exact appearance; using them is how a plugin stays consistent as the application's styling evolves.
4
+
5
+ ## Start from the host's containers
6
+
7
+ The host already draws the outer surface of every plugin view. A resource card has its shell and header, a settings page sits on the settings sheet, and an island opened through the SDK's island panel receives the shared title bar, toolbar slot, and content sheet. Put domain content inside these containers rather than drawing another card, header, or close control around it.
8
+
9
+ The island panel's title bar is where operations on the whole subject go: a primary action such as Save, and icon actions such as delete or restore defaults. Operations on one part of the content belong with that part, for example in a section header. A panel has no bottom action bar, because it is a non-modal workspace rather than a dialog.
10
+
11
+ ## Separate regions by tone, not outlines
12
+
13
+ Inside a sheet, a region reads as a region because its tone differs, not because something draws around it. The design language has a small set of layers:
14
+
15
+ - **Shell**: titles, navigation, and toolbars sit on the shell tone.
16
+ - **Sheet**: reading and editing content sits on a raised sheet in the card tone.
17
+ - **Group**: rows, fields, and repeated items that belong together recede into a group in the shell tone, with hairlines between rows.
18
+ - **Floating**: menus, popovers, tooltips, hover cards, and dialogs lift above content and keep their outer edge.
19
+
20
+ A plugin that needs a group fills it with the shell tone token, `--card-shell`, and leaves out the border; the shared settings layout and list controls already follow this rule. Inside something that is already recessed, such as a tool's output in the conversation, a sub-panel rises back to the card tone instead of adding an outline. When two areas are already separated by tone, adding a border makes the view feel heavier and louder than the rest of the application.
21
+
22
+ ## Use lines only when they mean something
23
+
24
+ Users learn that a line in Asterism tells them something: where focus is, what is selected, where a drop will land, or the state of a piece of work. A moving dashed outline means content is still forming, a still dashed outline means it ended incomplete, and a red line means the request that produced it failed. Hairlines between rows are the one structural line.
25
+
26
+ A plugin that draws decorative borders dilutes those meanings. Prefer the host's state presentation: tool views receive their state outline from the shared process block, and status uses the shared status badge, text, and icon components, which always pair color with an icon or label.
27
+
28
+ ## Let motion explain a change
29
+
30
+ Motion in the workbench answers a question for the reader: where did this come from, where did it go, or what changed? Selection indicators travel to the new item, deeper pages enter from the side and leave the way they came, arriving content fades in while leaving content clears quickly, lists fold their height as items join or leave, and values animate only when they change.
31
+
32
+ Plugin views can use the host-provided Motion library for the same purposes, with the shared timing. Shared controls already carry their own motion; a segmented toggle's indicator, for example, slides without any plugin code. Avoid motion that decorates a static state, replays when an item merely scrolls into view, or competes with a list's own scrolling. Respect reduced motion, which the host's Motion configuration and CSS already follow.
33
+
34
+ ## Choose controls by the kind of choice
35
+
36
+ The shared controls encode what a choice is, so the same kind of choice looks the same everywhere:
37
+
38
+ - A single choice among a few short options is a segmented toggle group.
39
+ - An immediate on/off setting is a switch; a choice inside a form or a multi-selection is a checkbox; an explained single choice is a radio group.
40
+ - A choice among many options, or one that needs search, uses the shared command and popover combination.
41
+ - Icon-only actions use the shared icon button, which supplies the accessible label and tooltip.
42
+ - A short name or explanation on hover is a tooltip; a preview read while hovering is a hover card; content the user opens on purpose, scrolls, or acts on is a popover behind a button.
43
+ - Button variants carry roles: one default button for the primary action in a region, outline for supporting actions, ghost for compact and row actions, destructive for irreversible confirmation.
44
+
45
+ Tooltips share the popover tone, so their content uses the same color tokens as any sheet content. The shared tooltip supplies its own delay, placement, and width; passing only a side and the content keeps every hint in the application on one rhythm. Disabled controls still show their tooltips, which is the natural place to say why an action is unavailable.
46
+
47
+ Building a lookalike control loses these meanings and the accessibility the shared one provides. Shared controls also follow the user's appearance settings for color, radius, density, and fonts without extra work.
48
+
49
+ ## Render content through the shared readers
50
+
51
+ Markdown, code, diffs, math, diagrams, JSON, and resource or skill references have shared renderers. Using them means a plugin's output reads like every other plugin's output, including streaming behavior, copyable code, and reference navigation. Tool headers use the shared header with a subject, summary, and metadata, and long inputs use the header excerpt rather than a truncated title.
52
+
53
+ ## Keep custom styling local
54
+
55
+ A plugin can style what is genuinely its own: a domain visualization, a canvas, a media viewer. Build that styling from the semantic color tokens and type roles so it follows the user's theme and both color schemes. CSS Modules keep plugin styles from leaking, while global styles share the document cascade with the host and every other plugin; avoid global selectors that would restyle shared controls or another plugin's views.
56
+
57
+ Check a view in light and dark modes, at each density, and with reduced motion before release. A typecheck cannot tell whether a view belongs in the workbench; looking at it beside the host's own views can.
@@ -14,7 +14,7 @@
14
14
  "zod": "^4.6.5"
15
15
  },
16
16
  "devDependencies": {
17
- "@asterism-app/sdk": "2.1.1",
17
+ "@asterism-app/sdk": "2.2.1",
18
18
  "typescript": "^7.0.2",
19
19
  "@types/node": "^26.6.1",
20
20
  "@types/react": "^19.3.0",
@@ -2,7 +2,7 @@
2
2
  import { createElement } from "react";
3
3
  import { z } from "zod";
4
4
  import { defineData, type Json } from "@asterism-app/sdk/contracts";
5
- import { toolRenderer, type ToolRenderProps } from "@asterism-app/sdk/renderer";
5
+ import { HeaderExcerpt, StreamingScrollArea, toolRenderer, type ToolRenderProps } from "@asterism-app/sdk/renderer";
6
6
 
7
7
  const Result = defineData("example.writer/write", z.object({ written: z.number() }));
8
8
  const targetSchema = z.object({ path: z.string() });
@@ -34,14 +34,30 @@ export const writerView = toolRenderer({ ...Result, targetSchema, tool: { argsSc
34
34
  execution: view, result: view,
35
35
  });
36
36
 
37
- /** Plugins render progressive output themselves; the shell manages automatic expansion and collapse based on declarations and user settings. */
37
+ /** Input context is stable while the report grows; execution and results render it in the same place. */
38
38
  const Report = defineData("example.writer/report", z.object({ text: z.string() }));
39
- function ReportBody({ phase, result }: ToolRenderProps<z.infer<typeof Report.schema>>) {
40
- const text = result?.data?.text ?? "";
41
- return createElement("pre", null, phase === "executing" ? text.slice(-2_000) : text);
39
+ const reportArgs = z.object({ question: z.string() });
40
+ type ReportProps = ToolRenderProps<z.infer<typeof Report.schema>, Json, z.infer<typeof reportArgs>>;
41
+ function ReportHeader({ args }: ReportProps) {
42
+ const question = args !== null && typeof args === "object" && !Array.isArray(args) && typeof args.question === "string" ? args.question : "";
43
+ // The excerpt belongs in a shrinkable title slot, not in a tooltip containing the complete question.
44
+ return createElement(HeaderExcerpt, { text: question });
42
45
  }
43
- export const reportView = toolRenderer(Report, {
46
+ function ReportBody(props: ReportProps) {
47
+ if (props.phase === "input") return null;
48
+ const text = props.result?.data?.text;
49
+ const status = props.phase === "settled" ? "No report" : "No report yet";
50
+ return createElement("div", null,
51
+ createElement("p", null, props.args.question),
52
+ createElement(StreamingScrollArea, {
53
+ label: "Report", initialScrollPosition: props.phase === "settled" ? "start" : "end",
54
+ children: createElement("pre", { style: { whiteSpace: "pre-wrap", overflowWrap: "anywhere" } }, text || status),
55
+ }),
56
+ );
57
+ }
58
+ export const reportView = toolRenderer({ ...Report, tool: { argsSchema: reportArgs } }, {
44
59
  label: "Report",
45
- execution: { bodyRenderer: ReportBody, streaming: ({ result }) => !!result?.data?.text },
46
- result: { bodyRenderer: ReportBody },
60
+ input: { headerRenderer: ReportHeader },
61
+ execution: { headerRenderer: ReportHeader, bodyRenderer: ReportBody, streaming: ({ result }) => !!result?.data?.text },
62
+ result: { headerRenderer: ReportHeader, bodyRenderer: ReportBody },
47
63
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asterism-app/sdk",
3
- "version": "2.1.1",
3
+ "version": "2.2.1",
4
4
  "description": "Public contracts and host capabilities for Asterism plugins",
5
5
  "license": "MIT",
6
6
  "author": "Chien Zhang",
@@ -1,4 +1,5 @@
1
1
  import type { ModelCost, ModelRates, ModalityRates, UnitPrice } from "./model-cost.ts";
2
+ import type { Usage } from "./models.ts";
2
3
 
3
4
  /** Quantities already split by billing category; callers are responsible for preventing overlap between totals and subcategories. */
4
5
  export interface CostQuantity {
@@ -47,3 +48,59 @@ export function totalEstimatedCost(estimates: readonly CostEstimate[]): { amount
47
48
  return { amount: known.length ? known.reduce((sum, estimate) => sum + estimate.amount!, 0) : null,
48
49
  incomplete: estimates.filter(estimate => estimate.status !== "complete").length };
49
50
  }
51
+
52
+ /** A zero total implies zero subtotals; other unknown subtotals are not filled with zero. Negative values mark contradictory usage. */
53
+ function splitUsageTotal(total: number | null, parts: (number | null)[]): { rest: number | null; parts: (number | null)[] } {
54
+ const known = parts.reduce<number>((sum, value) => sum + (value ?? 0), 0);
55
+ if (total !== null && known > total) return { rest: -1, parts: parts.map(() => -1) };
56
+ if (total === 0) return { rest: 0, parts: parts.map(() => 0) };
57
+ return { rest: total === null || parts.some(value => value === null) ? null : total - known, parts };
58
+ }
59
+ /** Estimate USD cost from protocol usage and configured pricing; multimodal inputs leave text-input pricing unknown. */
60
+ export function estimateUsageCost(usage: Usage | null, cost: ModelCost | null, inputHasFiles: boolean | null): CostEstimate {
61
+ const input = usage?.input ?? null;
62
+ const output = usage?.output ?? null;
63
+ const selected = selectModelRates(cost, input);
64
+ const inputs = splitUsageTotal(input, [usage?.cacheRead ?? null, usage?.cacheWrite ?? null]);
65
+ const textInput = (quantity: number | null) => inputHasFiles === false ? quantity : null;
66
+ const quantities: CostQuantity[] = [
67
+ { modality: "text", item: "input", quantity: textInput(inputs.rest), unit: "token" },
68
+ { modality: "text", item: "cacheRead", quantity: textInput(inputs.parts[0]!), unit: "token" },
69
+ { modality: "text", item: "cacheWrite", quantity: textInput(inputs.parts[1]!), unit: "token" },
70
+ ];
71
+ // output already includes reasoning; split thinking out only when a separate thinking price is explicitly configured, otherwise charge the output total once.
72
+ if (selected.rates?.text.reasoning) {
73
+ const outputs = splitUsageTotal(output, [usage?.reasoning ?? null]);
74
+ quantities.push({ modality: "text", item: "output", quantity: outputs.rest, unit: "token" },
75
+ { modality: "text", item: "reasoning", quantity: outputs.parts[0]!, unit: "token" });
76
+ } else quantities.push({ modality: "text", item: "output", quantity: output, unit: "token" });
77
+ return estimateModelCost(cost, input, quantities);
78
+ }
79
+ /** Net USD saved by prompt caching for a text request: cache-read discount minus any cache-write surcharge. */
80
+ export function estimateCacheSavings(usage: Usage | null, cost: ModelCost | null, inputHasFiles: boolean | null): number | null {
81
+ if (inputHasFiles !== false || !usage || !cost) return null;
82
+ const cacheRead = usage.cacheRead;
83
+ const cacheWrite = usage.cacheWrite;
84
+ if (cacheRead === null && cacheWrite === null) return null;
85
+ const readCount = cacheRead ?? 0;
86
+ const writeCount = cacheWrite ?? 0;
87
+ if (!Number.isFinite(readCount) || readCount < 0 || !Number.isFinite(writeCount) || writeCount < 0) return null;
88
+ if (readCount === 0 && writeCount === 0) return 0;
89
+ const selected = selectModelRates(cost, usage.input);
90
+ if (selected.unknownTier || !selected.rates) return null;
91
+ const inputPrice = selected.rates.text.input;
92
+ if (!inputPrice || inputPrice.unit !== "token") return null;
93
+ const inputPerToken = inputPrice.amount / inputPrice.per;
94
+ let saved = 0;
95
+ if (readCount > 0) {
96
+ const readPrice = selected.rates.text.cacheRead;
97
+ if (!readPrice || readPrice.unit !== "token") return null;
98
+ saved += readCount * (inputPerToken - readPrice.amount / readPrice.per);
99
+ }
100
+ if (writeCount > 0) {
101
+ const writePrice = selected.rates.text.cacheWrite;
102
+ if (!writePrice || writePrice.unit !== "token") return null;
103
+ saved -= writeCount * (writePrice.amount / writePrice.per - inputPerToken);
104
+ }
105
+ return Number.isFinite(saved) ? saved : null;
106
+ }
@@ -62,5 +62,5 @@ export const modelRunRecordSchema = z.discriminatedUnion("type", [
62
62
  z.strictObject({ type: z.literal("block"), block: modelBlockSchema }),
63
63
  z.strictObject({ type: z.literal("tool.begin"), block: modelBlockSchema }),
64
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() }),
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(), omittedFiles: z.array(z.string()).optional() }),
66
66
  ]);
package/src/models.ts CHANGED
@@ -84,7 +84,7 @@ export type ModelRunEvent =
84
84
  | { type: "tool.begin"; block: Extract<ModelBlock, { kind: "toolcall" }> }
85
85
  | { type: "tool.complete"; block: Extract<ModelBlock, { kind: "toolcall" }> }
86
86
  | { type: "progress"; blocks: readonly ModelLiveBlock[] }
87
- | { type: "diagnostic"; origin: "model" | "software"; code: string; message: string; level: "error" | "warning"; details?: ErrorDetails; responseId?: string };
87
+ | { type: "diagnostic"; origin: "model" | "software"; code: string; message: string; level: "error" | "warning"; details?: ErrorDetails; responseId?: string; omittedFiles?: readonly string[] };
88
88
  /** Deliver execution events synchronously; consumers save finalized records, exceptions stop execution, and no further events are delivered after returning. */
89
89
  export interface ModelRunObserver { event(event: ModelRunEvent): undefined }
90
90
  /** Used only for HTTP request identity; does not enter model messages, history, or resource authorization. */
@@ -92,6 +92,8 @@ export interface ModelRequestIdentity {
92
92
  userAgent?: string;
93
93
  /** Stable within a session; may be omitted for a one-off call without a session. */
94
94
  sessionId?: string;
95
+ /** Optional plugin-defined purpose identifier (e.g. `naming`). The host groups usage by plugin and purpose, and shows this value verbatim. */
96
+ purpose?: string;
95
97
  }
96
98
  /** Transient metadata from the actual HTTP response; contains no request credentials or body and is not automatically written to history. */
97
99
  export interface ModelResponse {
@@ -86,6 +86,8 @@ export interface RendererApplicationServices {
86
86
  readonly platform: "darwin" | "win32" | "linux";
87
87
  preferences(pluginId: string): import("./renderer-creation.ts").RendererPreferences;
88
88
  pickDirectory(initialPath?: string): Promise<string | null>;
89
+ /** Resolve a native File from a drop or picker without reading its contents. Null when a local path is unavailable. */
90
+ pathForFile(file: File): string | null;
89
91
  openLocalFile(path: string): Promise<void>;
90
92
  /** Select a local file in the system file manager; directory targets open in that manager. */
91
93
  showLocalFile(path: string, directory: boolean): Promise<void>;
@@ -0,0 +1,42 @@
1
+ import { createContext, createElement, useContext, type ComponentType, type ReactNode } from "react";
2
+
3
+ export interface HeaderExcerptProps {
4
+ /** Full value. Only a bounded, single-line prefix is rendered; keep the full value in the body. */
5
+ text: string;
6
+ /** Inherit the title's font for prose, or opt into monospace for code. */
7
+ font?: "inherit" | "mono";
8
+ }
9
+
10
+ export interface StreamingScrollAreaProps {
11
+ children: ReactNode;
12
+ /** Localized accessible name for the scrolling region. */
13
+ label: string;
14
+ /** Optional plugin layout class for the outer element. */
15
+ className?: string;
16
+ /** Used only at mount; keep the component mounted to preserve position when the content settles. Defaults to end. */
17
+ initialScrollPosition?: "start" | "end";
18
+ }
19
+
20
+ interface RendererUi {
21
+ HeaderExcerpt: ComponentType<HeaderExcerptProps>;
22
+ StreamingScrollArea: ComponentType<StreamingScrollAreaProps>;
23
+ }
24
+
25
+ const Ui = createContext<RendererUi | null>(null);
26
+ /** Host binding for shared presentation controls. */
27
+ export const RendererUiProvider = Ui.Provider;
28
+ function useRendererUi(): RendererUi {
29
+ const ui = useContext(Ui);
30
+ if (!ui) throw new Error("Renderer UI controls must be provided by the host.");
31
+ return ui;
32
+ }
33
+
34
+ /** An excerpt for a shrinkable title slot: up to 160 Unicode code points plus an ellipsis, then ellipsized to fit. */
35
+ export function HeaderExcerpt(props: HeaderExcerptProps) {
36
+ return createElement(useRendererUi().HeaderExcerpt, props);
37
+ }
38
+
39
+ /** A bounded, selectable viewport that follows new content only at the end. Place stable context outside it. */
40
+ export function StreamingScrollArea(props: StreamingScrollAreaProps) {
41
+ return createElement(useRendererUi().StreamingScrollArea, props);
42
+ }
package/src/renderer.ts CHANGED
@@ -16,6 +16,7 @@ export * from "./renderer-calls.ts";
16
16
  export * from "./renderer-creation.ts";
17
17
  export type * from "./renderer-commands.ts";
18
18
  export * from "./renderer-tools.ts";
19
+ export * from "./renderer-ui.ts";
19
20
  export * from "./renderer-records.ts";
20
21
  export * from "./renderer-card.ts";
21
22
  export * from "./renderer-island.ts";
@@ -71,6 +71,7 @@ export interface PluginContext {
71
71
  readonly webProviders: WebProviderServices;
72
72
  readonly web: WebServices;
73
73
  readonly messaging: MessagingServices;
74
+ readonly telemetry: import("./runtime-telemetry.ts").TelemetryServices;
74
75
  session(id: string): SessionExecutor;
75
76
  /** 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. */
76
77
  object<S extends Json>(sessionId: string, contract: ResourceContract<S>, id: string): ObjectExecutor;
@@ -0,0 +1,23 @@
1
+ export type ExternalUsageOutcome = "succeeded" | "failed" | "cancelled";
2
+
3
+ /**
4
+ * Non-model metered usage, such as a web search fee, kept in the host usage ledger. Requests are grouped by category and provider;
5
+ * `amount` in `currency` is a cost, and `quantity` in `unit` is a count. sessionId attributes the usage to a session's folder.
6
+ */
7
+ export interface ExternalUsageRecord {
8
+ readonly category: string;
9
+ readonly provider?: string;
10
+ readonly sessionId?: string | null;
11
+ readonly quantity?: number | null;
12
+ readonly unit?: string | null;
13
+ readonly currency?: string | null;
14
+ readonly amount?: number | null;
15
+ readonly outcome?: ExternalUsageOutcome;
16
+ readonly durationMs?: number | null;
17
+ readonly recordedAt?: number;
18
+ }
19
+
20
+ /** Usage reporting; a failed write is logged by the host and never reaches the caller. */
21
+ export interface TelemetryServices {
22
+ recordExternalUsage(record: ExternalUsageRecord): void;
23
+ }
package/src/runtime.ts CHANGED
@@ -56,3 +56,4 @@ export type * from "./runtime-application.ts";
56
56
  export * from "./runtime-shell.ts";
57
57
  export * from "./runtime-terminal.ts";
58
58
  export type * from "./runtime-mcp.ts";
59
+ export type * from "./runtime-telemetry.ts";