@asterism-app/sdk 2.3.0 → 2.4.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/README.md CHANGED
@@ -1,29 +1,5 @@
1
1
  # Asterism SDK
2
2
 
3
- The SDK is the shared boundary between Asterism and plugins. It supplies generic hosting capabilities while plugins own the meaning of their resources and workflows. Agent conversation and other paradigm-specific behavior belong to the plugin that implements them.
3
+ The SDK is the public hosting boundary between Asterism and plugins. Plugins own the meaning of their resources and workflows. Agent conversation and other paradigm-specific work belong to the plugin that implements them.
4
4
 
5
- ## Design against a shared boundary
6
-
7
- Use public contracts to share meaning without importing another implementation. Their runtime identity matters as well as their TypeScript shape. Public abstractions should express capabilities consumers need, not reproduce internal decomposition.
8
-
9
- Keep backend work and frontend presentation separate while making each capability's ownership understandable. The host composes contributions; it does not infer domain behavior from a plugin's private state.
10
-
11
- ## Develop for the target application
12
-
13
- Use a compatible SDK version for development and treat the running application as the runtime provider. Development dependencies supply declarations; peer dependencies express the host-provided relationship. Installing a newer SDK does not upgrade the application's capabilities.
14
-
15
- Validate both contract agreement and actual integration. Type checking cannot establish that a distributed plugin includes all required assets, works in the intended application, or releases the work it owns.
16
-
17
- ## Deliver an explicit build
18
-
19
- Use `@asterism-app/plugin-build` as an authoring dependency and run its `asterism-plugin-build` CLI explicitly. Source entries belong under `asterism.build`; the build writes the loaded artifact into `dist`. Build, add the package directory, and restart. Later source changes require another build and restart, not a different plugin mode.
20
-
21
- Declare host packages and other plugins' public packages as peer dependencies; the artifact keeps those imports external so they bind to the running instances. Ordinary dependencies stay private, and the backend loads them from the installed package.
22
-
23
- Build before packing and inspect the tarball. Typechecking and a successful build do not establish installed-application or platform compatibility.
24
-
25
- ## Keep authoring material purposeful
26
-
27
- The package includes prose guides and maintained source examples. Guides explain mental models, ownership, integration choices, and working principles; public declarations and examples carry concrete interfaces and assembly. The complete counter package provides a small design to adapt, not a required architecture for every plugin.
28
-
29
- These materials support software use and plugin development on demand. Runtime tool descriptions, guidelines, and schemas own tool invocation knowledge independently of the manual.
5
+ Start with [Design and deliver a plugin](docs/getting-started.md) for design choices and validation. Resolve interfaces from the public source and types for the target release, not from the manual. The Manual includes the counter example as a source prototype to inspect, not as an API reference.
@@ -1,61 +1,39 @@
1
- # Manage data and lifecycle
1
+ # Own data and work over time
2
2
 
3
- Choose storage from the meaning of the data. Latest values, historical facts, immutable bytes, and running processes answer different questions and need different owners.
3
+ Choose storage and lifetime from what a value means. Current values, historical facts, preserved bytes, and running processes answer different questions and have different owners.
4
4
 
5
- ## Separate current state from history
5
+ ## Choose what to preserve
6
6
 
7
- Current data answers what is true now. History explains what happened. Saving a current value is not a promise that browsing history will restore it; restoration needs a domain operation with a defined meaning.
7
+ Current data answers what is true now. History explains what happened. A counter might keep its latest value and record each increment; a document editor might promise a restorable body at each revision. Make restoration an explicit domain operation rather than promising it just because something is recorded.
8
8
 
9
- For example, a counter can keep its latest value while recording each increment for explanation. A document editor may instead need a restorable body at each revision. Decide which experience the resource promises before choosing its records and current data.
9
+ Keep plugin-wide data with the plugin and transient interface choices with the view. Keep business state separate from host identity and presentation. A domain field called “title” need not be the card title, and a domain identifier need not be the host resource identity.
10
10
 
11
- Keep plugin-wide private data with the plugin. Keep temporary interface choices with the view unless users need them to survive reopening. A running process is neither saved data nor a historical fact: it needs a live owner and cleanup.
12
-
13
- ## Treat encoding as a domain boundary
14
-
15
- Use a codec when the value plugin code works with differs from its stored representation. Keep conversion semantics with that declaration rather than scattering normalization through readers and writers. A one-way input transformation and a reversible storage conversion solve different problems.
16
-
17
- Check meaningful round trips for custom conversions. In particular, reading an old representation and writing a new one should preserve the domain value even when their JSON differs. Compatibility decoding can make an old fact readable without rewriting what was originally recorded.
18
-
19
- Separate host identity and presentation from business state. A domain field named “title” need not be the card title, and a domain identifier need not be the host resource identity. Conflating them makes renaming and reuse surprising.
20
-
21
- ## Decide what a template can reuse
22
-
23
- A data-copy template is appropriate when selected saved values remain meaningful under new host identities. A note can reuse its body; an Agent can reuse configuration without carrying pending work into a new session.
24
-
25
- Treat copying an address differently from cloning what it addresses. A resource that depends on an external account, embedded object identities, or private files may need an explicit domain-specific cloning operation instead of a data-copy template. Such an operation can explain what will be shared, copied, or reconnected.
26
-
27
- Choose titles according to the same distinction. Preserving a descriptive source title can help users recognize a reusable setup; generating a title can make sense when each instance represents new work.
11
+ A template copies setup that remains meaningful under new identities. It may reuse a note's body or an Agent's configuration, not their running work. Decide which saved values should carry over and what a copied address shares rather than clones. Decide whether a new object needs the original title or one derived from the new task.
28
12
 
29
13
  ## Commit facts, then observe them
30
14
 
31
- Complete network and file processing outside synchronous transactions, then commit the resulting state. Keep the commit focused on the facts that must become visible together.
32
-
33
- Use a pending operation record when consumers need to know about work before its result exists. Its identity represents one operation from published input to final outcome. Keep progress transient unless it has lasting domain meaning, and assign responsibility for ending abandoned work to the owner that started it.
15
+ Finish asynchronous preparation before committing related facts together. If an operation must be visible while pending, give it one durable identity from submission to final outcome. Keep progress transient unless it has lasting domain meaning.
34
16
 
35
- A snapshot fixes the evidence being read; it does not redirect later writes into the past. Reuse one snapshot for related queries when their conclusions need a common basis. Obtain a fresh one when the question is about current state.
17
+ A snapshot fixes the evidence being read, not the destination of future writes. Reuse it for related queries that need a common basis. Notifications are prompts to observe: read current state for a current-state consumer, and use durable facts if missing an event during downtime changes the result.
36
18
 
37
- Notifications are prompts to observe, not substitutes for saved state. A state-driven consumer should subscribe and read the current value, then reread when notified. An occurrence-driven consumer must decide whether missing an event during downtime is acceptable or whether the domain needs durable records.
19
+ Read another domain's history through its original public contract. Unreadable evidence is not absent evidence. Restoring an object's current presence does not mean it was just created; observe committed creation facts for historical reactions and attachment lifetimes for present work.
38
20
 
39
- ## Read history through its owner
21
+ ## Evolve a saved format without changing the fact
40
22
 
41
- Import the original public record contract rather than interpreting another domain's JSON by convention. Shared decoding keeps the meaning and compatibility policy with the author who owns the fact.
23
+ Use a codec when the stored representation differs from what domain code should see. Check that round trips preserve meaning. When an older encoding is still straightforward to read, compatible decoding can leave the saved bytes alone. When an incompatible representation must be converted together before the plugin runs, declare a startup migration instead of scattering repairs through readers and service startup. If the meaning changes rather than just the encoding, give the new fact a new contract.
42
24
 
43
- Unreadable evidence is different from absent evidence. Preserve that distinction when reporting or deciding whether to recover. A failed transfer is also not an empty query result. An interface should expose those differences rather than presenting an apparently complete account.
25
+ Version private formats independently of session history. A record group is for owned timeline contracts that must evolve together. Keep its identity and membership stable; do not move existing contracts between groups or assume a changed member inherits the correct version. Convert only the recorded data, using rules tied to the old format rather than today's business defaults. Preserve source, position, and the content the fact retains. Migration changes the persisted format; readers remain responsible for interpreting and validating the content. Do not revise past decisions, recreate resources, or repeat external effects.
44
26
 
45
- Distinguish a creation fact from current presence. Reconstructing an object while browsing history does not mean it was just created. Use historical observation to react to committed facts and attachment lifetimes to own work while a resource is present.
27
+ Test the conversion with a real old-format fixture and an expected encoding. Include records on alternate paths and retained content when relevant. Check that a second startup leaves the prepared data unchanged and that an interrupted or failed upgrade has a recovery path. Do not assume independent stores upgrade as one transaction; the plugin may remain unavailable while a previously prepared store is already on the new version.
46
28
 
47
- ## Choose between an address and preserved bytes
29
+ ## Separate addresses from preserved bytes
48
30
 
49
- A file reference is an address interpreted by its source resource. It is useful when a consumer should decide whether and when to read external content. Passing the address does not preserve a version of that content.
31
+ Use a file reference when the consumer should decide whether and when to read current external content. Use retained content when a record or export must still mean the same bytes later. Passing an address does not preserve a version or confer access.
50
32
 
51
- Retained immutable content is appropriate when a record, attachment, or export must continue to mean the same bytes. For example, a reference to a working file suits “review the current draft”; a retained attachment suits “explain the draft that was submitted.”
52
-
53
- Content identifiers alone are not ownership or access. Preserve retained references in the saved encoding, and transfer ownership before closing temporary content scopes. A reference synthesized only while decoding cannot preserve bytes that were never retained.
33
+ Keep retained references in the saved encoding and transfer ownership before closing temporary scopes. A reference synthesized only when reading cannot preserve bytes that were never retained.
54
34
 
55
35
  ## End work with its owner
56
36
 
57
- Bind shared services to the plugin lifetime and object-owned work to the resource lifetime. Register cleanup when creating the work, while its ownership is clear. Pass cancellation into the I/O it controls and wait for actual completion before releasing dependencies that work still uses.
58
-
59
- Use timeline activity tracking for work whose writes depend on the current history position. An external service may need to stop when its resource disappears without otherwise preventing history navigation. Choose based on that dependency, not merely on whether the operation is asynchronous.
37
+ Bind shared services to the plugin and object-owned work to the resource. Register cleanup at the point of ownership, pass cancellation into the I/O it controls, and wait for actual completion before releasing dependencies.
60
38
 
61
- Prepare changes to persistent file formats independently of ordinary service startup. Historical compatibility, current-state migration, and live service initialization have different failure consequences and should remain understandable separately.
39
+ Track timeline activity when work depends on a history position. A service may otherwise need to stop when its resource disappears without preventing history navigation. Choose based on that dependency, not simply because an operation is asynchronous.
@@ -1,41 +1,33 @@
1
- # Prepare for plugin development
1
+ # Design and deliver a plugin
2
2
 
3
- Plugin development starts with a capability users need, not a complete framework of extension points. Build one useful path through the application, then add other contributions when that path requires them.
3
+ Start with one useful path from a user's intent to a domain result. Decide who owns the state, what changes it, and how the result becomes visible. Add more surfaces only when that path needs them. A plugin owns installation, identity, and lifetime; features can share that ownership without sharing every implementation detail.
4
4
 
5
- ## Target a real application
5
+ ## Choose what to integrate with
6
6
 
7
- Choose the application release your plugin supports and develop against compatible public packages. Development declarations help the editor and type checker; they do not upgrade the APIs supplied by a running application. Use the exact development-dependency pins in the complete examples supplied by that target application, or its release's listed public-package versions. Release preparation pairs those examples with their target build. Registry tags such as `latest` and `next` identify channel heads, not the appropriate declarations for every installed or development application.
7
+ Extend an existing domain through its public contracts when that domain should still own the work. Own a resource when the capability has its own identity and lifetime. Own a paradigm only when you need to decide how work starts, how requests are assembled, and how execution is presented. A session does not require an Agent.
8
8
 
9
- Validate a copied project outside the application checkout. Workspace dependencies can hide missing authoring dependencies; an independent install and typecheck reveal what an external author actually receives.
9
+ Keep shared declarations separate from backend work and frontend presentation. Organize each capability so its state transitions remain understandable together. Publish contracts when other plugins need their meaning, not to expose the provider's internal structure. Import the original declarations: a copy can match their types without sharing their runtime identity.
10
10
 
11
- Host-provided public packages are shared boundaries, not private libraries to bundle into a plugin. Declare them, and other plugins' public packages you import, as peer dependencies; add development dependencies for the declarations the editor reads. The build keeps peer imports external so they bind to the running application's instances or the enabled provider. Ordinary private libraries remain the plugin's dependencies.
11
+ ## Resolve interfaces from the target release
12
12
 
13
- Preserve imports of original shared contracts. A copied declaration can look identical in TypeScript while no longer identifying the same operation at runtime.
13
+ Use the Manual's SDK counter and built-in Agent examples to inspect a small plugin before writing one. Read them to see how responsibilities fit together; there is no need to run or install them to learn from them.
14
14
 
15
- ## Build a narrow vertical slice
15
+ For implementation, start at the target release's public SDK or domain package exports, follow the types to their declarations, and trace a similar shipped capability and its tests in the application source. Check which parts are public before reusing them. Use the builder's source and CLI help for build configuration.
16
16
 
17
- Start with the plugin's business state, the operation that changes or reads it, and the smallest presentation needed to use it. Keep shared declarations independent of backend and frontend implementations. This makes the boundary visible without exposing implementation details as public API.
17
+ Develop against the packages for the application release you intend to support. The application and enabled providers supply shared packages at runtime; adding a development dependency does not install or upgrade the provider. Treat host-supplied packages as peer dependencies and keep ordinary private libraries with the plugin.
18
18
 
19
- Choose a stable plugin identity before sharing the package. Treat its display name and release version as product information, distinct from the contracts and namespace that identify its behavior.
19
+ ## Validate what users will load
20
20
 
21
- Avoid scaffolding unused services, views, and persistence. A small working capability makes ownership and cleanup easier to verify; an empty abstraction says little about whether the plugin works.
21
+ The application loads a completed artifact, even when using a local checkout. Build separately, restart to activate it, and test the package outside the development workspace so dependency hoisting cannot hide missing declarations. Rebuild and restart after changing source; replacing files under a running graph can break a later lazy load.
22
22
 
23
- ## Build before loading
23
+ Follow one action from its initiating surface to the committed result and back to the user. Check rejection, cancellation, reopening saved work, and cleanup with the owner gone. Type checking tests agreement with declarations; loading the delivered artifact tests the provider, dependencies, and files users actually receive. Use both.
24
24
 
25
- A plugin directory contains package metadata and a completed artifact in `dist`. Source entries are authoring inputs under `asterism.build`. The official `@asterism-app/plugin-build` package supplies the `asterism-plugin-build` command. Keep it as a development dependency and expose an explicit package build script.
25
+ ## Find the next design decision
26
26
 
27
- Install authoring dependencies, typecheck, and build before adding the package directory to Asterism. Then restart to activate the selection. Repeat the build and restart after source changes. A checkout is a user-owned package directory, not a separate plugin mode: the application neither compiles changed source at startup nor silently substitutes source when output is missing.
28
-
29
- A successful build replaces `dist` as a whole; a failed build leaves the previous output. Restart a running application after building, because it may still load parts of the replaced output lazily.
30
-
31
- ## Validate distinct boundaries
32
-
33
- Type checking establishes agreement with the declarations. Loading and exercising the plugin in the target application establishes whether its contributions and dependencies work together. Neither replaces the other.
34
-
35
- Check the normal path, meaningful invalid input, visible failures, and cleanup when the owning resource or plugin ends. Reopen saved work to distinguish durable state from accidental reliance on a live instance.
36
-
37
- ## Verify what users receive
38
-
39
- Test the distributed package in an installed application, not only the source checkout. Build before packing, and inspect the actual tarball. Use a clean release checkout. Include the completed output, root metadata, documentation, and translation catalogs, and declare every package the plugin imports at runtime in `dependencies` or `peerDependencies`. Installation must not need to compile plugin source. Files available only on the author's machine should not be necessary.
40
-
41
- Update public package versions intentionally and repeat the relevant integration checks. A compatible editor view is useful evidence, but the application remains the provider of runtime capabilities.
27
+ | If you need to decide… | Read |
28
+ | --- | --- |
29
+ | What an Agent can discover, call, and learn from an operation | [Resources and tools](resources-and-tools.md) |
30
+ | What to persist, migrate, or release | [Data and lifecycle](data-and-lifecycle.md) |
31
+ | How a workflow starts or receives external events | [Session entries](session-entries.md), [messaging](messaging.md) |
32
+ | What a view owns and how it fits the workbench | [Views and settings](views-and-settings.md), [visual language](visual-language.md) |
33
+ | What belongs in a plugin's own manual | [Plugin documentation](manual.md) |
package/docs/manual.md CHANGED
@@ -1,26 +1,20 @@
1
1
  # Publish useful plugin documentation
2
2
 
3
- A plugin can expose documentation and source examples through Asterism's Manual resource. This makes authoring material available on demand while keeping the same files usable outside the application.
4
-
5
- ## Choose what to publish
6
-
7
- Expose directories intended for users learning the software or authors developing an integration. Include that material in the distributed package. Internal fixtures, private working notes, and credentials have different audiences and belong outside the published material.
3
+ Publish design and usage topics through the Manual resource so an Agent can find the reasoning it needs without loading the whole handbook. Include small source examples when reading the prototype makes an integration easier to grasp. Keep test fixtures with the code they exercise and leave exact interfaces to the public declarations.
8
4
 
9
5
  Keep documentation with the domain that owns its meaning. Generic hosting concepts belong to the SDK; a plugin's behavior and extension rationale belong to that plugin or its public API package. A separate public API library can own its authoring material without becoming another executable plugin.
10
6
 
11
7
  ## Explain decisions that declarations cannot
12
8
 
13
- Use prose for mental models, responsibility boundaries, integration choices, and reasons to prefer one composition over another. Public types express concrete interfaces; maintained source examples demonstrate concrete assembly. Repeating either as a field list creates a second, weaker definition.
14
-
15
- An example is worth discussing when the explanation helps an author adapt it. Explain why a service is shared, why a record is durable, or why a view does not own a task. Let the example's source carry its exact syntax.
9
+ Explain decisions an Agent cannot recover from declarations: why a service is shared, when a record should be durable, or why a view does not own a task. For exact interfaces and concrete assembly, direct development to the target SDK, application source, and tests.
16
10
 
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.
11
+ Group independently readable articles by the reader's decisions. When a mechanism changes those decisions, revise their existing topic or remove outdated guidance rather than creating a page for the mechanism.
18
12
 
19
13
  ## Document shortcuts where they work
20
14
 
21
15
  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
16
 
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.
17
+ 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. Include it in the shipped manual.
24
18
 
25
19
  ## Keep runtime guidance with tools
26
20
 
@@ -1,53 +1,29 @@
1
- # Design resources and callable capabilities
1
+ # Design resources and tool calls
2
2
 
3
- A resource represents an object with identity and lifetime. A tool represents a model-callable operation. Keeping them independent lets the same operation work across different objects without forcing those objects into one domain model.
3
+ A resource is an object with identity and lifetime. A tool is an operation a model can choose. Keep them independent so the same operation can work across different objects without making them share a domain model.
4
4
 
5
- ## Choose the object boundary
5
+ ## Decide which capability should be callable
6
6
 
7
- Use a resource for something that belongs in a session and can be recognized or operated on independently. Give it responsibility for its state, model-facing projection, and object-owned work.
7
+ Use a resource when the work has a recognizable subject with its own state or lifetime. Keep model-facing state with that resource; it should let a model recognize the subject and its relevant condition. A card presents the object, but hiding it neither ends its work nor revokes links.
8
8
 
9
- A card is a presentation of that object, not its backend lifetime. Hiding a card should not silently end work that remains meaningful without it. Conversely, retaining saved data is not a reason to keep a live process running.
9
+ Expose a tool when a model needs to choose and perform the operation. When application code already knows what to do, use the owning domain service or typed action rather than routing through a model. Share the same business logic behind these surfaces. Choose a resource tool for work on a linked object; choose a top-level tool for work on the execution context or shared lifecycle that has no such subject.
10
10
 
11
- Ask for disposal confirmation when ending a live instance has consequences the user should decide about. Base the warning on work that actually exists, not on saved state that could hypothetically be restored. Warning discovery and cleanup have different purposes.
11
+ ## Design the call around intent
12
12
 
13
- ## Design information and access separately
13
+ Reuse a public tool contract when its meaning and shared input are the same across resources. A structured read, for example, can express the same operation while each implementation decides how to address its own content and views. A different effect or meaning deserves a different contract, even if it uses similar code. Name the operation for what the caller is asking it to do.
14
14
 
15
- A resource's model-facing state should let a model recognize the object and understand its relevant condition. Keep that projection with the resource implementation rather than relying on the host to interpret private saved state. Tool definitions explain operations; they are not a substitute for object state.
15
+ Choose structured input when the model must supply independent choices or when a distinct target makes resource-specific selection clearer. Choose freeform when the whole input belongs to one text syntax, and validate that syntax at the operation boundary. An operation that takes text and independent options can still be structured. Keep provider-specific encoding out of the domain contract.
16
16
 
17
- Directed links express availability to a receiver. The reverse relationship is independent, and a path through another object is not implicit access. A readable title, reference, or member directory does not grant authority over the object it names.
17
+ Design for discovery: explain the purpose, required context, result, and how its outputs can be used next in the tool's own guidance and schemas. Explain the absence of a result or an uncertain effect where it changes the caller's next decision. A short write receipt should report what changed, not repeat the input or the display diff. The model should be able to call the tool without having read this manual.
18
18
 
19
- For example, a bridge can choose recipients from its direct links without acquiring their private business state. Read current relationships when handling a new external event; a model request already in progress uses its captured scope.
19
+ ## Keep execution with its owner
20
20
 
21
- ## Choose a callable boundary
21
+ Treat links, tool discovery, and permission to execute as separate facts. A visible card or known address is not authority; a reverse link is independent. Bind access and configuration at the request boundary, but read ordinary mutable content when handling the operation.
22
22
 
23
- An application action or service call need not be a model tool. Expose it when a model needs that capability, and keep the implementation's business logic shared with other callers where appropriate.
23
+ Order operations according to their dependencies rather than whether they read or write. Require interaction only if a user's response is necessary to complete the work. Keep progress separate from durable results, and distinguish rejection, cancellation, partial completion, and uncertain effects. Stopping a caller does not undo completed effects.
24
24
 
25
- Reuse a tool declaration when the operation has the same meaning and shared arguments across resources. Keep resource-specific selection with the implementation. A distinct meaning deserves a distinct contract even when its code happens to resemble another operation.
25
+ ## Compose and verify calls through their actual surface
26
26
 
27
- A read operation illustrates the distinction: reading keeps its meaning while a resource decides how content is addressed and which view is useful. Name operations by that meaning, not by the file or package that happens to declare them.
27
+ Use session-bound execution when a model should work through the session's links and real resources. Use direct model execution when the caller supplies its own messages and executable tools without a workbench object. The caller owns conversation policy, recording, and retry decisions; session access alone does not make work depend on the current history position.
28
28
 
29
- Use a top-level capability for operations on the execution context or shared resource lifecycle, rather than inventing a placeholder resource solely to host them.
30
-
31
- ## Put invocation knowledge in the contract
32
-
33
- Tool descriptions, guidelines, and schemas must support use independently of the manual. Explain purpose, how outputs relate to later inputs, input meaning, result interpretation, and execution boundaries in the owning contract.
34
-
35
- Use examples to clarify data flow without prescribing a workflow. Describe an operation's own use of a file reference rather than assuming which resource produced it or which consumer follows it. Distinguish failure, cancellation, partial output, and uncertain effects when those differences affect what a caller can conclude.
36
-
37
- Choose scheduling according to ordering requirements, not simply whether an operation reads or writes. Require interaction only when completion depends on a user response; showing progress alone does not make backend work interactive.
38
-
39
- ## Compose model execution deliberately
40
-
41
- Session-bound model execution is useful when a request should act through a resource's links and real session. Direct model execution suits work whose messages and executable tools are supplied by the caller without a workbench object. Choose based on the access and history relationship, not on a presumed requirement to create an Agent.
42
-
43
- Capture configuration and authorization at the request boundary. Read ordinary mutable content when handling an operation. For a resource addressing a selected network, this keeps the meaning of its addresses stable through the tool batch without pretending the network's content is frozen.
44
-
45
- The caller owns conversation policy, historical recording, and retry decisions. Keep transient progress distinct from durable operation results. A generation failure does not necessarily mean that every earlier tool effect failed or that repeating the request is safe.
46
-
47
- Resource access and timeline activity are also separate. Work that depends on a history position needs the appropriate activity scope; merely holding access to a resource does not establish that dependency. Temporary conversations need explicit ownership of attachments that must survive into later requests.
48
-
49
- ## Separate services from their interfaces
50
-
51
- A backend capability does not automatically need a resource card or a model tool. Typed calls, events, and sustained channels serve different interaction needs; choose them according to whether the consumer requests a result, observes a change, or maintains a live connection.
52
-
53
- For example, a one-shot shell process and a persistent terminal need different owners. Cancelling a command concerns that process; closing one terminal view need not end a shell shared with other views. Host services supply the execution mechanics, while the plugin chooses the domain object, presentation, and callable interface.
29
+ Start at the target SDK's public declarations and follow a similar tool from registration to dispatch and result projection in the application source. Verify what discovery actually shows and run the operation through its intended caller, not just its handler. Check invalid input, inaccessible targets where relevant, and whether the result gives the caller enough evidence to continue without guessing or repeating an effect.
@@ -10,11 +10,11 @@ Use host presentation for containment and navigation. Keep the plugin's domain c
10
10
 
11
11
  ## Carry a tool view from input to result
12
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.
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. Let the excerpt yield to a distinct status label and make the complete input available in the expanded view.
14
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.
15
+ While the model generates input, a preview can follow the tail of the draft. Treat an incomplete structured preview as display data, not validated arguments. For a freeform view, preserve whitespace and distinguish empty text from missing input. Once the tool begins, its input is 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
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.
17
+ If a tool emits a growing report or log, 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
18
 
19
19
  ## Give expanded views a meaningful identity
20
20
 
@@ -17,7 +17,7 @@ Inside a sheet, a region reads as a region because its tone differs, not because
17
17
  - **Group**: rows, fields, and repeated items that belong together recede into a group in the shell tone, with hairlines between rows.
18
18
  - **Floating**: menus, popovers, tooltips, hover cards, and dialogs lift above content and keep their outer edge.
19
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.
20
+ A plugin that needs a group uses the shell tone rather than adding a 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
21
 
22
22
  ## Use lines only when they mean something
23
23
 
@@ -29,7 +29,7 @@ A plugin that draws decorative borders dilutes those meanings. Prefer the host's
29
29
 
30
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
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.
32
+ Plugin views should use the same motion cues and 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 in custom transitions as well.
33
33
 
34
34
  ## Choose controls by the kind of choice
35
35
 
@@ -14,7 +14,7 @@
14
14
  "zod": "^4.6.5"
15
15
  },
16
16
  "devDependencies": {
17
- "@asterism-app/sdk": "2.3.0",
17
+ "@asterism-app/sdk": "2.4.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.3.0",
3
+ "version": "2.4.0",
4
4
  "description": "Public contracts and host capabilities for Asterism plugins",
5
5
  "license": "MIT",
6
6
  "author": "Chien Zhang",
@@ -3,6 +3,8 @@ import type { Json } from "./json.ts";
3
3
 
4
4
  /** Read complete content or a byte range; open streams the selected bytes in chunks. */
5
5
  export interface ContentReader {
6
+ /** Validated byte length when the backing store exposes metadata without opening the stream. */
7
+ size?(ref: ContentRef): number;
6
8
  read(ref: ContentRef, range?: ContentRange): Promise<Uint8Array>;
7
9
  open(ref: ContentRef, range?: ContentRange): AsyncIterable<Uint8Array>;
8
10
  }
@@ -3,11 +3,16 @@ import { defineData } from "./presentation.ts";
3
3
  import { modelCostSchema } from "./model-cost.ts";
4
4
  import { thinkingSchema } from "./model-selection.ts";
5
5
 
6
+ export const modelMediaModalities = ["image", "audio", "video", "document"] as const;
7
+ export const modelMediaModalitySchema = z.enum(modelMediaModalities);
8
+ export type ModelMediaModality = z.infer<typeof modelMediaModalitySchema>;
9
+ export const modelInputModalitiesSchema = z.array(modelMediaModalitySchema);
10
+
6
11
  export const catalogModelSchema = z.object({
7
12
  providerId: z.string(), modelId: z.string(), name: z.string(), enabled: z.boolean(),
8
13
  contextWindow: z.number().nullable(), cost: modelCostSchema.nullable(),
9
14
  generation: z.object({ maxOutputTokens: z.number().nullable() }),
10
- capabilities: z.object({ reasoning: z.boolean(), tools: z.boolean(), thinkingLevels: z.array(thinkingSchema) }),
15
+ capabilities: z.object({ reasoning: z.boolean(), tools: z.boolean(), thinkingLevels: z.array(thinkingSchema), inputModalities: modelInputModalitiesSchema.optional() }),
11
16
  });
12
17
  /** Enabled model metadata available to runtime consumers; model is the complete provider/model expression. */
13
18
  export const modelInfoSchema = catalogModelSchema.omit({ providerId: true, modelId: true, enabled: true }).extend({
@@ -44,14 +44,19 @@ export function completionData<T extends Json>(completion: ModelCompletion | nul
44
44
  const result = contract.schema.safeParse(structuredClone(extension.data));
45
45
  return result.success ? result.data : null;
46
46
  }
47
+ export const toolCallInputSchema = z.discriminatedUnion("kind", [
48
+ z.strictObject({ kind: z.literal("structured"), value: jsonSchema }),
49
+ z.strictObject({ kind: z.literal("freeform"), text: z.string() }),
50
+ ]);
51
+ export const toolInputDraftSchema = z.strictObject({ kind: z.enum(["structured", "freeform"]), text: z.string() });
52
+
47
53
  const block = { responseId: id, requestParentId: id.nullable(), ordinal: z.number().int().nonnegative(),
48
54
  complete: z.boolean(), continuation: jsonSchema, source: modelSourceSchema, completion: modelCompletionSchema.nullable().optional(),
49
55
  /** Block generation start and end times (millisecond timestamps); blocks finalized before generation ends have a null end time, and unrecorded times are omitted. See outcome for tool execution times. */
50
56
  startedAt: z.number().nonnegative().optional(), endedAt: z.number().nonnegative().nullable().optional() };
51
57
  /** Tool call block shape without the completion invariant, for contracts that store input and outcome separately. */
52
58
  export const modelToolCallBlockSchema = z.strictObject({ ...block, kind: z.literal("toolcall"), callId: id, name: id,
53
- /** Original model text; retained only when parsed arguments are unavailable (the call is incomplete), otherwise arguments is authoritative. */
54
- argumentsText: z.string().nullable(), arguments: jsonSchema, outcome: toolOutcomeSchema.nullable(), invocation: toolInvocationSchema.optional() });
59
+ input: toolCallInputSchema.nullable(), draft: toolInputDraftSchema.nullable(), outcome: toolOutcomeSchema.nullable(), invocation: toolInvocationSchema.optional() });
55
60
  export const modelBlockSchema = z.discriminatedUnion("kind", [
56
61
  z.strictObject({ ...block, kind: z.literal("thinking"), text: z.string(), summary: z.string() }),
57
62
  z.strictObject({ ...block, kind: z.literal("text"), text: z.string() }),
package/src/models.ts CHANGED
@@ -19,10 +19,18 @@ export interface SystemPrompt { blocks: readonly PromptBlock[] }
19
19
  /** Reasoning text is the plaintext delivered by the protocol, and summary is an independent summary; both can coexist or be empty, and neither fills the other.
20
20
  * continuation carries only native data such as signatures/ciphertext, shaped by the producing protocol; target projection determines whether it can be reused.
21
21
  */
22
+ /** Completed tool input in Asterism's vocabulary, independent of provider wire encoding. */
23
+ export type ToolCallInput = { kind: "structured"; value: Json } | { kind: "freeform"; text: string };
24
+ /** Unfinished generation for display and recording, never for execution. */
25
+ export interface ToolInputDraft { kind: ToolCallInput["kind"]; text: string }
26
+ export type ModelToolDeclaration = { name: string; description: string } & (
27
+ { kind: "structured"; parameters: Json } | { kind: "freeform" }
28
+ );
29
+
22
30
  export type ModelPart =
23
31
  | { kind: "thinking"; text: string; summary: string; continuation: Json }
24
32
  | { kind: "text"; text: string; continuation: Json }
25
- | { kind: "toolcall"; callId: string; name: string; arguments: Json; continuation: Json };
33
+ | { kind: "toolcall"; callId: string; name: string; input: ToolCallInput; continuation: Json };
26
34
  export type ModelItem =
27
35
  | { kind: "input" | "context"; parts: readonly ModelInputPart[] }
28
36
  // scope and adapter (the producing protocol's continuation format) constrain native data; they do not gate public content in cross-model requests.
@@ -34,11 +42,11 @@ export interface Usage {
34
42
  }
35
43
  export type StreamPart =
36
44
  | { id: string; kind: "text" | "thinking" }
37
- | { id: string; kind: "toolcall"; callId: string; name: string };
45
+ | { id: string; kind: "toolcall"; callId: string; name: string; inputKind: ToolCallInput["kind"] };
38
46
  export type ModelEvent =
39
47
  | { type: "part.start"; part: StreamPart }
40
48
  | { type: "part.delta"; partId: string; delta: string; channel?: "summary" }
41
- | { type: "part.end"; partId: string; arguments?: Json; continuation?: Json }
49
+ | { type: "part.end"; partId: string; input?: ToolCallInput; continuation?: Json }
42
50
  | { type: "finish"; reason: string; usage: Usage | null; responseId?: string; rawFinishReason?: string; source?: ModelSource; timing?: RequestTiming; response?: ModelResponse | null };
43
51
  export type ModelSource = { model: string; adapter: string; scope: string };
44
52
  /** Failure message is a standalone English summary; details preserve original diagnostic text and response data. */
@@ -66,15 +74,14 @@ export type ModelBlock = {
66
74
  } & (
67
75
  | { kind: "thinking"; text: string; summary: string }
68
76
  | { kind: "text"; text: string }
69
- | { kind: "toolcall"; callId: string; name: string; argumentsText: string | null; arguments: Json; outcome: ToolOutcome | null;
77
+ | { kind: "toolcall"; callId: string; name: string; input: ToolCallInput | null; draft: ToolInputDraft | null; outcome: ToolOutcome | null;
70
78
  /** Original input preview identity; available even when execution never produced an outcome. */
71
79
  invocation?: ToolInvocationInfo }
72
80
  );
73
81
  export type ModelLiveBlock = { id: string; responseId: string; ordinal: number } & (
74
82
  | { kind: "text"; text: string; endedAt: number | null }
75
83
  | { kind: "thinking"; text: string; startedAt: number; endedAt: number | null }
76
- /** During the input phase, arguments is a display preview parsed tolerantly and cannot be used for execution; other phases contain complete arguments. */
77
- | { kind: "toolcall"; name: string; argumentsText: string; arguments: Json; state: "input" | "ready" | "executing";
84
+ | { kind: "toolcall"; name: string; input: ToolCallInput | null; draft: ToolInputDraft | null; state: "input" | "ready" | "executing";
78
85
  invocation: ToolInvocationInfo | null; result: Extract<ToolResult, { kind: "running" }> | null;
79
86
  /** One-shot attention time, present only in live execution; history does not replay notices. */
80
87
  noticeAt?: number }
@@ -107,7 +114,7 @@ export interface ModelResponse {
107
114
  receivedAt: number;
108
115
  headers: Readonly<Record<string, string>>;
109
116
  }
110
- export interface ModelToolCall { callId: string; name: string; arguments: Json }
117
+ export interface ModelToolCall { callId: string; name: string; input: ToolCallInput }
111
118
  export interface ModelToolObserver {
112
119
  prepared?(call: ModelToolCall, info: ToolInvocationInfo): void;
113
120
  started?(call: ModelToolCall, info: ToolInvocationInfo): void;
@@ -117,8 +124,8 @@ export interface ModelToolObserver {
117
124
  }
118
125
  /** Executable tools supplied by the requesting paradigm or a host-bound request environment. */
119
126
  export interface ModelTools {
120
- readonly declarations: readonly { name: string; description: string; parameters: Json }[];
121
- preview?(name: string, args: Json): ToolInvocationInfo;
127
+ readonly declarations: readonly ModelToolDeclaration[];
128
+ preview?(name: string, input: ToolCallInput | null): ToolInvocationInfo;
122
129
  execute(calls: readonly ModelToolCall[], signal: AbortSignal,
123
130
  settle: (call: ModelToolCall, outcome: ToolOutcome) => void, observer: ModelToolObserver): Promise<void>;
124
131
  }
@@ -144,7 +151,7 @@ export type ModelRunResult = {
144
151
  /** The final request's input context; an independent copy for domain extension producers to read. */
145
152
  export interface ModelRequestContext {
146
153
  system: SystemPrompt;
147
- tools: readonly { name: string; description: string; parameters: Json }[];
154
+ tools: readonly ModelToolDeclaration[];
148
155
  }
149
156
  export interface StreamRequest extends ModelRequestIdentity {
150
157
  target: ModelTarget;
@@ -152,7 +159,7 @@ export interface StreamRequest extends ModelRequestIdentity {
152
159
  messages: ModelItem[];
153
160
  /** The output limit for this completion; uses the smaller of this value and the model's configured limit. */
154
161
  maxOutputTokens?: number;
155
- tools?: { name: string; description: string; parameters: Json }[];
162
+ tools?: ModelToolDeclaration[];
156
163
  signal: AbortSignal;
157
164
  }
158
165
  export interface ModelInputOptions { content?: ContentReader }
@@ -12,12 +12,10 @@ export type ToolInput = JsonObject | null;
12
12
  /** The transport supplies JSON values; this schema constrains only their root shape. */
13
13
  export const toolInputSchema = z.looseObject({}).nullable() as z.ZodType<ToolInput>;
14
14
 
15
- export interface ToolContract<A extends ToolInput = ToolInput> extends ContractReference {
15
+ interface ToolMetadata extends ContractReference {
16
16
  name: string;
17
17
  description: string;
18
18
  guidelines: readonly string[];
19
- /** Structured parameters; a tool determines its fields and whether null is accepted. */
20
- argsSchema: z.ZodType<A>;
21
19
  /** Execution requires an endpoint that can receive user interaction. Output rendering alone does not require it. */
22
20
  requiresInteraction?: boolean;
23
21
  /**
@@ -27,16 +25,35 @@ export interface ToolContract<A extends ToolInput = ToolInput> extends ContractR
27
25
  */
28
26
  requiresNotice?: boolean;
29
27
  }
30
- /** Tool definitions fix selection descriptions, usage guidance, and args; implementations add only target/result and execution information. */
31
- export interface ImplementationContract<S extends Json, T extends ToolInput, A extends ToolInput, O extends Json> extends DataContract<O> {
28
+ export interface StructuredToolContract<A extends ToolInput = ToolInput> extends ToolMetadata {
29
+ kind?: "structured";
30
+ /** Structured parameters; a tool determines its fields and whether null is accepted. */
31
+ argsSchema: z.ZodType<A>;
32
+ }
33
+ export interface FreeformToolContract extends ToolMetadata {
34
+ kind: "freeform";
35
+ argsSchema?: never;
36
+ }
37
+ export type ToolContract<A extends ToolInput = ToolInput> = StructuredToolContract<A> | FreeformToolContract;
38
+
39
+ interface ImplementationMetadata<S extends Json, O extends Json> extends DataContract<O> {
32
40
  resource: ResourceContract<S>;
33
- tool: ToolContract<A>;
34
- /** Structured selection within the resource; each implementation determines whether null is accepted. */
35
- targetSchema: z.ZodType<T>;
36
41
  effect: "read" | "write";
37
42
  /** Sequential operations share submission order; parallel operations can overlap either lane. */
38
43
  execution: "parallel" | "sequential";
39
44
  }
45
+ /** Implementations of structured tools add a target schema; freeform implementations receive the original text. */
46
+ export interface StructuredImplementationContract<S extends Json, T extends ToolInput, A extends ToolInput, O extends Json> extends ImplementationMetadata<S, O> {
47
+ tool: StructuredToolContract<A>;
48
+ /** Structured selection within the resource; each implementation determines whether null is accepted. */
49
+ targetSchema: z.ZodType<T>;
50
+ }
51
+ export interface FreeformImplementationContract<S extends Json, O extends Json> extends ImplementationMetadata<S, O> {
52
+ tool: FreeformToolContract;
53
+ targetSchema?: never;
54
+ }
55
+ export type ImplementationContract<S extends Json, T extends ToolInput, A extends ToolInput, O extends Json> =
56
+ StructuredImplementationContract<S, T, A, O> | FreeformImplementationContract<S, O>;
40
57
  export function defineResource<S extends Json>(kind: string, stateSchema: z.ZodType<S>): ResourceContract<S> {
41
58
  return { kind, stateSchema };
42
59
  }
@@ -45,16 +62,31 @@ function requireDescription(schema: z.ZodType, subject: string): void {
45
62
  if (!schema.description?.trim()) throw new Error(`Missing schema description: ${subject}`);
46
63
  try { z.toJSONSchema(schema); } catch (error) { throw new Error(`Schema is not representable as JSON Schema: ${subject}`, { cause: error }); }
47
64
  }
48
- export function defineTool<A extends ToolInput>(definition: ToolContract<A>): ToolContract<A> {
65
+ export function defineTool<A extends ToolInput>(definition: StructuredToolContract<A>): StructuredToolContract<A>;
66
+ export function defineTool(definition: FreeformToolContract): FreeformToolContract;
67
+ export function defineTool(definition: ToolContract): ToolContract;
68
+ export function defineTool(definition: ToolContract): ToolContract {
49
69
  if (!definition.name.trim() || !definition.description.trim()) throw new Error("Tool name and description must not be empty.");
50
70
  if (definition.guidelines.some(guideline => !guideline.trim())) throw new Error(`Empty tool guideline: ${definition.name}`);
51
- requireDescription(definition.argsSchema, `${definition.name}.args`);
71
+ if (definition.kind === "freeform") {
72
+ if (/\s/.test(definition.name)) throw new Error(`Freeform tool names must be a single token: ${definition.name}`);
73
+ if ("argsSchema" in definition) throw new Error(`Freeform tools do not declare an args schema: ${definition.name}`);
74
+ } else requireDescription(definition.argsSchema, `${definition.name}.args`);
52
75
  return { ...definition, ...contractReferenceSchema.parse({ id: definition.id }), guidelines: [...definition.guidelines] };
53
76
  }
77
+ export function defineImplementation<S extends Json, T extends ToolInput, A extends ToolInput, O extends Json>(
78
+ definition: StructuredImplementationContract<S, T, A, O>,
79
+ ): StructuredImplementationContract<S, T, A, O>;
80
+ export function defineImplementation<S extends Json, O extends Json>(
81
+ definition: FreeformImplementationContract<S, O>,
82
+ ): FreeformImplementationContract<S, O>;
54
83
  export function defineImplementation<S extends Json, T extends ToolInput, A extends ToolInput, O extends Json>(
55
84
  definition: ImplementationContract<S, T, A, O>,
56
- ): ImplementationContract<S, T, A, O> {
57
- requireDescription(definition.targetSchema, `${definition.id}.target`);
85
+ ): ImplementationContract<S, T, A, O>;
86
+ export function defineImplementation(definition: ImplementationContract<Json, ToolInput, ToolInput, Json>) {
87
+ if (definition.tool.kind === "freeform") {
88
+ if ("targetSchema" in definition) throw new Error(`Freeform tools do not declare a target schema: ${definition.id}`);
89
+ } else requireDescription(definition.targetSchema!, `${definition.id}.target`);
58
90
  requireDescription(definition.schema, `${definition.id}.result`);
59
91
  return definition;
60
92
  }
@@ -4,6 +4,8 @@ import type { ContentReader } from "./content-runtime.ts";
4
4
  /** The host binds input drafts to contracts; business input carries only ContentRef. The host closes drafts after command success and preserves them for retry after failure. */
5
5
  export interface RendererContentInput extends ContentReader {
6
6
  stage(source: Blob | Uint8Array, options?: { signal?: AbortSignal; progress?(bytes: number, total: number): void }): Promise<ContentRef>;
7
+ /** Release this draft's hold on the reference. Captured submissions and persistent references are unaffected. */
8
+ release(ref: ContentRef): Promise<void>;
7
9
  close(): Promise<void>;
8
10
  }
9
11
  export interface RendererInputOptions { content?: RendererContentInput }
@@ -3,7 +3,7 @@ import type { Json } from "./json.ts";
3
3
  import type { DataContract } from "./presentation.ts";
4
4
  import type { ConfigContract } from "./config.ts";
5
5
  import type { ModelLiveBlock } from "./models.ts";
6
- import type { ToolRenderProps, ToolView } from "./renderer-tools.ts";
6
+ import type { AnyToolRenderProps, ToolView } from "./renderer-tools.ts";
7
7
  import type { EventSubscriber } from "./events.ts";
8
8
  import type { ResourceDescription } from "./renderer.ts";
9
9
  import type { UiText } from "./i18n.ts";
@@ -15,7 +15,7 @@ export interface RendererResources {
15
15
  }
16
16
  export interface RendererCatalogs { get<T extends Json>(contract: DataContract<T>): T | null; error: UiText | null }
17
17
  export interface RendererTools {
18
- resolve(props: ToolRenderProps): ToolView & { props: ToolRenderProps };
18
+ resolve(props: AnyToolRenderProps): ToolView & { props: AnyToolRenderProps };
19
19
  preparation(name: string): string;
20
20
  /** Localized name of a tool by its model-facing name and implementation contract; null when no view declares one. */
21
21
  label(name: string, implementation: string | null): string | null;
@@ -2,21 +2,25 @@ import { createElement, type ComponentType, type ReactNode } from "react";
2
2
  import type { z } from "zod";
3
3
  import type { UiText } from "./i18n.ts";
4
4
  import type { Json } from "./json.ts";
5
+ import type { ToolInputDraft } from "./models.ts";
5
6
  import { reference, type ContractReference, type DataContract } from "./presentation.ts";
6
7
  import type { ToolCompletion, ToolInvocationInfo, ToolResult } from "./tool-result.ts";
7
8
 
8
- interface ToolCallProps<T, A> {
9
+ interface ToolIdentityProps {
9
10
  name: string;
11
+ invocation: ToolInvocationInfo;
12
+ }
13
+ interface ToolCallProps<T, A> extends ToolIdentityProps {
14
+ kind?: "structured";
10
15
  target: T;
11
16
  args: A;
12
- invocation: ToolInvocationInfo;
13
17
  }
14
- /** Partial JSON has not passed the argument contract; fields may be missing, incomplete, or of the wrong type. */
18
+ /** Partial JSON has not passed the argument contract. */
15
19
  export interface ToolInputRenderProps extends ToolCallProps<Json, Json> {
16
20
  phase: "input";
17
21
  result: null;
18
- /** Original unfinished input; the host derives a display-only argument preview when resolving the view. */
19
- argumentsText?: string;
22
+ /** Original unfinished input; the host derives a display-only preview when resolving the view. */
23
+ draft?: ToolInputDraft | null;
20
24
  }
21
25
  /** Waiting for scheduling and execution share a view; complete arguments have passed contract validation. */
22
26
  export interface ToolExecutionRenderProps<D = Json, T = Json, A = Json> extends ToolCallProps<T, A> {
@@ -30,6 +34,18 @@ export interface ToolResultRenderProps<D = Json, T = Json, A = Json> extends Too
30
34
  export type ToolRenderProps<D = Json, T = Json, A = Json> =
31
35
  | ToolInputRenderProps | ToolExecutionRenderProps<D, T, A> | ToolResultRenderProps<D, T, A>;
32
36
 
37
+ /** A freeform renderer receives exact text, including an empty string; null means no text was captured. */
38
+ interface FreeformCallProps extends ToolIdentityProps {
39
+ kind: "freeform";
40
+ text: string | null;
41
+ }
42
+ export type FreeformToolInputRenderProps = FreeformCallProps & { phase: "input"; result: null };
43
+ export type FreeformToolExecutionRenderProps<D = Json> = FreeformCallProps & Pick<ToolExecutionRenderProps<D>, "phase" | "result">;
44
+ export type FreeformToolResultRenderProps<D = Json> = FreeformCallProps & Pick<ToolResultRenderProps<D>, "phase" | "result">;
45
+ export type FreeformToolRenderProps<D = Json> = FreeformToolInputRenderProps | FreeformToolExecutionRenderProps<D> | FreeformToolResultRenderProps<D>;
46
+ /** Used by the conversation host before resolving a specific renderer. */
47
+ export type AnyToolRenderProps = ToolRenderProps | FreeformToolRenderProps;
48
+
33
49
  /** All three states use the same two independently optional entry points; the same declaration can be reused across phases. */
34
50
  export interface ToolPhaseView<P> {
35
51
  headerRenderer?: ComponentType<P>;
@@ -45,15 +61,22 @@ export interface ToolExecutionPhaseView<P> extends ToolStreamingPhaseView<P> {
45
61
  /** Pure function: returns true when the body requires user attention; the shell immediately expands once on the first match during execution, independently of streaming preferences, and users can still collapse it. */
46
62
  attention?: (props: P) => boolean;
47
63
  }
48
- export interface ToolRendererDefinition<D = Json, T = Json, A = Json> {
64
+ interface ToolViewOptions {
49
65
  label?: UiText;
50
66
  icon?: ReactNode;
51
- /** Whether the conversation shell exposes raw argument/result details; defaults to true. */
67
+ /** Whether the conversation shell exposes raw call/result details; defaults to true. */
52
68
  details?: boolean;
69
+ }
70
+ export interface ToolRendererDefinition<D = Json, T = Json, A = Json> extends ToolViewOptions {
53
71
  input?: ToolStreamingPhaseView<ToolInputRenderProps>;
54
72
  execution?: ToolExecutionPhaseView<ToolExecutionRenderProps<D, T, A>>;
55
73
  result?: ToolPhaseView<ToolResultRenderProps<D, T, A>>;
56
74
  }
75
+ export interface FreeformToolRendererDefinition<D = Json> extends ToolViewOptions {
76
+ input?: ToolStreamingPhaseView<FreeformToolInputRenderProps>;
77
+ execution?: ToolExecutionPhaseView<FreeformToolExecutionRenderProps<D>>;
78
+ result?: ToolPhaseView<FreeformToolResultRenderProps<D>>;
79
+ }
57
80
  export interface ToolView {
58
81
  label?: UiText;
59
82
  icon?: ReactNode;
@@ -71,7 +94,7 @@ export interface ToolRenderer {
71
94
  label?: UiText;
72
95
  /** Static operation icon, available to call summaries without rendering arguments or results. */
73
96
  icon?: ReactNode;
74
- resolve(props: ToolRenderProps): ToolView | null;
97
+ resolve(props: AnyToolRenderProps): ToolView | null;
75
98
  }
76
99
 
77
100
  function render<P extends { phase: ToolRenderProps["phase"] }>(
@@ -87,26 +110,56 @@ function render<P extends { phase: ToolRenderProps["phase"] }>(
87
110
  };
88
111
  }
89
112
 
90
- /** Dispatch by phase; streaming input is not treated as valid arguments, while execution and results share complete argument and output validation. */
113
+ type StructuredViewContract<D extends Json, T extends Json, A extends Json> = DataContract<D> & {
114
+ kind?: "structured";
115
+ targetSchema?: z.ZodType<T>;
116
+ tool?: { kind?: "structured"; argsSchema: z.ZodType<A> };
117
+ };
118
+ type FreeformViewContract<D extends Json> = (DataContract<D> & { tool: { kind: "freeform" } })
119
+ | (ContractReference & { kind: "freeform"; resultSchema: z.ZodType<D> });
120
+
121
+ /** Structured and freeform views match only their own input kind. Completed result data is decoded in either case. */
122
+ export function toolRenderer<D extends Json>(contract: FreeformViewContract<D>, definition: FreeformToolRendererDefinition<D>): ToolRenderer;
91
123
  export function toolRenderer<D extends Json, T extends Json = Json, A extends Json = Json>(
92
- contract: DataContract<D> & { targetSchema?: z.ZodType<T>; tool?: { argsSchema: z.ZodType<A> } },
93
- definition: ToolRendererDefinition<D, T, A>,
124
+ contract: StructuredViewContract<D, T, A>, definition: ToolRendererDefinition<D, T, A>,
125
+ ): ToolRenderer;
126
+ export function toolRenderer<D extends Json, T extends Json, A extends Json>(
127
+ contract: StructuredViewContract<D, T, A> | FreeformViewContract<D>,
128
+ definition: ToolRendererDefinition<D, T, A> | FreeformToolRendererDefinition<D>,
94
129
  ): ToolRenderer {
95
- return { contract: reference(contract), label: definition.label, icon: definition.icon, resolve(props) {
96
- if (props.phase === "input") return definition.input ? render(definition, definition.input, props) : null;
97
- const data = props.result?.data;
98
- const parsed = data === null || data === undefined ? null : contract.schema.safeParse(data);
99
- if (parsed && !parsed.success) return null;
130
+ if (isFreeform(contract)) {
131
+ const view = definition as FreeformToolRendererDefinition<D>;
132
+ const schema = "resultSchema" in contract ? contract.resultSchema : contract.schema;
133
+ return { contract: reference(contract), label: view.label, icon: view.icon, resolve(props) {
134
+ if (props.kind !== "freeform") return null;
135
+ if (props.phase === "input") return view.input ? render(view, view.input, props) : null;
136
+ const data = decodeData(schema, props.result?.data);
137
+ if (data === undefined) return null;
138
+ if (props.phase === "settled") return render(view, view.result, { ...props, result: { ...props.result, data } });
139
+ return render(view, view.execution, { ...props, result: props.result ? { ...props.result, data } : null });
140
+ } };
141
+ }
142
+ const view = definition as ToolRendererDefinition<D, T, A>;
143
+ return { contract: reference(contract), label: view.label, icon: view.icon, resolve(props) {
144
+ if (props.kind === "freeform") return null;
145
+ if (props.phase === "input") return view.input ? render(view, view.input, props) : null;
146
+ const data = decodeData(contract.schema, props.result?.data);
147
+ if (data === undefined) return null;
100
148
  const target = contract.targetSchema?.safeParse(props.target);
101
149
  const args = contract.tool?.argsSchema.safeParse(props.args);
102
150
  if (target && !target.success || args && !args.success) return null;
103
151
  // Pure data contracts without an argument schema preserve raw JSON; type erasure occurs only at the registration boundary.
104
152
  const input = { target: (target ? target.data : props.target) as T, args: (args ? args.data : props.args) as A };
105
- if (props.phase === "settled") return render(definition, definition.result, {
106
- ...props, ...input, result: { ...props.result, data: parsed?.data ?? null },
107
- });
108
- return render(definition, definition.execution, {
109
- ...props, ...input, result: props.result ? { ...props.result, data: parsed?.data ?? null } : null,
110
- });
153
+ if (props.phase === "settled") return render(view, view.result, { ...props, ...input, result: { ...props.result, data } });
154
+ return render(view, view.execution, { ...props, ...input, result: props.result ? { ...props.result, data } : null });
111
155
  } };
112
156
  }
157
+ function isFreeform<D extends Json>(contract: StructuredViewContract<D, Json, Json> | FreeformViewContract<D>): contract is FreeformViewContract<D> {
158
+ return ("kind" in contract && contract.kind === "freeform") || ("tool" in contract && contract.tool?.kind === "freeform");
159
+ }
160
+ /** Undefined is reserved for invalid data; null denotes absent data and bypasses the schema. */
161
+ function decodeData<D extends Json>(schema: z.ZodType<D>, data: Json | undefined): D | null | undefined {
162
+ if (data === null || data === undefined) return null;
163
+ const parsed = schema.safeParse(data);
164
+ return parsed.success ? parsed.data : undefined;
165
+ }
@@ -11,6 +11,7 @@ import type { RecordContract, SessionRecord } from "./records.ts";
11
11
  import type { EventContract, PluginEvents } from "./events.ts";
12
12
  import type { ToolCompletion, ToolInvocationInfo, ToolModelOutput } from "./tool-result.ts";
13
13
  import type { PluginConfig, PluginLogger, PluginSecrets, PluginTasks } from "./runtime.ts";
14
+ import type { ModelMediaModality } from "./model-catalog.ts";
14
15
  import type { ModelServices } from "./models.ts";
15
16
  import type { ResourceRef, ResourceSnapshot, SessionSnapshot, SessionDirectory } from "./workspace.ts";
16
17
  import type { ActionContract, CreationContract } from "./commands.ts";
@@ -50,6 +51,10 @@ export interface PluginContext {
50
51
  readonly sessions: SessionDirectory;
51
52
  readonly createSession: SessionCreation;
52
53
  readonly dir: string;
54
+ /** Reconstructible data in the application data root, excluded from recovery points. */
55
+ readonly cacheDir: string;
56
+ /** Plugin-specific system temporary path. Create it as needed; files may disappear and are not backed up. */
57
+ readonly tempDir: string;
53
58
  /** Resolve a package-relative asset, independently of writable plugin data. */
54
59
  readonly assets: { path(relativePath: string): string };
55
60
  readonly agentCatalog: AgentCatalog;
@@ -162,7 +167,7 @@ export type CallResult<D extends Json = Json> =
162
167
  | OptionalData<Exclude<ToolCompletion, { kind: "succeeded" | "partial" }>, D>;
163
168
  export type PreparedResult = CallResult & ToolInvocationInfo;
164
169
  /** Tool caller identity captured at the request boundary; carries neither private resource state nor operation permissions. */
165
- export type ToolCaller = Readonly<Pick<ResourceSnapshot, "ref" | "title"> & { agent?: string }>;
170
+ export type ToolCaller = Readonly<Pick<ResourceSnapshot, "ref" | "title"> & { agent?: string; modelInputModalities?: readonly ModelMediaModality[] }>;
166
171
  export interface ToolInvocation extends ToolInvocationInfo {
167
172
  effect: "read" | "write";
168
173
  /** Sequential operations share submission order; parallel operations can overlap either lane. */
@@ -174,7 +179,7 @@ export interface ToolContribution {
174
179
  readonly contract: ImplementationContract<Json, ToolInput, ToolInput, Json>;
175
180
  /** Bind resource-specific access and configuration at the model request boundary. The returned contribution handles that request's calls. */
176
181
  capture?(resource: ResourceSnapshot, object: ObjectReader, caller: ToolCaller): ToolContribution;
177
- /** Raw model inputs are validated against the target and argument contracts before execution. */
182
+ /** Validate raw input before execution. Structured inputs use target and args; freeform uses a null target and the exact text in args. */
178
183
  prepare(resource: ResourceSnapshot, object: ObjectExecutor, target: Json, args: Json, caller: ToolCaller, interactive: boolean): ToolInvocation | PreparedResult;
179
184
  }
180
185
  export interface ModuleContribution {
@@ -202,8 +207,8 @@ export interface PluginContribution extends ModuleContribution {
202
207
  modules?: readonly PluginModule[];
203
208
  }
204
209
  /**
205
- * Format declarations for persistent plugin files; paths are relative to extensions/<pluginId>, and migration key n means n → n+1.
206
- * Versions are stamped by the writer: JSON uses a `{ version, data }` envelope, and SQLite uses `PRAGMA user_version`.
210
+ * Persistent plugin formats. Migration key n means n → n+1.
211
+ * Private files use paths relative to extensions/<pluginId> and store their version in the JSON envelope or SQLite header.
207
212
  */
208
213
  export type PluginStorageDeclaration = {
209
214
  kind: "json"; path: string; version: number;
@@ -211,11 +216,22 @@ export type PluginStorageDeclaration = {
211
216
  } | {
212
217
  kind: "sqlite"; path: string; version: number;
213
218
  migrations: Readonly<Record<number, (db: DatabaseSync) => void>>;
214
- };
219
+ } | PluginRecordStorageDeclaration;
220
+ /** A versioned set of owned session record contracts. The host migrates encoded data before plugin setup. */
221
+ export interface PluginRecordStorageDeclaration {
222
+ kind: "records";
223
+ /** Stable identifier within the plugin, independent of display names and file paths. */
224
+ id: string;
225
+ /** Stable, disjoint set of qualified contracts owned by this plugin. Existing untracked history starts at version 1. */
226
+ contracts: readonly string[];
227
+ version: number;
228
+ /** Synchronous transforms of encoded record data. Identity, provenance, and content reference membership stay fixed. */
229
+ migrations: Readonly<Record<number, (contract: string, data: Json) => Json>>;
230
+ }
215
231
  /** Default export of the storage entry point (manifest `asterism.storage`); the host imports it separately before the plugin runtime. */
216
232
  export function defineStorage(declarations: readonly PluginStorageDeclaration[]): readonly PluginStorageDeclaration[] {
217
233
  for (const item of declarations) if (!Number.isSafeInteger(item.version) || item.version < 1)
218
- throw new Error(`Storage ${item.path} must declare a positive integer version.`);
234
+ throw new Error(`Storage ${item.kind === "records" ? item.id : item.path} must declare a positive integer version.`);
219
235
  return Object.freeze([...declarations]);
220
236
  }
221
237
  export interface PluginDefinition {
@@ -2,7 +2,7 @@ import type { ActionContract, CreationContract } from "./commands.ts";
2
2
  import type { z } from "zod";
3
3
  import { jsonSchema, type Json } from "./json.ts";
4
4
  import { defaultToolModel, type ToolModelOutput } from "./tool-result.ts";
5
- import type { ResourceContract, ImplementationContract, ToolInput } from "./module-contract.ts";
5
+ import type { ResourceContract, ImplementationContract, StructuredImplementationContract, FreeformImplementationContract, ToolInput } from "./module-contract.ts";
6
6
  import type { RecordContract } from "./records.ts";
7
7
  import { reference, present, type DataContract } from "./presentation.ts";
8
8
  import { PluginApiError } from "./runtime.ts";
@@ -67,13 +67,29 @@ export function implementResource<S extends Json, V extends Json>(
67
67
  attach(parse(resource.stateSchema, snapshot.data, "resource"), object, lifetime) } : {}),
68
68
  };
69
69
  }
70
+ interface ResourceToolContext<D extends Json> {
71
+ object: ObjectExecutor;
72
+ caller: ToolCaller;
73
+ signal: AbortSignal;
74
+ interactive: boolean;
75
+ publish(data: D): void;
76
+ }
77
+ interface StructuredToolHandler<S extends Json, T extends ToolInput, A extends ToolInput, D extends Json> {
78
+ call(data: S, target: T, args: A, context: ResourceToolContext<NoInfer<D>>): Promise<CallResult<NoInfer<D>>>;
79
+ toModel?(data: D): ToolModelOutput;
80
+ }
81
+ interface FreeformToolHandler<S extends Json, D extends Json> {
82
+ call(data: S, input: string, context: ResourceToolContext<NoInfer<D>>): Promise<CallResult<NoInfer<D>>>;
83
+ toModel?(data: D): ToolModelOutput;
84
+ }
70
85
  export function implementTool<S extends Json, T extends ToolInput, A extends ToolInput, D extends Json>(
71
- contract: ImplementationContract<S, T, A, D>, definition: {
72
- call(data: S, target: T, args: A, context: {
73
- object: ObjectExecutor; caller: ToolCaller; signal: AbortSignal; interactive: boolean; publish(data: NoInfer<D>): void;
74
- }): Promise<CallResult<NoInfer<D>>>;
75
- toModel?(data: D): ToolModelOutput;
76
- },
86
+ contract: StructuredImplementationContract<S, T, A, D>, definition: StructuredToolHandler<S, T, A, D>,
87
+ ): ToolContribution;
88
+ export function implementTool<S extends Json, D extends Json>(
89
+ contract: FreeformImplementationContract<S, D>, definition: FreeformToolHandler<S, D>,
90
+ ): ToolContribution;
91
+ export function implementTool<S extends Json, T extends ToolInput, A extends ToolInput, D extends Json>(
92
+ contract: ImplementationContract<S, T, A, D>, definition: StructuredToolHandler<S, T, A, D> | FreeformToolHandler<S, D>,
77
93
  ): ToolContribution {
78
94
  const identity = reference(contract);
79
95
  return {
@@ -82,14 +98,25 @@ export function implementTool<S extends Json, T extends ToolInput, A extends Too
82
98
  const state = contract.resource.stateSchema.safeParse(resource.data);
83
99
  if (!state.success) return { kind: "failed", implementation: identity,
84
100
  error: { code: "invalid_resource", message: "The resource state does not match its backend contract." } };
85
- const parsedTarget = contract.targetSchema.safeParse(target, { reportInput: true });
86
- const parsedArgs = contract.tool.argsSchema.safeParse(args, { reportInput: true });
87
- if (!parsedTarget.success || !parsedArgs.success) return { kind: "rejected", implementation: identity,
88
- error: { code: "invalid_arguments", message: [
89
- `Invalid arguments for ${contract.resource.kind}/${contract.tool.name}.`,
90
- ...(!parsedTarget.success ? [resourceValidationMessage(parsedTarget.error, "target", contract.tool.argsSchema)] : []),
91
- ...(!parsedArgs.success ? [resourceValidationMessage(parsedArgs.error, "args", contract.targetSchema)] : []),
92
- ].join("\n") } };
101
+ let invoke: (context: ResourceToolContext<D>) => Promise<CallResult<D>>;
102
+ if (contract.tool.kind === "freeform") {
103
+ if (target !== null || typeof args !== "string") return { kind: "rejected", implementation: identity,
104
+ error: { code: "invalid_arguments", message: "This resource tool requires freeform text." } };
105
+ const handler = definition as FreeformToolHandler<S, D>;
106
+ invoke = context => handler.call(state.data, args, context);
107
+ } else {
108
+ const targetSchema = contract.targetSchema!;
109
+ const parsedTarget = targetSchema.safeParse(target, { reportInput: true });
110
+ const parsedArgs = contract.tool.argsSchema.safeParse(args, { reportInput: true });
111
+ if (!parsedTarget.success || !parsedArgs.success) return { kind: "rejected", implementation: identity,
112
+ error: { code: "invalid_arguments", message: [
113
+ `Invalid arguments for ${contract.resource.kind}/${contract.tool.name}.`,
114
+ ...(!parsedTarget.success ? [resourceValidationMessage(parsedTarget.error, "target", contract.tool.argsSchema)] : []),
115
+ ...(!parsedArgs.success ? [resourceValidationMessage(parsedArgs.error, "args", targetSchema)] : []),
116
+ ].join("\n") } };
117
+ const handler = definition as StructuredToolHandler<S, T, A, D>;
118
+ invoke = context => handler.call(state.data, parsedTarget.data, parsedArgs.data, context);
119
+ }
93
120
  return {
94
121
  effect: contract.effect, execution: contract.execution, implementation: identity,
95
122
  // Model projections consume decoded values.
@@ -106,7 +133,7 @@ export function implementTool<S extends Json, T extends ToolInput, A extends Too
106
133
  return encoded;
107
134
  };
108
135
  try {
109
- const result = await definition.call(state.data, parsedTarget.data, parsedArgs.data, { object, caller, signal, interactive,
136
+ const result = await invoke({ object, caller, signal, interactive,
110
137
  publish(data) { if (active) publish?.(snapshot(data)); } });
111
138
  if (result.kind === "succeeded" || result.kind === "partial") {
112
139
  if (result.data === undefined) throw new PluginApiError("invalid_argument", "The tool did not provide final data.");
@@ -1,4 +1,4 @@
1
- import { defineTool, type ToolContract, type ToolInput } from "./module-contract.ts";
1
+ import { defineTool, type StructuredToolContract, type FreeformToolContract, type ToolInput } from "./module-contract.ts";
2
2
  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";
@@ -23,20 +23,31 @@ export interface TopLevelToolContext<D extends Json = Json> {
23
23
  recordUsage(subject: UsageSubject): void;
24
24
  }
25
25
  /** Top-level tools declare their definition and implementation together, independently of resource support relationships. */
26
- export interface TopLevelTool<A extends ToolInput = ToolInput, D extends Json = Json> extends ToolContract<A> {
26
+ interface TopLevelExecution<D extends Json> {
27
27
  /** Encodes D for progress/history and decodes it for views and model projection. */
28
28
  readonly resultSchema: z.ZodType<D>;
29
29
  readonly effect: "read" | "write";
30
30
  /** Sequential operations share submission order; parallel operations can overlap either lane. */
31
31
  readonly execution: "parallel" | "sequential";
32
- execute(args: A, context: TopLevelToolContext<D>): Promise<CallResult<D>>;
33
32
  toModel?(data: D): ToolModelOutput;
34
33
  }
35
- export function defineTopLevelTool<A extends ToolInput, D extends Json>(definition: TopLevelTool<A, D>): TopLevelTool {
34
+ export interface StructuredTopLevelTool<A extends ToolInput, D extends Json> extends StructuredToolContract<A>, TopLevelExecution<D> {
35
+ execute(args: A, context: TopLevelToolContext<D>): Promise<CallResult<D>>;
36
+ }
37
+ export interface FreeformTopLevelTool<D extends Json> extends FreeformToolContract, TopLevelExecution<D> {
38
+ execute(input: string, context: TopLevelToolContext<D>): Promise<CallResult<D>>;
39
+ }
40
+ export type TopLevelTool<A extends ToolInput = ToolInput, D extends Json = Json> = StructuredTopLevelTool<A, D> | FreeformTopLevelTool<D>;
41
+ export function defineTopLevelTool<A extends ToolInput, D extends Json>(definition: StructuredTopLevelTool<A, D>): StructuredTopLevelTool<ToolInput, Json>;
42
+ export function defineTopLevelTool<D extends Json>(definition: FreeformTopLevelTool<D>): FreeformTopLevelTool<Json>;
43
+ export function defineTopLevelTool(definition: TopLevelTool): TopLevelTool {
36
44
  if (!definition.resultSchema.description?.trim()) throw new Error(`Missing result schema description: ${definition.id}`);
37
- const tool = defineTool(definition);
38
- return { ...definition, ...tool,
39
- execute: (args, context) => definition.execute(args as A, context as TopLevelToolContext<D>),
40
- ...(definition.toModel ? { toModel: (data: Json) => definition.toModel!(data as D) } : {}),
41
- } as TopLevelTool;
45
+ if (definition.kind === "freeform") return { ...definition, ...defineTool(definition),
46
+ execute: (input: string, context: TopLevelToolContext) => definition.execute(input, context),
47
+ ...(definition.toModel ? { toModel: data => definition.toModel!(data) } : {}),
48
+ };
49
+ return { ...definition, ...defineTool(definition),
50
+ execute: (args, context) => definition.execute(args, context),
51
+ ...(definition.toModel ? { toModel: data => definition.toModel!(data) } : {}),
52
+ };
42
53
  }
@@ -1,33 +0,0 @@
1
- # Adapt a small plugin
2
-
3
- The SDK's counter package in `examples/counter` is a complete plugin, not a specification for every plugin's structure. Its maintained source shows concrete assembly. Use it to understand ownership and then change the design to fit the capability you need.
4
-
5
- ## Follow one change through the system
6
-
7
- The counter separates a shared declaration, backend work, and a card that presents the result. Backend and frontend import the same contracts; sharing a name or copying a schema would not create the same runtime identity.
8
-
9
- An increment updates the current value and records the change together. That is a deliberate product choice: current data supports use now, while the record explains what happened. The counter does not promise that browsing history restores its value. A different resource may need a different relationship between current state and history.
10
-
11
- The card initiates work without becoming its durable owner. This separation matters when a view closes, remounts, or fails while the resource remains present. UI pending state belongs to the interaction; committed results belong to the backend.
12
-
13
- The model-facing read operation exposes an existing capability rather than inventing a second source of truth. Its registration does not itself grant access to the counter. Treat visibility, authorization, and presentation as separate choices.
14
-
15
- ## Adapt ownership before adding features
16
-
17
- Choose a distinct plugin identity for a new package. Keep shared contracts independent of executable implementations, but group a capability's code so its state transitions remain understandable together.
18
-
19
- Decide whether each new piece of state is a current value, a historical fact, a preference, or temporary interaction state. Decide who ends any new asynchronous work. A connection shared by all counters would belong to the plugin; a process meaningful only for one counter would belong to that resource.
20
-
21
- A Home entry can start a session around the counter without introducing an Agent or a first message. Keep that independence when adapting the example unless conversation is part of the new plugin's domain.
22
-
23
- ## Build the package you will load
24
-
25
- The counter's package manifest keeps source entries under `asterism.build`; the build writes the loaded artifact into `dist`. Its build script invokes `asterism-plugin-build`. Install dependencies, typecheck, and build explicitly; add the package directory to Asterism and restart. Rebuild and restart after source changes rather than expecting the application to compile them.
26
-
27
- The counter intentionally exposes its contracts as `asterism-example-counter/contracts` in both realms. Its internal relative imports and public entry share one build graph per realm. Consumers need the provider enabled and declare that package as a peer dependency; installing a declaration package alone is not enough.
28
-
29
- ## Check the adapted design
30
-
31
- Use a compatible application and public SDK for development. Type checking checks contract agreement; loading the package and exercising it checks the integration.
32
-
33
- Trace one change from the initiating interface to saved state and history. Then check invalid input, visible failure, reopening saved objects, and cleanup. These checks should test promises your resource makes, not merely confirm that the copied example still has the same controls.
@@ -1,37 +0,0 @@
1
- # Organize a plugin
2
-
3
- A plugin is a unit of installation, identity, settings, and lifetime. Internal modules group capabilities that share that ownership; they need not become separate public abstractions.
4
-
5
- ## Separate responsibilities, keep capabilities cohesive
6
-
7
- Shared contracts describe transferable data and operations. Backend implementations own work and persistence. Frontend views present state and collect input. Keep shared declarations independent of libraries that belong only to one implementation environment.
8
-
9
- A view reaches backend behavior through typed communication rather than importing its implementation. Within that boundary, keep a capability's declarations, behavior, and presentation understandable together. Compose capabilities through explicit dependencies instead of exposing internal layers merely because they exist.
10
-
11
- ## Choose a domain boundary
12
-
13
- Use a domain's public extension points when adding to its existing behavior. A plugin with its own resource can instead own that resource's behavior and presentation. Extending an Agent and implementing a new paradigm are different commitments.
14
-
15
- A paradigm may define how work starts, how requests are assembled, and how execution is presented. Sessions and host capabilities do not require a conversation card. Choose the composition that fits the workflow rather than treating the bundled paradigm as the host's mandatory object model.
16
-
17
- ## Publish only what consumers need
18
-
19
- A public package is useful when multiple plugins need the same declarations or service boundary. Publish capabilities with an intentional meaning for consumers, not a mirror of the provider's internal organization.
20
-
21
- For a small extension, public exports from the implementation package may be sufficient. A separate API library can make sense when the shared domain has its own authoring surface and should remain independent of implementation imports. Neither choice makes the library a second plugin or gives consumers access to private state.
22
-
23
- Import original public values. Shared contracts carry runtime identity as well as types, so a local copy is not a substitute for the provider's declaration. Development package versions support authoring; the enabled provider supplies the running implementation.
24
-
25
- ## Separate source inputs from delivered code
26
-
27
- The package root owns identity, release metadata, translations, and manual declarations. `asterism.build` holds source inputs, and the build writes loading metadata into `dist`. Keeping those roles separate lets a source checkout and a published package use the same loader without requiring the application to transform TypeScript.
28
-
29
- Owned public entries are listed as exact import specifiers per realm and resolve through the package's own `exports`. Compile each realm's implementation and owned public entries together so the provider uses the same declarations as its consumers. A separate authoring API package can supply types without becoming a separately activated plugin.
30
-
31
- Package dependency declarations carry the boundary. Peer dependencies name what the application or other plugins supply; imports of them stay external and resolve to the running instances. Ordinary dependencies are private: the backend loads them from the installed package with their own files and native binaries, and the browser build bundles them. Backend and renderer graphs are separate: identity is shared within a realm, not memory shared between processes or with the browser. Root documentation and translation metadata remain with the package rather than moving into executable loading metadata.
32
-
33
- ## Keep service ownership with the provider
34
-
35
- A provider owns shared initialization and cleanup. Consumers depend on the capability they use and release their own subscriptions or requests without ending services shared by others.
36
-
37
- Keep that ownership explicit when composing modules. A dependency should explain why a capability is needed, not require consumers to understand the provider's file layout or startup internals.