@asterism-app/sdk 1.9.0 → 1.10.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,9 +14,13 @@ Use host presentation facilities for the surrounding card or operation. Keep dom
14
14
 
15
15
  ## Open expanded content
16
16
 
17
- Resource card views, settings pages, and islands can use the renderer island capability to open plugin content. Islands open at the right end of the screen and belong to the island that opened them; closing an island closes the islands it opened. Opening a key that is already open locates that island and keeps its content, so the key decides between one shared island and separate ones. `has(key)` reports whether a key is open, for example to mark the selected row. The host owns ordering, sizing, and the island menu.
17
+ Resource card views, settings pages, and islands can use the renderer island capability to open plugin content. Islands open at the right end of the screen and belong to the island that opened them; closing an island closes the islands it opened. Opening a key that is already open locates that island and keeps its content and ownership, so the key decides between one shared island and separate ones. Keys are unique within a screen and isolated by plugin identity; include resource, session, or parent context when distinct editors need separate keys. `has(key)` reports whether a key is open, for example to mark the selected row. The host owns ordering, sizing, and the island menu.
18
18
 
19
- Supply a plugin-local identity, accessible label, opening element, and content renderer. Choose a content surface for an editor or another view that needs more width. The host manages layout and focus. The opened view has an independent plugin region; pass its resource reference and other domain inputs explicitly rather than relying on the source component's React context or mount lifetime.
19
+ Supply a plugin-local lookup key, accessible label, opening element, and content renderer. Choose a content surface for an editor or another view that needs more width. The host manages layout and focus. The opened view has an independent plugin region; pass its resource reference and other domain inputs explicitly rather than relying on the source component's React context or mount lifetime.
20
+
21
+ For a settings editor that creates an entry and remains open for editing, bind its content key with `useRendererIslandKey`. Derive the key from the editor's current persisted identity: use a distinct creation key before the first save, then update the identity and normalized draft from the successful save result. The hook binds the new key in place, releasing the creation key so another blank editor can open. Derive it from saved identity rather than unsaved ID input; a successful rename uses the same mechanism. Keep creation and saved-object keys disjoint, including for objects named `new`.
22
+
23
+ The island instance remains mounted with its position, width, focus, scroll, guards, and children intact. Only content lookup changes. An occupied target key is reported by the host and leaves both islands unchanged; a successful save is not rolled back or retried as creation. Imperative `bindKey` reports whether binding succeeded and applies only to ordinary islands opened by the same plugin, not an enclosing host-managed island. A key binding does not change a resource island's saved navigation destination.
20
24
 
21
25
  Escape is not a general island close shortcut. For a cancellable task, its island owner declares one action with `useRendererIslandCancel`; pass null when the task has no cancellation action. Local controls handle Escape first, and an island without an action does not pass cancellation to its opening island. The callback owns the outcome: to dismiss the task, call the island's normal close operation so unsaved-change guards still apply. Functional windows and the shared panel frame do not declare cancellation automatically.
22
26
 
@@ -14,7 +14,7 @@ const usage: HeadersUsageProvider = {
14
14
  const value = balance.safeParse(amount), code = currency.safeParse(unit);
15
15
  if (!amount.trim() || !value.success || !code.success) throw new UsageQueryError("protocol");
16
16
  return [{ id: "wallet", type: "balance", scope: "account", label: "Account balance",
17
- remaining: value.data, currency: code.data }] satisfies UsageItem[];
17
+ remaining: value.data, unit: { type: "currency", code: code.data } }] satisfies UsageItem[];
18
18
  },
19
19
  };
20
20
  export default definePlugin({ namespace: ns, setup: () => ({ usageProviders: [usage] }) });
@@ -17,9 +17,9 @@ const usage: UsageProvider = {
17
17
  if (!parsed.success) throw new UsageQueryError("protocol");
18
18
  const value = parsed.data;
19
19
  return [
20
- { id: "wallet", type: "balance", scope: "account", label: "Balance", remaining: value.balance, currency: value.currency },
21
- { id: "five-hours", type: "quota", scope: "plan", label: "5h", value: { type: "ratio", remaining: value.remainingRatio },
22
- window: { mode: "rolling", durationMs: 18_000_000, resetAt: value.resetAt } },
20
+ { id: "wallet", type: "balance", scope: "account", label: "Balance", remaining: value.balance, unit: { type: "currency", code: value.currency } },
21
+ { id: "five-hours", type: "quota", scope: "plan", value: { type: "ratio", remaining: value.remainingRatio },
22
+ window: { mode: "rolling", periodSeconds: 18_000, resetAt: value.resetAt } },
23
23
  ] satisfies UsageItem[];
24
24
  },
25
25
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@asterism-app/sdk",
3
- "version": "1.9.0",
3
+ "version": "1.10.0",
4
4
  "description": "Public contracts and host capabilities for Asterism plugins",
5
5
  "license": "MIT",
6
6
  "author": "Chien Zhang",
@@ -4,31 +4,46 @@ import { uiTextSchema } from "./i18n.ts";
4
4
  /** Usage implementations have global catalog identities, independent of configured model connections. */
5
5
  export const providerUsageIdSchema = z.string().trim().min(1).max(160).regex(/^\S+$/u);
6
6
 
7
+ /**
8
+ * Units shared by balances and quota quantities: ISO currencies format natively, a site-defined symbol prefixes the amount,
9
+ * and a count carries its own label.
10
+ */
11
+ export const usageUnitSchema = z.discriminatedUnion("type", [
12
+ z.strictObject({ type: z.literal("currency"), code: z.string().regex(/^[A-Z]{3}$/u) }),
13
+ z.strictObject({ type: z.literal("symbol"), symbol: z.string().trim().min(1) }),
14
+ z.strictObject({ type: z.literal("count"), label: uiTextSchema }),
15
+ ]);
16
+ export type UsageUnit = z.infer<typeof usageUnitSchema>;
17
+
7
18
  const identity = {
8
- id: z.string().trim().min(1), label: uiTextSchema,
19
+ id: z.string().trim().min(1),
9
20
  scope: z.enum(["account", "plan", "key", "connection"]),
10
21
  };
11
22
  export const quotaValueSchema = z.discriminatedUnion("type", [
12
23
  z.strictObject({ type: z.literal("ratio"), remaining: z.number().min(0).max(1) }),
13
- z.strictObject({ type: z.literal("quantity"), remaining: z.number().nonnegative(), limit: z.number().positive(), unit: uiTextSchema })
24
+ z.strictObject({ type: z.literal("quantity"), remaining: z.number().nonnegative(), limit: z.number().positive(), unit: usageUnitSchema })
14
25
  .refine(value => value.remaining <= value.limit, "Remaining quota cannot exceed its limit."),
15
26
  ]);
16
27
  export const usageItemSchema = z.discriminatedUnion("type", [
17
- z.strictObject({ ...identity, type: z.literal("balance"), remaining: z.number(), currency: z.string().regex(/^[A-Z]{3}$/u) }),
28
+ z.strictObject({ ...identity, type: z.literal("balance"), label: uiTextSchema, remaining: z.number(), unit: usageUnitSchema }),
18
29
  z.strictObject({ ...identity, type: z.literal("quota"), value: quotaValueSchema,
30
+ /** Optional when the period alone names the window; presentation appends the period to any label. */
31
+ label: uiTextSchema.optional(),
19
32
  category: z.enum(["allowance", "rate_limit"]).optional(),
20
33
  window: z.strictObject({
21
34
  mode: z.enum(["rolling", "fixed", "unknown"]),
22
- /** Supply an actual fixed duration only when known; unknown periods must not be fabricated as weeks or months. */
23
- durationMs: z.number().positive().nullable(),
35
+ /** Window length in seconds. The provider knows its service's windows even when the response omits them; null only when it genuinely does not. */
36
+ periodSeconds: z.number().positive().nullable(),
37
+ /** Epoch milliseconds. */
24
38
  resetAt: z.number().nonnegative().nullable(),
25
39
  }),
26
- }),
40
+ }).refine(item => item.label !== undefined || item.window.periodSeconds !== null, "A quota needs a label or a known period."),
27
41
  ]);
28
42
  export const usageItemsSchema = z.array(usageItemSchema).refine(items => new Set(items.map(item => item.id)).size === items.length,
29
43
  "Usage item IDs must be unique.");
30
44
  export type UsageItem = z.infer<typeof usageItemSchema>;
31
45
  export type QuotaItem = Extract<UsageItem, { type: "quota" }>;
46
+ export type BalanceItem = Extract<UsageItem, { type: "balance" }>;
32
47
  export const providerUsageErrorSchema = z.enum(["unavailable", "credential", "authentication", "unsupported", "rate_limit", "network", "timeout", "protocol", "server"]);
33
48
  export type ProviderUsageError = z.infer<typeof providerUsageErrorSchema>;
34
49
  export const usageProviderInfoSchema = z.strictObject({ id: providerUsageIdSchema, label: uiTextSchema, owner: z.string(),
@@ -42,6 +57,19 @@ export function quotaRemaining(item: QuotaItem): number {
42
57
  export function primaryQuota(items: readonly UsageItem[]): QuotaItem | null {
43
58
  let selected: QuotaItem | null = null;
44
59
  for (const item of items) if (item.type === "quota" && (!selected ||
45
- (item.window.durationMs ?? Infinity) < (selected.window.durationMs ?? Infinity))) selected = item;
60
+ (item.window.periodSeconds ?? Infinity) < (selected.window.periodSeconds ?? Infinity))) selected = item;
46
61
  return selected;
47
62
  }
63
+
64
+ export type UsagePeriodUnit = "year" | "month" | "week" | "day" | "hour" | "minute" | "second";
65
+ const periodUnits: readonly [UsagePeriodUnit, number][] = [
66
+ ["year", 31_536_000], ["month", 2_592_000], ["week", 604_800], ["day", 86_400], ["hour", 3_600], ["minute", 60],
67
+ ];
68
+ /** States a period in the largest unit that expresses it within one decimal place; months and years count as 30 and 365 days. */
69
+ export function usagePeriodParts(seconds: number): { value: number; unit: UsagePeriodUnit } {
70
+ for (const [unit, size] of periodUnits) {
71
+ const tenths = seconds / size * 10;
72
+ if (tenths >= 10 && Math.abs(tenths - Math.round(tenths)) < 1e-9) return { value: Math.round(tenths) / 10, unit };
73
+ }
74
+ return { value: seconds, unit: "second" };
75
+ }
@@ -1,4 +1,4 @@
1
- import { createContext, createElement, useContext, useEffect, useRef, type ComponentType, type ReactNode } from "react";
1
+ import { createContext, createElement, useContext, useEffect, useLayoutEffect, useRef, type ComponentType, type ReactNode } from "react";
2
2
  import type { UiText } from "./i18n.ts";
3
3
 
4
4
  /**
@@ -6,7 +6,7 @@ import type { UiText } from "./i18n.ts";
6
6
  * closing an island also closes the islands it opened. The host manages order, width, position, motion, and focus; plugins provide identity, an accessible name, and content.
7
7
  */
8
8
  export interface RendererIslandSpec {
9
- /** Island identity unique within the plugin; the host isolates it by plugin identity. Opening an identity that is already open locates that island and keeps its content. */
9
+ /** Initial content lookup key unique within the plugin. Opening an already bound key locates that island and keeps its content. */
10
10
  key: string;
11
11
  /** The island's accessible name and overflow navigation hint. */
12
12
  label: UiText;
@@ -23,6 +23,10 @@ export type RendererCloseGuard = () => boolean | Promise<boolean>;
23
23
  export interface RendererIsland {
24
24
  /** Whether an island with this plugin key is open in the screen. */
25
25
  has(key: string): boolean;
26
+ /** Bind this island to a new content key without remounting or changing layout, ownership, focus, or close guards.
27
+ * An occupied key is reported by the host and returns false without changing either island; absent, host-managed, or other-plugin islands return false.
28
+ */
29
+ bindKey(key: string): boolean;
26
30
  /** Open an island owned by this one at the right end of the screen, or locate the open island with the same key. Resolves to whether it is shown. */
27
31
  open(spec: RendererIslandSpec): Promise<boolean>;
28
32
  /** Close this island and the islands it opened; has no effect on host-managed islands such as the one containing a plugin settings page. force skips guards. */
@@ -61,6 +65,11 @@ function required<T>(value: T | null, name: string): T {
61
65
  }
62
66
  /** Available within resource cards, plugin settings pages, and islands they open. Opened content has its own region; pass domain inputs explicitly. */
63
67
  export function useRendererIsland(): RendererIsland { return required(useContext(Island), "island"); }
68
+ /** Keep an editor bound to its current persisted identity. Use a distinct creation key until the first successful save. */
69
+ export function useRendererIslandKey(key: string) {
70
+ const island = useRendererIsland();
71
+ useLayoutEffect(() => { island.bindKey(key); }, [island, key]);
72
+ }
64
73
  /** Register a close guard for the containing island; null guard permits closing, and the guard always uses the latest callback. */
65
74
  export function useRendererCloseGuard(guard: RendererCloseGuard | null) {
66
75
  const island = useRendererIsland();
@@ -0,0 +1,28 @@
1
+ import { usagePeriodParts, type UsageItem, type UsageUnit } from "./provider-usage.ts";
2
+ import type { I18n } from "./renderer-i18n.ts";
3
+
4
+ /** Compact output abbreviates large amounts for tight surfaces while small amounts keep their cents. */
5
+ const numberOptions = (value: number, compact: boolean): Intl.NumberFormatOptions => compact
6
+ ? { notation: "compact", maximumFractionDigits: Math.abs(value) < 1000 ? 2 : 1 } : { maximumFractionDigits: 2 };
7
+
8
+ export function formatUsageAmount(i18n: I18n, value: number, unit: UsageUnit, options: { compact?: boolean } = {}): string {
9
+ const compact = options.compact === true;
10
+ if (unit.type === "currency") return i18n.formatNumber(value, { style: "currency", currency: unit.code, ...(compact && numberOptions(value, true)) });
11
+ const number = i18n.formatNumber(value, numberOptions(value, compact));
12
+ return unit.type === "symbol" ? `${unit.symbol} ${number}` : `${number} ${i18n.text(unit.label)}`;
13
+ }
14
+ /** Counts state their label once after both numbers; currencies and symbols mark each amount. */
15
+ export function formatUsageQuantity(i18n: I18n, remaining: number, limit: number, unit: UsageUnit): string {
16
+ if (unit.type === "count") return `${i18n.formatNumber(remaining)} / ${i18n.formatNumber(limit)} ${i18n.text(unit.label)}`;
17
+ return `${formatUsageAmount(i18n, remaining, unit)} / ${formatUsageAmount(i18n, limit, unit)}`;
18
+ }
19
+ /** Narrow units read as 5h or 1w; months use the short form because the narrow month collides with minutes. */
20
+ export function formatUsagePeriod(i18n: I18n, seconds: number): string {
21
+ const { value, unit } = usagePeriodParts(seconds);
22
+ return i18n.formatNumber(value, { style: "unit", unit, unitDisplay: unit === "month" ? "short" : "narrow", maximumFractionDigits: 1 });
23
+ }
24
+ export function usageItemLabel(i18n: I18n, item: UsageItem): string {
25
+ if (item.type === "balance") return i18n.text(item.label);
26
+ const period = item.window.periodSeconds === null ? null : formatUsagePeriod(i18n, item.window.periodSeconds);
27
+ return [item.label === undefined ? null : i18n.text(item.label), period].filter(part => part !== null).join(" · ");
28
+ }
package/src/renderer.ts CHANGED
@@ -4,6 +4,7 @@ import type { UiText } from "./i18n.ts";
4
4
  import type { CardAppearance } from "./card.ts";
5
5
  export type { CardAppearance } from "./card.ts";
6
6
  export * from "./renderer-i18n.ts";
7
+ export * from "./renderer-usage.ts";
7
8
  import type { ActionContract, CreationContract } from "./commands.ts";
8
9
  import type { Json } from "./json.ts";
9
10
  import { reference, type ContractReference, type DataContract } from "./presentation.ts";
@@ -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, jsonArgumentHint } from "./tool-validation.ts";
10
+ import { 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";
@@ -89,7 +89,6 @@ export function implementTool<S extends Json, T extends ToolInput, A extends Too
89
89
  `Invalid arguments for ${contract.resource.kind}/${contract.tool.name}.`,
90
90
  ...(!parsedTarget.success ? [validationMessage(parsedTarget.error, "target")] : []),
91
91
  ...(!parsedArgs.success ? [validationMessage(parsedArgs.error, "args")] : []),
92
- jsonArgumentHint,
93
92
  ].join("\n") } };
94
93
  return {
95
94
  effect: contract.effect, execution: contract.execution, implementation: identity,