{"modulePath":"github.com/epzero/basamento","version":"v0.0.0-20261123040955-ecee8c2d92a7","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package node\n\nPackage node implements the \\`model\\` node handler (ADR-0011).\n\nThe handler turns one model node into flow code: it validates the node's parameters against the model's schema, prices the invocation with model/catalog, reserves the estimate against the run's budget, starts the invocation with a client ref that is stable across every attempt, follows its events, waits for its result, ingests output files with provenance and settles the reservation. An ambiguous start is looked up before anything is sent again; when the provider cannot answer, the run waits at gate \"ambiguous\\_start\" (REQ-MODEL-004, REQ-MODEL-005, REQ-MODEL-006, REQ-MODEL-007, REQ-MODEL-008, REQ-MODEL-009, REQ-MODEL-010).\n\nThe package is the only part of model that imports package runtime: the handler's side effects are durable steps, while pricing, validation and the client ref stay deterministic flow code (ADR-0011, docs/architecture/ model-layer.md §4).\n\nA Handler is bound to one composition: the invoker, the catalog, the blob store and the run's budget. It is safe for concurrent runs. The budget is read from the run context (WithBudget) so a run never spends another run's account. Waiting (poll, webhook, socket, command) is the adapter's business: the node only follows events and waits for the result through model.Invoker.\n\n## Constants\n\n```go\nconst AmbiguousStartGate = \"ambiguous_start\"\n```\nAmbiguousStartGate is the gate family a run waits at when a start's outcome is unknown and the provider cannot resolve it by lookup (REQ-MODEL-005). A person resolves it with a payload naming the invocation, if there is one. The node waits at one instance per invocation, AmbiguousStartGate + \".\" + the client ref, so parallel map items never share a gate.\n\n```go\nconst DefaultStartAttempts = 3\n```\nDefaultStartAttempts bounds the start attempts of one logical invocation. It mirrors the model layer's default attempt budget (REQ-MODEL-043): a start that fails without reaching the provider is retried, but never forever.\n\n## Functions\n\n```go\nfunc ClientRef(salt []byte, visit, node string, input []byte) string\n```\nClientRef derives the stable client ref of one logical invocation from the run's salt, the run-scoped visit token, the node's path and the node's input (REQ-MODEL-004, docs/architecture/model-layer.md §4). It is a hash, never a literal concatenation, so the ref carries no tenant, model or input text.\n\nThe salt is what keeps two runs apart: both start their first invocation with the same visit token, so without it they would share one provider invocation. The visit token is what makes two visits of one node in a run distinct: a node reached again on a cycle, or another item of a map, gets its own token and therefore its own ref. A replayed run derives the same salt and the same token from the same position and recreates the same ref, which is what lets a runtime resume a start instead of repeating it.\n\n```go\nfunc ParamHash(params json.RawMessage) string\n```\nParamHash is the provenance hash of a call's parameters: the SHA-256 of their canonical JSON. An absent parameter object hashes as an empty object.\n\n```go\nfunc WithBudget(ctx context.Context, b Budget) context.Context\n```\nWithBudget returns a context carrying b as the run's budget. A later call replaces the earlier one; the parent context is unchanged.\n\n## Types\n\n```go\ntype Asset struct {\n\t// Ref points at the content-addressed bytes.\n\tRef model.AssetRef `json:\"ref\"`\n\t// Provenance is the metadata stored alongside the bytes.\n\tProvenance Provenance `json:\"provenance\"`\n\t// ProvenanceBlobKey is the content key of the stored provenance JSON.\n\tProvenanceBlobKey string `json:\"provenance_blob_key\"`\n}\n```\nAsset is one output file stored with the provenance that explains it (REQ-MODEL-008).\n\n```go\ntype Budget interface {\n\t// Reserve holds amount under key. It fails with core.CodeBudgetExceeded\n\t// when the run's remaining budget cannot cover amount (REQ-MODEL-007).\n\t// Reserving the same key again is a no-op that keeps the first amount.\n\tReserve(key string, amount int64) error\n\t// Settle closes key's reservation, charging actual milli-points and\n\t// releasing the rest. It is a no-op for a key with no open reservation;\n\t// the first settlement of a key wins.\n\tSettle(key string, actual int64) error\n\t// Remaining reports the milli-points left under the run's ceiling and\n\t// whether the account has one. A settlement may carry the account past\n\t// its ceiling when the actual charge exceeds the reservation; the\n\t// remaining is then negative, and the node fails the run closed.\n\tRemaining() (remaining int64, bounded bool)\n}\n```\nBudget is one run's spend account, in milli-points. The model node reserves a paid invocation's estimated cost before starting it and settles the reservation with the invocation's actual cost when it ends (REQ-MODEL-006).\n\nImplementations must be idempotent per key: the node may run its flow code again on replay and must not reserve or charge twice. The key is the invocation's client ref, so it names one logical invocation of one run.\n\n```go\nfunc BudgetFrom(ctx context.Context) (Budget, bool)\n```\nBudgetFrom returns the budget carried by ctx, and whether there is one. A run without a budget cannot start a priced invocation: every priced call reserves the estimate before it starts (REQ-MODEL-006), so the node fails one before it reaches the provider. Only a model with no price runs unmetered.\n\n```go\ntype Config struct {\n\t// Name is the node's id in the flow. The host fills it in; it is part of\n\t// the client ref and of every step name.\n\tName string\n\t// Model is the model id the catalog holds.\n\tModel string `json:\"model\"`\n\t// Op is the capability the call asks for.\n\tOp model.Capability `json:\"op\"`\n\t// InputTokens is the counted input tokens of the call, used by the price\n\t// estimate (REQ-MODEL-077). Zero when the model's formula does not price\n\t// tokens.\n\tInputTokens int64 `json:\"input_tokens,omitempty\"`\n\t// OutputLimit is the call's output token limit, used by the estimate.\n\tOutputLimit int64 `json:\"output_limit,omitempty\"`\n}\n```\nConfig is a model node's spec: which model it invokes and how its call is sized for the price estimate. The spec is the node's IR \\`spec\\` object:\n\n\t{\"model\": \"sim-video\", \"op\": \"video.generate\", \"output_limit\": 0}\n\n```go\nfunc ConfigFromSpec(name string, spec json.RawMessage) (Config, error)\n```\nConfigFromSpec decodes a model node's IR spec. name is the node's key in the flow, which the host passes separately because it is not part of the IR node object.\n\n```go\ntype Deps struct {\n\t// Invoker is the provider adapter the node starts and follows.\n\tInvoker model.Invoker\n\t// Catalog holds descriptors and prices. The node validates against the\n\t// descriptor's parameter schema and prices the call with it\n\t// (REQ-MODEL-067, REQ-MODEL-077).\n\tCatalog *catalog.Catalog\n\t// Steps registers the node's durable steps on first use.\n\tSteps StepRegistrar\n\t// Blobs stores output files ingested with provenance (REQ-MODEL-008).\n\t// It is required for a model that returns output files: a successful\n\t// invocation with outputs and no blob store fails the node instead of\n\t// dropping them.\n\tBlobs platform.Blob\n\t// Fetch downloads an output. Nil uses HTTPS for a URL (public addresses\n\t// only, no redirects) and the filesystem for a path.\n\tFetch Fetcher\n\t// OutputRoot is the directory a command-line provider writes output files\n\t// to. A result's Path is only read when it resolves under this root; an\n\t// empty root rejects every path output, so a network provider cannot make\n\t// the node read an arbitrary file. The root is set by the composition for\n\t// local providers, never by a provider's result.\n\tOutputRoot string\n\t// MaxStartAttempts bounds the start attempts of one invocation; zero\n\t// means DefaultStartAttempts.\n\tMaxStartAttempts int\n}\n```\nDeps is what a model node handler needs. Invoker and Catalog are required; the rest is optional.\n\n```go\ntype Fetcher func(ctx context.Context, out model.Output) ([]byte, string, error)\n```\nFetcher downloads one output. It returns the bytes and their content type.\n\n```go\ntype Handler struct {\n\t// contains filtered or unexported fields\n}\n```\nHandler is the model node handler. Create one per composition and share it across runs; the run's budget travels in each run's context (WithBudget).\n\n```go\nfunc New(d Deps) (*Handler, error)\n```\nNew returns a handler over deps.\n\n```go\nfunc (h *Handler) Handle(dc runtime.DurableContext, cfg Config, input json.RawMessage) (out Output, retErr error)\n```\nHandle runs one model node. It validates, prices, reserves, starts, follows the invocation, waits for its result, ingests outputs and settles the reservation, in that order (docs/architecture/model-layer.md §4).\n\nThe returned error is a platform error: invalid\\_argument, internal, budget\\_exceeded, unsupported, vendor\\_error, cancelled, ambiguous\\_start or the provider's own code. internal covers a priced call with no run budget. The reservation is settled on every path after it was taken. When the invocation started but its actual charge is unknown, the node fails closed and charges the reserved estimate rather than releasing it.\n\n```go\ntype Input struct {\n\tParams       json.RawMessage             `json:\"params,omitempty\"`\n\tMessages     json.RawMessage             `json:\"messages,omitempty\"`\n\tTools        json.RawMessage             `json:\"tools,omitempty\"`\n\tOutputSchema json.RawMessage             `json:\"output_schema,omitempty\"`\n\tText         map[string]string           `json:\"text,omitempty\"`\n\tAssets       map[string][]model.AssetRef `json:\"assets,omitempty\"`\n\tSeed         *int64                      `json:\"seed,omitempty\"`\n\tInputTokens  int64                       `json:\"input_tokens,omitempty\"`\n\tOutputLimit  int64                       `json:\"output_limit,omitempty\"`\n}\n```\nInput is a model node's input: the call's parameters and media, as the flow's inbound mapping produces them.\n\n```go\ntype Memory struct {\n\t// contains filtered or unexported fields\n}\n```\nMemory is an in-process Budget for tests and the embedded profile. It is safe for concurrent use and records every reservation so a caller can read back what was held and what was charged per key. A settled charge keeps counting against the limit: settlement frees the reservation, not the money.\n\n```go\nfunc NewMemory(limit int64) *Memory\n```\nNewMemory returns a budget that allows spending up to limit milli-points. A negative limit is unlimited.\n\n```go\nfunc (m *Memory) Charged(key string) int64\n```\nCharged reports what was charged under key, zero before settlement.\n\n```go\nfunc (m *Memory) ChargedTotal() int64\n```\nChargedTotal is the sum of every settlement.\n\n```go\nfunc (m *Memory) Held(key string) int64\n```\nHeld reports the amount currently held under key, zero when nothing is held.\n\n```go\nfunc (m *Memory) HeldTotal() int64\n```\nHeldTotal is the sum of every open reservation.\n\n```go\nfunc (m *Memory) Limit() int64\n```\nLimit is the budget's ceiling in milli-points; a negative limit is unlimited.\n\n```go\nfunc (m *Memory) Remaining() (int64, bool)\n```\nRemaining implements Budget.\n\n```go\nfunc (m *Memory) Reserve(key string, amount int64) error\n```\nReserve implements Budget.\n\n```go\nfunc (m *Memory) Reserved(key string) int64\n```\nReserved reports the amount that was reserved under key, settled or not.\n\n```go\nfunc (m *Memory) Settle(key string, actual int64) error\n```\nSettle implements Budget. The first settlement of a key wins, so a replayed flow does not charge twice.\n\n```go\nfunc (m *Memory) Settled(key string) bool\n```\nSettled reports whether key's reservation was closed.\n\n```go\ntype Output struct {\n\tState        model.State     `json:\"state\"`\n\tClientRef    string          `json:\"client_ref\"`\n\tMessage      json.RawMessage `json:\"message,omitempty\"`\n\tVectors      [][]float32     `json:\"vectors,omitempty\"`\n\tAssets       []Asset         `json:\"assets,omitempty\"`\n\tUsage        *model.Usage    `json:\"usage,omitempty\"`\n\tCostMpts     int64           `json:\"cost_mpts\"`\n\tReservedMpts int64           `json:\"reserved_mpts\"`\n}\n```\nOutput is what the node returns to the flow: the invocation's result and the cost that settled it.\n\n```go\ntype Provenance struct {\n\tModel      string `json:\"model\"`\n\tOp         string `json:\"op\"`\n\tParamsHash string `json:\"params_hash\"`\n\tSeed       *int64 `json:\"seed,omitempty\"`\n\tCostMpts   int64  `json:\"cost_mpts\"`\n\tMedia      string `json:\"media,omitempty\"`\n\tMime       string `json:\"mime,omitempty\"`\n}\n```\nProvenance is what a stored output records about its invocation: the model, the hash of the parameters, the seed and the settled cost.\n\n```go\ntype StartOutcome struct {\n\t// Handle identifies the invocation. It is set when the invocation is\n\t// running, whether the start was acknowledged or found by lookup.\n\tHandle model.Handle `json:\"handle\"`\n\t// Attempts is how many times Start was called.\n\tAttempts int `json:\"attempts\"`\n\t// Resolved reports that an ambiguous attempt was resolved by lookup.\n\tResolved bool `json:\"resolved,omitempty\"`\n\t// Ambiguous reports that the outcome of the start is unknown and the\n\t// provider cannot answer a lookup. The caller must open the\n\t// \"ambiguous_start\" gate instead of starting again (REQ-MODEL-005).\n\tAmbiguous bool `json:\"ambiguous,omitempty\"`\n}\n```\nStartOutcome is how a start ended.\n\n```go\ntype Starter struct {\n\t// Invoker is the provider adapter.\n\tInvoker model.Invoker\n\t// MaxAttempts bounds the attempts of one logical invocation; zero means\n\t// DefaultStartAttempts.\n\tMaxAttempts int\n}\n```\nStarter starts one logical invocation with a stable client ref. Every attempt it makes carries req.ClientRef (REQ-MODEL-004), and an attempt whose outcome is unknown is resolved by lookup before anything is sent again (REQ-MODEL-005).\n\n```go\nfunc (s Starter) Start(ctx context.Context, req model.Request) (StartOutcome, error)\n```\nStart calls Start until the provider accepts, the outcome is ambiguous, or the attempts are spent.\n\nA retryable start error that may have reached the provider (a timeout after sending) is resolved by Lookup before anything is sent again:\n\n  - lookup finds the invocation: the start is resolved, no second start.\n  - lookup answers \"nothing\" or cannot answer: the outcome is unknown — a forgotten ref cannot prove the start never landed — and the call returns Ambiguous; starting again would risk a second charge (REQ-MODEL-005).\n\nAny other retryable error means the provider rejected the start before accepting it, so the next attempt may use the same client ref.\n\nA non-retryable error ends the start at once: the provider refused it and there is nothing ambiguous about it.\n\n```go\ntype StepRegistrar interface {\n\tRegisterStep(name string, fn runtime.StepFunc, d runtime.StepDefaults) error\n}\n```\nStepRegistrar registers the handler's durable steps. runtime.Runtime satisfies it. The handler registers a step the first time a run needs it, because a step's name carries the invocation's client ref: two visits of one node in a run must not share one recorded result. A runtime with a static registry (the Temporal runtime) registers the same names from the flow definitions before its workers start.\n\n","path":"github.com/epzero/basamento/model/node","name":"node","synopsis":"Package node implements the `model` node handler (ADR-0011).","isRedistributable":true}
