@sequenceholdings/managed-functions
v0.5.17
Published
Managed Function context and opt-in cache runtime
Readme
@sequenceholdings/managed-functions
Saved process forms and discussion (prepared 0.5.5)
Saved business content is a separate opt-in from run metadata. Requires SDK
0.5.5+, CLI 0.9.5+ and Atlas advertising processes_content_read. Publish the
coordinated package chain and deploy Atlas before activating consumers.
service_account: process-reader
capabilities:
processes:
read: [request-review]
content:
forms: [request-review]
comments: [request-review]Content lists are distinct subsets of processes.read. The combined IDs,
including repetitions in content lists, fit within 8192 bytes. Declarations
grant no access. Every call checks the live invocation, active function version,
current declarations and enabled attached account. The account needs process/run
Viewer plus the resource's existing form or discussion read authority. Process
Viewer alone cannot disclose content; discussion access does not admit forms.
Metadata-only declarations retain their existing behavior.
const platform = createFunctionPlatformClient({ request, baseUrl });
const forms = await platform.activity.forms.get({ process, runId });
let cursor: string | undefined;
do {
const page = await platform.activity.comments.listPage({ process, runId, cursor });
await consumeComments(page.comments);
cursor = page.nextCursor ?? undefined;
} while (cursor !== undefined);Forms return saved human-step panels with step/node/parent/branch identities,
field keys and labels, values, and a submission or initial source. Loop and
parallel instances remain separate. Initial values use the node's explicit
initialValuesFromMetadata key, restricted to declared fields. Submissions
preserve saved business keys after schema drift. Responses exclude drafts,
prefill lookups, action controls, raw outputs and execution context. Histories
over 200 steps or responses over 4 MiB fail explicitly without truncation.
Comments include saved/derived discussion entries with identity, text, author subject/display name, timestamp and step/node identity. Pages contain at most 50 entries. Cursors are opaque and bound to the run/process. Continue until null, including through an empty page. Denied/unavailable sources are errors, never successful empty results. Separate reads are live observations, not a transactionally frozen snapshot. Applications own capture consistency, business filters, classification, caching and publication. Audit events record identities and operation names without business content.
Unified invocation client (prepared 0.5.1)
Create one client inside each invocation. The bootstrap snapshots only delivered platform credential headers; it never derives authority from a user payload or forwards the incoming bearer. Each domain initializes on its first call, so a directory-only invocation works without process or execution credentials. Unavailable domains fail closed with their existing typed errors before sending. Do not cache this client across invocations.
import { createFunctionPlatformClient } from "@sequenceholdings/managed-functions";
const platform = createFunctionPlatformClient({ request, baseUrl: platformOrigin });
const page = await platform.directory.listGroupMembers({ tenant, groupId, limit: 50 });
const run = await platform.lattice.runs.get({ process, runId });
const runs = await platform.lattice.runs.listPage({ process, limit: 50 });
// These require a delivered Lattice execution credential with matching bindings.
const execution = await platform.lattice.execution.getContext();
const completion = await platform.lattice.execution.getHumanCompletion({ nodeId: "reminder" });| Namespace | Authority and behavior |
| --- | --- |
| directory.resolve/listGroupMembers | Attached service account's dedicated directory credential; exact lookups and live roster pages |
| lattice.runs.get/listPage | Dedicated process-read credential; manifest-declared processes and current Viewer grants |
| lattice.completedNodes.get | Same process-read credential; exact completed run/process/node selection |
| lattice.getCompletedAgentReference | Both process-read and separate agent-read credentials; bounded recovery reference |
| lattice.execution.getContext/getRunCreatorAccess/getHumanCompletion/getHumanCompletions/getParallelSnapshot | Dedicated execution credential; verified invocation, execution and causal-receipt bindings |
| invocation.getInvocationContext/getCallerCapabilities | Dedicated invocation-identity credential; actual caller and attached account remain separate |
Directory and process reads use the shared platform contracts, clients and bounded transport. Specialized execution/human-proof and invocation-identity verification remain primitive adapters. Each request sends only its own credential; the completed-agent reference is the explicit two-credential exception. Local envelope and expiry checks never replace Atlas signature, active-invocation and live-grant checks. No operator administration or Lattice run-start capability is implied. Preserve empty pages with a non-null cursor and continue until null. Process pages reject mismatched selectors, duplicate runs, repeated/oversized cursors and excess rows; run summaries exclude authored state, outputs, metadata and error details.
The same bootstrap covers the existing runtime domains:
const files = platform.storage.service.workspace(workspaceId);
const members = await platform.directory.caller.resolveMembers({ groupId, subs });
const response = await platform.agents.getCompletedRun({ agent, runId });
const source = await platform.workflows.captureCompletedRun({ workflow, runId });Caller/service Storage are explicit as platform.storage.caller and .service.
Agent source/conversation verification lives in platform.agents.evidence;
workflow verification in platform.workflows.evidence; monitoring publish/get/
catalog in .monitoring; bounded actual-human Abrigo reads in .abrigo.read.
All legacy factories remain compatibility adapters over shared domain contracts,
selection/receipt validation and the same bounded HTTP engine. Credentials,
receiver binding prechecks and runtime provenance bootstrap remain primitive-owned.
ORM remains a separate primitive. Continue using generated operation clients and
@sequenceholdings/managed-functions/orm for caller/service ORM execution; this
bootstrap does not expose a data executor.
For separately provisioned OAuth process dispatch, use the Platform server
createServiceAccountTokenProvider and createServicePlatformClient bootstrap.
It never uses an invocation credential as process-start authority. Provider
Slack calls and application-owned business policies remain application-owned.
Existing createFunctionServiceDirectoryClient,
createFunctionServiceProcessesClient, createFunctionLatticeClient and
createFunctionInvocationClient remain supported with the same error identities.
This release is prepared and unpublished. Consumers pinned to older releases must
keep their current factories until the coordinated Platform/Storage/primitive releases are
published; do not update an app's source ahead of its resolvable lockfile.
Group-member directory lookup (internal rollout)
Functions can resolve selected members of existing Atlas groups to active, canonical user identities. This is an opt-in read capability, not a staff registry, permission grant, arbitrary directory search, or authentication API.
capabilities:
directory:
groups: ["<existing-group-id>"]import { createFunctionDirectoryClient } from '@sequenceholdings/managed-functions'
const directory = createFunctionDirectoryClient({
baseUrl: process.env.ATLAS_ORIGIN!,
request: req,
})
const { members } = await directory.resolveMembers({
groupId,
subs: [selectedCanonicalSubject],
})Use userIds instead of subs to resolve row IDs selected from the existing
group picker; never submit both. Each call accepts 1–50 selectors. Missing,
disabled, tombstoned, wrong-tenant, or nonmember selections are omitted. Exact
subject lookup does not accept an email alias. For a save, require the selected
subject to appear exactly in the response; a failed request is not an empty
successful lookup. Historical display labels may retain inactive identities,
but cannot validate a new assignment.
Atlas supplies a dedicated five-minute x-sequence-directory-token only for
declared groups on direct human invocations. System runners and service accounts
are not supported. Each read rechecks current function invocation access,
active version, declared group scope, active caller, caller group visibility,
and active target identities inside the function's tenant. No service identity
widens the caller's directory visibility. The function still enforces its own
application action permissions. Validation is point-in-time, not atomic with
an application's later transaction.
Directory and process-read clients share the SDK's invocation transport and
{ request, baseUrl, fetchImpl? } options. Both accept Fetch Headers or Node
request headers (case-insensitively), reject duplicate credentials, check expiry
before each read, and validate responses. FunctionDirectoryReadError exposes
status and code, like FunctionProcessReadError; failures are never an empty
member list. Directory replies must contain only distinct requested identities.
Sharing transport does not share authority: process reads retain service-account
credentials, while directory reads retain their separate human-caller credential.
The internal SDK bridge is POST /api/managed-functions/directory/members;
ordinary Auth0 bearers, storage tokens and ORM tokens do not authenticate it.
Results are not cached; successful reads emit an audit event. The client never
follows redirects or forwards an unrelated credential. Allow the Atlas origin
in the function's existing egress policy. Reviewed Atlas/CLI and SDK releases
are required before consumers opt in (SDK 0.4.1+, CLI 0.5.2+, and Atlas
advertising directory_members). Preflight rejects absent/disabled support
and incompatible tooling before upload; older deployments do not supply the
header. This addition does not activate or redeploy any consumer. The existing
package root remains Preview/blocked on publication; the raw HTTP route is
internal, not a new public API contract.
Tenant deployments reuse ATLAS_ARTIFACT_STUDIO_SIGNING_KEY, already provided
by the OpCo secrets catalog for Managed Functions. Delegation uses a separate
HMAC domain, audience, environment, function version and invocation binding.
There are no new secrets, migrations, groups or grants. Missing signing
configuration fails closed, including local development.
@sequenceholdings/managed-functions is the TypeScript SDK for Managed
Functions. It provides caller-scoped ORM access, explicit service-account ORM
access, and opt-in caching. The
/orm import loads only the dependency-free ORM execution client, without
initializing cache, storage, authentication or tracing libraries.
Managed Functions is a workflow-agnostic platform primitive. The runtime owns generic invocation, isolation, secrets, egress, caching, and observability; deployed functions own business logic. Primitive code must not identify a function consumer or branch on a function ID.
Immutable function releases
With CLI 0.5.5, SDK 0.4.2, and a platform deployment advertising the
immutable_release capability, opt in before a new function's first deployment:
function:
id: lending-capture-release-20261013
title: Lending capture release
immutable_release: trueThe first successful activation records a permanent platform flag. That function identity cannot subsequently deploy, promote, roll back, change its runtime configuration, or redeploy for rotated secret versions. Removing the manifest field cannot undo the flag. Create a new function ID for the next release, and retain old identities while workflows still reference them. A mutable function that already activated cannot be converted into an immutable release.
An exact retry of an already successful deployment returns its stored result
without replacing the runtime. Failed initial deployments remain retryable until
activation succeeds. Omission or false retains existing mutable behavior.
ORM as the invoking user
Default SQL (introduced in SDK 0.4.0)
With the matching Atlas runtime, use the same caller-scoped executor without an operation manifest:
const orm = createFunctionOrmExecutor({ request, baseUrl: platformOrigin, namespace: 'lending' })
const result = await orm.sql({
sql: `SELECT l.id, c.name FROM lending.loans l
JOIN party.customers c ON c.id = l."customerId"`,
})The invocation still needs its existing declared data bindings covering every
read object, including policy dependencies. SQL does not grant extra access.
Namespace access, row policies, foreign exports and optional consumer contracts
remain enforced. Results contain columns, array-valued rows, and truncated;
numeric/bigint SQL results are always exact strings. Read-only SELECT queries
are bounded to 1,000 rows / 8 MiB. Source versions are not proof of publication
or server rollout; the registered-operation workflow below remains supported.
Registered operations
Available in SDK 0.2.0 and later. Install the SDK in the function package;
the separate ORM authoring/compiler package is not needed in the deployed
function. From SDK 0.5.0, call operations by name: the platform resolves the
name against the namespace's active version on every call, so the function
keeps working when a schema change rehashes every operation, and it needs no
copy of operations.manifest.json. A namespace re-apply that keeps the
operation's name and variables needs no function redeploy.
import type { Request, Response } from '@google-cloud/functions-framework'
import { createFunctionOrmExecutor, FunctionOrmError } from '@sequenceholdings/managed-functions/orm'
// Nonsecret configuration: use your deployment's URL, never request input.
const platformOrigin = 'https://your-environment.example.com'
export async function handler(request: Request, response: Response) {
try {
// Create inside every invocation; never keep this executor in module state.
const orm = createFunctionOrmExecutor({
request,
baseUrl: platformOrigin,
namespace: 'directory',
})
const profile = await orm.execute('GetMyProfile', {})
response.json(profile)
} catch (error) {
if (error instanceof FunctionOrmError) {
response.status(403).json({ error: error.code })
return
}
// Do not expose arbitrary exceptions or upstream response bodies.
response.status(502).json({ error: 'PROFILE_UNAVAILABLE' })
}
}The manifest declares the data scope. Acting on behalf of the caller (this
example) needs no service account. To also act as the function itself
(createFunctionServiceOrmExecutor, system-runner invocations), name a
service_account you hold the actor role on. With a service_account named, the account acts in every declared namespace,
unless you mark specific namespaces with service: true (which requires an
account): then only those. The account's token and namespace floor cover only
those service-mode namespaces.
A deploy that needs an account and names none is refused with how to create or
pick one.
Replace these illustrative names with your namespace, relations and mutation
names:
capabilities:
data:
directory:
tables: [my_profile]
operations: [UpdateMyProfile]
query: falseBinding a named account needs the deployer's permission to act as it. The human caller
needs function invocation access plus the namespace runtime grants and operation
capabilities. tables covers read relations, including linked selections and
policy dependencies; operations contains persisted mutation names. These
declarations restrict access; they do not grant the caller access. Apply matching
namespace operations before deploying consumers. Open the Managed Functions guide at /docs/managed-functions/overview on
your administrator-supplied platform URL for provisioning, grants and deployment.
createFunctionOrmExecutor({ request, baseUrl, namespace, manifest?, operationSelection?, fetchImpl? })
returns an isolated executor with execute(operationName, variables?). It sends
only an operation name (or hash) and variables, never document text.
operationSelection defaults to 'name'. A manifest is optional: functions
that already pass one keep working, and it is used only as a one-time fallback
when the platform predates name selectors. operationSelection: 'hash' pins the
exact generated contract from manifest instead, and fails once a schema
change retires that version. The optional fetchImpl is for
testing or an application-owned transport; it must honor redirect: 'error'.
It never retries requests, follows redirects, reads credentials from a request
body, substitutes a service token, or configures process-wide ORM state. Reuse
within one handler invocation is supported; discard it when the handler returns.
By default numeric and bigint values come back as JSON numbers, which
JavaScript rounds past 15-17 significant digits. Pass
jsonScalars: 'lossless-v1' to receive them as strings ("250000.00"); the
executor then refuses any successful result the platform does not acknowledge
in that form, with OrmOperationError code LOSSLESS_TRANSPORT_UNAVAILABLE.
Send numeric and bigint variables as decimal strings in either mode.
baseUrl must be an explicitly configured HTTPS origin, with no path, query,
fragment or embedded credentials. Loopback HTTP is accepted for a local platform.
There is no automatic environment URL: the helper never trusts a request header
or body to choose where it sends a delegated credential.
Gateway caller metadata
The invoke gateway supplies x-sequence-function-caller, a base64url JSON object
with kind (human or service), sub, email, functionSlug, bodyHash
(SHA-256 of the dispatched JSON body), and exp (Unix milliseconds). Email is
nullable. System runners and service accounts receive no human email; the person
who initiated a workflow is not silently treated as its acting user.
This metadata is gateway-owned and requires platform-only authenticated ingress (Cloud Run IAM or the authenticated local runtime). It is not a bearer token or signature. Do not accept it on a public handler, forward caller-supplied headers, or use the hash as authentication. Consumers must check function/body binding and expiry. Identity comes from the effective authenticated principal, including platform-authorized impersonation, rather than tool arguments. An external integration must still verify that this identity owns the vendor account it uses.
Caller identity and trust boundary
createFunctionCallerOrmExecutor takes the same options and acts as the actual
invoking human or platform service account. It requires the distinct
gateway-delivered caller credential, explicitly signed as caller mode. Agents
preserve their authenticated run account; a Lattice node with an explicit
run_as.service_account can use that account's namespace floor, capabilities
and row policies. A system/M2M run has no caller credential, and a recorded run
starter is never used as the actor. Missing or denied caller access never falls
back to the function's attached account. This helper requires a matching
platform runtime; older deployments fail closed with MISSING_CALLER_CONTEXT.
Caller service accounts are checked for current existence and disabled state
on every ORM operation. The delegated grant has its own invocation expiry; it
does not promise to track revocation of the API credential that started it.
The legacy createFunctionOrmExecutor helper supports direct human invocations through the platform gateway.
Scheduled/system-runner and service-account invocations fail closed. They do not
silently become an attached service account or a recorded human initiator.
createFunctionServiceOrmExecutor takes the same options and executes as the
function's attached service_account instead. Use it for invocations with no
human caller, such as a Lattice managed-function step, or where the function must
deliberately act beyond its caller. The account's grants, capabilities and row
policies apply, not the caller's, so enforce any per-user rule in the handler.
The person who started the invocation stays on the credential for audit.
No Function UUID, profile lookup, signing key, bearer token or claims decoder is
required in application code.
The platform must control ingress to the deployed handler. The helper consumes the request delivered by that gateway; it does not authenticate arbitrary HTTP requests or make a publicly reachable Functions Framework server safe. Its local metadata checks only reject an unsupported or expired invocation mode. The ORM server verifies the credential's signature and expiry, checks its declared scope, resolves the caller's current permissions, and enforces row policies on every operation. The helper exposes no decoded caller identity or capabilities for use as a separate authorization decision.
seq-studio function dev does not mint delegated user identity. A missing
context there is expected; validate pure handler logic with supplied test
executors and verify real caller permissions through a deployed invocation.
Do not copy real invocation headers into fixtures or logs.
Errors and recovery
FunctionOrmError.code is stable and safe to return without including the
exception's stack or request headers:
| Code | Recovery |
| --- | --- |
| INVALID_CONFIGURATION | Correct the trusted origin or fetch configuration. |
| MISSING_CALLER_CONTEXT | Declare the data binding. Caller mode: invoke through the platform as a signed-in user. Service mode: also declare service_account and invoke through the platform. |
| INVALID_CALLER_CONTEXT | Verify that the request came through the supported platform runtime. |
| UNSUPPORTED_CALLER | The invocation mode doesn't match the helper: use createFunctionOrmExecutor for a direct human invocation, and createFunctionServiceOrmExecutor for a system-runner (Lattice) invocation. |
| EXPIRED_CALLER_CONTEXT | Begin a new invocation and construct a new executor. |
Invalid manifests, unknown operations and ORM failures propagate OrmClientError
or OrmOperationError, also exported from /orm. An OrmOperationError exposes
status and code; handle those instead of returning its upstream message.
A denied write is still denied; the helper supplies no permission
fallback. A network error may follow a successful write: use application-level
idempotency and inspect persisted results before retrying.
Read process run status as the service account
The process-read client requires SDK 0.3.5, CLI 0.4.6, and an environment
advertising processes_read support. These release requirements are not proof
that a particular environment has been upgraded. Deployment preflight checks
the environment before uploading.
Declare the exact processes and the account that will read them:
service_account: document-runtime
capabilities:
processes:
read: [document-review, document-review-part]The declaration permits at most 128 distinct process IDs, with at most 8192 bytes across their names. It grants no process permissions. The attached account needs process Viewer access, including visibility of every run for paged reads. Process Invoker normally implies Viewer. Processes whose runs have narrower visibility are refused instead of returning an incomplete activity list that could be mistaken for proof that no run exists.
import { createFunctionServiceProcessesClient } from '@sequenceholdings/managed-functions'
// Construct inside the handler, using its platform-delivered request and a
// deployment-configured origin. Never choose the origin from user input.
const processes = createFunctionServiceProcessesClient({
request,
baseUrl: 'https://your-environment.example.com',
})
const run = await processes.getRun({ process: 'document-review', runId })
const page = await processes.listRunsPage({
process: 'document-review',
statuses: ['pending', 'running'],
entity: { type: 'document', ids: documentIds },
limit: 100,
})The SDK 0.4.4 / CLI 0.6.6 release candidates (awaiting publication) add
processes.getCompletedNode({ process, runId, nodeId }). It returns only
{ runId, processId, processVersion, nodeId, stepId, completedAt } after both
the run and its latest top-level step have committed successfully. The exact
node must have no outgoing edges in the run's immutable pinned bundle. The
existing invocation-bound process scope and current Process/Run Viewer grants
apply. Historical successful steps in running, cancelled or failed runs,
parallel child steps, and ambiguous serial positions are refused with
409 node_not_completed; workers can retry without sending their side effect.
The caller must separately check its expected process version and allowed
terminal node. No authored metadata, state or output is exposed. This method
requires the matching server deployment; the older processes_read capability
alone does not advertise support for this new operation.
With SDK 0.4.2 and both exact process and agent read declarations,
processes.getCompletedAgentReference({ process, runId, nodeId }) recovers only
{ stepId, attempt, agentId, agentRunId, threadId } for a unique completed
top-level agent step in a terminal process run. The parent may have failed,
timed out or been cancelled after that agent finished. Both live credentials
must belong to the same receiving invocation. Current Process, Run, Agent, Job
and Thread visibility, actual source ownership, frozen bundle pins and immutable
private execution source remain enforced. Active or ambiguous attempts are
refused. The reference grants no history access and does not assert successful
business completion; the application still checks its current generation,
release and lease before using it.
getRun returns only id, processId, status, entityType, entityId,
startedAt and completedAt. Dates are ISO strings; entity fields and
completedAt may be null. Runtime error text, metadata, state, output and steps
are not exposed. listRunsPage returns { runs, nextCursor }; follow every
non-null cursor with the same filters. Each page permits at most 500 runs and
500 entity IDs. entity.id and entity.ids are mutually exclusive.
archived: true selects archived runs instead of the default unarchived runs.
The client sends only an invocation-bound process credential and never follows redirects or retries. Atlas rechecks the function version, organization, declarations, current service-account attachment and permissions. Completed invocation records revoke access; bounded expiry covers delayed ledger writes. Create a new client for each invocation and never log or persist its headers. Local handler execution without platform delegation cannot use this client.
FunctionProcessReadError exposes status and code. Only
404 / run_not_found proves the expected run is absent after authorization.
Denied, expired, unavailable or malformed reads must not be treated as an
empty activity list. Reads do not atomically reserve work: applications must
still coordinate concurrent starts through a durable claim or idempotency
mechanism.
Resolve exact directory principals
This addition targets SDK 0.4.2, CLI 0.5.5, and a deployment advertising
directory_resolve. Confirm public package availability before installing the
new versions. Declare exact registered tenant scopes and attach an account:
service_account: app-directory-reader
capabilities:
directory:
resolve: [example_tenant]import { createFunctionServiceDirectoryClient } from '@sequenceholdings/managed-functions'
const directory = createFunctionServiceDirectoryClient({ request, baseUrl: platformOrigin })
const result = await directory.resolve({
tenant: 'example_tenant',
lookups: [{ type: 'email', value: '[email protected]' }],
})Use at most 50 distinct exact email or subject lookups per call and at most 16 tenant scopes in the declaration. The account needs the separate current Directory Reader grant for the requested tenant; directory administration is not a substitute. Each call rechecks the current function version, declaration, live invocation and account. The client uses only its invocation-scoped directory credential and refuses redirects.
resolved entries contain the original lookup plus sub, email and name;
unresolved contains the remaining lookups. Inactive, deleted, unlinked,
ambiguous and machine identities are unresolved. Unknown or inaccessible
tenants return the same authorization error. This is not a searchable user
listing. DirectoryPrincipalResolveError exposes status and code; a denied,
unavailable or malformed response must not become an empty resolution result.
Abrigo reads as the actual caller
The upcoming SDK 0.4.2 and CLI 0.5.5 support a deployment-advertised
abrigo_read capability. Declare only the needed finite read operations in
capabilities.abrigo.read and attach a service_account for the receiving
function. createFunctionCallerAbrigoClient({ request, baseUrl: platformOrigin })
provides read(query) for workflow, entity, entityGroupSummary,
loanRoles, relatedLoanRoles, workflowLoanMappings, workflowDocuments
and customerDocuments, plus the narrow reviewWorkflow,
reviewWorkflowDocuments and reviewWorkflowCustomerDocuments. A declaration
contains 1 to 11 distinct operations.
All reads use the invocation's actual human caller, live receiver lease and current function Invoker grant. The original eight operations also require that person's current Abrigo integration access. The three review operations use the native document-read gate, which also admits Underwriting Approvers. Service-account and system callers are refused; the attached function account never supplies replacement authority. The client has no arbitrary path, write, actor or credential parameter.
Review queries take only a workflowId, plus pagination for documents.
reviewWorkflow returns exactly { id, customerId }. The customer-document
operation derives the actual workflow customer at the broker; callers cannot
select a customerId. Each response retains authoritative workflowId and
customerId, including empty pages. Application code must compare each page's
customer with the initial workflow customer to detect changes while paging.
Both document review operations require an object envelope with an items
array bounded by the requested perPage; vendor pagination metadata is retained.
Collection queries require an explicit page from 1 to 100 and perPage from
1 to 500. Responses are bounded to 1 MiB and refuse malformed JSON, nonfinite
numbers and unsafe integers, so vendor IDs are never silently rounded.
Oversized or unavailable reads fail explicitly. Application code still
validates the response, pagination completeness and business membership.
FunctionAbrigoReadError retains a safe status/code without exposing vendor
error bodies.
Verified invocation identity
With SDK 0.4.2, CLI 0.5.5 and a host advertising invocation_identity, a
function with an attached service_account can opt into its verified receiver
and actual caller:
capabilities:
invocation:
identity: trueimport { createFunctionInvocationClient } from '@sequenceholdings/managed-functions'
const invocation = createFunctionInvocationClient({ request, baseUrl: platformOrigin })
const { receiver, caller } = await invocation.getInvocationContext()With capabilities.invocation: { identity: true, caller_capabilities: true },
invocation.getCallerCapabilities() returns { receiver, caller, capabilities }.
It accepts no subject or host selector. Atlas rechecks the exact live invocation,
receiver/version and current human caller, resolves that caller's function
access and custom-role grants, and intersects the result with the receiver's
current declared capability vocabulary (at most 256 pins). Service/system
callers are refused; this method cannot borrow a run starter or attached
service account's grants. Revoked or undeclared grants are absent, and failures
never supply capability authority. It does not accept unsigned claim headers.
This opt-in requires deployed invocation_caller_capabilities support, SDK
0.4.4 and CLI 0.6.6. Identity-only manifests retain their previous behavior.
Do not cache this current observation as a lasting grant or expose the
invocation credential to a browser.
The receiver identifies this function, version, invocation, organization and attached service account. The caller is the authenticated human, service account or system principal that invoked it; the attached account and a workflow's recorded starter are not substitutes for that caller. The request has no caller-supplied identity selector. Each read verifies the signed credential, current invocation, attached account and actual caller's current function Invoker access; expired or revoked context fails closed. Identity metadata grants no ORM access or domain authority: the handler must check its own expected release and business policy, and use a separately declared caller or service executor for data access.
Trusted Lattice execution and human actions
Functions invoked by a first-class Lattice node can opt into invocation-scoped
context reads. Attach a service_account and declare:
capabilities:
lattice:
context: trueThese reads also require the actual caller's current process Viewer and run Viewer access. Process Invoker already inherits those Viewer permissions; the attached account does not replace the actual caller's authorization.
import { createFunctionLatticeClient } from '@sequenceholdings/managed-functions'
const lattice = createFunctionLatticeClient({ request, baseUrl: 'https://your-environment.example.com' })
const execution = await lattice.getExecutionContext()
const review = await lattice.getHumanCompletion({ nodeId: 'review' })
const votes = await lattice.getHumanCompletions({ nodeId: 'vote', ancestorNodeId: 'review' })
const committee = await lattice.getParallelSnapshot({ nodeId: 'committee', ancestorNodeId: 'review' })execution.input is the persisted node mapper output. execution.ctxSnapshot
includes platform-owned run/entity identity and only data explicitly mapped as
input.context; omitted upstream, state and metadata remain hidden. A reviewed
node can explicitly map { context: ctx, input: domainInput } when it needs the
full context. Direct function invocations have no Lattice credential.
execution.receiver.invoker identifies the authenticated caller, including its
kind and authentication method. attachedServiceAccountSub identifies the
function's separate attached account. Neither is inferred from the run starter;
the SDK checks both against the invocation credential.
execution.run.startProvenance describes the verified authorization that
admitted this pinned run: its actor, start mode and basis, authorization time,
and scheduler admission when applicable. The platform verifies the persisted
stamp against the actual run pins and recorded starter; authored trigger reasons
or context metadata are never substitutes. Older runs may omit this field or
return null. A start stamp records the original admission decision, rather
than granting current permissions or identifying a later human action.
getRunCreatorAccess() returns current, invocation-bound evidence for the
retained signed run starter: { creator: { sub, tenant, platformOperator } | null,
observedAt, ...executionIdentity }. The platform resolves a current active human
and evaluates its shared operator policy; app-authored metadata and email domains
cannot establish this authority. Missing provenance, deleted/disabled identities,
or ambiguous aliases return creator: null; directory outages fail the request.
Operator evaluation retains the shared platform policy, including its FGA cache
and configured legacy-role fallback; this is not instantaneous role revocation. This is a current observation, not an impersonation credential or a
replacement for business authorization. It accepts no subject or run selector.
Human reads verify a platform-signed receipt against the actual completed step,
current receiving invocation, frozen graph and causal subprocess lineage. The
caller must still check the expected action, task, approval generation and
business authority. Run starters, advanced_by, email and assertedBy alone are
not approval evidence. Forked/copied history, timeouts, stale attempts and revoked
invocations fail closed; legacy completions without receipts require a fresh
human action. getHumanCompletions returns at most 64 selected causal receipts.
For parallel nodes declared with captureProvenance: true,
getParallelSnapshot returns the completed join's canonical proof and frozen
observedAt, its causal ancestor receipt, and at most 64 actual branches. Branch
IDs, indexes, items, step attempts, statuses and human receipt IDs are preserved.
An early join may include pending branches; later cancellation does not rewrite
that observation. The SDK preserves the server's proof and timestamp, while the
platform verifies the signed source rows. The handler still decides whether the
observed votes satisfy its business policy.
Opt-in cache
Opt-in caching inside a Managed Function. When the manifest declares a cache block, the platform passes a process-reused context as the HTTP handler's third argument. Existing two-argument handlers keep working.
cache:
enabled: true
tier: custom-pico
replicas: 0
default_ttl_seconds: 30Each function/environment gets a dedicated private Valkey instance. The baseline is one pico node with no replicas or persistence. Instances incur charges while idle. Only Sequence organization members can change an enabled cache to a nonbaseline tier or replica count; other authors can retain an already-approved configuration or return to baseline. Supported tiers: custom-pico, custom-micro, custom-mini; replicas: 0–5.
import type { ManagedFunctionContext } from '@sequenceholdings/managed-functions'
import type { Request, Response } from '@google-cloud/functions-framework'
export async function handler(req: Request, res: Response, context: ManagedFunctionContext) {
// Authenticate and authorize EVERY invocation before accessing shared cached data.
// Include tenant, permission scope, arguments, and authoritative data version
// in keys whenever they affect the result.
const result = await context.cache.getOrCompute('public-catalog:v1', { ttlSeconds: 30 }, async () => {
const response = await fetch('https://api.example.com/catalog')
if (!response.ok) throw new Error('Catalog unavailable')
return response.json()
})
res.json(result)
}Contract
All methods are asynchronous. Values are lossless JSON, at most 1 MiB; keys are nonempty strings, at most 512 UTF-8 bytes. TTL is an integer from 1 to 86,400 seconds. CacheOptions is { ttlSeconds?: number }, defaulting to the manifest TTL. Generic reads assert a type; they do not validate your schema.
| Method | Result |
| --- | --- |
| get<T>(key): Promise<T \| undefined> | Missing/expired → undefined; cached null is a hit. Does not extend TTL. |
| set(key, value, options?): Promise<void> | Atomic upsert with a new TTL. |
| setIfAbsent(key, value, options?): Promise<boolean> | Atomic insert+TTL; false leaves the existing value and TTL unchanged. |
| delete(key): Promise<boolean> | true if removed, otherwise false. |
| getOrCompute<T>(key, options, loader): Promise<T> | Hit or computed value; stores successful JSON results. |
Explicit CRUD throws CacheError with DISABLED, UNAVAILABLE, UNKNOWN_OUTCOME, INVALID_ARGUMENT, or INVALID_VALUE. A lost mutation acknowledgement has an unknown outcome and is never replayed automatically. getOrCompute bypasses disabled/unavailable caching and failed cache writes; loader errors and invalid inputs/results propagate. A cache failure never retries the loader. Coalescing is bounded and process-local: duplicate computation is possible. This is not an idempotency or exactly-once primitive.
Authors own authorization, read/write choices, and invalidation. A concurrent loader can repopulate a deleted key with old data; use authoritative versioned keys or bypass the cache when freshness is required. Every activation gets a fresh key namespace; old entries expire naturally.
Deliver app-owned monitoring observations
Monitoring delivery requires SDK 0.4.2, CLI 0.5.5, and a deployment
advertising monitoring_deliveries. Declare the exact producer namespaces:
service_account: app-effects
capabilities:
monitoring:
producers: [inbox, documents]Declarations grant no monitoring authority. The attached account needs the
producer namespace's runtime floor and pinned emit-monitoring capability.
Continuous Improvement must also register that exact namespace and authorize
publishing or catalog reads. Registrations default to inactive with both
operations disabled. Only a human with current Monitoring Admin authority can
review and change this consent; owning or creating a namespace cannot approve
its use of CI. Deployment never creates registrations or grants that consent.
The namespace and function must belong to the same registered tenant. Every
call rechecks the current manifest, active version, live invocation reservation,
account availability, and namespace claims. Bearer, ORM, Storage, and process
credentials are never accepted as monitoring credentials.
Invocation credentials bind the registration ID and epoch. Publish, receipt lookup, and catalog reads lock and recheck current consent on their transaction connection. Revocation blocks old credentials, including after re-enabling a producer. A new invocation can recover an older immutable receipt after renewed consent; the receipt retains its original accepted epoch and business payload hash.
import {
createFunctionServiceMonitoringClient,
monitoringPayloadHash,
} from '@sequenceholdings/managed-functions'
const monitoring = createFunctionServiceMonitoringClient({ request, baseUrl: platformOrigin })
const payloadHash = monitoringPayloadHash({ events, observation })
const receipt = await monitoring.publish({ producer: 'inbox', businessKey, payloadHash, events, observation })
// After an ambiguous response, look up the immutable key before retrying.
const recovered = await monitoring.get({ producer: 'inbox', businessKey })The app freezes accepted inputs, timestamps, event keys, and optional interpreted
CI annotations before computing the hash. Object keys are sorted, array order
is retained, and contract defaults are applied. idempotencyKey on each input
event identifies one claim within the delivery; Atlas derives a storage key
from the trusted tenant, namespace, business key, and that claim key. It cannot
overwrite another producer's or a legacy native event.
An identical retry returns the same receipt; changed content under the same
business key returns 409. Up to 100 events and 512 KiB per delivery are
accepted. A legitimate zero-event result still receives a hash-bound receipt.
get throws FunctionMonitoringError with status 404 if the key is absent.
Both publishing and lookup require producer authorization.
getBucketCatalog({ producer }) reads only the complete active taxonomy
metadata under the separate namespace read-monitoring-catalog capability.
Freeze that catalog with the analysis inputs. More than 2000 buckets or 512 KiB
returns an explicit size error; the client never treats a partial catalog as complete.
confirmed means the submitted CI events and supplied product observations
committed atomically. It does not mean later triage, clustering, or agent analysis
completed. The source app performs analysis and constructs neutral events;
intake never reads native Inbox data to interpret a completion or correction.
Local development
Run seq-studio function dev --dir . --port 8080 after installing dependencies. Enabled caching without a Valkey connection uses bounded process-local TTL/LRU storage (16 MiB encoded payloads, 10,000 entries); it is reset on restart and not shared across processes. The harness compiles TypeScript with the project's installed compiler. A deployed enabled cache without connection configuration fails startup; it never falls back silently.
For an explicit private Valkey development connection, set SEQUENCE_FUNCTION_CACHE_CONFIG to JSON containing cache plus connection: { host, port, serverIdentity, caCertificates, keyPrefix }. Use ADC with permission on that test instance and network connectivity to its PSC endpoint. serverIdentity must match the server certificate. Do not put passwords or tokens in configuration. The deployed runtime always obtains short-lived tokens from its attached service account.
Runtime bounds
One multiplexed TLS connection per process, at most 128 pending operations, 150 ms command and 1.5 s connection deadlines. Three failures open a five-second circuit breaker. New connections acquire a valid IAM token; live authenticated connections can outlast token expiry. TLS verifies the trusted certificate chain and expected DNS/IP identity. No offline queue, mutation replay, plaintext, or verification bypass.
Cloud Run emits aggregate managed_function.cache logs every 30 seconds of active use with operation/error counts and total/maximum operation latency. Keys, values, and credentials are never logged. Cache memory, evictions and hit rate appear beside function metrics; actual compute/cache spend, credits and billing freshness remain in Billing.
Functions without a cache manifest block retain their existing two-argument handler. An explicit cache: { enabled: false } supplies a disabled context.cache, allowing getOrCompute to run its loader without caching.
Completed agent responses
With SDK 0.4.2, CLI 0.5.5 and a deployment advertising agents_read, declare
exact agent IDs in capabilities.agents.read and attach a service_account.
Inside each invocation, call
createFunctionServiceAgentsClient({ request, baseUrl: platformOrigin }).getCompletedRun({ agent, runId }).
The account needs current agent Viewer access. The declaration grants no access
to another caller's conversations: both the run and private thread must belong
to the attached account, or be a verified completed upstream agent step in the
same immutable Lattice execution context.
The response contains persisted completed output, assistant text, citation resources and a neutral conversation projection for counts and tool-state metrics. It excludes reasoning, reasoning-derived compaction, arbitrary tool results and inputs, and private thread configuration. Reused conversations and experimental ORM history are denied. Verified same-step structured-output re-asks remain readable; messages changed after completion are refused. Results over 1,000 messages or 8 MiB fail explicitly; a partial response never substitutes for a full generated answer. No thread listing or arbitrary thread-ID read exists.
For protected application source records, declare the same exact IDs in
capabilities.agents.evidence on a deployment advertising agents_evidence_verify.
createFunctionServiceAgentsClient(...).captureCompletedRun({ agent, runId })
returns { response, responseHash, sourceReceipt } for a completed source owned
by the attached account. This neutral capture also requires the live read
credential; it cannot capture another user's source through upstream lineage.
The signed receipt identifies the actual service account and the invocation that
captured evidence, separately from the original agent-run creator. Human captures
identify the actual signed-in user instead. Neither kind grants read access.
createFunctionAgentEvidenceClient({ request, baseUrl: platformOrigin }).verifySourceEvidence({ agent, runId, response, responseHash, sourceReceipt })
verifies supplied historical bytes without fetching conversation history. Its
separate invocation credential rechecks the current function version, attached
account, exact evidence scopes, positive invocation lease and Agent Viewer floor.
The result separates the historical source from the current receiving invocation.
The application must also enforce its protected release, source and receiver
associations. Capture responses over 512 KiB and verification requests over
768 KiB fail before writing; neither operation truncates evidence.
For an explicitly captured user sidebar, call the same evidence client's
verifyConversationEvidence({ agent, threadId, response, responseHash, sourceReceipt }).
This separate source projection binds a durable settled conversation revision
and cutoff rather than inventing an agent run. It verifies only previously
authorized captured bytes; the function gains no arbitrary thread-read access.
Completed private workflow sources
The upcoming SDK 0.4.2 and CLI 0.5.5 add separate workflow capture and
evidence clients. Confirm publication and the deployment's workflows_read
and workflows_evidence_verify features before depending on them. Declare
exact workflow IDs in capabilities.workflows.read and
capabilities.workflows.evidence, and attach an approved service_account.
createFunctionServiceWorkflowsClient({ request, baseUrl: platformOrigin })
provides captureCompletedRun({ workflow, runId }). Capture requires both
declarations, the source-owning account's current Workflow Invoker and root
and child Job Viewer access, and the exact verified completed upstream
workflow execution. It returns { response, responseHash, sourceReceipt }
for the root's persisted merged JSON. The signed evidence retains failed or
skipped branch outcomes; capture does not imply every branch succeeded. It
does not read conversations or reuse an Agent response type.
createFunctionWorkflowEvidenceClient({ request, baseUrl: platformOrigin })
provides verifySourceEvidence({ workflow, runId, response, responseHash,
sourceReceipt }). Verification uses its separate evidence declaration and
current invocation credential. It verifies supplied historical bytes without
fetching output. The signed historical source, any genuine job-admission
reference, and the current receiver remain separate: the application must
bind them to its protected current task and intent. Historical evidence grants
no current source-read authority or application write authority.
Capture is bounded to 512 KiB, verification requests to 768 KiB, and opaque
source receipts to 16 KiB. Incomplete or changed source records are refused;
oversized results fail explicitly without truncation. Clients preserve typed
FunctionWorkflowReadError status/code failures rather than treating them as
empty results.
Runtime tracing
Newly deployed function entrypoints install request-scoped tracing automatically,
including two-argument handlers without caching. Ordinary global fetch calls to
the current platform propagate the invocation context; ORM and storage delegation
also retain the original initiator when a function explicitly acts as its service
account. Normal resource authorization still applies.
Global fetch calls to declared external hosts record hostname, method, status
and duration. Paths, queries, bodies, credentials and arbitrary errors are not
stored. Other networking transports and redirect hops are outside this capture.
External requests receive no platform attribution headers from this runtime.
Completed external and nonprimitive Atlas API spans are exported in small batches while the handler keeps working (50 ms batching delay, 500 ms per batch including one retry). The final batch starts fire-and-forget when the HTTP response ends (or the handler returns or throws); the response and errors never wait for export. Calls limited to instrumented primitive execution routes send no export. The runtime aborts unfinished exports at their deadline or on client disconnect. Callback-style handlers remain traced until their response ends.
Delivery remains best effort: a slow or unavailable collector, or CPU throttled
after the response, can leave spans unacknowledged. Each traced invocation that
captured egress logs one traces.function_egress.summary JSON line once its
export settles. Every captured span is acknowledged, rejected, abandoned,
or unacknowledged; dropped spans were never captured. Only known loss
(rejected, abandoned, or dropped) logs at warn; unacknowledged spans log
at info because the collector may have stored them after the response. A
refusal on the retry after an uncertain first attempt stays unacknowledged. The runtime
limits each invocation to 100 spans and 10 batches (20 POST attempts including
retries), preserving span IDs across a retry. Failures preserve the handler's
result. The platform allows its own collector hostname through managed egress,
without making collector availability a readiness dependency. Existing deployed
revisions need redeployment to pick up the entrypoint. Standalone functions dev
does not mint trusted invocation context.
Same-deployment Atlas API calls outside instrumented primitive execution routes are reported as Atlas API dependencies with registered route templates. Query strings, dynamic path values and request/response bodies are not persisted. Successful reads of a Lattice process or run link to the owning process; direct HTTP run starts already use server-recorded spans and preserve the request chain. Transport classification is shared with the platform host; function authors do not need to import or configure instrumentation.
Scoped service group rosters
createFunctionServiceDirectoryClient().listGroupMembers() reads bounded pages
of active members of explicitly declared groups. It requires Managed Functions
SDK 0.4.4, Studio CLI 0.6.6, and a host advertising directory_rosters.
service_account: notification-worker
capabilities:
directory:
resolve: [banksouth]
rosters: ["11111111-1111-4111-8111-111111111111"]const directory = createFunctionServiceDirectoryClient({ request, baseUrl })
let cursor: string | undefined
do {
const page = await directory.listGroupMembers({
tenant: 'banksouth', groupId, limit: 50, cursor,
})
await consume(page.members)
cursor = page.nextCursor ?? undefined
} while (cursor)The manifest permits at most 64 concrete group IDs, with at most 8192 bytes across their names so the signed invocation credential stays bounded. It does not grant access: the attached service account independently needs the tenant directory's Reader relation and the group's roster Reader relation. An explicit group Reader grant does not confer membership, group management, or access to resources shared with that group. Existing members and owners inherit roster Reader, so their existing access is preserved. New service accounts should receive Reader, not membership. Organization or application administration is not a runtime fallback. The actual attached account is checked on every page; the invoking human/system identity never supplies its grants. No user-mode directory API gains service mode.
Atlas intersects the signed invocation's groups with the current function
manifest, verifies the live function/version/account/invocation, and checks both
grants again before reading. Deleted groups and inactive, deleted, or foreign
tenant users are excluded. The caller cannot request inactive identities or
choose another principal. Results contain only id, sub, name, email, and
deactivated: false. Membership is read live, not as a transaction-wide snapshot.
Pagination scans membership positions, so a page may have zero members and a
non-null nextCursor; continue until the cursor is null. Cursors expire after an
hour and bind the tenant, group, function, immutable version and service account.
They cannot be moved to another read scope. Access can be revoked between pages.
Platform operators manage roster Reader grants separately from membership. Only verified human group owners or Sequence operators may grant/revoke them, and granting a service account additionally requires Actor on that account. Public and group-principal roster grants are not supported. The shared FGA model and Atlas host must both contain roster Reader support before granting it; older hosts still require membership. During host-first rollout, the new host checks existing Member access first and checks Reader only after a Member denial, so existing members remain usable while the model and client pins converge. Errors in authorization still fail closed. This is a host permission change, not a new SDK method or a reason to add a machine to a staff group.
Provisioning group roster access
Platform SDK 0.1.0, Managed Functions 0.5.1 and Studio CLI 0.8.2 prepare typed roster provisioning; these packages await separate publication. The host's existing group roster governance and Reader model must be available. An upgrade alone grants nothing.
seq-studio access grant group <group-id> --key roster-reader --principal-type user --principal-id 'service-account|<account-id>' -e <env>
seq-studio access revoke group <group-id> --key roster-reader --principal-type user --principal-id 'service-account|<account-id>' -e <env>The CLI uses createOperatorPlatformClient from @sequenceholdings/platform/server
with its current control-plane login. groups.rosterAccess.grant and revoke
send atomic deltas through the existing permission surface. They validate mutation
counts, then read the complete direct-grant receipt and confirm the exact target
and direct Reader state. They never replace other principals or remove membership.
A failed or concurrent confirmation is surfaced without replaying the mutation.
The shared transport owns origin validation, redirect refusal, deadlines, bounded responses and structured errors; the CLI supplies only its current session and host-scoped edge credentials. Atlas requires a verified human group owner or platform operator, plus service-account Actor standing for grants, and revalidates the target identity after writing. Revocation does not require Actor. An unavailable or unauthorized group fails closed. Directory Reader and the exact declared roster allowlist remain separate runtime gates.
createFunctionServiceDirectoryClient retains its signature and dedicated header,
but delegates to the shared directory client through an invocation transport.
The legacy administrative export accepts a typed operator transport. No invocation
credential becomes a governance credential and no SDK HTTP route becomes a direct
public contract. See the shared SDK architecture.
