@asterism-app/sdk 2.1.1 → 2.2.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/views-and-settings.md +8 -0
- package/examples/counter/package.json +1 -1
- package/examples/tool-renderer.ts +24 -8
- package/package.json +1 -1
- package/src/model-cost-estimate.ts +57 -0
- package/src/model-records.ts +1 -1
- package/src/models.ts +3 -1
- package/src/renderer-services.ts +2 -0
- package/src/renderer-ui.ts +42 -0
- package/src/renderer.ts +1 -0
- package/src/runtime-contracts.ts +2 -0
- package/src/runtime-telemetry.ts +31 -0
- package/src/runtime.ts +1 -0
|
@@ -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.
|
|
@@ -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
|
-
/**
|
|
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
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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
|
-
|
|
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
|
-
|
|
46
|
-
|
|
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,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
|
+
}
|
package/src/model-records.ts
CHANGED
|
@@ -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 for host telemetry grouping; independent of model messages and authorization. */
|
|
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 {
|
package/src/renderer-services.ts
CHANGED
|
@@ -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";
|
package/src/runtime-contracts.ts
CHANGED
|
@@ -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;
|
|
@@ -193,6 +194,7 @@ export interface ModuleContribution {
|
|
|
193
194
|
tools?: readonly ToolContribution[];
|
|
194
195
|
observers?: readonly SessionObserver[];
|
|
195
196
|
preparers?: readonly CommandPreparer[];
|
|
197
|
+
modelPurposes?: readonly import("./runtime-telemetry.ts").ModelPurposeDeclaration[];
|
|
196
198
|
}
|
|
197
199
|
/** Named module entry point: plugins provide contributions, and the host handles assembly and invocation. */
|
|
198
200
|
export interface PluginModule { setup(plugin: PluginContext): ModuleContribution }
|
|
@@ -0,0 +1,31 @@
|
|
|
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
|
+
export type ExternalUsageOutcome = "succeeded" | "failed" | "cancelled";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Non-model metered usage, such as a web search fee, kept in the host usage ledger. Requests are grouped by category and provider;
|
|
13
|
+
* `amount` in `currency` is a cost, and `quantity` in `unit` is a count. sessionId attributes the usage to a session's folder.
|
|
14
|
+
*/
|
|
15
|
+
export interface ExternalUsageRecord {
|
|
16
|
+
readonly category: string;
|
|
17
|
+
readonly provider?: string;
|
|
18
|
+
readonly sessionId?: string | null;
|
|
19
|
+
readonly quantity?: number | null;
|
|
20
|
+
readonly unit?: string | null;
|
|
21
|
+
readonly currency?: string | null;
|
|
22
|
+
readonly amount?: number | null;
|
|
23
|
+
readonly outcome?: ExternalUsageOutcome;
|
|
24
|
+
readonly durationMs?: number | null;
|
|
25
|
+
readonly recordedAt?: number;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Usage reporting; a failed write is logged by the host and never reaches the caller. */
|
|
29
|
+
export interface TelemetryServices {
|
|
30
|
+
recordExternalUsage(record: ExternalUsageRecord): void;
|
|
31
|
+
}
|
package/src/runtime.ts
CHANGED