@asterism-app/sdk 2.2.1 → 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.
@@ -14,7 +14,7 @@
14
14
  "zod": "^4.6.5"
15
15
  },
16
16
  "devDependencies": {
17
- "@asterism-app/sdk": "2.2.1",
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.1",
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
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
+ }
@@ -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,
@@ -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;