integration.runtime
Runtime integration with secret management
@lssm-tech/integration.runtimebun add @lssm-tech/integration.runtimeManifest declarations describe the current workspace; they do not verify registry publication or runtime execution.
Package guide
Website: https://contractspec.io
Runtime integration with secret management.
Declaration generation uses tsconfig.build.json to omit test sources from published artifacts. Development typechecking and bun test retain the cross-package governed-workspace integration tests.
What It Provides
- Layer: integration.
- Consumers:
providers-impls, bundles, apps that need secrets or channel routing. - Related ContractSpec packages include
@lssm-tech/lib.contracts-integrations,@lssm-tech/lib.contracts-spec,@lssm-tech/lib.logger,@lssm-tech/tool.bun,@lssm-tech/tool.typescript.
Installation
npm install @lssm-tech/integration.runtime
or
bun add @lssm-tech/integration.runtime
Usage
Import the root entrypoint from @lssm-tech/integration.runtime, or choose a documented subpath when you only need one part of the package surface.
The channel runtime keeps policy evaluation deterministic and auditable:
- Signature-invalid events are rejected before processing.
MessagingPolicyEnginecan be replaced by a contract-backed policy evaluator throughChannelRuntimeService.ChannelApprovalServiceexposes a generic approval queue for CLI, API, web, or custom operator surfaces via the shared channel store.ControlPlaneSkillRegistryServiceverifies, installs, lists, and disables signed skill artifacts against an allowlisted trust policy.- Compiled plans now carry deterministic plan and step IDs, DAG dependency metadata, typed step I/O schema refs, actor audit context, and approval timeout fallback state.
- Capability grants are intended to be bound by the hosting application, for example through
CHANNEL_RUNTIME_DEFAULT_CAPABILITY_GRANTS, rather than trusted from inbound event payload metadata. - Hosting applications should also bind a server-side actor via
actorResolverso runtime approvals and execution are attributed to the authenticated service, operator, or agent principal rather than raw inbound channel claims. - Telemetry now carries
traceId,sessionId, andworkflowIdwhen callers provide them in inbound metadata. - Trace services now persist stage-level trace events so operators can inspect the full intent -> plan -> policy -> action -> outcome chain.
- Tracked approval migrations preserve historical ledger IDs through
006, add reviewer-runtime issuer/nonce/RLS support in006a, and require explicit public-metadata authority provisioning before materialization or enrollment; reusable schema source contains no operator identity or implicit admin enrollment. - Historical reviewer-grant migration statements remain internal implementation files consumed by the existing migration composition; export generation does not expose a separate
reviewer-grant-decision-migrationpackage subpath.
Notion delta binding
NotionDeltaSync accepts the owning NotionDeltaProvider adapter port with queryDatabase and search methods. Existing project-management Notion providers remain assignable; no provider SDK or reverse dependency is required by the runtime. Complete provider objects remain the change payloads. Cursor paging, timestamp filtering, storage keys and checkpoint defaults are preserved. Provider/storage failures propagate, and the host retains provider authority.
Run the credential-free paging/payload/checkpoint fixtures with bun --no-env-file test src/delta/notion.test.ts from this package. The explicit tsgo --project tsconfig.notion-delta-compat.json gate checks actual concrete provider assignability and rejects malformed payloads; it is separate from production declaration emission.
Enterprise agent platform
Use @lssm-tech/integration.runtime/agent-platform to compose an exact, digest-bound deployment plan from portable capabilities and provider profiles. Built-in candidate profiles cover Vercel and Railway as deployment platforms, Supabase as a managed data/auth/realtime/queue/scheduler service, and Docker as an isolation and packaging substrate. Consumers can replace or combine them without changing the agent, collaboration, improvement, or maintenance domain contracts.
The same subpath exposes:
- an authenticated collaboration gateway with durable replay and best-effort realtime signalling;
- fail-closed production qualification against the exact plan, profile, environment, required suites, loss acceptance, and enterprise controls; and
- stable profile and plan digests for evidence, audit, and release promotion.
Every composition also requires five provider-independent baseline gates: governance/security, supply-chain security, observability export, load/resilience, and clean-consumer release. Provider-specific suites extend these gates; they cannot replace them. The complete suite set is stored in the digest-bound plan, and qualification recomputes it from pinned profiles before execution.
Built-in profiles are intentionally candidate. A provider marketing claim or local unit test never promotes a plan; the target environment must produce a passing qualification report.
The Postgres execution-lane store implements the optional team transaction boundary with a short row-locking transaction and monotonic revision CAS. Independent replicas cannot both lease or finalize the same team state, and stale full-state writes fail closed. The managed CompanyOS schema keeps FORCE RLS and adds the revision column through forward migration 0060. Lost commit acknowledgements raise an explicit unknown-outcome error so callers must reconcile durable state before retrying.
The queue and workflow execution-lane team backends forward the existing bounded worker delegation unchanged, together with its workOrderId and deadlineAt. Their payload retains the legacy roleProfile alias and the existing run, worker and write-scope fields. It does not forward the whole launch object, descriptors, provider handles or unrelated parent context. Worker handlers must preserve and enforce those delegated bounds; receiving a payload is not a grant or production activation. The adapters retain their run/worker-to-job or workflow correlation for stop, pause and resume. Their in-memory handle maps do not establish durable exactly-once execution.
Provider OAuth handlers and credential custody
The ./oauth subpaths (github, github-app, notion, slack, teams) call the provider token endpoints and return raw credentials. They keep no state: storage, refresh and revocation belong to the host.
- Persist every returned token only through a
SecretProviderthat encrypts at rest, such asGcpSecretManagerProvideror the AES-GCM Postgres provider in@lssm-tech/integration.communication-os-persistence. Database rows keep the secret reference only. Never put a token in a plaintext column, a configuration object, a URL, a log line, a telemetry attribute or an error message, and never log or serialize a whole exchange result. SlackOAuth2Handler.exchangeCodeposts the code form-encoded tooauth.v2.access, the only body Slack reads for OAuth methods. It returns the bot token (accessToken,xoxb-) and, when user scopes were requested, the installing user's token inauthedUser.accessToken(xoxp-). A user-scope-only install has noaccessToken;exchangeCodeForBotTokenrejects such an install withmissing_bot_token, and an exchange without any token rejects withmissing_access_token. The user token acts as that person with every granted user scope, so it is a second credential: store it as theuserTokenfield of themessaging.slacksecret payload next tobotToken, and discard theauthedUsertokens when the host has no user-scoped feature.incomingWebhook.urlis also a credential, because anyone holding it can post to the channel.- Slack OAuth v2 bot token rotation is available through
refreshToken. Persist the rotated access and refresh tokens together through encryptedSecretProvidercustody and retain the returned expiry. Themessaging.slacksecret contract declares optionalbotRefreshToken,userRefreshToken,botExpiresAt, anduserExpiresAt. The central delegated-connection broker serializes refresh and revocation using a database row lock. Other hosts must adopt this lifecycle before enabling rotation; merely installing the handler does not activate it. - On disconnect, call
revokeTokenfor the bot token and for any stored user token. It throwsSlackOAuthErrorwhen Slack refuses, so a failed revocation is never reported as success. GitHubAppHandleraccepts the PKCS#1 key GitHub downloads (BEGIN RSA PRIVATE KEY) as well as PKCS#8, with real line breaks or with literal\nescapes as in a one-line environment variable. Load it from aSecretProvider. An unreadable key rejects with a fixedGitHubAppErrormessage, with no key material and no underlying cause, before any request to GitHub.SlackOAuthError,GitHubOAuthErrorandGitHubAppErrorcarry only the provider's error code or message. They never include client secrets, authorization codes, tokens, app JWTs or private keys;test/oauth/credential-redaction.test.tslocks this and checks that the handlers write nothing to the console.
Operation outbox (D-244 F6)
@lssm-tech/integration.runtime/operation-outbox provides the PostgreSQL transactional outbox and idempotency store behind the kernel's EventOutboxPort and IdempotencyPort. It also provides an ordered at-least-once relay (FOR UPDATE SKIP LOCKED leases, backoff, dead letters) and durable consumer receipts that deduplicate by event id. See src/operation-outbox/README.md for operator notes. The schema is the placeholder migration migrations/9xxx_outbox_operation_events.sql.
Architecture
src/channelis part of the package's public or composition surface.src/agent-platformcomposes provider profiles, authenticated multiplayer transport, and production qualification.src/health.tsis part of the package's public or composition surface.src/index.tsis the root public barrel and package entrypoint.src/runtime.health.test.tsis part of the package's public or composition surface.src/runtime.tsis part of the package's public or composition surface.src/secretsis part of the package's public or composition surface.src/transportis part of the package's public or composition surface.
Public Entry Points
- Export
.resolves through./src/index.ts. - Export
./agent-platformresolves through./src/agent-platform/index.ts. - Export
./agent-platform/baseline-suitesresolves through./src/agent-platform/baseline-suites.ts. - Export
./channelresolves through./src/channel/index.ts. - Export
./channel/approvalresolves through./src/channel/approval.ts. - Export
./channel/authorizationresolves through./src/channel/authorization.ts. - Export
./channel/base-typesresolves through./src/channel/base-types.ts. - Export
./channel/dispatcherresolves through./src/channel/dispatcher.ts. - Export
./channel/githubresolves through./src/channel/github.ts. - Export
./channel/memory-storeresolves through./src/channel/memory-store.ts. - Export
./channel/plan-typesresolves through./src/channel/plan-types.ts. - Export
./channel/plan-utilsresolves through./src/channel/plan-utils.ts. - Export
./channel/plannerresolves through./src/channel/planner.ts. - Export
./channel/planner-typesresolves through./src/channel/planner-types.ts. - Export
./channel/policyresolves through./src/channel/policy.ts. - Export
./channel/postgres-queriesresolves through./src/channel/postgres-queries.ts. - Export
./channel/postgres-schemaresolves through./src/channel/postgres-schema.ts. - Export
./channel/postgres-storeresolves through./src/channel/postgres-store.ts. - Export
./channel/replay-fixturesresolves through./src/channel/replay-fixtures.ts. - Export
./channel/serviceresolves through./src/channel/service.ts. - Export
./channel/slackresolves through./src/channel/slack.ts. - Export
./channel/storeresolves through./src/channel/store.ts. - Export
./channel/telegramresolves through./src/channel/telegram.ts. - Export
./channel/telemetryresolves through./src/channel/telemetry.ts. - Export
./channel/traceresolves through./src/channel/trace.ts. - Export
./channel/typesresolves through./src/channel/types.ts. - Export
./channel/whatsapp-metaresolves through./src/channel/whatsapp-meta.ts. - Export
./channel/whatsapp-twilioresolves through./src/channel/whatsapp-twilio.ts. - Export
./healthresolves through./src/health.ts. - Export
./runtimeresolves through./src/runtime.ts. - Export
./secretsresolves through./src/secrets/index.ts. - Export
./secrets/env-secret-providerresolves through./src/secrets/env-secret-provider.ts. - Export
./secrets/gcp-secret-managerresolves through./src/secrets/gcp-secret-manager.ts. - Export
./secrets/managerresolves through./src/secrets/manager.ts. - Export
./secrets/providerresolves through./src/secrets/provider.ts. - Export
./transportresolves through./src/transport/index.ts. - Export
./transport/auth-resolverresolves through./src/transport/auth-resolver.ts. - Export
./transport/transport-factoryresolves through./src/transport/transport-factory.ts. - Export
./transport/version-negotiatorresolves through./src/transport/version-negotiator.ts. - The package publishes 130 total export subpaths; keep docs aligned with
package.json.
Local Commands
bun run dev— contractspec-bun-build devbun run build— contractspec-bun-build buildbun run test— bun test --pass-with-no-testsbun run lint— bun lint:fixbun run lint:check— biome check .bun run lint:fix— biome check --write --unsafe --only=nursery/useSortedClasses . && biome check --write .bun run typecheck— tsgo --noEmitbun run publish:pkg— bun publish --tolerate-republish --ignore-scripts --verbosebun run publish:pkg:canary— bun publish:pkg --tag canarybun run clean— rimraf dist .turbobun run build:bundle— contractspec-bun-build transpilebun run build:types— contractspec-bun-build typesbun run prebuild— contractspec-bun-build prebuild
Recent Updates
- Replace eslint+prettier by biomejs to optimize speed.
- Resolve lint, build, and type errors across nine packages.
- Add Composio universal fallback, fix provider-ranking types, and expand package exports.
- Add first-class transport, auth, versioning, and BYOK support across all integrations.
- Add monorepo-aware environment resolution helpers that materialize framework aliases and redact secret values in reports.
- Upgrade dependencies.
- Stabilize lint gate and runtime contract typing.
- Add provider-adaptable enterprise agent-platform composition and fail-closed live qualification for Vercel, Railway, Supabase, Docker, and custom profiles.
Notes
- Secret providers must implement the
providerinterface; never read secrets directly. - Environment resolution reports must stay redacted; secret and sensitive values are never serialized into examples, reports, telemetry, or errors.
- Channel stores (memory, postgres) are swappable; do not couple to a specific backend.
- Never import from apps or bundles.
Internal Builder filesystem integration now stages replacements and explicit new files, checks all preimage hashes before mutation, rejects symlinks/hardlinks and duplicate paths, and restores replacements on caught failures. It requires an exclusively owned checkout. Creation requires create: true with preimageHash absent and never overwrites. The exported workspace adapter still requires production qualification: durable crash recovery, Git worktree lifecycle and artifact retention remain to be implemented.
Internal Git checkout support clones only an exact commit from a host-owned local repository, avoids object hardlinks, removes the source remote and discards ambient Git credentials/config. Hook and fsmonitor execution are disabled. The returned checkout is distinct from dirty source files and owns its cleanup directory. This is a trusted-host checkout primitive, not a sandbox for hostile repositories or concurrent agents; durable lease/recovery and full patch-port integration remain.
The internal Git patch workspace composes exact-commit checkout and staged edits behind BuilderPatchWorkspacePort. It rejects dirty/stale workspaces, creates a candidate commit, and persists a patch, Git bundle and digest receipt before checkout disposal. Changes are conservatively classified unknown for review. Its additive /builder export enables host composition; durable restart reconciliation and full authority/provider/check integration remain required. Artifact directories are host-owned and must be kept outside provider-writable execution roots.
Artifact and checkout roots must be disjoint after realpath resolution. The adapter reserves each artifact directory exclusively before mutation and flushes the bundle plus receipt directory before returning a candidate. Dirty workspaces are rejected before edits and never receive a success receipt. Restart recovery is still not qualified; these checks do not imply crash-consistent completion.
The internal workspace journal writes immutable created/applying/disposed markers in the host-owned artifact directory. Creation is recorded before its deterministic checkout allocation; applying is recorded before file effects. Read-only restart inspection distinguishes prepared, effect_unknown, candidate_unverified and disposed states. It never executes a stored path or infers success from a partial receipt. This enables reconciliation, not automatic resumption or cleanup; artifact digest verification and process-exclusion proofs remain required.
Read-only candidate verification compares patch and Git-bundle bytes with the host receipt after checkout disposal. It uses bounded streaming reads, rejects symlink/hardlink artifacts and detects changed files. Receipt scope must match the creation journal. Integrity verification is not code review, Git semantic validation, execution authority or release approval.
The governed-workspace integration test runs the existing governed patch service against real Git checkouts and retained artifacts, enforcing pre-mutation then post-diff authority before checks. Provider/signature/store behavior is a test fixture; this is not live provider or durable authority qualification.
The integration proof also passes through workspace-ai's file-proposal bridge, using a real checkout snapshot and rejecting provider path metadata as authority. The agent response remains deterministic test data; no external model run is implied.
Internal reconciliation can dispose prepared or integrity-verified candidate checkouts only inside a host coordinator callback that excludes execution for the whole operation. Unknown effects are retained for review. Paths are derived from the configured checkout root and validated ID, never used directly from journal content. The runtime coordinator must supply real exclusion; test callbacks are not production process-fencing evidence.
A prepared marker alone cannot authorize deletion of a non-empty checkout: reconciliation retains those contents for review. Candidate cleanup is exercised against a real Git patch and bundle using only its persisted journal and artifacts, without the original adapter map. Host executor exclusion is still required.
The Git patch adapter now excludes overlapping apply and disposal calls for each workspace within one adapter instance. Disposal cannot remove an actively written checkout; the lock releases only after the operation settles. Failed apply remains non-replayable. This is local lifecycle exclusion, not cross-process claim fencing.
The canonical /builder barrel exports createBuilderGitPatchWorkspace and verifyBuilderPatchArtifact. These are additive compatibility surfaces for trusted host composition; exports do not qualify hostile-code isolation or grant authority.
Vercel hosted-preview observation
The Builder barrel exposes createVercelPreviewDeploymentReader, a read-only implementation of the existing Vercel discovery driver for one exact deployment, and createVercelBuilderPreviewHost, which composes persisted release bindings, provider metadata and a fresh health request. Team/project/deployment mismatches, unsafe URLs, failed health and binding revocation fail closed. Provider responses are byte-bounded and reduced to public deployment fields; health requests never receive API credentials. The Builder runtime separately validates the canonical deployment receipt before persisting ready.
Authentication supports scoped SecretProvider references or a distinct host-authenticated transport. The September 8 pilot read was live-qualified using Vercel CLI authentication; this does not qualify long-lived SecretProvider credentials, provisioning, a canonical release receipt, or the entire Vercel provider lifecycle. The host requires authorized persisted bindings; it does not create deployment authority or manufacture missing source/artifact evidence.
API shape reference: https://vercel.com/docs/rest-api/reference/endpoints/deployments/get-a-deployment
Preview discovery consumes the shared library-owned provider port directly. There is no runtime-to-Vercel-integration dependency; the Vercel adapter and this read-only host specialize one shared contract rather than importing sibling integrations.
Railway hosted-preview observation
createRailwayPreviewDeploymentReader implements the shared library discovery port for one exact project/environment/service/deployment tuple. Its fixed GraphQL query requests identity, status, static URL and active deployment IDs, never deployment messages, metadata, variables, or inferred source revisions. Project-token and bearer-token authentication are explicit SecretProvider modes; a host-authenticated transport remains a separate qualification mode.
createRailwayBuilderPreviewHost requires canonical release binding and fresh health. A shared service URL qualifies only when the expected deployment is the sole active deployment, checked before and after the health request. Health reads carry no provider credentials. Binding revocation, routing change, GraphQL errors, missing source/artifact receipt evidence, unsafe URLs and cancellation fail closed. Readers and host observations are bounded to twenty seconds. No provisioning or mutation is implemented by this observer.
Official endpoint/authentication reference: https://docs.railway.com/integrations/api
Retained candidate artifacts can be read through BuilderRetainedPatchArtifactReadPort. The local createBuilderRetainedPatchArtifactReader binds a protected project artifact root and checks the exact work order, base/head revisions and patch hash. It verifies both retained patch and bundle bytes after checkout disposal, rejects ambiguous matches and fails explicitly when its bounded inventory is exceeded. Cancellation returns no artifact. This is read-only artifact evidence, not member authorization, deployment authority or a hosted preview.
Durable local Builder authoring
openLocalBuilderAuthoring(absolutePrivateDirectory) lazily opens file-backed PGlite with the existing Builder PostgreSQL schema and PostgresBuilderStore. The directory must be private and cannot be a symlink. One exclusive owner lock prevents concurrent opens; confirmed close releases the lock. An interrupted process leaves the lock for operator reconciliation rather than guessing that another owner is dead. No in-memory fallback or new domain tables are introduced.
Always await close before reopening. This storage adapter does not authenticate users or authorize execution; local API startup still needs current AuthOS sessions and scoped Connect authority. PGlite is loaded only when opening the local store, not when importing the shared Builder entry point.
Delegated platform connections
./connections exposes createPlatformConnectionService and the provider/store ports; ./connections/types is the type-only port entry. Login accounts are not API grants. The host supplies a reviewed provider capability catalog, exact HTTPS callback origin, authenticated identity/application/organization binding, durable single-use state storage, and an encrypted SecretProvider. Request input cannot select provider endpoints, token references, or broader scopes. Provider-specific PKCE support is explicit; providers without PKCE still require the session-bound single-use state.
Every read checks persisted grant ownership and the requested capability, and provider readers retain resource and account bindings. The store locks the grant while refreshing, reading, or revoking to prevent cross-replica credential races. Disconnect always removes local custody and cuts off subsequent reads. If the provider refuses revocation or has no scoped revocation API, the response truthfully reports providerRevoked: false; a provider permissions-management URL is included when the adapter supplies one. This does not prove upstream revocation or production acceptance.
./connections/secret-provider extracts the existing PostgreSQL AES-GCM vault behind configurable safe schema/column mappings. CommunicationOS retains its historical reference hashing and authenticated-data prefix; the identity host uses its own tables, reference namespace, and dedicated master key. Schema creation and key lifecycle remain host-owned.
Relationships
Arrows point from a package to its direct dependency. Counts are derived from captured workspace manifests.
18 declarations
@google-cloud/secret-manager^7.1.0
@lssm-tech/lib.agent-collaborationworkspace:^
Read the package manual ↗@lssm-tech/lib.contracts-integrationsworkspace:^
Read the package manual ↗@lssm-tech/lib.contracts-runtime-coreworkspace:^
Read the package manual ↗@lssm-tech/lib.contracts-runtime-kernelworkspace:^
Read the package manual ↗@lssm-tech/lib.agent-protocol-specworkspace:^
Read the package manual ↗
Declared capabilities
Runtime integration with secret management
Scripts
publish:pkgbun publish --tolerate-republish --ignore-scripts --verbosepublish:pkg:canarybun publish:pkg --tag canarybuildcontractspec-bun-build buildbuild:bundlecontractspec-bun-build transpilebuild:typescontractspec-bun-build typesdevcontractspec-bun-build devcleanrimraf dist .turbolintbun lint:fixlint:fixnode ../../../scripts/biome.cjs check --write --unsafe --only=nursery/useSortedClasses . && node ../../../scripts/biome.cjs check --write .lint:checknode ../../../scripts/biome.cjs check .testbun test --pass-with-no-testsprebuildcontractspec-bun-build prebuildtypechecktsgo --noEmit