@asterism-app/sdk 2.2.0 → 2.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.
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.
@@ -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.2.0",
17
+ "@asterism-app/sdk": "2.3.0",
18
18
  "typescript": "^7.0.2",
19
19
  "@types/node": "^26.6.1",
20
20
  "@types/react": "^19.3.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asterism-app/sdk",
3
- "version": "2.2.0",
3
+ "version": "2.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
@@ -39,6 +39,7 @@ export * from "./messaging.ts";
39
39
  export * from "./session-title.ts";
40
40
 
41
41
  export * from "./usage-state.ts";
42
+ export * from "./usage-subjects.ts";
42
43
 
43
44
  export * from "./shell.ts";
44
45
  export * from "./terminal.ts";
package/src/models.ts CHANGED
@@ -7,6 +7,7 @@ import type { ToolOutcome, ToolInvocationInfo, ToolResult } from "./tool-result.
7
7
  import type { RequestTiming } from "./model-records.ts";
8
8
  import type { Presentation } from "./presentation.ts";
9
9
  import type { ErrorDetails } from "./error-details.ts";
10
+ import type { UsageSubject } from "./usage-subjects.ts";
10
11
 
11
12
  /** Standard levels shared across the application; protocol encoding does not change public values. */
12
13
  export const thinkingLevels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
@@ -87,13 +88,15 @@ export type ModelRunEvent =
87
88
  | { type: "diagnostic"; origin: "model" | "software"; code: string; message: string; level: "error" | "warning"; details?: ErrorDetails; responseId?: string; omittedFiles?: readonly string[] };
88
89
  /** Deliver execution events synchronously; consumers save finalized records, exceptions stop execution, and no further events are delivered after returning. */
89
90
  export interface ModelRunObserver { event(event: ModelRunEvent): undefined }
90
- /** Used only for HTTP request identity; does not enter model messages, history, or resource authorization. */
91
+ /** Request identity for HTTP and the usage ledger; does not enter model messages, history, or resource authorization. */
91
92
  export interface ModelRequestIdentity {
92
93
  userAgent?: string;
93
94
  /** Stable within a session; may be omitted for a one-off call without a session. */
94
95
  sessionId?: string;
95
- /** Optional plugin-defined purpose identifier for host telemetry grouping; independent of model messages and authorization. */
96
+ /** Optional plugin-defined purpose identifier (e.g. `naming`). The host groups usage by plugin and purpose, and shows this value verbatim. */
96
97
  purpose?: string;
98
+ /** Subjects this request used, such as prompt sections; recorded with the request when it settles. Invalid subjects are logged and omitted. */
99
+ usage?: readonly UsageSubject[];
97
100
  }
98
101
  /** Transient metadata from the actual HTTP response; contains no request credentials or body and is not automatically written to history. */
99
102
  export interface ModelResponse {
@@ -58,3 +58,9 @@ export function parseModelUrl(value: string): ModelExpression | null {
58
58
  export function referenceMarkdown(label: string, url: string): string {
59
59
  return `[${label.replace(/[\r\n]+/gu, " ").replace(/[\\[\]]/gu, "\\$&")}](${url})`;
60
60
  }
61
+
62
+ /** Markdown links whose destination uses a reference scheme; the label is unescaped. Destinations are not parsed further. */
63
+ export function* referenceLinks(text: string): Generator<{ index: number; length: number; label: string; url: string }> {
64
+ for (const match of text.matchAll(/\[((?:\\[^\r\n]|[^\\\]\r\n])*)\]\(((?:resource|skill|model):[^()\s]+)\)/gu))
65
+ yield { index: match.index, length: match[0].length, label: match[1]!.replace(/\\([\\[\]])/gu, "$1"), url: match[2]! };
66
+ }
@@ -194,7 +194,6 @@ export interface ModuleContribution {
194
194
  tools?: readonly ToolContribution[];
195
195
  observers?: readonly SessionObserver[];
196
196
  preparers?: readonly CommandPreparer[];
197
- modelPurposes?: readonly import("./runtime-telemetry.ts").ModelPurposeDeclaration[];
198
197
  }
199
198
  /** Named module entry point: plugins provide contributions, and the host handles assembly and invocation. */
200
199
  export interface PluginModule { setup(plugin: PluginContext): ModuleContribution }
@@ -1,13 +1,19 @@
1
1
  import type { ContentReader, RetainedContentScope } from "./content-runtime.ts";
2
2
  import type { ModelRunRequest, ModelRunResult, ModelRunObserver, PromptFile, SystemPrompt } from "./models.ts";
3
+ import type { UsageSubject } from "./usage-subjects.ts";
3
4
  import type { ResourceRef } from "./workspace.ts";
4
5
 
5
- export interface ResourceModelRequest extends Omit<ModelRunRequest, "tools" | "system" | "sessionId"> {
6
+ export interface ResourceModelRequest extends Omit<ModelRunRequest, "tools" | "system" | "sessionId" | "usage"> {
6
7
  /** Resource whose current links and tool caller identity supply this request's access. */
7
8
  access: ResourceRef;
8
9
  /** Paradigm-defined Agent role name, passed to tool implementations as caller identity. */
9
10
  agent?: string;
10
11
  system: SystemPrompt | ((files: readonly PromptFile[]) => SystemPrompt);
12
+ /**
13
+ * Subjects this request used, recorded with the request when it settles. A function is called once after `system` is prepared,
14
+ * so subjects can describe the prepared prompt. Invalid declarations are logged and omitted.
15
+ */
16
+ usage?: readonly UsageSubject[] | (() => readonly UsageSubject[]);
11
17
  tools?: { allow?: readonly string[]; exclude?: readonly string[] };
12
18
  /** Resource type policy for calls; inspection retains information and adds a restriction notice. */
13
19
  resources?: { allow?: readonly string[]; exclude?: readonly string[] };
@@ -7,7 +7,7 @@ import type { RecordContract } from "./records.ts";
7
7
  import { reference, present, type DataContract } from "./presentation.ts";
8
8
  import { PluginApiError } from "./runtime.ts";
9
9
  import type { ContextFile, ObjectReader, ObjectExecutor, CreationContribution, ActionContribution, CommandPreparer, CreationPreparation, ActionPreparation, ExternalPreparation, ResourceContribution, ToolContribution, Preparation, CallResult, Lifetime } from "./runtime-contracts.ts";
10
- import { validationMessage } from "./tool-validation.ts";
10
+ import { resourceValidationMessage, validationMessage } from "./tool-validation.ts";
11
11
  import type { ToolCaller } from "./runtime-contracts.ts";
12
12
  import { encodeJson } from "./data-encoding.ts";
13
13
  import type { ResourceSnapshot } from "./workspace.ts";
@@ -82,13 +82,13 @@ export function implementTool<S extends Json, T extends ToolInput, A extends Too
82
82
  const state = contract.resource.stateSchema.safeParse(resource.data);
83
83
  if (!state.success) return { kind: "failed", implementation: identity,
84
84
  error: { code: "invalid_resource", message: "The resource state does not match its backend contract." } };
85
- const parsedTarget = contract.targetSchema.safeParse(target);
86
- const parsedArgs = contract.tool.argsSchema.safeParse(args);
85
+ const parsedTarget = contract.targetSchema.safeParse(target, { reportInput: true });
86
+ const parsedArgs = contract.tool.argsSchema.safeParse(args, { reportInput: true });
87
87
  if (!parsedTarget.success || !parsedArgs.success) return { kind: "rejected", implementation: identity,
88
88
  error: { code: "invalid_arguments", message: [
89
89
  `Invalid arguments for ${contract.resource.kind}/${contract.tool.name}.`,
90
- ...(!parsedTarget.success ? [validationMessage(parsedTarget.error, "target")] : []),
91
- ...(!parsedArgs.success ? [validationMessage(parsedArgs.error, "args")] : []),
90
+ ...(!parsedTarget.success ? [resourceValidationMessage(parsedTarget.error, "target", contract.tool.argsSchema)] : []),
91
+ ...(!parsedArgs.success ? [resourceValidationMessage(parsedArgs.error, "args", contract.targetSchema)] : []),
92
92
  ].join("\n") } };
93
93
  return {
94
94
  effect: contract.effect, execution: contract.execution, implementation: identity,
@@ -1,11 +1,3 @@
1
- import type { UiText } from "./i18n.ts";
2
-
3
- /** Plugin-declared model call purpose; requests pass its id as `purpose`, and usage statistics group and label them by it. */
4
- export interface ModelPurposeDeclaration {
5
- readonly id: string;
6
- readonly label: UiText;
7
- }
8
-
9
1
  export type ExternalUsageOutcome = "succeeded" | "failed" | "cancelled";
10
2
 
11
3
  /**
@@ -3,6 +3,7 @@ import type { Json } from "./json.ts";
3
3
  import type { ObjectReader, ToolSession } from "./objects.ts";
4
4
  import type { CallResult, ToolCaller } from "./runtime-contracts.ts";
5
5
  import type { ToolModelOutput } from "./tool-result.ts";
6
+ import type { UsageSubject } from "./usage-subjects.ts";
6
7
  import type { z } from "zod";
7
8
 
8
9
  export interface TopLevelToolContext<D extends Json = Json> {
@@ -15,6 +16,11 @@ export interface TopLevelToolContext<D extends Json = Json> {
15
16
  /** Captured resource-type tool-call restriction, or null when calls are allowed; creation and discovery remain available. */
16
17
  resourceToolRestriction(kind: string): string | null;
17
18
  publish(data: D): void;
19
+ /**
20
+ * Declare a subject this call used, such as the skill it read. The host records declarations with this call when it settles,
21
+ * attributed to the declaring plugin and the calling request; declarations after the call settles are ignored. Invalid subjects are logged and omitted.
22
+ */
23
+ recordUsage(subject: UsageSubject): void;
18
24
  }
19
25
  /** Top-level tools declare their definition and implementation together, independently of resource support relationships. */
20
26
  export interface TopLevelTool<A extends ToolInput = ToolInput, D extends Json = Json> extends ToolContract<A> {
@@ -1,14 +1,46 @@
1
- import type { z } from "zod";
1
+ import { z } from "zod";
2
+
3
+ type IssueDetail = (issue: z.core.$ZodIssue, path: readonly PropertyKey[]) => string | undefined;
4
+
5
+ function formatIssues(issues: readonly z.core.$ZodIssue[], parent: readonly PropertyKey[], detail?: IssueDetail): string {
6
+ return issues.map(issue => {
7
+ const path = [...parent, ...issue.path];
8
+ return detail?.(issue, path) ?? (issue.code === "invalid_union"
9
+ ? `${path.map(String).join(".")}: must match one of these alternatives: ${issue.errors.map(branch => `(${formatIssues(branch, path, detail)})`).join(" OR ")}`
10
+ : `${path.map(String).join(".")}: ${issue.message}`);
11
+ }).join("; ");
12
+ }
2
13
 
3
14
  /** Preserve field paths and specific validation reasons from union branches so the model can correct the raw JSON arguments. */
4
15
  export function validationMessage(error: z.ZodError, field: string): string {
5
- const format = (issues: readonly z.core.$ZodIssue[]): string => issues.map(issue => {
6
- const path = [field, ...issue.path.map(String)].filter(Boolean).join(".");
7
- return issue.code === "invalid_union"
8
- ? `${path}: must match one of these alternatives: ${issue.errors.map(branch => `(${format(branch)})`).join(" OR ")}`
9
- : `${path}: ${issue.message}`;
10
- }).join("; ");
11
- return format(error.issues);
16
+ return formatIssues(error.issues, field ? [field] : []);
17
+ }
18
+
19
+ function declaresRootField(schema: z.core.$ZodType, key: string): boolean {
20
+ if (schema instanceof z.ZodObject) return Object.hasOwn(schema.shape, key);
21
+ if (schema instanceof z.ZodNullable) return declaresRootField(schema.unwrap(), key);
22
+ if (schema instanceof z.ZodUnion) {
23
+ // A hint must not depend on guessing which object variant the caller intended.
24
+ const variants = schema.options.filter(option => !(option instanceof z.ZodNull));
25
+ return variants.length > 0 && variants.every(option => declaresRootField(option, key));
26
+ }
27
+ return false;
28
+ }
29
+
30
+ /** Format a resource input error parsed with reportInput, without including raw input values in the hints. */
31
+ export function resourceValidationMessage(error: z.ZodError, field: "args" | "target", otherSchema: z.ZodType): string {
32
+ const other = field === "args" ? "target" : "args";
33
+ return formatIssues(error.issues, [field], (issue, path) => {
34
+ if (issue.code === "unrecognized_keys") return issue.keys.map(key => {
35
+ const at = [...path, key].map(String).join(".");
36
+ return path.length === 1 && declaresRootField(otherSchema, key)
37
+ ? `${at}: Not accepted here. This tool implementation declares it as ${other}.${key}.`
38
+ : `${at}: Unknown field at this location for this tool implementation.`;
39
+ }).join("; ");
40
+ if (path.length > 1 && issue.input === undefined &&
41
+ (issue.code === "invalid_type" || issue.code === "invalid_value" || issue.code === "invalid_union"))
42
+ return `${path.map(String).join(".")}: Required field is missing.`;
43
+ });
12
44
  }
13
45
 
14
46
  export const jsonArgumentHint = 'target and args are JSON objects or null matching their schemas. Example: target: {"path":"README.md"}, args: {}.';
@@ -0,0 +1,34 @@
1
+ import { z } from "zod";
2
+
3
+ const text = z.string().min(1);
4
+
5
+ /**
6
+ * Something a model request or one of its tool calls used, declared by the plugin that knows the fact. The host records it in the usage
7
+ * ledger with the request or call that is current where it is declared; the declaring plugin, session, and request come from that context.
8
+ * `kind` and `relation` are open identifiers: the host interprets the kinds it owns (`usageSubjectKinds`) and shows other values verbatim.
9
+ */
10
+ export const usageSubjectSchema = z.strictObject({
11
+ kind: text,
12
+ /** Identity within the kind, such as a skill name. */
13
+ id: text,
14
+ /** Owner scope within the kind, such as the skill source an entry resolved from; null when unresolved. */
15
+ source: text.nullable().optional(),
16
+ /** How the subject was used, such as `read` or `context` (`usageRelations`). */
17
+ relation: text,
18
+ /** Part within the subject, such as a package-relative file. */
19
+ part: text.nullable().optional(),
20
+ /** Non-negative amount in a kind-defined unit, such as prompt characters. */
21
+ quantity: z.number().finite().nonnegative().nullable().optional(),
22
+ });
23
+ export type UsageSubject = z.input<typeof usageSubjectSchema>;
24
+
25
+ /** Kinds whose meaning the host owns. A `skill` subject's id is the skill name and its source the catalog source ID. */
26
+ export const usageSubjectKinds = {
27
+ skill: "skill",
28
+ /** A skill catalog projected into a request; quantity is its prompt characters. */
29
+ skillCatalog: "skill-catalog",
30
+ /** Execution unit context: id is the performer label/key, source its instance scope, and part the unit identity if available. */
31
+ workUnit: "work-unit",
32
+ } as const;
33
+ /** Relations whose meaning the host owns: the model tried to read the subject, or it occupied request context. */
34
+ export const usageRelations = { read: "read", context: "context" } as const;