@wildo-ai/saas-backend-lib 1.1.12 → 1.1.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/base-classes/models/manual-controllers.backend.definition.d.ts.map +1 -1
- package/dist/esm/base-classes/models/manual-controllers.backend.definition.js +2 -0
- package/dist/esm/base-classes/models/manual-controllers.backend.definition.js.map +1 -1
- package/dist/esm/base-classes/services/repositories/stored-field-omission.backend.d.ts +4 -0
- package/dist/esm/base-classes/services/repositories/stored-field-omission.backend.d.ts.map +1 -1
- package/dist/esm/base-classes/services/repositories/stored-field-omission.backend.js +20 -5
- package/dist/esm/base-classes/services/repositories/stored-field-omission.backend.js.map +1 -1
- package/dist/esm/base-classes/services/services/resource-operation-custom-implementation-registry.backend.service.d.ts +3 -0
- package/dist/esm/base-classes/services/services/resource-operation-custom-implementation-registry.backend.service.d.ts.map +1 -1
- package/dist/esm/base-classes/services/services/resource-operation-custom-implementation-registry.backend.service.js +10 -1
- package/dist/esm/base-classes/services/services/resource-operation-custom-implementation-registry.backend.service.js.map +1 -1
- package/dist/esm/base-classes/services/services/resource-operation-custom-implementation.factory.backend.d.ts +22 -0
- package/dist/esm/base-classes/services/services/resource-operation-custom-implementation.factory.backend.d.ts.map +1 -1
- package/dist/esm/base-classes/services/services/resource-operation-custom-implementation.factory.backend.js +25 -1
- package/dist/esm/base-classes/services/services/resource-operation-custom-implementation.factory.backend.js.map +1 -1
- package/dist/esm/base-classes/services/services/resource-operation-transaction-persistence.backend.utils.d.ts +38 -3
- package/dist/esm/base-classes/services/services/resource-operation-transaction-persistence.backend.utils.d.ts.map +1 -1
- package/dist/esm/base-classes/services/services/resource-operation-transaction-persistence.backend.utils.js +68 -5
- package/dist/esm/base-classes/services/services/resource-operation-transaction-persistence.backend.utils.js.map +1 -1
- package/dist/esm/base-classes/services/services/resource-status-transition.custom-impl.backend.service.d.ts +2 -2
- package/dist/esm/base-classes/services/services/resource-status-transition.custom-impl.backend.service.d.ts.map +1 -1
- package/dist/esm/base-classes/services/services/resource-status-transition.custom-impl.backend.service.js +6 -3
- package/dist/esm/base-classes/services/services/resource-status-transition.custom-impl.backend.service.js.map +1 -1
- package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.d.ts +83 -0
- package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.d.ts.map +1 -1
- package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.js +217 -14
- package/dist/esm/base-classes/services/services/services-registry-handler.backend.service.js.map +1 -1
- package/dist/esm/compliance/approval-seals/approval-seal-currency.backend.d.ts +32 -0
- package/dist/esm/compliance/approval-seals/approval-seal-currency.backend.d.ts.map +1 -0
- package/dist/esm/compliance/approval-seals/approval-seal-currency.backend.js +36 -0
- package/dist/esm/compliance/approval-seals/approval-seal-currency.backend.js.map +1 -0
- package/dist/esm/compliance/approval-seals/approval-seal-on-record.backend.d.ts +38 -0
- package/dist/esm/compliance/approval-seals/approval-seal-on-record.backend.d.ts.map +1 -0
- package/dist/esm/compliance/approval-seals/approval-seal-on-record.backend.js +83 -0
- package/dist/esm/compliance/approval-seals/approval-seal-on-record.backend.js.map +1 -0
- package/dist/esm/compliance/approval-seals/approval-seal-presentation-read.backend.d.ts +36 -0
- package/dist/esm/compliance/approval-seals/approval-seal-presentation-read.backend.d.ts.map +1 -0
- package/dist/esm/compliance/approval-seals/approval-seal-presentation-read.backend.js +51 -0
- package/dist/esm/compliance/approval-seals/approval-seal-presentation-read.backend.js.map +1 -0
- package/dist/esm/compliance/approval-seals/approval-seal-relay-store.backend.d.ts +46 -0
- package/dist/esm/compliance/approval-seals/approval-seal-relay-store.backend.d.ts.map +1 -1
- package/dist/esm/compliance/approval-seals/approval-seal-relay-store.backend.js +68 -0
- package/dist/esm/compliance/approval-seals/approval-seal-relay-store.backend.js.map +1 -1
- package/dist/esm/compliance/approval-seals/approval-seal-store.backend.d.ts +27 -0
- package/dist/esm/compliance/approval-seals/approval-seal-store.backend.d.ts.map +1 -1
- package/dist/esm/compliance/approval-seals/approval-seal-store.backend.js +42 -3
- package/dist/esm/compliance/approval-seals/approval-seal-store.backend.js.map +1 -1
- package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.contracts.d.ts +26 -1
- package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.contracts.d.ts.map +1 -1
- package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.contracts.js +10 -0
- package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.contracts.js.map +1 -1
- package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.controller.d.ts +10 -1
- package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.controller.d.ts.map +1 -1
- package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.controller.js +60 -28
- package/dist/esm/compliance/approval-seals/approval-seals-admin.backend.controller.js.map +1 -1
- package/dist/esm/compliance/approval-seals/approval-seals-on-record.backend.controller.d.ts +90 -0
- package/dist/esm/compliance/approval-seals/approval-seals-on-record.backend.controller.d.ts.map +1 -0
- package/dist/esm/compliance/approval-seals/approval-seals-on-record.backend.controller.js +373 -0
- package/dist/esm/compliance/approval-seals/approval-seals-on-record.backend.controller.js.map +1 -0
- package/dist/esm/compliance/approval-seals/decision-presentation.backend.d.ts +29 -2
- package/dist/esm/compliance/approval-seals/decision-presentation.backend.d.ts.map +1 -1
- package/dist/esm/compliance/approval-seals/decision-presentation.backend.js +40 -3
- package/dist/esm/compliance/approval-seals/decision-presentation.backend.js.map +1 -1
- package/dist/esm/compliance/electronic-signatures/pdf-signature-structure.backend.d.ts.map +1 -1
- package/dist/esm/compliance/electronic-signatures/pdf-signature-structure.backend.js +34 -6
- package/dist/esm/compliance/electronic-signatures/pdf-signature-structure.backend.js.map +1 -1
- package/dist/esm/compliance/electronic-signatures/signature-request-evidence-files.backend.d.ts +30 -6
- package/dist/esm/compliance/electronic-signatures/signature-request-evidence-files.backend.d.ts.map +1 -1
- package/dist/esm/compliance/electronic-signatures/signature-request-evidence-files.backend.js +67 -22
- package/dist/esm/compliance/electronic-signatures/signature-request-evidence-files.backend.js.map +1 -1
- package/dist/esm/compliance/electronic-signatures/signature-request-poll.batch.backend.service.d.ts.map +1 -1
- package/dist/esm/compliance/electronic-signatures/signature-request-poll.batch.backend.service.js +18 -1
- package/dist/esm/compliance/electronic-signatures/signature-request-poll.batch.backend.service.js.map +1 -1
- package/dist/esm/compliance/electronic-signatures/signature-requests.backend.service.d.ts +66 -1
- package/dist/esm/compliance/electronic-signatures/signature-requests.backend.service.d.ts.map +1 -1
- package/dist/esm/compliance/electronic-signatures/signature-requests.backend.service.js +161 -14
- package/dist/esm/compliance/electronic-signatures/signature-requests.backend.service.js.map +1 -1
- package/dist/esm/compliance/electronic-signatures/signed-document-validation.backend.d.ts +47 -0
- package/dist/esm/compliance/electronic-signatures/signed-document-validation.backend.d.ts.map +1 -1
- package/dist/esm/compliance/electronic-signatures/signed-document-validation.backend.js.map +1 -1
- package/dist/esm/external-providers/services/content-safety.backend.service.d.ts +27 -2
- package/dist/esm/external-providers/services/content-safety.backend.service.d.ts.map +1 -1
- package/dist/esm/external-providers/services/content-safety.backend.service.js +46 -1
- package/dist/esm/external-providers/services/content-safety.backend.service.js.map +1 -1
- package/dist/esm/external-providers/services/embeddings.backend.service.d.ts.map +1 -1
- package/dist/esm/external-providers/services/embeddings.backend.service.js +2 -0
- package/dist/esm/external-providers/services/embeddings.backend.service.js.map +1 -1
- package/dist/esm/external-providers/services/external-providers-registry.backend.service.d.ts +11 -0
- package/dist/esm/external-providers/services/external-providers-registry.backend.service.d.ts.map +1 -1
- package/dist/esm/external-providers/services/external-providers-registry.backend.service.js +23 -0
- package/dist/esm/external-providers/services/external-providers-registry.backend.service.js.map +1 -1
- package/dist/esm/external-providers/services/provider-service-account-token.backend.d.ts +19 -1
- package/dist/esm/external-providers/services/provider-service-account-token.backend.d.ts.map +1 -1
- package/dist/esm/external-providers/services/provider-service-account-token.backend.js +41 -1
- package/dist/esm/external-providers/services/provider-service-account-token.backend.js.map +1 -1
- package/dist/esm/files/utils/file-parent-read-context.backend.d.ts +27 -2
- package/dist/esm/files/utils/file-parent-read-context.backend.d.ts.map +1 -1
- package/dist/esm/files/utils/file-parent-read-context.backend.js +23 -4
- package/dist/esm/files/utils/file-parent-read-context.backend.js.map +1 -1
- package/dist/esm/flows-actors/content-guardrails/classifier-availability.backend.utils.d.ts +26 -0
- package/dist/esm/flows-actors/content-guardrails/classifier-availability.backend.utils.d.ts.map +1 -1
- package/dist/esm/flows-actors/content-guardrails/classifier-availability.backend.utils.js +100 -8
- package/dist/esm/flows-actors/content-guardrails/classifier-availability.backend.utils.js.map +1 -1
- package/dist/esm/flows-actors/content-guardrails/record-owner-policy.backend.d.ts +3 -1
- package/dist/esm/flows-actors/content-guardrails/record-owner-policy.backend.d.ts.map +1 -1
- package/dist/esm/flows-actors/content-guardrails/record-owner-policy.backend.js +8 -2
- package/dist/esm/flows-actors/content-guardrails/record-owner-policy.backend.js.map +1 -1
- package/dist/esm/flows-actors/models/function-tools.backend.definitions.d.ts +43 -0
- package/dist/esm/flows-actors/models/function-tools.backend.definitions.d.ts.map +1 -1
- package/dist/esm/flows-actors/models/function-tools.backend.definitions.js +37 -0
- package/dist/esm/flows-actors/models/function-tools.backend.definitions.js.map +1 -1
- package/dist/esm/flows-actors/services/agent-work-decisions.backend.service.d.ts +7 -0
- package/dist/esm/flows-actors/services/agent-work-decisions.backend.service.d.ts.map +1 -1
- package/dist/esm/flows-actors/services/agent-work-decisions.backend.service.js +8 -3
- package/dist/esm/flows-actors/services/agent-work-decisions.backend.service.js.map +1 -1
- package/dist/esm/flows-actors/services/agents.backend.service.d.ts +31 -6
- package/dist/esm/flows-actors/services/agents.backend.service.d.ts.map +1 -1
- package/dist/esm/flows-actors/services/agents.backend.service.js +78 -30
- package/dist/esm/flows-actors/services/agents.backend.service.js.map +1 -1
- package/dist/esm/flows-actors/services/autonomous-agent-turn.backend.service.d.ts.map +1 -1
- package/dist/esm/flows-actors/services/autonomous-agent-turn.backend.service.js +4 -0
- package/dist/esm/flows-actors/services/autonomous-agent-turn.backend.service.js.map +1 -1
- package/dist/esm/flows-actors/services/conversational-execution.backend.service.d.ts +28 -2
- package/dist/esm/flows-actors/services/conversational-execution.backend.service.d.ts.map +1 -1
- package/dist/esm/flows-actors/services/conversational-execution.backend.service.js +132 -22
- package/dist/esm/flows-actors/services/conversational-execution.backend.service.js.map +1 -1
- package/dist/esm/flows-actors/services/flow-actor-executions.custom-impl.backend.service.d.ts.map +1 -1
- package/dist/esm/flows-actors/services/flow-actor-executions.custom-impl.backend.service.js +12 -8
- package/dist/esm/flows-actors/services/flow-actor-executions.custom-impl.backend.service.js.map +1 -1
- package/dist/esm/flows-actors/services/flows-actors-registry.service.d.ts +5 -0
- package/dist/esm/flows-actors/services/flows-actors-registry.service.d.ts.map +1 -1
- package/dist/esm/flows-actors/services/flows-actors-registry.service.js +18 -2
- package/dist/esm/flows-actors/services/flows-actors-registry.service.js.map +1 -1
- package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.d.ts +33 -0
- package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.d.ts.map +1 -1
- package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.js +58 -0
- package/dist/esm/flows-actors/utils/acp-session-runner.backend.utils.js.map +1 -1
- package/dist/esm/inbound/services/inbound-delivery-dispatch.backend.service.d.ts +12 -1
- package/dist/esm/inbound/services/inbound-delivery-dispatch.backend.service.d.ts.map +1 -1
- package/dist/esm/inbound/services/inbound-delivery-dispatch.backend.service.js +23 -4
- package/dist/esm/inbound/services/inbound-delivery-dispatch.backend.service.js.map +1 -1
- package/dist/esm/inbound/services/inbound-delivery-receiver.backend.service.d.ts +12 -1
- package/dist/esm/inbound/services/inbound-delivery-receiver.backend.service.d.ts.map +1 -1
- package/dist/esm/inbound/services/inbound-delivery-receiver.backend.service.js +55 -17
- package/dist/esm/inbound/services/inbound-delivery-receiver.backend.service.js.map +1 -1
- package/dist/esm/inbound/services/inbound-delivery-store.backend.service.d.ts +22 -1
- package/dist/esm/inbound/services/inbound-delivery-store.backend.service.d.ts.map +1 -1
- package/dist/esm/inbound/services/inbound-delivery-store.backend.service.js +52 -9
- package/dist/esm/inbound/services/inbound-delivery-store.backend.service.js.map +1 -1
- package/dist/esm/inbound/services/inbound-delivery-stored-body.backend.service.d.ts +79 -0
- package/dist/esm/inbound/services/inbound-delivery-stored-body.backend.service.d.ts.map +1 -0
- package/dist/esm/inbound/services/inbound-delivery-stored-body.backend.service.js +211 -0
- package/dist/esm/inbound/services/inbound-delivery-stored-body.backend.service.js.map +1 -0
- package/dist/esm/inbound/services/inbound-delivery-subject-erasure-severance.backend.d.ts +2 -2
- package/dist/esm/inbound/services/inbound-delivery-subject-erasure-severance.backend.d.ts.map +1 -1
- package/dist/esm/inbound/services/inbound-delivery-subject-erasure-severance.backend.js +9 -1
- package/dist/esm/inbound/services/inbound-delivery-subject-erasure-severance.backend.js.map +1 -1
- package/dist/esm/index.d.ts +1 -0
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +1 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/inject/models/container.d.ts.map +1 -1
- package/dist/esm/inject/models/container.js +6 -0
- package/dist/esm/inject/models/container.js.map +1 -1
- package/dist/esm/inject/models/service-types.d.ts +5 -0
- package/dist/esm/inject/models/service-types.d.ts.map +1 -1
- package/dist/esm/inject/models/service-types.js +3 -0
- package/dist/esm/inject/models/service-types.js.map +1 -1
- package/dist/esm/monitoring/observability/models/observability.backend.schemas.d.ts +5 -0
- package/dist/esm/monitoring/observability/models/observability.backend.schemas.d.ts.map +1 -1
- package/dist/esm/monitoring/observability/models/observability.backend.schemas.js.map +1 -1
- package/dist/esm/monitoring/observability/services/metrics.service.d.ts +34 -1
- package/dist/esm/monitoring/observability/services/metrics.service.d.ts.map +1 -1
- package/dist/esm/monitoring/observability/services/metrics.service.js +49 -0
- package/dist/esm/monitoring/observability/services/metrics.service.js.map +1 -1
- package/dist/esm/notifications/webhooks/controllers/webhook-auto-controller.backend.service.d.ts +6 -1
- package/dist/esm/notifications/webhooks/controllers/webhook-auto-controller.backend.service.d.ts.map +1 -1
- package/dist/esm/notifications/webhooks/controllers/webhook-auto-controller.backend.service.js +15 -4
- package/dist/esm/notifications/webhooks/controllers/webhook-auto-controller.backend.service.js.map +1 -1
- package/dist/esm/notifications/webhooks/outbound/services/m2m-webhook-delivery-log.custom-impl.backend.service.d.ts.map +1 -1
- package/dist/esm/notifications/webhooks/outbound/services/m2m-webhook-delivery-log.custom-impl.backend.service.js +3 -1
- package/dist/esm/notifications/webhooks/outbound/services/m2m-webhook-delivery-log.custom-impl.backend.service.js.map +1 -1
- package/dist/esm/runtime/services/http-server.backend.service.d.ts +3 -1
- package/dist/esm/runtime/services/http-server.backend.service.d.ts.map +1 -1
- package/dist/esm/runtime/services/http-server.backend.service.js +11 -3
- package/dist/esm/runtime/services/http-server.backend.service.js.map +1 -1
- package/dist/esm/runtime/services/utils/inbound-endpoint-raw-body.backend.utils.d.ts +22 -0
- package/dist/esm/runtime/services/utils/inbound-endpoint-raw-body.backend.utils.d.ts.map +1 -1
- package/dist/esm/runtime/services/utils/inbound-endpoint-raw-body.backend.utils.js +54 -0
- package/dist/esm/runtime/services/utils/inbound-endpoint-raw-body.backend.utils.js.map +1 -1
- package/dist/esm/security/authentications/services/auth-methods/auth-password-reset.backend.service.d.ts +51 -0
- package/dist/esm/security/authentications/services/auth-methods/auth-password-reset.backend.service.d.ts.map +1 -1
- package/dist/esm/security/authentications/services/auth-methods/auth-password-reset.backend.service.js +87 -15
- package/dist/esm/security/authentications/services/auth-methods/auth-password-reset.backend.service.js.map +1 -1
- package/dist/esm/security/authentications/services/custom-impls/siem-delivery-dlq.custom-impl.backend.service.d.ts.map +1 -1
- package/dist/esm/security/authentications/services/custom-impls/siem-delivery-dlq.custom-impl.backend.service.js +5 -2
- package/dist/esm/security/authentications/services/custom-impls/siem-delivery-dlq.custom-impl.backend.service.js.map +1 -1
- package/dist/esm/security/authentications/services/custom-impls/sso-config-domain-verification.custom-impl.backend.service.d.ts.map +1 -1
- package/dist/esm/security/authentications/services/custom-impls/sso-config-domain-verification.custom-impl.backend.service.js +65 -24
- package/dist/esm/security/authentications/services/custom-impls/sso-config-domain-verification.custom-impl.backend.service.js.map +1 -1
- package/dist/esm/security/authorizations/super-admin-floor.backend.utils.d.ts +64 -1
- package/dist/esm/security/authorizations/super-admin-floor.backend.utils.d.ts.map +1 -1
- package/dist/esm/security/authorizations/super-admin-floor.backend.utils.js +84 -2
- package/dist/esm/security/authorizations/super-admin-floor.backend.utils.js.map +1 -1
- package/dist/esm/security/oauth-clients/oauth-clients.custom-impl.backend.service.d.ts +14 -0
- package/dist/esm/security/oauth-clients/oauth-clients.custom-impl.backend.service.d.ts.map +1 -1
- package/dist/esm/security/oauth-clients/oauth-clients.custom-impl.backend.service.js +13 -5
- package/dist/esm/security/oauth-clients/oauth-clients.custom-impl.backend.service.js.map +1 -1
- package/dist/esm/users/services/anonymous-consent.custom-impl.backend.service.d.ts.map +1 -1
- package/dist/esm/users/services/anonymous-consent.custom-impl.backend.service.js +6 -2
- package/dist/esm/users/services/anonymous-consent.custom-impl.backend.service.js.map +1 -1
- package/dist/esm/users/services/user-force-password-reset.custom-impl.backend.service.d.ts +7 -0
- package/dist/esm/users/services/user-force-password-reset.custom-impl.backend.service.d.ts.map +1 -1
- package/dist/esm/users/services/user-force-password-reset.custom-impl.backend.service.js +65 -20
- package/dist/esm/users/services/user-force-password-reset.custom-impl.backend.service.js.map +1 -1
- package/dist/esm/users/services/user-role-administration.custom-impl.backend.service.d.ts.map +1 -1
- package/dist/esm/users/services/user-role-administration.custom-impl.backend.service.js +11 -4
- package/dist/esm/users/services/user-role-administration.custom-impl.backend.service.js.map +1 -1
- package/dist/esm/users/services/user-self-custom-implementations.backend.d.ts.map +1 -1
- package/dist/esm/users/services/user-self-custom-implementations.backend.js +4 -2
- package/dist/esm/users/services/user-self-custom-implementations.backend.js.map +1 -1
- package/dist/esm/users/services/user-super-admin-floor.custom-impl.backend.service.d.ts.map +1 -1
- package/dist/esm/users/services/user-super-admin-floor.custom-impl.backend.service.js +16 -0
- package/dist/esm/users/services/user-super-admin-floor.custom-impl.backend.service.js.map +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/package.json +10 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agents.backend.service.js","sourceRoot":"","sources":["../../../../src/flows-actors/services/agents.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACzD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAkC,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5F,OAAO,UAAU,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,EAAE,cAAc,EAAmB,MAAM,uEAAuE,CAAC;AAExH,OAAO,EAAE,qBAAqB,EAA2C,MAAM,iFAAiF,CAAC;AACjK,OAAO,EAAE,4BAA4B,EAAE,MAAM,2EAA2E,CAAC;AACzH,OAAO,EAAE,kCAAkC,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,6EAA6E,CAAC;AAE3M,OAAO,EAAE,wBAAwB,EAAE,MAAM,kFAAkF,CAAC;AAE5H,OAAO,EAAE,kBAAkB,EAAE,MAAM,gDAAgD,CAAC;AACpF,OAAO,EAAE,aAAa,EAAE,MAAM,8DAA8D,CAAC;AAC7F,OAAO,EAAE,0BAA0B,EAAE,MAAM,kEAAkE,C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AAC;IAC/F,OAAO,MAAM,CAAC,MAAM,CAAC,0BAA0B,CAAC,CAAC,QAAQ,CAAC,MAAoC,CAAC;QAC7F,CAAC,CAAC,EAAE,MAAM,EAAE,MAAoC,EAAE;QAClD,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC","sourcesContent":["import 'reflect-metadata';\nimport { mkdirSync } from 'node:fs';\nimport { isDeepStrictEqual } from 'node:util';\nimport { AsyncResource } from 'node:async_hooks';\nimport { injectable, inject, optional } from 'inversify';\nimport { z } from 'zod';\nimport { ExecutionContext_ExecutionType, jsonParsingSchemaOf } from '@wildo-ai/saas-models';\nimport Bottleneck from 'bottleneck';\nimport { mcpServerDestinationHost } from '@wildo-ai/saas-models';\nimport { McpOutcomeKind, type McpSession } from '~wildo-backend-lib/flows-actors/models/mcp-client.backend.definitions';\nimport type { AuditLogsBackendService } from '~wildo-backend-lib/compliance/audit-trails/services/audit-logs.backend.service';\nimport { CaseTenantReadingKind, type ProviderCallRecorderBackendService } from '~wildo-backend-lib/flows-actors/services/provider-call-recorder.backend.service';\nimport { deriveToolApprovalSigningKey } from '~wildo-backend-lib/flows-actors/utils/tool-approval-signing.backend.utils';\nimport { CONVERSATION_DELIVERY_OF_OPERATION, ConversationDelivery, invocationConversationOf, invocationInstructionsOf } from '~wildo-backend-lib/flows-actors/utils/invocation-instructions.backend.utils';\nimport type { McpClientBackendService } from '~wildo-backend-lib/flows-actors/services/mcp-client.backend.service';\nimport { McpCredentialOutcomeKind } from '~wildo-backend-lib/flows-actors/services/mcp-credential-resolver.backend.service';\nimport type { McpCredentialResolverBackendService } from '~wildo-backend-lib/flows-actors/services/mcp-credential-resolver.backend.service';\nimport { SAAS_SERVICE_TYPES } from '~wildo-backend-lib/inject/models/service-types';\nimport { LoggerService } from '~wildo-backend-lib/monitoring/logger/services/logger.service';\nimport { ErrorBuilderBackendService } from '~wildo-backend-lib/errors/services/error-builder.backend.service';\nimport { describeCaughtError, projectCaughtErrorLogFields } from '~wildo-backend-lib/errors/utils/error-log-level-classification.backend.utils';\nimport { IMAGE_MODEL_PROVIDER_ACCOUNT_REFUSAL_IS_FINAL, MODEL_PROVIDER_ACCOUNT_REFUSAL_IS_FINAL, describeModelCallError, readModelProviderAccountRefusal } from '~wildo-backend-lib/flows-actors/utils/model-call-error-description.backend.utils';\nimport { FlowsActorsRegistryService } from './flows-actors-registry.service';\nimport { ExternalProvidersRegistryBackendService, RuntimeAgentClientProtocolProfile } from '~wildo-backend-lib/external-providers/services/external-providers-registry.backend.service';\nimport { BackendProviderRegistryBackendService } from '~wildo-backend-lib/external-providers/services/backend-provider-registry.backend.service';\nimport { resolveProviderContractBaseUrl, type ProviderContractEndpointFields } from '~wildo-backend-lib/external-providers/services/provider-http-access.backend';\nimport { ProviderClientCredentialsTokenError, ProviderClientCredentialsTokenFailure } from '~wildo-backend-lib/external-providers/services/provider-client-credentials-token.backend';\nimport { resolveProviderAiSdkCredential } from '~wildo-backend-lib/external-providers/services/provider-service-account-token.backend';\nimport { PromptCompilerBackendService } from './prompt-compiler.backend.service';\nimport {\n FlowsActors_Agent,\n type FlowsActors_OutputModerationPolicy,\n RedactionType,\n ResourcePrimaryScope,\n FlowsActors_Agent_Status,\n FlowsActors_Agent_Invocation,\n type FlowsActors_Agent_LLMConfiguration,\n type FlowsActors_Agent_ImageConfiguration,\n isImageAgentConfiguration,\n isCodingAgentConfiguration,\n EngineCapability,\n type FlowsActors_Agent_ModelAlternative,\n PromptIR_ContextItem,\n PromptIR_TrustLevel,\n PromptIR_ContextSourceKind,\n ErrorType,\n ErrorCustomMessageReference,\n isWildoBackendError,\n PersonalDataCategory,\n sortPersonalDataCategories,\n AgentCallOutcome,\n AgentTraceabilityLevel,\n type AgentCallTrace,\n type AgentCallTraceError,\n type AgentOperationObservation,\n type AgentTraceabilityPolicy,\n type AgentTraceContext,\n type AgentCallTraceSink,\n StructuredGenerationExecutionMode,\n FlowsActors_Agent_Skill_Type,\n isLLMAgentConfiguration,\n FlowsActors_SourceKind,\n FlowsActors_ToolCallPhase,\n type FlowsActors_Source,\n FlowsActors_ScreenedContentSource,\n effectiveAgentContentGuardrails,\n resolveRepresentingOrganizationIdsInOrganization,\n AgentSuspensionRefusalReason,\n AgentSuspensionScope,\n A2A_TOKEN_BUDGET_FEATURE_ID,\n A2ATokenBudgetDenialReason,\n ModelSpendDoor,\n modelSpendDoorPayerFallsBackToAttributedWork,\n} from '@wildo-ai/saas-models';\nimport { APPLICATION_ENV_UNDECLARED_MESSAGE, readDeclaredApplicationEnvironment } from '~wildo-backend-lib/config/models/app-env-config.backend.schemas';\nimport {\n APPLICATION_ENVIRONMENT,\n LLMProvider_ExecutionArtifactMetadata,\n LLMProvider_ExecutionTransportMetadata,\n LLMProvider_ExecutionTransportKind,\n LLMProvider_ExecutionTransportMetadataSchema,\n LLMProvider_UsageSchema,\n LLMProvider_StructuredGenerationFailureKind,\n LLMProvider_StructuredGenerationFailureSchema,\n type LLMProvider_StructuredGenerationFailure,\n ExternalProvider_ExchangeProtocol_Kind,\n ExternalProvider_RateLimitConfigurationSchema,\n LLMProvider_Configuration,\n LLMProvider_OperationKey,\n LLMProvider_GenerateStructuredInputSchema,\n LLMProvider_GenerateStructuredOutputSchema,\n LLMProvider_MessageRole,\n type LLMProvider_ImageContent,\n type ImageProvider_OperationKey,\n CodingAgent_OperationKey,\n AgentClientProtocol_AuthMode,\n AgentClientProtocol_PermissionCeiling,\n AgentClientProtocol_WorkingDirectoryPolicy,\n AgentClientProtocol_PermissionEscalationBehaviour,\n agentClientProtocolInFlightGuardsCanFire,\n type AgentClientProtocol_ExecutionProfile,\n type CodingAgent_RunTaskOutput,\n AgentClientProtocol_HostConfigurationInheritance,\n CodingAgent_UsageSchema,\n AgentClientProtocol_ExecutionTransportMetadataSchema,\n type AgentClientProtocol_ExecutionTransportMetadata,\n type ImageProvider_GenerateImageOutput,\n CodingAgent_EndOfTurnClassification,\n CodingAgent_StopReason,\n type CodingAgent_ContinuationRecord,\n type CodingAgent_SessionSuspension,\n type CodingAgent_Usage,\n ProviderProtocolRuntimeKind,\n isLLMCatalogProvider,\n LLM_MODEL_CATALOG,\n LLM_Model_IO_Capability,\n type LLM_Model,\n validateReasoningEffortForModel,\n CODING_AGENT_NOT_SIGNED_IN_MESSAGE_PREFIX,\n CodingAgentHostLoginState,\n ContentSafetyScreeningOutcome,\n ContentSafetyModerationOutcome,\n type ContentSafety_HarmCategory,\n} from '@wildo-ai/external-connectors-models';\nimport { buildAgentSubprocessEnvironment, probeCodingAgentHostLoginAsync } from '@wildo-ai/external-connectors-private/backend-runtime';\nimport type { NativeConstrainedDecodingContract, ProviderSdkFactoryContext, StrictStructuredOutputProfile } from '@wildo-ai/external-connectors-private/backend-runtime';\nimport { asSchema, generateText, streamText, generateObject, generateImage, NoObjectGeneratedError, tool, jsonSchema, stepCountIs, wrapImageModel, wrapLanguageModel, type JSONSchema7 } from 'ai';\nimport { STREAMED_GENERATION_IDLE_DEADLINE_MS, STREAMED_GENERATION_TOTAL_DEADLINE_MS, streamedGenerationDeadlineMiddleware } from '../utils/streamed-generation-deadline.backend.utils';\nimport {\n latestCumulativeCost,\n startACPAgentSession,\n type ACPAgentSession,\n} from '~wildo-backend-lib/flows-actors/utils/acp-session-runner.backend.utils';\nimport {\n ACP_RESULT_TOOL_NAME,\n ACP_RESULT_TOOL_SERVER_NAME,\n startAcpResultToolServer,\n} from '~wildo-backend-lib/flows-actors/utils/acp-result-tool-server.backend.utils';\nimport { executeBoundedSubprocess, resolveTrustedWorkingDirectory } from '~wildo-backend-lib/flows-actors/utils/bounded-subprocess.backend.utils';\nimport type { FunctionTool, FunctionToolExecutionContext } from '~wildo-backend-lib/flows-actors/models/function-tools.backend.definitions';\nimport { FunctionToolPersonalDataOutputKind, argumentsAToolExecutesWith, sdkInputSchemaOfFunctionTool, isFunctionToolOfferedToTurn, modelToolNameForFunctionRef, resolveFunctionToolApprovalGate } from '~wildo-backend-lib/flows-actors/models/function-tools.backend.definitions';\nimport {\n PersonalDataGuard,\n PersonalDataPlaceholderRefusal,\n PersonalDataPlaceholderTable,\n modelCopyOfPersonAuthoredToolCalls,\n reviewerEditStatementsOf,\n withReviewerEditStatements,\n treatRecordsResult,\n} from '~wildo-backend-lib/flows-actors/content-guardrails/personal-data-guard.backend.utils';\nimport { ToolResultScreen, type ToolResultScreeningRecord } from '~wildo-backend-lib/flows-actors/content-guardrails/tool-result-screen.backend.utils';\nimport { ClassifierBackedContentGuardrail, contentGuardrailClassifierGapOf } from '~wildo-backend-lib/flows-actors/content-guardrails/classifier-availability.backend.utils';\nimport { AgentOperationObservationRecorder } from '~wildo-backend-lib/flows-actors/services/agent-operation-observation.backend.utils';\nimport { getCurrentWorkAttributionFrame } from '~wildo-backend-lib/runtime/models/work-attribution.als.backend';\nimport { getCurrentModelSpendFrame } from '~wildo-backend-lib/runtime/models/model-spend-frame.als.backend';\nimport type { ModelCallSpendMeter } from '~wildo-backend-lib/flows-actors/a2a/services/a2a-token-budget.backend.service';\nimport { estimateModelCallTokens, modelCallUsageIsPartial, reportedModelCallTokens } from '~wildo-backend-lib/flows-actors/services/model-call-token-estimate.backend.utils';\nimport { agentPoliciesInFrame, readAgentPolicies, turnPolicyOrganizationIds, type AgentPolicyLookup } from '~wildo-backend-lib/flows-actors/content-guardrails/agent-policy.backend';\nimport { treatRecordsResultByOwner, treatToolTreatedResultByPossibleOwners, unattributedRowOwnershipOf, type RecordOwnerPolicyContext } from '~wildo-backend-lib/flows-actors/content-guardrails/record-owner-policy.backend';\nimport { observingRecordOwners, organizationNamedByRecord, type ToolCallRecordOwners } from '~wildo-backend-lib/flows-actors/content-guardrails/tool-call-record-owners.backend';\nimport { resolveCallerOrganizationIds } from '~wildo-backend-lib/security/authorizations/scope-root-collection-confinement.backend';\nimport { AgentSuspensionLookupKind, readAgentSuspension, type AgentSuspensionLookup } from '~wildo-backend-lib/flows-actors/agent-suspension/agent-suspension.backend';\nimport type { RepositoriesRegistryHandlerBackendService } from '~wildo-backend-lib/base-classes/services/repositories/repositories-registry-handler.backend.service';\nimport {\n AgentOutputWithheldError,\n OutputModerationGuard,\n type OutputWithholding,\n} from '~wildo-backend-lib/flows-actors/content-guardrails/output-moderation.backend.utils';\nimport { type ContentSafetyBackendService, type ContentSafetyModerationResult } from '~wildo-backend-lib/external-providers/services/content-safety.backend.service';\nimport {\n AutonomousTurnTrigger,\n FlowsActors_ExecutionErrorCode,\n FlowsActors_ModeratedOutputKind,\n admitsDecisionSuspension,\n outputModerationCategories,\n resolveModelCallAttribution,\n type ExecutionContext_InitiatorIds,\n type ModelCallAttributionInput,\n type FlowsActors_InitiationKind,\n type HumanDecision_RouteKind,\n describeModelProviderAccountRefusal,\n type ModelProviderAccountRefusal,\n type WildoError_Backend,\n} from '@wildo-ai/saas-models';\nimport { toPortableModelToolName } from '~wildo-backend-lib/flows-actors/models/model-tool-name.backend.utils';\nimport { userInputToContextItem } from '~wildo-backend-lib/flows-actors/utils/prompt-ir-adapters.backend.utils';\nimport { runWithAgentActorFrame } from '~wildo-backend-lib/runtime/models/agent-actor-frame.als.backend';\nimport type { AuditAgentActor } from '@wildo-ai/saas-models';\nimport type { AuditPrincipalFacts } from '~wildo-backend-lib/compliance/audit-trails/utils/audit-actor.backend.utils';\nimport {\n DEFAULT_MAX_STRUCTURED_DATA_FIELD_ALLOWED,\n planStructuredGenerationShape,\n StructuredGenerationPlanKind,\n} from '~wildo-backend-lib/flows-actors/utils/structured-generation-plan.backend.utils';\nimport {\n StrictStructuredOutputSchemaKind,\n deriveStrictStructuredOutputSchema,\n exceedsConstrainedDecodingLimits,\n isCompiledGrammarSizeRefusal,\n isConstrainedDecodingComplexityRefusal,\n isStrictSchemaRequestRefusal,\n measureConstrainedDecodingComplexity,\n withoutDecodingValidationConstraints,\n} from '~wildo-backend-lib/flows-actors/utils/strict-structured-output-schema.backend.utils';\nimport { CryptoKey_Purpose } from '@wildo-ai/saas-models';\nimport type { AppConfigurationService } from '~wildo-backend-lib/config/services/app-configuration.backend.service';\nimport { applicationSymmetricKeyOf } from '~wildo-backend-lib/security/crypto-keys/application-symmetric-keys.backend';\nimport { withModelCallFailover, type ModelCallCandidate, type ModelCallFailover } from '~wildo-backend-lib/flows-actors/utils/model-call-failover.backend.utils';\n\n\n\ninterface executeOperationParams {\n providerClient: any;\n providerRef: string;\n config: FlowsActors_Agent['config'];\n operationKey: LLMProvider_OperationKey;\n systemPrompt: string;\n instructions: string;\n input: any;\n llmProviderConfig?: LLMProvider_Configuration;\n /** #2292 Phase 3: the agent's output moderation, when it declares one. The model is wrapped with its middleware. */\n outputModeration?: OutputModerationGuard;\n /** #2841: the invocation's operation observation; the model is wrapped innermost with its middleware. */\n operationObservation?: AgentOperationObservationRecorder;\n /** #2301: where each hand-over to a declared alternative model is written, for the invocation's trace. */\n modelFailovers?: ModelCallFailover[];\n}\n\n/**\n * #2292 Phase 3: what a BUFFERED operation's result is, as output moderation names it. Total over the operation keys, so a\n * new operation is a compile error here rather than a call whose output escapes moderation. A structured answer is judged\n * by its string leaves; a reply as it is.\n */\nconst MODERATED_OUTPUT_KIND_OF_OPERATION: Readonly<Record<LLMProvider_OperationKey, FlowsActors_ModeratedOutputKind>> = {\n [LLMProvider_OperationKey.GENERATE_TEXT]: FlowsActors_ModeratedOutputKind.REPLY,\n [LLMProvider_OperationKey.CHAT_COMPLETION]: FlowsActors_ModeratedOutputKind.REPLY,\n [LLMProvider_OperationKey.CHAT_MULTIMODAL]: FlowsActors_ModeratedOutputKind.REPLY,\n [LLMProvider_OperationKey.STREAM_TEXT]: FlowsActors_ModeratedOutputKind.REPLY,\n [LLMProvider_OperationKey.GENERATE_STRUCTURED]: FlowsActors_ModeratedOutputKind.STRUCTURED_OUTPUT,\n [LLMProvider_OperationKey.STREAM_STRUCTURED]: FlowsActors_ModeratedOutputKind.STRUCTURED_OUTPUT,\n};\n\n/**\n * The organizations one model call works for (#2843, #2292 R8): whose suspensions refuse it, and whose agent policies\n * tighten its guardrails. Built ONCE per call, at its entry point, by `AgentsBackendService.buildCallOrganizationScope`\n * (a streaming turn through `buildStreamingCallOrganizationScope`, which wraps it), and handed to both the admission and\n * the execution, so the organizations a call is refused for and those it is tightened for cannot differ.\n */\ninterface ModelCallOrganizationScope {\n /** The organization the call is made for: the one its refusal or moderation row is recorded in. */\n readonly organizationId?: string;\n /**\n * Every other organization whose work the call is: the case's tenant, the run's requester's organization, when they\n * differ from `organizationId`. Each one's suspensions and policies apply too: a suspension only refuses and a policy\n * only tightens, so applying one more organization's can never let through what one of them stops.\n */\n readonly alsoWorkedForOrganizationIds?: readonly string[];\n /** The organizations a principal acting in `organizationId` represents there (#2618). */\n readonly representingOrganizationIds?: readonly string[];\n /**\n * Why an organization the call may work for could not be known: the case it works on could not be read. The call is\n * refused, as for an unreadable suspension or policy: that organization may have suspended the agent or tightened it.\n */\n readonly unreadable?: string;\n}\n\n/** Every organization a call's scope names, its own first, each once. */\nfunction organizationIdsOfCallScope(scope: ModelCallOrganizationScope): string[] {\n return turnPolicyOrganizationIds(scope.organizationId, [...(scope.alsoWorkedForOrganizationIds ?? []), ...(scope.representingOrganizationIds ?? [])]);\n}\n\ninterface CompiledExecutionPrompts {\n systemPrompt: string;\n instructions: string;\n}\n\n/**\n * What a single operation helper (`executeGenerateText`, `executeGenerateStructured`, …)\n * hands back to {@link AgentsBackendService.executeOperation}.\n *\n * Named rather than written inline at each helper because it grew a THIRD member:\n * a structured generation can legitimately complete with no object, and the reason it\n * did has to survive the four hops between the helper that learns it and the caller\n * that reports it. An inline `{ output; usage? }` at every signature silently drops any\n * fourth field at the first hop that re-declares the shape — which is exactly how the\n * approval suspension was lost once already (see the warning in\n * {@link AgentsBackendService.finalizeInvocationSuccess}).\n */\ninterface AgentOperationExecutionResult {\n output: unknown;\n usage?: any;\n /**\n * Present ONLY when a structured generation returned `{ object: undefined }`. Every\n * other outcome — success, or a provider fault that throws — leaves it absent.\n */\n structuredGenerationFailure?: LLMProvider_StructuredGenerationFailure;\n}\n\ninterface AgentExecutionResult extends AgentOperationExecutionResult {\n output: unknown;\n usage?: unknown;\n /**\n * #2301: each hand-over of a model call to an alternative the agent declared, in order. Absent when every call was\n * answered by the agent's own model. The last one names the model that answered the final step.\n */\n modelFailovers?: readonly ModelCallFailover[];\n /**\n * How the call was physically executed.\n *\n * A UNION, because a coding run is not an LLM call with a different wire\n * format and its metadata is owned by the coding-agent family. Before this was\n * widened, the ACP executor returned through a double cast and finalization\n * parsed the result with the LLM schemas — which would have thrown on the\n * first real dispatch, in a path no test and no live probe had exercised.\n */\n transport?: LLMProvider_ExecutionTransportMetadata | AgentClientProtocol_ExecutionTransportMetadata;\n /**\n * Present when the turn SUSPENDED at a human-in-the-loop approval boundary rather than\n * completing. A caller that ignores it treats a paused turn as a finished one — which would\n * record a terminal status for work that has not happened.\n */\n approvalSuspension?: AgentApprovalSuspension;\n}\n\n/**\n * A host's decision to run language-model calls on an ACP agent instead of an API key (#3472).\n *\n * The development companion installs one at startup: its creation lane makes hundreds of structured calls per run,\n * and on a metered API key that cost exploded, while every developer using Wildo already runs a coding agent on their\n * own subscription. With a route installed, a language-model agent whose provider is in `routedProviderRefs` has its\n * text and structured calls served by a locked-down session of the route's ACP agent, and its result returned through\n * the host's `submit_result` tool (`acp-result-tool-server.backend.utils.ts`). Everything above the call — prompts,\n * schemas, validators, the correction loop — is unchanged; only the transport and the model differ.\n *\n * What stays on the API, by construction: image generation (no ACP agent generates images), a call whose input\n * carries images (not yet measured over ACP), streaming calls, and an agent under an output-moderation guard (the\n * guard is an API middleware). Each is logged when it happens, so a call that still spends API tokens says why.\n */\nexport interface LanguageModelAgentClientProtocolRoute {\n /** The provider whose ACP binding serves the calls, e.g. `anthropic` (Claude Code through its adapter). */\n readonly acpProviderRef: string;\n /** The ACP execution profile of that provider the sessions start under (its auth posture, its environment). */\n readonly executionProfileRef: string;\n /** The model every routed call runs on, a member of the ACP binding's `models`. */\n readonly model: string;\n /** Language-model agents on these providers are routed; every other agent keeps its own transport. */\n readonly routedProviderRefs: readonly string[];\n /** The working directory of every session: a scratch directory, never an application workspace. */\n readonly scratchDirectory: string;\n /** How many routed sessions may run at once. Each is an agent process. */\n readonly maximumConcurrentSessions: number;\n /** The longest one routed call may take, all its turns together. */\n readonly callTimeoutMs: number;\n /** Refused submissions after which a call stops asking and reports the last refusal. */\n readonly maximumSubmissions: number;\n}\n\n/** The operations a route serves: a prompt in, one result out. */\nconst ROUTABLE_LANGUAGE_MODEL_OPERATIONS: ReadonlySet<LLMProvider_OperationKey> = new Set([\n LLMProvider_OperationKey.GENERATE_STRUCTURED,\n LLMProvider_OperationKey.GENERATE_TEXT,\n LLMProvider_OperationKey.CHAT_COMPLETION,\n]);\n\n/** Turns a routed call may add after one that ended without an accepted result, to ask for the submission. */\nconst ROUTED_CALL_REMINDER_TURNS = 2;\n\n/**\n * Backend-only authority supplied by the installed host for an Agent call.\n *\n * A spawned agent operates in a real filesystem workspace, but that workspace is\n * neither provider configuration nor task data: profiles are portable and task\n * callers must never choose process working directories. The host that owns\n * the installed application resolves the physical root and passes it here only\n * for the invocation that needs it. API-backed Agents intentionally require no\n * host context.\n */\nexport interface AgentInvocationHostContext {\n workspaceRootPath?: string;\n /**\n * Narrows what a CODING agent may touch, beyond the profile's permission\n * ceiling. Supplied by the host that owns the task's mutation scope; returning\n * false denies, whatever the ceiling permits. Host authority, not authored\n * configuration — a portable profile cannot know a task's scope.\n */\n isPermittedCodingLocation?: (absolutePath: string) => boolean;\n /**\n * Optional read boundary for ACP client callbacks and declared non-mutating tool locations. Research supplies its evidence\n * store; ordinary coding leaves this absent so a narrow write scope still permits source reading.\n * Host authority only: a task prompt or portable execution profile cannot broaden it.\n */\n isPermittedCodingReadLocation?: (absolutePath: string) => boolean;\n /**\n * Live progress from a coding session. Best-effort by contract: the runner\n * swallows anything this throws, because a progress sink must never be able\n * to fail the run it observes.\n */\n onCodingSessionEvent?: (event: { readonly kind: string; readonly payload: unknown }) => void;\n /** Operator-initiated cancellation of a coding session. Cooperative first, kill second. */\n codingSessionAbortSignal?: AbortSignal;\n /**\n * Judge what a coding agent's END-OF-TURN message actually meant, so the turn\n * ladder can auto-continue a self-imposed pause and park a genuine question.\n *\n * The JUDGMENT is host authority, not engine mechanism: it is an auxiliary LLM\n * call, and the host (the companion) owns model resolution and the deliberation\n * infrastructure. The engine owns the LADDER — when to call this, how many\n * continuations to allow, how to record the result — and it FAILS OPEN: if this\n * is absent, throws, or times out, the turn is treated as complete. An\n * autonomous coding lane must never hang, or discard a mutated workspace, on an\n * auxiliary call. Absence therefore reproduces the pre-ladder single-turn\n * behaviour exactly, which is why every non-coding caller can ignore it.\n */\n classifyCodingTurnEnd?: (input: {\n readonly finalMessage: string;\n readonly turnIndex: number;\n }) => Promise<CodingAgent_EndOfTurnClassification>;\n /**\n * Live phase transitions for a coding session — distinct from\n * {@link onCodingSessionEvent}, which relays the agent's own frames. This fires\n * when the LADDER changes state: a new turn starting, or the session parking on\n * a question. Best-effort, like the event sink: never allowed to fail the run.\n */\n onCodingSessionStateChange?: (state: CodingSessionLadderState) => void;\n}\n\n/** The ladder phases a live coding session transitions through. */\nexport enum CodingSessionLadderPhase {\n /** A turn is executing. */\n RUNNING = 'running',\n /** The session parked on a question and is waiting for an operator answer. */\n AWAITING_INPUT = 'awaiting_input',\n}\n\n/** A phase transition in the turn ladder, surfaced to the host for live relay. */\nexport interface CodingSessionLadderState {\n readonly phase: CodingSessionLadderPhase;\n /** 1-based index of the turn this state refers to. */\n readonly turnIndex: number;\n /** The agent's question, present only when `phase` is `AWAITING_INPUT`. */\n readonly question?: string;\n}\n\n/** True when an execution result carries a CODING transport rather than an LLM one. */\nfunction isAgentClientProtocolTransport(\n transport: LLMProvider_ExecutionTransportMetadata | AgentClientProtocol_ExecutionTransportMetadata | undefined,\n): transport is AgentClientProtocol_ExecutionTransportMetadata {\n return transport?.protocolKind === ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL;\n}\n\ntype ResolvedAgentExecution =\n | {\n transport: 'api';\n providerRef: string;\n operationKey: LLMProvider_OperationKey;\n llmProviderConfig?: LLMProvider_Configuration;\n }\n | {\n transport: 'acp';\n providerRef: string;\n operationKey: CodingAgent_OperationKey;\n executionProfileRef: string;\n acpProfile: RuntimeAgentClientProtocolProfile;\n acpExecutionProfile: AgentClientProtocol_ExecutionProfile;\n };\n\n/**\n * The provider's declaration of whether its agent escalates before mutating.\n *\n * Structurally identical to the `permissionEscalation` member of the ACP runtime\n * contract, and declared locally rather than imported because that contract type\n * lives in the provider-module package, which this engine package does not\n * depend on. The narrowing below is by the enum member, so a contract that grew\n * a fourth behaviour would fail this file's exhaustiveness rather than fall into\n * a silent default.\n */\ntype AgentClientProtocolPermissionEscalationDeclaration =\n | { behaviour: typeof AgentClientProtocol_PermissionEscalationBehaviour.RAISES_BEFORE_MUTATION }\n | {\n behaviour: typeof AgentClientProtocol_PermissionEscalationBehaviour.RAISES_ONLY_UNDER_HOST_CONFIGURATION;\n configurationEnvironmentVariableName: string;\n }\n | { behaviour: typeof AgentClientProtocol_PermissionEscalationBehaviour.NEVER_RAISES };\n\n\n/**\n * Thrown by {@link AgentsBackendService.invokeAgentStreaming} when honest token\n * streaming is not available for the requested agent:\n * - `'transport'` — the agent uses the CLI transport (v1 streams over the API\n * transport only; the session-oriented CLI runtime is a future workstream);\n * - `'operation'` — the operation is non-text (structured / multimodal / image),\n * which has no token-delta stream.\n * Callers may catch this to fall back to the buffered {@link AgentsBackendService.invokeAgent}.\n */\nexport class AgentStreamingUnsupportedError extends Error {\n constructor(public readonly reason: 'transport' | 'operation', message: string) {\n super(message);\n this.name = 'AgentStreamingUnsupportedError';\n }\n}\n\n/**\n * The usage a model call reported, as {@link AgentsBackendService} normalizes it — the shape the\n * invocation carries on `executionContext.usage` (parsed there by `LLMProvider_UsageSchema`).\n */\nexport interface AgentModelCallUsage {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n tokenUsageComplete: boolean;\n inputTokenDetails?: { noCacheTokens?: number; cacheReadTokens?: number; cacheWriteTokens?: number };\n /** The output split (#1598): absent `reasoningTokens` means the provider did not report it, never zero. */\n outputTokenDetails?: { textTokens?: number; reasoningTokens?: number };\n}\n\n/**\n * Thrown when the model provider FAILED a streamed call — refused it (an HTTP 4xx such as Anthropic's\n * `400 Your credit balance is too low`), broke off mid-stream (an `overloaded_error` event), or failed a\n * later step of the tool loop.\n *\n * ## Why this exists (#2191)\n *\n * AI-SDK v7 does not THROW a provider failure out of `streamText`. It delivers it as an `error` PART on\n * `fullStream` — exactly as it delivers a cancellation as an `abort` part — and `fullStream` then ends\n * cleanly. `textStream` drops the part altogether. So a reader that only handles the part types it\n * expects sees an empty, successful stream, and the turn was recorded COMPLETED with no assistant\n * message: an exhausted, revoked or misconfigured key read as \"the model chose not to act\", the client\n * never received `AGENT_FAILED`, and the reason existed only in a stack the SDK printed to stderr.\n *\n * Every reader of an AI-SDK stream in this service therefore turns an `error` part into this error,\n * which every invocation path already treats as a failed call: the failure trace carries its message,\n * the provider-call record its {@link code} (the HTTP status), and the conversational runtime records\n * the turn FAILED. It is NOT a backend error built by the error builder — `isWildoBackendError` does not\n * match it — so a caller that needs the distinction tests `instanceof AgentModelCallFailedError`.\n *\n * Not every `error` part is the provider's: the SDK reports its own failures the same way (an invalid\n * prompt, a forged tool-approval signature on a resume, a stream that ended with no output). Only a\n * failure carrying an HTTP status is a provider REFUSAL, which is why {@link statusCode} is optional\n * and the runtime words its log line by it.\n *\n * ## The usage it carries\n *\n * Steps that FINISHED before the failure really consumed provider tokens (a tool loop whose second\n * model call is refused already paid for its first). Throwing would otherwise drop that consumption on\n * the floor — the same unmetered-spend shape the aborted-stream fix closed — so the per-step total\n * rides on the error and the failure paths meter it. When NO step finished (the call was refused\n * outright) `usage` is ABSENT, not zero: zero would read downstream as \"the provider reported a token\n * count\" (the provider-call evidence counts it) and as \"a metered call reported nothing\" (the token\n * budget warns that spend escaped it), and neither is true of a call the provider never ran.\n */\nexport class AgentModelCallFailedError extends Error {\n /** The provider's HTTP status when the failure was an HTTP refusal (`APICallError.statusCode`). */\n public readonly statusCode?: number;\n /**\n * `HTTP_<status>` for a provider refusal, absent otherwise. Read by the agent-call trace (`error.code`),\n * which is the only part of the error the provider-call record keeps, so a 400 credit refusal and a 529\n * overload stay distinguishable there.\n */\n public readonly code?: string;\n /**\n * The failure exactly as the SDK delivered it on the stream — usually an `APICallError`. NOT ENUMERABLE (#2368): the\n * engine's log normalizer serializes every own enumerable key of an error, and this one holds the prompt\n * (`requestBodyValues`), the vendor's body and headers and the request URL, so a caller logging this error would\n * record all of them by value. Read it by name; describe it with `describeModelCallError`.\n */\n declare public readonly providerError: unknown;\n /**\n * The provider ACCOUNT's refusal behind the failure (#3204): no credits left, a spend or usage limit, billing. Present\n * only then; the message then says which provider and what to do, in the shape every layer reads back\n * (`describeModelProviderAccountRefusal`).\n */\n public readonly accountRefusal?: ModelProviderAccountRefusal;\n\n constructor(\n providerError: unknown,\n /** What the steps that finished before the failure consumed; absent when none finished. */\n public readonly usage?: AgentModelCallUsage,\n ) {\n const statusCode = AgentModelCallFailedError.statusCodeOf(providerError);\n // The vendor's message, redacted (#2368): a refusal can quote the prompt content it refused, and this message is\n // logged and carried on the failure. `describeModelCallError` keeps its quoted identifiers and limits, never a value.\n const described = String(describeModelCallError(providerError).errorMessage ?? 'no message');\n const accountRefusal = readModelProviderAccountRefusal(providerError);\n super(accountRefusal !== undefined ? describeModelProviderAccountRefusal(accountRefusal) : statusCode !== undefined\n ? `The model provider refused the call (HTTP ${statusCode}): ${described}`\n : `The model call failed on the stream: ${described}`);\n this.name = 'AgentModelCallFailedError';\n Object.defineProperty(this, 'providerError', { value: providerError, enumerable: false, writable: false, configurable: false });\n this.statusCode = statusCode;\n this.code = statusCode !== undefined ? `HTTP_${statusCode}` : undefined;\n if (accountRefusal !== undefined) this.accountRefusal = accountRefusal;\n }\n\n /**\n * The HTTP status of an `APICallError`, or of the LAST attempt when the SDK gave up retrying (a retryable\n * 429/529 arrives as a `RetryError` whose own object carries no status, only `lastError`).\n */\n private static statusCodeOf(error: unknown): number | undefined {\n if (!error || typeof error !== 'object') return undefined;\n const own = (error as { statusCode?: unknown }).statusCode;\n if (typeof own === 'number') return own;\n const last = (error as { lastError?: { statusCode?: unknown } }).lastError?.statusCode;\n return typeof last === 'number' ? last : undefined;\n }\n}\n\n/**\n * `streamText`'s `onError`, passed by every reader in this service. The SDK's default prints the raw\n * failure to stderr; here the `error` PART itself fails the call and is logged with the provider's\n * details (see {@link AgentModelCallFailedError}), so printing it again would only duplicate it without\n * structure. Named so each call site states why it is silent rather than repeating an empty arrow.\n */\nconst SUPPRESS_SDK_STREAM_ERROR_PRINT = (): void => undefined;\n\n/** Max agent↔tool round-trips per streaming turn (bounds tool-call loops). */\nconst MAX_TOOL_STEPS = 6;\n\n/**\n * Strip assistant `reasoning` content parts that carry NO text, for the multi-step\n * tool-loop continuation.\n *\n * WHY: extended-thinking models (e.g. Sonnet-5) emit an assistant `reasoning` part whose `text` is\n * EMPTY — the thinking itself lives in the provider-encrypted `providerOptions.anthropic.signature`.\n * When the AI-SDK v7 tool loop re-feeds that assistant message to the model for the NEXT step, the\n * provider prompt validation rejects the empty-text part\n * (`AI_TypeValidationError: … expected 'reasoning' | 'reasoning-file' | 'tool-call'`) — so the second\n * step never runs: a read→create chain dies after the first tool and the reply comes back empty.\n *\n * WHAT: drop ONLY the text-less reasoning parts. Reasoning parts that DO carry text round-trip fine\n * and are preserved, as are text / tool-call / tool-result parts — so nothing user-visible and no\n * tool causality is lost. An assistant message left with no parts at all is dropped entirely (an\n * empty content array is itself invalid).\n *\n * Pure + total: returns a NEW array only when something changed, never mutates the caller's\n * messages, and passes through any non-array content untouched.\n */\nexport function stripEmptyReasoningParts(messages: readonly any[] | undefined): any[] {\n if (!Array.isArray(messages)) return [];\n const isTextlessReasoning = (part: any): boolean =>\n !!part && typeof part === 'object' && part.type === 'reasoning'\n && (typeof part.text !== 'string' || part.text.length === 0);\n\n const result: any[] = [];\n for (const message of messages) {\n if (!message || message.role !== 'assistant' || !Array.isArray(message.content)) {\n result.push(message);\n continue;\n }\n if (!message.content.some(isTextlessReasoning)) {\n result.push(message);\n continue;\n }\n const content = message.content.filter((part: any) => !isTextlessReasoning(part));\n // An assistant message whose parts were ALL text-less reasoning has nothing left to send.\n if (content.length === 0) continue;\n result.push({ ...message, content });\n }\n return result;\n}\n\n/**\n * A source part of the model stream, as the conversation keeps it (#2524): the SDK's `sourceType` read into the model\n * vocabulary, and only the fields a person is shown. Read by shape — the part crossed a provider boundary.\n */\nfunction toFlowsActorsSource(part: unknown): FlowsActors_Source {\n const bag = (part ?? {}) as { sourceType?: unknown; url?: unknown; title?: unknown; mediaType?: unknown; filename?: unknown };\n const text = (value: unknown): string | undefined => (typeof value === 'string' && value.length > 0 ? value : undefined);\n const title = text(bag.title);\n if (bag.sourceType === FlowsActors_SourceKind.DOCUMENT) {\n const mediaType = text(bag.mediaType);\n const filename = text(bag.filename);\n return { kind: FlowsActors_SourceKind.DOCUMENT, ...(title ? { title } : {}), ...(mediaType ? { mediaType } : {}), ...(filename ? { filename } : {}) };\n }\n const url = text(bag.url);\n return { kind: FlowsActors_SourceKind.URL, ...(title ? { title } : {}), ...(url ? { url } : {}) };\n}\n\n/**\n * One phase of a tool call, surfaced to the streaming caller as it happens (#2524).\n *\n * All three phases carry the SDK's `toolCallId`, so a caller can join a call to its result or its error. The result and\n * the error used to arrive with the tool's name only — nothing to join on, nothing to show — and the conversational\n * runtime dropped both.\n */\n/** #2292: see `AgentsBackendService.personalDataGuards`. Keyed by the invocation's request object; nothing outlives it. */\nconst PERSONAL_DATA_GUARD_BY_INVOCATION = new WeakMap<object, PersonalDataGuard>();\n/** #2841: see `AgentsBackendService.operationObservationOf`. Keyed by the invocation's request object; nothing outlives it. */\nconst AGENT_OPERATION_OBSERVATION_BY_INVOCATION = new WeakMap<object, AgentOperationObservationRecorder>();\n\nexport interface FunctionToolStreamEvent {\n phase: FlowsActors_ToolCallPhase;\n toolCallId: string;\n toolName: string;\n /** What the agent passed. Every phase. */\n input?: unknown;\n /** What the tool returned. RESULT only. */\n output?: unknown;\n /** What the tool threw. ERROR only. */\n error?: unknown;\n}\n\n/** Callbacks a streaming invocation forwards to the caller. */\nexport interface AgentStreamHandlers {\n onDelta: (delta: string) => void;\n onToolEvent?: (event: FunctionToolStreamEvent) => void;\n /**\n * The model's REASONING, as it streams (#2524). Forwarded for every model that emits it; whether a person is shown\n * it is the caller's decision (`FlowsActors_Agent.disclosure.reasoning`), never this layer's.\n */\n onReasoningDelta?: (delta: string) => void;\n /** A source the model cited, as the provider reported it (#2524). */\n onSource?: (source: FlowsActors_Source) => void;\n /**\n * Cooperative cancellation for the model call.\n *\n * Carried HERE rather than as a new parameter because `handlers` is already threaded\n * unchanged through every hop of the streaming path\n * (`invokeAgentStreaming` → `executeAgentViaApiStreaming` → `streamOperation` →\n * `streamTextToDeltas` → `streamText`). Adding a positional argument at four levels\n * is exactly the arity hazard that has already produced one silent `undefined` in this\n * codebase; riding the object that is passed anyway changes no call signature.\n *\n * Semantically it belongs: this interface is the stream's control surface, and\n * \"stop streaming\" is part of controlling a stream.\n *\n * When absent the model call is simply uncancellable — the previous behaviour.\n */\n abortSignal?: AbortSignal;\n}\n\ninterface streamOperationParams {\n providerClient: any;\n /** The provider the agent names: the first candidate of a declared model failover (#2301). */\n providerRef: string;\n /** #2301: where each hand-over to a declared alternative model is written, for the invocation's trace. */\n modelFailovers?: ModelCallFailover[];\n config: FlowsActors_Agent['config'];\n operationKey: LLMProvider_OperationKey;\n systemPrompt: string;\n instructions: string;\n input: any;\n handlers: AgentStreamHandlers;\n tools?: Record<string, any>;\n /** #2292 Phase 3: the agent's output moderation, when it declares one. The model is wrapped with its middleware. */\n outputModeration?: OutputModerationGuard;\n /** #2841: the invocation's operation observation; the model is wrapped innermost with its middleware. */\n operationObservation?: AgentOperationObservationRecorder;\n /**\n * Call-level tool-approval configuration (human-in-the-loop), keyed by identifier-safe tool name.\n *\n * Rides the params OBJECT rather than a positional argument, for the reason already recorded on\n * `abortSignal` above: this value crosses four levels, and adding a positional parameter at four\n * levels is the arity hazard that has already produced one silent `undefined` here.\n */\n toolApproval?: Record<string, ToolApprovalDecision>;\n /**\n * Secret used to HMAC-sign approval requests and verify them on replay.\n *\n * REQUIRED whenever `toolApproval` is present — without it a client can forge an approval for\n * exactly the tools someone marked dangerous enough to gate. The caller fails closed rather than\n * passing `toolApproval` with no secret.\n */\n toolApprovalSecret?: string;\n /**\n * #2855: the invocation's personal-data guard, when the agent runs under a treatment: every model step is sent the\n * person-authored tool calls of its messages treated by it (`modelCopyOfPersonAuthoredToolCalls`).\n */\n personalDataGuard?: PersonalDataGuard;\n}\n\n/**\n * A turn that SUSPENDED at a human-in-the-loop approval boundary instead of completing.\n *\n * Not an error and not a terminal failure: the tool loop stopped, the model is waiting, and the run\n * state below is everything needed to resume once a human decides. `sdkModelMessages` is the SDK's\n * own resume payload — opaque to us by design.\n */\nexport interface AgentApprovalSuspension {\n approvalId: string;\n toolCallId: string;\n toolName: string;\n toolArgs?: Record<string, unknown>;\n sdkModelMessages: Record<string, unknown>[];\n /** #3364 step 3: the output moderation the turn was judged under when it paused, when it judged anything. */\n outputModerationAtPause?: FlowsActors_OutputModerationPolicy;\n}\n\n/**\n * The per-tool approval decision handed to the model SDK.\n *\n * semantic-literal-boundary: `'user-approval'` and `'denied'` are the model SDK's own\n * `ToolApprovalStatus` vocabulary, not Wildo's. This type is the thin adapter where they are\n * produced; they must not spread past {@link AgentsBackendService.buildToolApprovalConfiguration}.\n */\ntype ToolApprovalDecision = 'user-approval' | { type: 'denied'; reason: string };\n\n// ── Who may leave a gated call waiting for a person (#1611) ──\n// It is decided by ONE predicate,\n// `admitsDecisionSuspension` (saas-models, #1611), per tool, from the turn's principal, the door that\n// opened it and the route the tool's gate declares. It used to be an allow-list of one execution type\n// here (`USER_REQUEST`), which made every machine turn deny every gated call; the predicate keeps that\n// floor and admits exactly one more case — an organization machine whose turn was opened by the\n// autonomous entry point, pausing on a REVIEWER route (ROLE or ASSIGNEE), which a person in the\n// organization can answer.\n//\n// Why this stays an ALLOW-list inside the predicate rather than a deny-list of machines: the execution\n// vocabulary has nine members, and every case below is one where nobody can give the decision —\n//\n// - `ORGANIZATION_MACHINE` on an A2A turn, and `APPLICATION_MACHINE` — the caller is a machine waiting\n// for a reply, and nobody is routed its decisions;\n// - `INTERNALLY_INITIATED_REQUEST`, `WEBHOOK_CALLBACK`, `INBOUND_DELIVERY` — system-initiated; an\n// inbound-triggered turn that must ask goes through the autonomous entry point instead;\n// - `PUBLIC_EXECUTION`, `ANONYMOUS_SESSION` — no accountable identity, so no audit record of an approver;\n// - `CONSUMABLE_TOKEN` — a one-off credential not established to sustain a response channel.\n//\n// A deny-list would let the NEXT execution type inherit \"suspend\", and a principal that cannot answer\n// suspending is a turn waiting on a decision nobody is routed; the allow-list fails that closed.\n\n\n/**\n * Project only structural validation metadata from nested SDK/Zod errors.\n * Provider validation errors retain the rejected value in their message, so\n * logging `cause.message` would copy private model output into ordinary logs.\n * The one exception is a `custom` issue's message, which Zod never composes —\n * see {@link projectStructuredIssueRefinementMessage} for why that is the same\n * boundary rather than a hole in it.\n */\n/**\n * The TOP-LEVEL key names of a structured generation, for `unrecognized_keys` diagnosis only.\n *\n * Returns names, never values, and never recurses: a nested key could be a map keyed by user content,\n * whereas the root of a schema-driven generation is schema shape. Any parse failure yields nothing rather\n * than leaking a fragment of the raw text through an error message.\n */\nfunction projectStructuredRootKeyNames(text: unknown): readonly string[] | undefined {\n if (typeof text !== 'string' || text.length === 0) return undefined;\n try {\n const parsed: unknown = JSON.parse(text);\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined;\n return Object.keys(parsed).slice(0, 64);\n } catch {\n return undefined;\n }\n}\n\n/**\n * What one issue's SCHEMA expected — `expected`, `format`, `pattern`, `values` — read off the issue's own\n * fields and never off its message, which is where the rejected value lives. Each is schema shape: a type\n * name, a format name, the schema's regex, an enum's members. Without them a retry is told only WHERE it\n * failed, and on 2026-09-13 a model repeated the same `invalid_type` three times for want of \"array\".\n */\nfunction projectStructuredIssueExpectation(issue: object): {\n readonly expected?: string;\n readonly format?: string;\n readonly pattern?: string;\n readonly values?: readonly string[];\n} {\n const candidate = issue as { expected?: unknown; format?: unknown; pattern?: unknown; values?: unknown };\n const values = Array.isArray(candidate.values)\n ? candidate.values.filter((value) => ['string', 'number', 'boolean'].includes(typeof value)).map(String)\n : undefined;\n return {\n ...(typeof candidate.expected === 'string' ? { expected: candidate.expected } : {}),\n ...(typeof candidate.format === 'string' ? { format: candidate.format } : {}),\n ...(typeof candidate.pattern === 'string' ? { pattern: candidate.pattern } : {}),\n ...(values && values.length > 0 ? { values } : {}),\n };\n}\n\n/**\n * The authored message of a `custom` issue, and of NO OTHER CODE.\n *\n * `code: \"custom\"` is the one code Zod never raises by itself: it exists because a `.refine()` or\n * `.superRefine()` in this repository's own source called `addIssue`, so the message is the schema\n * author's sentence rather than Zod's rendering of the rejected value. That is what makes it safe to\n * carry under the same boundary as `expected` and `keys` — and it is the whole content the issue has,\n * since a cross-field refinement has no leaf schema to report an `expected` from.\n *\n * The code check is the guarantee, not a filter: widen it to any other code and this function starts\n * copying a message Zod composed around the input, which is the disclosure\n * {@link projectStructuredValidationIssues} exists to prevent.\n */\nfunction projectStructuredIssueRefinementMessage(code: string, issue: object): { readonly refinementMessage?: string } {\n if (code !== 'custom') return {};\n const message = (issue as { message?: unknown }).message;\n return typeof message === 'string' && message.length > 0 ? { refinementMessage: message } : {};\n}\n\nfunction projectStructuredValidationIssues(\n error: unknown,\n): ReadonlyArray<{\n readonly code: string;\n readonly path: readonly (string | number)[];\n readonly keys?: readonly string[];\n readonly expected?: string;\n readonly format?: string;\n readonly pattern?: string;\n readonly values?: readonly string[];\n readonly refinementMessage?: string;\n}> {\n let current = error;\n for (let depth = 0; depth < 4 && typeof current === 'object' && current !== null; depth += 1) {\n const record = current as { cause?: unknown; issues?: unknown };\n if (Array.isArray(record.issues)) {\n return record.issues.flatMap((issue) => {\n if (typeof issue !== 'object' || issue === null) return [];\n const candidate = issue as { code?: unknown; path?: unknown };\n if (typeof candidate.code !== 'string' || !Array.isArray(candidate.path)) return [];\n const path = candidate.path.filter((segment): segment is string | number => typeof segment === 'string' || typeof segment === 'number');\n // `unrecognized_keys` additionally carries the offending KEY NAMES, and those are projected. A key\n // a model invented against a strict object is schema shape, not model content -- the boundary this\n // function exists to hold is about VALUES, which are never included. Without the names the issue is\n // undiagnosable: it reports only that some unknown key exists at the root, which cost several live\n // runs on 2026-08-21 before the key could be identified any other way.\n const rawKeys = (issue as { keys?: unknown }).keys;\n const keys = Array.isArray(rawKeys)\n ? rawKeys.filter((key): key is string => typeof key === 'string')\n : undefined;\n return [{\n code: candidate.code,\n path,\n ...(keys && keys.length > 0 ? { keys } : {}),\n ...projectStructuredIssueExpectation(issue),\n ...projectStructuredIssueRefinementMessage(candidate.code, issue),\n }];\n });\n }\n current = record.cause;\n }\n return [];\n}\n\n/**\n * The agent frame one tool call runs in (#1595): which agent, in which conversational execution and\n * actors system, calling which tool. Identifiers only — never the call's arguments or a digest of them.\n *\n * `agentExecutionId` is absent when the agent was invoked outside any conversational execution (an\n * application calling `invokeAgent` with its own tool context): the frame names the agent it knows\n * rather than invent an execution. `decisionRef` names the human decision whose answer let this call run —\n * set on the tool context by the resume of an approval-gated turn (#1594), absent on every ordinary call.\n */\nfunction agentActorForToolCall(\n agent: FlowsActors_Agent,\n toolContext: FunctionToolExecutionContext | undefined,\n /** Absent for work the agent does outside any one tool call — MCP discovery at turn start. */\n toolName?: string,\n): AuditAgentActor {\n return {\n agentRef: agent.ref,\n ...(toolContext?.executionId ? { agentExecutionId: toolContext.executionId } : {}),\n ...(toolContext?.systemRef ? { systemRef: toolContext.systemRef } : {}),\n ...(toolName ? { toolName } : {}),\n ...(toolContext?.decisionRef ? { decisionRef: toolContext.decisionRef } : {}),\n };\n}\n\n/** One way of sending a structured call: the schema `generateObject` receives and the provider options beside it. */\ninterface PreparedStructuredOutputCall {\n /** The Zod schema as it is, or the strict JSON Schema validated through it. */\n readonly schema: z.ZodSchema<any> | ReturnType<typeof jsonSchema>;\n /** AI-SDK `providerOptions`, keyed by the SDK's provider id: OpenAI's strict flag, or a provider's declared path (#3146). */\n readonly providerOptions: { readonly providerOptions?: Readonly<Record<string, Readonly<Record<string, unknown>>>> };\n /**\n * Sent without the agent's reasoning setting (#3146): the call forces a tool, which a provider may refuse beside\n * manual extended thinking, and a forced tool call produces no reasoning anyway.\n */\n readonly withoutReasoning?: boolean;\n}\n\n/** The id of an AI-SDK language model (`LanguageModel.modelId`), or `undefined` for a model object that carries none. */\nfunction languageModelId(model: unknown): string | undefined {\n const modelId = (model as { modelId?: unknown } | null | undefined)?.modelId;\n return typeof modelId === 'string' ? modelId : undefined;\n}\n\n/** How a structured call is sent, strictly when it can be (#2344). See `prepareStructuredOutputSchema`. */\ninterface PreparedStructuredOutputSchema {\n /**\n * The CONSTRAINED call, tried first: the derived strict form for a provider that requests one, or the schema as it\n * is for a provider whose native constrained decoding admits it (#3146). Absent when there is none.\n */\n readonly strict: PreparedStructuredOutputCall | undefined;\n /**\n * The constrained call once more with the schema's validation-only keywords removed (#3204), tried when the provider\n * refused `strict` as too complex to compile, before `lax`. Present only for a provider whose native constrained\n * decoding has limits: there, giving up decoding-time patterns keeps the answer's shape, and giving up the grammar\n * entirely does not.\n */\n readonly relaxed?: PreparedStructuredOutputCall;\n /**\n * The schema as it is, unconstrained: strict mode off where the provider has an opinion, or the provider's declared\n * unconstrained path where its native decoding has limits. Sent when `strict` is absent or was refused. For a model\n * that admits no unconstrained path it is the relaxed constrained call, the only fallback that model accepts.\n */\n readonly lax: PreparedStructuredOutputCall;\n /** Set when `lax` is the relaxed constrained call (a model with no unconstrained path, #3204), so the log names it. */\n readonly laxIsRelaxedConstrained?: boolean;\n /** Whether the call that answered (or threw) decoded strictly. Cleared when a refusal falls back to `lax`. */\n decodedStrictly: boolean;\n /** A rejected answer's text in the ORIGINAL schema's shape, for a retry that patches it. */\n readonly restoreAnswerText: (text: string) => string;\n}\n\n@injectable()\nexport class AgentsBackendService {\n\n protected logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n // Bottleneck instances per provider for rate limiting LLM calls\n private readonly bottleneckInstances: Map<string, Bottleneck> = new Map();\n\n /** The installed language-model route and its own limiter, when a host installed one (#3472). */\n private languageModelRoute: { readonly route: LanguageModelAgentClientProtocolRoute; readonly limiter: Bottleneck } | undefined;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger) private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService) private readonly errorBuilder: ErrorBuilderBackendService,\n @inject(SAAS_SERVICE_TYPES.FlowsActorsRegistryService) private readonly flowsActorsRegistry: FlowsActorsRegistryService,\n @inject(SAAS_SERVICE_TYPES.ExternalProvidersRegistryService) private readonly externalProvidersRegistry: ExternalProvidersRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.BackendProviderRegistryService) private readonly backendProviderRegistryService: BackendProviderRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.PromptCompilerService) private readonly promptCompiler: PromptCompilerBackendService,\n @inject(SAAS_SERVICE_TYPES.AgentCallTraceSink) @optional() private readonly agentTraceSink?: AgentCallTraceSink,\n @inject(SAAS_SERVICE_TYPES.AgentTraceabilityPolicy) @optional() private readonly agentTracePolicy?: AgentTraceabilityPolicy,\n /**\n * OPTIONAL, because an application that declares no MCP server needs neither bound — and an\n * agent with no `mcpRefs` never reaches them. Absence degrades to \"this agent gets its\n * `functionRefs` and nothing else\", which is exactly what it got before #491.\n */\n @inject(SAAS_SERVICE_TYPES.McpClientService) @optional() private readonly mcpClient?: McpClientBackendService,\n @inject(SAAS_SERVICE_TYPES.McpCredentialResolverService) @optional() private readonly mcpCredentialResolver?: McpCredentialResolverBackendService,\n /**\n * OPTIONAL, and feature-detected at every emission. An audit sink that is absent must never fail\n * the act it was going to observe — the same stance the file-scanning lane takes, and the reason\n * an observation is fire-and-forget rather than awaited into the turn's critical path.\n */\n @inject(SAAS_SERVICE_TYPES.AuditLogsService) @optional() private readonly auditLogs?: AuditLogsBackendService,\n /**\n * OPTIONAL for the same reason: a host that binds no recorder still makes its calls. When bound, it\n * is called for EVERY physical call, before the traceability gate below (see\n * `ProviderCallRecorderBackendService` for why the record cannot share that gate).\n */\n @inject(SAAS_SERVICE_TYPES.ProviderCallRecorder) @optional() private readonly providerCallRecorder?: ProviderCallRecorderBackendService,\n /**\n * #2292: the classifier an agent declaring `contentGuardrails.promptInjection` screens its tool results through.\n * OPTIONAL like the two above, and appended LAST (DI positions are order-sensitive); an agent that declares\n * screening refuses to run without it.\n */\n @inject(SAAS_SERVICE_TYPES.ContentSafetyService) @optional() private readonly contentSafety?: ContentSafetyBackendService,\n /**\n * #2292 R8: reads the agent policy of each organization a turn acts for. OPTIONAL and appended LAST: a process\n * with no repository handler holds no tenant rows, so no organization can have tightened anything there.\n */\n @inject(SAAS_SERVICE_TYPES.RepositoriesRegistryHandlerService) @optional() private readonly repositoriesRegistry?: RepositoriesRegistryHandlerBackendService,\n /**\n * #2935: the model-spend meter every call this service makes is charged through, and asked before, when the work it\n * is made in pays per call (a flow's step). OPTIONAL and appended LAST: a host that binds no budget service (a minimal\n * test container) has no allowance to charge or enforce. The engine's own container binds it everywhere, the dev\n * companion's included; a companion call charges nothing because it is made for no organization (no frame, no\n * attribution).\n */\n @inject(SAAS_SERVICE_TYPES.A2ATokenBudgetService) @optional() private readonly modelSpend?: ModelCallSpendMeter,\n /**\n * Where the tool-approval key is read (#2893). OPTIONAL and appended LAST: without it no approval-gated tool can run,\n * which is the fail-closed answer {@link resolveToolApprovalSecretOrThrow} gives.\n */\n @inject(SAAS_SERVICE_TYPES.AppConfigService) @optional() private readonly appConfig?: AppConfigurationService,\n ) {\n this.logDebug = this.logger.debugByType('AgentsBackend');\n this.logger.setDebugTypeLogging('AgentsBackend', false);\n\n this.logDebug('Agents backend service created');\n }\n\n // ================================\n // Structured Data Chunking Utilities\n // ================================\n\n\n private mergeChunkedObjects<T extends Record<string, unknown>>(chunks: T[]): T {\n if (chunks.length === 0) {\n return {} as T;\n }\n if (chunks.length === 1) {\n return chunks[0];\n }\n\n // Deep merge nested objects instead of shallow merge\n const result = { ...chunks[0] } as any;\n\n for (let i = 1; i < chunks.length; i++) {\n const chunk = chunks[i];\n for (const key in chunk) {\n if (chunk.hasOwnProperty(key)) {\n const chunkValue = chunk[key];\n const resultValue = result[key];\n\n // If both values are plain objects, deep merge them\n if (\n chunkValue !== null &&\n typeof chunkValue === 'object' &&\n !Array.isArray(chunkValue) &&\n resultValue !== null &&\n typeof resultValue === 'object' &&\n !Array.isArray(resultValue) &&\n resultValue.constructor === Object &&\n chunkValue.constructor === Object\n ) {\n result[key] = this.mergeChunkedObjects([resultValue, chunkValue]);\n } else {\n // Otherwise, use the chunk value (last one wins for conflicts)\n result[key] = chunkValue;\n }\n }\n }\n }\n\n return result as T;\n }\n\n // ================================\n // Bottleneck Rate Limiting\n // ================================\n\n\n /**\n * Schedule `job` on a provider's limiter, running it in the async context of the CALLER that scheduled it (#2935 review).\n *\n * Bottleneck runs a job from inside its own submission and drain chain, so without the bind a job scheduled while\n * another job is in flight, queued or not, can inherit THAT caller's `AsyncLocalStorage` frames. Measured with the\n * engine's Bottleneck: with one slot, turn B's job queued behind turn A's ran with A's frames; with ten free slots\n * and no queueing at all, B scheduled within a millisecond of A still ran with A's frames. Every frame read inside a\n * model call leaked that way: the spend frame (B's nested agent would be charged to A's organization, and refused\n * under A's requester when A is a flow), the work-attribution frame (B's provider-call cost recorded against A's\n * case), the turn-policy frame (B's guardrails tightened, or loosened, by A's organizations), the agent-actor and\n * relationship-provenance frames, and a database session frame. The last four predate the spend frame; one bind fixes\n * them all. `AsyncResource.bind` captures the context at the call, so the job runs as its own caller whatever drains\n * it.\n */\n private scheduleOnLimiter<T>(limiter: Bottleneck, options: Bottleneck.JobOptions, job: () => Promise<T>): Promise<T> {\n return limiter.schedule(options, AsyncResource.bind(job));\n }\n\n private getBottleneckForProvider(\n providerRef: string,\n protocolKind: ExternalProvider_ExchangeProtocol_Kind = ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER\n ): Bottleneck {\n const limiterKey = `${providerRef}:${protocolKind}`;\n if (this.bottleneckInstances.has(limiterKey)) {\n const existingLimiter = this.bottleneckInstances.get(limiterKey)!;\n this.logDebug('Returning existing bottleneck instance for provider', { providerRef, protocolKind });\n return existingLimiter;\n }\n\n this.logDebug('Creating new bottleneck instance for provider', { providerRef, protocolKind });\n const config = this.externalProvidersRegistry.getProviderConfiguration(providerRef, protocolKind);\n\n const rateLimitConfig = config && 'rateLimitConfig' in config && config.rateLimitConfig\n ? ExternalProvider_RateLimitConfigurationSchema.parse(config.rateLimitConfig)\n : ExternalProvider_RateLimitConfigurationSchema.parse({});\n\n // Create bottleneck options\n const bottleneckOptions: Record<string, number | undefined> = {\n maxConcurrent: rateLimitConfig.maxConcurrent ?? 10,\n minTime: rateLimitConfig.minTime,\n reservoir: rateLimitConfig.reservoir,\n reservoirRefreshInterval: rateLimitConfig.reservoirRefreshInterval,\n reservoirRefreshAmount: rateLimitConfig.reservoirRefreshAmount,\n };\n\n // Remove undefined values\n Object.keys(bottleneckOptions).forEach(key => {\n if (bottleneckOptions[key] === undefined) {\n delete bottleneckOptions[key];\n }\n });\n\n // Create and store bottleneck instance\n const limiter = new Bottleneck(bottleneckOptions);\n\n // Add event listeners for rate limiting visibility\n this.setupBottleneckEventListeners(limiter, limiterKey);\n\n this.bottleneckInstances.set(limiterKey, limiter);\n\n this.logDebug('Bottleneck instance created for provider', {\n providerRef,\n protocolKind,\n maxConcurrent: bottleneckOptions.maxConcurrent,\n minTime: bottleneckOptions.minTime,\n reservoir: bottleneckOptions.reservoir\n });\n\n return limiter;\n }\n\n /**\n * Setup event listeners on bottleneck instance to track rate limiting behavior\n */\n private setupBottleneckEventListeners(limiter: Bottleneck, providerRef: string): void {\n // Track when jobs are queued (delayed due to rate limiting)\n limiter.on('queued', (info: any) => {\n const jobId = info?.options?.id || 'unknown';\n this.logDebug('API call queued (rate limited - will be delayed)', {\n providerRef,\n jobId,\n queued: limiter.queued(),\n running: limiter.running(),\n done: limiter.done(),\n });\n });\n\n // Track when jobs start running (immediate or after queuing)\n limiter.on('executing', (info: any) => {\n const jobId = info?.options?.id || 'unknown';\n this.logDebug('API call executing (running now)', {\n providerRef,\n jobId,\n queued: limiter.queued(),\n running: limiter.running(),\n done: limiter.done(),\n });\n });\n\n // Track when jobs complete\n limiter.on('done', (info: any) => {\n const jobId = info?.options?.id || 'unknown';\n this.logDebug('API call completed through rate limiter', {\n providerRef,\n jobId,\n queued: limiter.queued(),\n running: limiter.running(),\n done: limiter.done(),\n });\n });\n\n // Track when jobs are dropped (queue full or other reasons)\n limiter.on('dropped', (info: any) => {\n const jobId = info?.options?.id || 'unknown';\n this.logger.warn('API call dropped by rate limiter (queue full or limit exceeded)', {\n providerRef,\n jobId,\n queued: limiter.queued(),\n running: limiter.running(),\n });\n });\n\n // Track when reservoir is depleted\n limiter.on('depleted', () => {\n this.logDebug('Rate limiter reservoir depleted (waiting for refresh)', {\n providerRef,\n queued: limiter.queued(),\n running: limiter.running(),\n });\n });\n\n // Track errors in the limiter\n limiter.on('error', (error: any) => {\n this.logger.error('Rate limiter error', {\n providerRef,\n ...projectCaughtErrorLogFields(error),\n stack: error instanceof Error ? error.stack : undefined,\n });\n });\n }\n\n // ================================\n // Agent Invocation\n // ================================\n\n /**\n * @wildo_source:part:start saas.backend.flows-actors.invoke-agent facet:layer:backend facet:family:flows-actors\n *\n * Run ONE agent, once, and await its complete answer. This is the seam an\n * application calls to use its `AI_LLM` capability from its own backend code\n * (a service, a custom resource operation, a batch job).\n *\n * Inject it by DI symbol:\n * `@inject(SAAS_SERVICE_TYPES.AgentsBackendService) private readonly agentsService: AgentsBackendService`\n * — import both from `@wildo-ai/saas-backend-lib`.\n *\n * The engine owns everything around the call: it resolves the agent by\n * `request.agentRef` (unknown ref → throws), refuses a non-`ACTIVE` agent,\n * compiles `promptSpec` into a provider-shaped system prompt, resolves the\n * provider client + API key (fail-closed if unconfigured), schedules the call\n * through that provider's rate limiter, normalizes the output to the\n * operation's wrapped shape, and emits the usage/latency trace. You supply an\n * invocation and read `result.output`.\n *\n * **Function tools do NOT run on this path.** An agent's declared\n * `capabilities.tools.functionRefs` are resolved and executed only by the\n * STREAMING/conversational path ({@link invokeAgentStreaming}). A one-shot\n * agent must therefore receive everything it needs in `request.input` — fetch\n * the data yourself first. Declaring tools here is silently inert, not an error.\n *\n * @param request the invocation envelope (`agentRef` + `input` + empty `output` seed).\n * @param traceContext optional correlation for the agent-call trace sink.\n * @param hostContext backend-owned physical execution context, required only\n * once the selected declared transport is CLI.\n * @returns the same envelope with `output` normalized and `executionContext` enriched.\n * @throws a typed backend error — unknown/inactive agent, an agent an administrator suspended (`AGENT_SUSPENDED`, a\n * CONFLICT, read back with `agentSuspensionRefusalOf`, #2843), missing provider key,\n * missing `input.schema` on a structured call, or a provider failure. A provider failure\n * delivered on a STREAMED operation (`STREAM_TEXT`, `STREAM_STRUCTURED`) throws\n * `AgentModelCallFailedError` instead (exported from `@wildo-ai/saas-backend-lib`, not a\n * backend error: test it with `instanceof`), carrying the provider's error, its HTTP\n * `statusCode` when it refused, and the `usage` of the steps that finished first. Inside a flow run, or\n * outside any turn or flow for work attributed to an organization (your own operation or handler, #2957), a\n * `FEATURE_LIMIT_EXCEEDED` backend error when the organization's model allowance is spent, or `INFRASTRUCTURE`\n * when it cannot be checked, before the model is called (#2935).\n *\n * Every call is charged to the model allowance of the work it is made in (#2935): the conversational turn or flow\n * run around it, else the organization its work is attributed to, whose allowance is also asked before the call\n * (#2957). A call whose provider reported no usage is charged an estimate. Application code needs to do nothing for\n * this, except pass `attribution` when its work is attributed to no organization otherwise.\n */\n public async invokeAgent(\n request: FlowsActors_Agent_Invocation<any, any, any>,\n traceContext?: AgentTraceContext,\n hostContext?: AgentInvocationHostContext,\n ): Promise<FlowsActors_Agent_Invocation<any, any, any>> {\n /** @wildo_source:part:end saas.backend.flows-actors.invoke-agent */\n const startTime = Date.now();\n const callTimestamp = new Date(startTime).toISOString();\n\n this.logDebug('Invoking agent', { agentRef: request.agentRef,hasInput: !!request.input,hasExecutionContext: !!request.executionContext });\n\n const agent = this.flowsActorsRegistry.getAgentOrThrow(request.agentRef);\n\n const organizationScope = await this.buildCallOrganizationScope(request.initiator?.organizationId, traceContext?.attribution);\n await this.validateAgentStatus(agent, organizationScope);\n await this.admitModelSpend(request.agentRef, traceContext);\n\n try {\n const result = await this.executeAgent(agent, request, organizationScope, hostContext);\n this.logDebug('Agent invocation completed', {agentRef: request.agentRef,executionTime: Date.now() - startTime,hasOutput: !!result.output });\n return await this.finalizeInvocationSuccess(request, agent, result, startTime, callTimestamp, traceContext);\n } catch (error) {\n await this.traceInvocationFailure(request, agent, error, startTime, callTimestamp, traceContext);\n throw error;\n }\n }\n\n /**\n * Streaming counterpart of {@link invokeAgent}: runs the agent over the API\n * transport and forwards each token delta through `streamHandlers.onDelta` as\n * it arrives (honest token streaming — no buffer-collapse). The returned\n * invocation carries the fully-assembled, normalized output + enriched\n * `executionContext`, identical in shape to `invokeAgent`, so persistence and\n * tracing are unchanged.\n *\n * Only text-producing operations over the API transport stream. CLI-transport\n * agents and non-text operations (structured / multimodal / image) throw\n * {@link AgentStreamingUnsupportedError}; callers may catch it to fall back to\n * the buffered `invokeAgent`.\n */\n public async invokeAgentStreaming(\n request: FlowsActors_Agent_Invocation<any, any, any>,\n streamHandlers: AgentStreamHandlers,\n toolContext?: FunctionToolExecutionContext,\n traceContext?: AgentTraceContext,\n ): Promise<FlowsActors_Agent_Invocation<any, any, any>> {\n const startTime = Date.now();\n const callTimestamp = new Date(startTime).toISOString();\n\n this.logDebug('Invoking agent (streaming)', { agentRef: request.agentRef, hasToolContext: !!toolContext });\n\n const agent = this.flowsActorsRegistry.getAgentOrThrow(request.agentRef);\n // The organizations the turn works for, the same scope its guardrails are tightened for (`executeAgentStreaming`).\n const organizationScope = await this.buildStreamingCallOrganizationScope(toolContext, request.initiator?.organizationId, traceContext?.attribution);\n await this.validateAgentStatus(agent, organizationScope);\n await this.admitModelSpend(request.agentRef, traceContext);\n\n try {\n const result = await this.executeAgentStreaming(agent, request, streamHandlers, organizationScope, toolContext);\n this.logDebug('Agent streaming invocation completed', { agentRef: request.agentRef, executionTime: Date.now() - startTime });\n return await this.finalizeInvocationSuccess(request, agent, result, startTime, callTimestamp, traceContext);\n } catch (error) {\n await this.traceInvocationFailure(request, agent, error, startTime, callTimestamp, traceContext);\n throw error;\n }\n }\n\n /**\n * A structured answer from ANOTHER agent's provider and model, under instructions of the engine's own (#2720).\n *\n * Some engine steps serve an agent's turn without being that agent: composing the form through which a question the\n * agent raised is asked of a person is one. Such a step runs on the agent's provider and resolved model, because the\n * provider key and the spend are what the application chose for that agent. Its usage is recorded against the\n * work-attribution frame it runs in, so the CALLER runs it inside the frame of the work it serves: the composer's\n * caller re-opens the paused turn's frame (`runWithWorkAttributionFrame`). It has its own instructions and no tools.\n *\n * Nothing is registered. The derived agent exists for this one call, under a ref that says whose model it borrowed\n * (`<agentRef>#<purpose>`), so the trace names it and the application's agent catalog never lists it.\n *\n * Only an LLM agent on the API transport can serve: a coding agent, an image agent and a CLI transport have no\n * structured call. The error says so, and the caller's own fallback decides what happens next.\n *\n * @returns the object the provider produced, re-parsed with `schema`.\n */\n public async generateStructuredOnAgentModel<T extends z.ZodTypeAny>(params: {\n /** The agent whose provider and model the call borrows. */\n agentRef: string;\n /** What the call is for, appended to the derived agent's ref and named in its trace. */\n purpose: string;\n /** The derived agent's role, in place of the borrowed agent's own. */\n role: string;\n instructions: readonly string[];\n prompt: string;\n schema: T;\n traceContext?: AgentTraceContext;\n }): Promise<z.infer<T>> {\n const agent = this.flowsActorsRegistry.getAgentOrThrow(params.agentRef);\n // The organizations the call works for (`buildCallOrganizationScope`): the explicit attribution's, the work frame's, the\n // case's tenant, and the run's requester's. A flow's `agent.call` step names none itself; its run's organization comes\n // from its spend frame. The borrowed agent's suspensions are asked for each (#2843), the call is made for the first,\n // so its guardrails are that organization's and an output-moderation row it leaves is routed there (#2292).\n // Engine-derived throughout, never a caller's.\n const organizationScope = await this.buildCallOrganizationScope(params.traceContext?.attribution?.organizationId, params.traceContext?.attribution);\n await this.validateAgentStatus(agent, organizationScope);\n if (!isLLMAgentConfiguration(agent.config)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: { agentRef: agent.ref, message: 'Only a language-model agent can serve a structured call on its model.' },\n });\n }\n const derived: FlowsActors_Agent = {\n ...agent,\n ref: `${agent.ref}#${params.purpose}`,\n config: { ...agent.config, operationKey: LLMProvider_OperationKey.GENERATE_STRUCTURED },\n operationDefinition: {\n ...agent.operationDefinition,\n operationKey: LLMProvider_OperationKey.GENERATE_STRUCTURED,\n inputSchema: LLMProvider_GenerateStructuredInputSchema,\n outputSchema: LLMProvider_GenerateStructuredOutputSchema,\n },\n promptSpec: { role: params.role, skillType: FlowsActors_Agent_Skill_Type.GENERATION, instructions: [...params.instructions] },\n capabilities: undefined,\n } as FlowsActors_Agent;\n if (this.resolveAgentExecution(derived).transport !== 'api') {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: { agentRef: agent.ref, message: 'A structured call needs the agent to run on the API transport.' },\n });\n }\n await this.admitModelSpend(derived.ref, params.traceContext);\n\n const startTime = Date.now();\n const callTimestamp = new Date(startTime).toISOString();\n const request = {\n agentRef: derived.ref,\n initiator: organizationScope.organizationId ? { organizationId: organizationScope.organizationId } : {},\n invocationContext: [],\n input: { prompt: params.prompt, schema: params.schema },\n output: { object: {} },\n executionContext: { callTimestamp },\n artifactBindings: [],\n } as unknown as FlowsActors_Agent_Invocation<any, any, any>;\n try {\n const result = await this.executeAgent(derived, request, organizationScope);\n const finalized = await this.finalizeInvocationSuccess(request, derived, result, startTime, callTimestamp, params.traceContext);\n return params.schema.parse((finalized.output as { object: unknown }).object) as z.infer<T>;\n } catch (error) {\n await this.traceInvocationFailure(request, derived, error, startTime, callTimestamp, params.traceContext);\n throw error;\n }\n }\n\n /**\n * Shared success finalizer for buffered + streaming invocations: enrich the\n * execution context (timing / usage / transport), normalize the output for the\n * agent's operation, and emit the best-effort policy-gated success trace. Every\n * caller of invokeAgent* — companion, backend flows, minions, workers — gets\n * the trace for free; the sink decides where it lands. See\n * `agent-call-trace-sink.backend.ts`.\n */\n private async finalizeInvocationSuccess(\n request: FlowsActors_Agent_Invocation<any, any, any>,\n agent: FlowsActors_Agent,\n result: AgentExecutionResult,\n startTime: number,\n callTimestamp: string,\n traceContext?: AgentTraceContext,\n ): Promise<FlowsActors_Agent_Invocation<any, any, any>> {\n const executionTime = Date.now() - startTime;\n const finishedAt = new Date().toISOString();\n const executionContext = {\n ...request.executionContext,\n callDuration: executionTime,\n executionTime,\n finishedAt,\n // Parsed by the envelope actually received. A coding run reports context\n // and cost the LLM usage schema does not model, and an ACP transport\n // record is not a member of the LLM transport union — running either\n // through the LLM schemas throws, and it throws AFTER the workspace has\n // been mutated.\n ...(result.usage\n ? {\n usage: isAgentClientProtocolTransport(result.transport)\n ? CodingAgent_UsageSchema.parse(result.usage)\n : LLMProvider_UsageSchema.parse(result.usage),\n }\n : {}),\n ...(result.transport\n ? {\n transport: isAgentClientProtocolTransport(result.transport)\n ? AgentClientProtocol_ExecutionTransportMetadataSchema.parse(result.transport)\n : LLMProvider_ExecutionTransportMetadataSchema.parse(result.transport),\n }\n : {}),\n // A structured generation that produced no object carries the reason it did not.\n // It rides on `executionContext` beside `usage` because that is the envelope the\n // whole invocation contract already publishes for provider-learned facts — and\n // because the trace sink receives this same object as its `context`, so the reason\n // reaches traceability without a second wiring. Parsed rather than spread so a\n // malformed reason cannot silently enter the published contract.\n ...(result.structuredGenerationFailure\n ? { structuredGenerationFailure: LLMProvider_StructuredGenerationFailureSchema.parse(result.structuredGenerationFailure) }\n : {}),\n // #2301: each hand-over of a model call to a declared alternative (who failed, who served, why). It reaches the trace\n // sink with this context; the provider-call record below names the provider and model that answered.\n ...(result.modelFailovers && result.modelFailovers.length > 0 ? { modelFailovers: result.modelFailovers.map((failover) => ({ ...failover })) } : {}),\n };\n const output = this.normalizeOperationOutput(agent.config.operationKey, result.output);\n const servedBy = result.modelFailovers?.at(-1);\n await this.emitAgentCallTrace(\n {\n agentRef: request.agentRef,\n provider: servedBy?.toProviderRef ?? agent.config.providerRef,\n model: servedBy?.toModel ?? agent.config.model,\n callTimestamp,\n outcome: AgentCallOutcome.SUCCESS,\n input: request.input,\n output,\n context: executionContext,\n ...this.personalDataTraceOf(request),\n },\n traceContext,\n this.operationObservationOf(request).snapshot({ failed: false, awaitingDecision: result.approvalSuspension !== undefined }),\n );\n // Carry the approval suspension onto the returned invocation.\n //\n // ⚠️ This method REBUILDS the result rather than spreading it, so anything the execution layer\n // learned that is not `output`/`executionContext` is dropped here by construction. That is what\n // happened to the suspension: it was threaded correctly through the stream reader, the operation\n // and the transport, and then silently lost at this fifth hop — the turn reported COMPLETED with\n // empty text while the tool sat unapproved, which is exactly the outcome the whole feature\n // exists to prevent. The unit pins could not see it because they stub `invokeAgentStreaming` and\n // never reach this method; only the live lane did.\n //\n // Deliberately kept as an explicit field rather than switching to `...result`: this rebuild is\n // intentional (the invocation is the caller's request plus its answer, not the internal\n // execution record), and spreading would leak transport internals onto a public shape.\n return { ...request, output, executionContext, ...(result.approvalSuspension ? { approvalSuspension: result.approvalSuspension } : {}) };\n }\n\n /** Shared failure tracer for buffered + streaming invocations. */\n private async traceInvocationFailure(\n request: FlowsActors_Agent_Invocation<any, any, any>,\n agent: FlowsActors_Agent,\n error: unknown,\n startTime: number,\n callTimestamp: string,\n traceContext?: AgentTraceContext,\n ): Promise<void> {\n await this.emitAgentCallTrace(\n {\n agentRef: request.agentRef,\n provider: agent.config.providerRef,\n model: agent.config.model,\n callTimestamp,\n outcome: AgentCallOutcome.FAILURE,\n input: request.input,\n context: {\n ...request.executionContext,\n executionTime: Date.now() - startTime,\n // A provider failure after finished steps still cost tokens, and the provider-call record\n // prices what the trace carries (#2191). Absent for every other failure, as before.\n ...(modelCallUsageOfFailure(error) ? { usage: LLMProvider_UsageSchema.parse(modelCallUsageOfFailure(error)) } : {}),\n },\n error: this.buildAgentCallTraceError(error),\n ...this.personalDataTraceOf(request),\n },\n traceContext,\n this.operationObservationOf(request).snapshot({ failed: true, error }),\n );\n }\n\n /**\n * #2292: the guard each invocation's tools treated through, by the invocation's request object, so its counts reach the\n * trace on success AND on failure (a failed call still sent its model what the guard let through). Module-level and\n * read through a getter: it holds no state of this instance, and a service built without its constructor reaches it.\n */\n private get personalDataGuards(): WeakMap<object, PersonalDataGuard> {\n return PERSONAL_DATA_GUARD_BY_INVOCATION;\n }\n\n /** #2292: what a call's model was not sent in clear, as its trace carries it; nothing for an unguarded call. */\n private personalDataTraceOf(request: object): { personalData?: AgentCallTrace['personalData'] } {\n const guard = this.personalDataGuards.get(request);\n if (!guard) return {};\n const categories = Object.keys(guard.counts.byCategory).filter((category) => category.length > 0) as PersonalDataCategory[];\n return { personalData: { treatment: guard.treatment, fieldsWithheld: guard.counts.fields, categoriesWithheld: [...sortPersonalDataCategories(categories)] } };\n }\n\n /**\n * #2841: what this invocation is observed doing, for its operation record — created on first use, by the invocation's\n * request object, like its personal-data guard, so every hop that already holds the request (the guards' construction,\n * the stream, the trace emitter) reads the same observation without a new positional argument.\n */\n private operationObservationOf(request: object): AgentOperationObservationRecorder {\n let observation = AGENT_OPERATION_OBSERVATION_BY_INVOCATION.get(request);\n if (!observation) {\n observation = new AgentOperationObservationRecorder();\n AGENT_OPERATION_OBSERVATION_BY_INVOCATION.set(request, observation);\n }\n return observation;\n }\n\n /**\n * #2841: the model the call runs on, wrapped INNERMOST with the observation's middleware, which reads the model id the\n * provider reports from each response. Innermost so a response output moderation withholds still reports its model.\n */\n private observedModel(model: any, observation: AgentOperationObservationRecorder | undefined): any {\n if (!observation) return model;\n return wrapLanguageModel({ model, middleware: observation.middleware() });\n }\n\n /**\n * #2935: ask the model-spend gate before a call, as the payer of the work it is made in (the ambient spend frame). Only\n * a payer whose door is asked per call (a flow's step) can be refused; the refusal is recorded by the gate, and the\n * call fails here with the budget's error, BEFORE anything reaches the provider and before a trace exists (a refused\n * call was not a provider call, so it leaves no provider-call record).\n *\n * #2957: with NO payer (a call an application's own code makes in no turn, no flow and no operation: an inbound\n * handler, a job), the gate is asked for the organization the call would be charged to\n * ({@link organizationOfAttributedWork}, the derivation {@link chargeModelCall} uses), through the door\n * `organization_work`. So the allowance that refuses is the allowance that would have been charged, and an organization\n * whose allowance is spent cannot keep spending through its application's own backend code. A call attributed to no\n * organization, outside any operation, is asked nothing and charged nothing: it is the host's own spend (the dev\n * companion, platform tooling).\n *\n * #2957: a call made inside a RESOURCE OPERATION has the operation's principal as its payer (`resource_operation`, opened\n * by the services registry). That door falls back to the work the call was made for\n * (`modelSpendDoorPayerFallsBackToAttributedWork`), so the work's organization is derived for it too and handed to the\n * gate, which charges and refuses the principal's own allowance, else that organization's, else the application's, and\n * refuses a call none of them can pay for.\n *\n * - spent: `FEATURE_LIMIT_EXCEEDED` (HTTP 403, the plan-limit error), naming the limit and its counts;\n * - not verifiable (the plan or the counter could not be read): `INFRASTRUCTURE` (503, retryable), as the A2A door\n * answers an unverifiable allowance;\n * - no allowance can be named (`PAYER_UNRESOLVED`): `CONFIGURATION`, because the application made a model call from an\n * operation whose principal, work and application pay for nothing. Its remedy is the call site's: name the\n * organization the work is for (`traceContext.attribution`), or run it as a principal that pays.\n *\n * assurance-control: WILDO.AI.MODEL_SPEND_LIMIT — a model call made in work whose door is asked per call (a flow's step), or made in no turn and no flow for an organization, is refused before the model runs once its organization's allowance is spent or unverifiable.\n */\n private async admitModelSpend(agentRef: string, traceContext: AgentTraceContext | undefined): Promise<void> {\n if (!this.modelSpend) return;\n const payer = getCurrentModelSpendFrame();\n const decision = payer && !modelSpendDoorPayerFallsBackToAttributedWork(payer.door)\n ? await this.modelSpend.admitModelCall(payer)\n : await this.modelSpend.admitModelCall(payer, await this.organizationOfAttributedWork(traceContext));\n if (decision.kind === 'ok') return;\n if (decision.reason === A2ATokenBudgetDenialReason.PAYER_UNRESOLVED) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n featureId: A2A_TOKEN_BUDGET_FEATURE_ID,\n reason: decision.reason,\n door: payer?.door ?? ModelSpendDoor.ORGANIZATION_WORK,\n agentRef,\n modelSpendRefusalReason: decision.reason,\n message: 'This model call was made from an operation whose principal, work and application name no model allowance, so the model was not called. Name the organization the work is for in the call\\'s attribution, or make the call as a principal that pays.',\n },\n });\n }\n const spent = decision.reason === A2ATokenBudgetDenialReason.ALLOWANCE_EXHAUSTED;\n throw this.errorBuilder.buildError(spent ? ErrorType.FEATURE_LIMIT_EXCEEDED : ErrorType.INFRASTRUCTURE, undefined, {\n customMessageReference: spent ? ErrorCustomMessageReference.FEATURE_LIMIT_EXCEEDED : ErrorCustomMessageReference.INFRASTRUCTURE,\n context: {\n featureId: A2A_TOKEN_BUDGET_FEATURE_ID,\n reason: decision.reason,\n door: payer?.door ?? ModelSpendDoor.ORGANIZATION_WORK,\n agentRef,\n // Read back by `modelSpendRefusalOf`, so a caller (a flow's step) can tell a spend refusal from a provider failure.\n modelSpendRefusalReason: decision.reason,\n ...(typeof decision.allowanceTokens === 'number' ? { allowanceTokens: decision.allowanceTokens } : {}),\n ...(typeof decision.consumedTokens === 'number' ? { consumedTokens: decision.consumedTokens } : {}),\n message: spent\n ? 'The organization\\'s model allowance for this period is spent, so the model was not called.'\n : 'The organization\\'s model allowance could not be checked, so the model was not called.',\n },\n });\n }\n\n /**\n * #2957: the organization a call's WORK is attributed to, read before the call, for a call with no payer or a payer\n * whose door falls back to its work (a resource operation): the call site's explicit attribution, else the ambient\n * work frame (`resolveModelCallAttribution`), with a named work-unit case's own tenant winning\n * (`ProviderCallRecorderBackendService.organizationOfAttribution`, which never throws). The same derivation\n * {@link chargeModelCall} makes after the call, so the allowance asked and the allowance charged cannot differ.\n * `undefined` when the call is attributed to no organization.\n */\n private async organizationOfAttributedWork(traceContext: AgentTraceContext | undefined): Promise<string | undefined> {\n const attribution = resolveModelCallAttribution(traceContext?.attribution, getCurrentWorkAttributionFrame()).attribution;\n if (!attribution.caseRef || !this.providerCallRecorder) return attribution.organizationId;\n return this.providerCallRecorder.organizationOfAttribution(attribution);\n }\n\n /**\n * #2935: charge one model call to the payer of the work it was made in: the spend frame (a turn's or a flow run's door\n * and principal), else the organization the call's cost record names (the call site's explicit attribution, else the\n * ambient work frame, with a named work-unit case's own tenant winning, as the provider-call recorder derives it), else\n * nobody (a call made for no organization). The ONE place a model call's tokens reach an\n * allowance, for every entry point of this service, on success and on failure.\n *\n * The tokens are the provider's reported total, else the sum of the counters it reported, else a coding transport's\n * `contextUsed` (a lower bound). A successful call whose report the provider marked incomplete is charged the larger\n * of what it reported and the estimate. A call that SUCCEEDED and reported none is charged an estimate from what it\n * sent and returned (`estimateModelCallTokens`, decided at that module): never nothing, never refused. A call\n * that FAILED and reported none is charged nothing: the provider answered with an error before any step finished, and\n * a provider does not bill a request it refused. A failure after finished steps carries their usage, and is charged it.\n *\n * Never throws: metering must not fail a call that already ran.\n *\n * assurance-control: WILDO.AI.MODEL_SPEND_LIMIT — every model call the agent service makes is charged to the allowance of the work it was made in, a call that reported no usage at an estimate.\n */\n private chargeModelCall(trace: AgentCallTrace, traceContext: AgentTraceContext | undefined): void {\n const meter = this.modelSpend;\n if (!meter) return;\n try {\n const reportedTokens = reportedModelCallTokens(trace.context);\n const succeeded = trace.outcome === AgentCallOutcome.SUCCESS;\n // A call that succeeded ran, so it is charged at least one token even when it sent and returned nothing readable.\n const estimateOf = (): number => Math.max(1, estimateModelCallTokens(trace.input, trace.output));\n // No report: the estimate. A report the provider marked incomplete (an image model counting its input, not its\n // output): the larger of the two, so a partial count is never the whole charge.\n const estimated = succeeded && (reportedTokens === undefined || modelCallUsageIsPartial(trace.context));\n const totalTokens = reportedTokens === undefined\n ? (succeeded ? estimateOf() : 0)\n : (estimated ? Math.max(reportedTokens, estimateOf()) : reportedTokens);\n if (!(totalTokens > 0)) return;\n // Read synchronously: the frames belong to the call being charged.\n const payer = getCurrentModelSpendFrame();\n const attribution = resolveModelCallAttribution(traceContext?.attribution, getCurrentWorkAttributionFrame()).attribution;\n const charge = (attributedOrganizationId: string | undefined): void => meter.recordModelCallSpend({\n payer, attributedOrganizationId, totalTokens, estimated, agentRef: trace.agentRef,\n });\n // With no payer, or a payer whose door falls back to its work (#2957: a resource operation), the organization is the\n // one the call's cost record names: a named case's own tenant wins over the frame's\n // (`ProviderCallRecorderBackendService.organizationOfAttribution`, the recorder's own derivation). A work unit's\n // operation frame carries the case and no tenant, so without this the call would be charged to nobody.\n // `organizationOfAttributedWork` is the same derivation, asked before the call (#2957).\n const chargedFromWork = !payer || modelSpendDoorPayerFallsBackToAttributedWork(payer.door);\n if (!chargedFromWork || !attribution.caseRef || !this.providerCallRecorder) {\n charge(attribution.organizationId);\n return;\n }\n void this.providerCallRecorder.organizationOfAttribution(attribution).then(charge, (error: unknown) => {\n this.logger.warn('A model call could not be charged to its allowance (non-fatal)', { agentRef: trace.agentRef, ...projectCaughtErrorLogFields(error) });\n });\n } catch (error) {\n this.logger.warn('A model call could not be charged to its allowance (non-fatal)', { agentRef: trace.agentRef, ...projectCaughtErrorLogFields(error) });\n }\n }\n\n /**\n * Emit one agent-call trace to the configured sink — best-effort and gated by\n * the resolved policy level (per-call `levelOverride` wins; default `NONE` →\n * skip, so output is byte-identical when traceability is off). A sink failure\n * is swallowed (debug-logged): tracing must never turn a successful agent call\n * into a failed one.\n */\n private async emitAgentCallTrace(\n trace: AgentCallTrace,\n traceContext?: AgentTraceContext,\n /** #2841: what the invocation was observed doing, for its operation record beside the provider-call record. */\n operation?: AgentOperationObservation,\n ): Promise<void> {\n // #2935: the call's spend, synchronously and before any await, so it reads the frames of the call it is charging.\n this.chargeModelCall(trace, traceContext);\n // The provider-call RECORD first, ungated: evidence of the call must not depend on whether an\n // observability provider raised the traceability level. The recorder never throws. Its attribution\n // (#1598) is the call site's explicit `traceContext.attribution`, else the ambient work frame. The operation\n // (#2841) is not part of the trace: sinks receive the trace as before, and only the recorder's store receives it.\n // assurance-control: WILDO.AI.OPERATION_RECORD — the invocation's observation reaches the recorder (when the container\n // binds one) on success and on failure, before and whatever the traceability level.\n await this.providerCallRecorder?.record(trace, traceContext?.attribution ? { attribution: traceContext.attribution } : undefined, operation);\n const sink = this.agentTraceSink;\n if (!sink) {\n return;\n }\n const level = traceContext?.levelOverride ?? this.agentTracePolicy?.level ?? AgentTraceabilityLevel.NONE;\n if (level === AgentTraceabilityLevel.NONE) {\n return;\n }\n try {\n await sink.recordAgentCall({ trace, level, context: traceContext });\n } catch (err) {\n this.logDebug('Agent-call trace sink failed (non-fatal)', {\n agentRef: trace.agentRef,\n ...projectCaughtErrorLogFields(err),\n });\n }\n }\n\n /** Build the JSON-serializable trace error shape from a thrown value. */\n private buildAgentCallTraceError(error: unknown): AgentCallTraceError {\n if (error instanceof Error) {\n const code = (error as Error & { code?: string }).code;\n return {\n name: error.name,\n message: error.message,\n ...(code ? { code } : {}),\n };\n }\n // A non-Error, non-string throw still carries information — a JSON-RPC error object, a refusal\n // shape. Serialize it (bounded) rather than replacing it with a sentence that says nothing.\n if (typeof error === 'string') return { message: error };\n try {\n const serialized = JSON.stringify(error);\n if (serialized && serialized !== '{}') return { message: `Non-Error thrown: ${serialized.slice(0, 500)}` };\n } catch { /* circular or hostile — fall through to the sentinel */ }\n return { message: 'Unknown agent invocation error' };\n }\n\n /**\n * Normalize executor outputs to the shared transport-neutral LLM contract.\n *\n * The current execution helpers naturally produce provider/raw payloads such as\n * plain strings or plain objects. Downstream consumers, however, already rely on\n * the wrapped shared schemas (`{ text }`, `{ object }`, `{ message }`, etc.).\n * Centralizing the normalization here fixes the runtime boundary once instead of\n * forcing every caller to guess the provider-shaped payload.\n */\n private normalizeOperationOutput(\n operationKey: LLMProvider_OperationKey | ImageProvider_OperationKey | CodingAgent_OperationKey,\n output: unknown,\n ): unknown {\n // Image outputs (`{ images }`) are already shaped by executeImageAgent, and\n // coding outputs (`{ finalMessage, stopReason, … }`) by the ACP executor —\n // both are produced in their published shape rather than as a raw provider\n // payload, so both fall through the `default` arm unchanged. Only the LLM\n // arms need wrapping, because only they receive a bare string or object.\n switch (operationKey) {\n case LLMProvider_OperationKey.GENERATE_TEXT:\n if (this.isRecord(output) && typeof output.text === 'string') {\n return output;\n }\n return { text: typeof output === 'string' ? output : JSON.stringify(output ?? '') };\n\n case LLMProvider_OperationKey.CHAT_COMPLETION:\n case LLMProvider_OperationKey.CHAT_MULTIMODAL:\n if (this.isRecord(output) && this.isRecord(output.message)) {\n return output;\n }\n return {\n message: {\n role: LLMProvider_MessageRole.ASSISTANT,\n content: typeof output === 'string' ? output : JSON.stringify(output ?? ''),\n },\n };\n\n case LLMProvider_OperationKey.GENERATE_STRUCTURED:\n if (this.isRecord(output) && 'object' in output) {\n return output;\n }\n return { object: output };\n\n case LLMProvider_OperationKey.STREAM_TEXT:\n if (this.isRecord(output) && typeof output.textDelta === 'string') {\n return output;\n }\n return { textDelta: typeof output === 'string' ? output : JSON.stringify(output ?? '') };\n\n case LLMProvider_OperationKey.STREAM_STRUCTURED:\n if (this.isRecord(output) && ('object' in output || 'partialObject' in output)) {\n return output;\n }\n return { object: output };\n\n default:\n return output;\n }\n }\n\n private isRecord(value: unknown): value is Record<string, any> {\n return typeof value === 'object' && value !== null;\n }\n\n /**\n * Execute agent with LLM provider using @ai-sdk\n */\n private async executeAgent(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n /** The organizations the call works for, as its entry point derived them for its admission. */\n organizationScope: ModelCallOrganizationScope,\n hostContext?: AgentInvocationHostContext,\n ): Promise<AgentExecutionResult> {\n this.logDebug('Executing agent', {\n agentRef: agent.ref,\n operationKey: agent.config.operationKey,\n providerRef: agent.config.providerRef,\n model: agent.config.model,\n executionProfileRef: agent.config.executionProfileRef,\n });\n\n // Modality dispatch: an image agent routes to the IMAGE_PROVIDER path.\n // AUDIO/VIDEO modalities are reserved — their configs have no arm yet, so\n // they cannot reach here; if one ever does, `executeImageAgent`'s provider\n // resolution fail-closes. The LLM/text + CLI path below is unchanged.\n if (isImageAgentConfiguration(agent.config)) {\n return this.executeImageAgent(agent, request);\n }\n\n // A coding agent routes to the ACP session transport. It produces no\n // artifact modality — its product is a changed workspace — so it is\n // dispatched by its own arm rather than by an artifact-modality branch.\n if (isCodingAgentConfiguration(agent.config)) {\n return this.executeAgentViaACP(agent, request, hostContext);\n }\n\n const execution = this.resolveAgentExecution(agent);\n\n if (execution.transport === 'acp') {\n // Unreachable in practice: a coding agent is dispatched by its arm above,\n // before prompts are compiled. Kept so the transport union is handled\n // exhaustively here rather than falling into the API branch, which is\n // what an unhandled member would silently do. It compiles its own prompts.\n return this.executeAgentViaACP(agent, request, hostContext);\n }\n\n // #2292 R8: the guardrails as the organizations this call works for tightened them: the scope its admission was asked\n // for, so a call is tightened by exactly the organizations whose suspensions it answered to.\n const guarded = await this.agentUnderTurnPolicies(agent, organizationScope);\n const outputModeration = this.outputModerationGuardOf(guarded, { initiator: request.initiator, observation: this.operationObservationOf(request) });\n // Compiled once the route is decided, because the route decides how a conversation reaches the model: a routed call\n // has one prompt, an API call the operation's own channel (`CONVERSATION_DELIVERY_OF_OPERATION`).\n if (this.languageModelRouteServes(guarded, execution.operationKey, request.input, outputModeration)) {\n const routedPrompts = await this.buildExecutionPrompts(agent, request, ConversationDelivery.SINGLE_PROMPT);\n return this.executeLanguageModelOperationViaACP(guarded, request, execution.operationKey, routedPrompts);\n }\n const prompts = await this.buildExecutionPrompts(agent, request, CONVERSATION_DELIVERY_OF_OPERATION[execution.operationKey]);\n return this.executeAgentViaApi(guarded, request, execution, prompts, outputModeration);\n }\n\n /**\n * Execute an IMAGE-modality agent via an `IMAGE_PROVIDER` transport.\n *\n * Mirrors the LLM API path (provider-enabled check → apiKey → SDK client →\n * rate-limited call) but resolves the `IMAGE_PROVIDER` binding and calls the\n * AI-SDK `experimental_generateImage` against `client.imageModel(model)`.\n * Image-generation parameters come from the image config arm (`size` /\n * `quality` / `background` / `outputFormat` / `n`), NOT LLM sampling.\n *\n * Usage is the image model's own token report when it makes one (#2935);\n * transport metadata is not populated (the shared `executionContext` schema\n * is LLM-shaped). The best-effort agent-call trace still records\n * provider/model/input/output.\n */\n private async executeImageAgent(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n ): Promise<AgentExecutionResult> {\n const config = agent.config as FlowsActors_Agent_ImageConfiguration;\n const providerRef = config.providerRef;\n const protocolKind = ExternalProvider_ExchangeProtocol_Kind.IMAGE_PROVIDER;\n\n if (!this.externalProvidersRegistry.isProviderEnabled(providerRef, protocolKind)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_PROVIDER_NOT_ENABLED,\n // CLIENT-VISIBLE since 2026-09-18: both are allow-listed in `sanitizeErrorForClient`, because a\n // refusal that does not name the provider it refused cannot be acted on (#1304).\n context: { providerRef, protocolKind },\n });\n }\n\n const apiKey = this.externalProvidersRegistry.getProviderApiKey(providerRef, protocolKind);\n if (!apiKey) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { providerRef, protocolKind, message: this.externalProvidersRegistry.describeMissingProviderApiKey(providerRef, protocolKind) },\n });\n }\n\n const binding = this.backendProviderRegistryService.getProtocolBinding(providerRef, protocolKind);\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.IMAGE) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: { providerRef, message: 'Image runtime contract not available for provider' },\n });\n }\n\n // #3425: a service-account image arm (Vertex Imagen) is handed a token minted from the key, never the key, with its\n // deployment parameters read from their declared slots, through the resolver the LLM and embeddings arms share.\n const imageContext = this.sdkFactoryContextOf(providerRef, binding.runtimeContract, 'image');\n const resolvedImageCredential = await this.resolveAiSdkCredential(providerRef, protocolKind, binding.runtimeContract, apiKey);\n const client: any = await binding.runtimeContract.sdkFactory(resolvedImageCredential.credential, {\n ...imageContext,\n ...(resolvedImageCredential.deploymentParameters === undefined ? {} : { deploymentParameters: resolvedImageCredential.deploymentParameters }),\n });\n if (typeof client?.imageModel !== 'function') {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_IMAGE_GENERATION_NOT_SUPPORTED,\n context: { providerRef }, // diagnostic (log-only)\n });\n }\n\n const input = request.input as { prompt?: unknown; referenceImages?: unknown } | undefined;\n const prompt = typeof input?.prompt === 'string' ? input.prompt : String(request.input ?? '');\n if (prompt.length === 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_IMAGE_PROMPT_REQUIRED,\n context: { agentRef: agent.ref }, // diagnostic (log-only)\n });\n }\n\n const providerOptions: Record<string, any> = {};\n const openaiOptions: Record<string, any> = {};\n if (config.quality) openaiOptions.quality = config.quality;\n if (config.background) openaiOptions.background = config.background;\n if (config.outputFormat) openaiOptions.output_format = config.outputFormat;\n if (Object.keys(openaiOptions).length > 0) providerOptions.openai = openaiOptions;\n\n // `any` on the args object sidesteps the SDK's strict `${number}x${number}`\n // size template-literal type (our `size` is an enum incl. `auto`); the\n // rest of this service uses the same `any` pragmatism for model/options.\n const genArgs: any = {\n // #3204: a refused account is final inside the SDK's retry loop, as for a language model.\n model: wrapImageModel({ model: client.imageModel(config.model), middleware: IMAGE_MODEL_PROVIDER_ACCOUNT_REFUSAL_IS_FINAL }),\n prompt,\n ...(config.n !== undefined ? { n: config.n } : {}),\n ...(config.size !== undefined ? { size: config.size } : {}),\n ...(config.seed !== undefined ? { seed: config.seed } : {}),\n ...(Object.keys(providerOptions).length > 0 ? { providerOptions } : {}),\n };\n\n const limiter = this.getBottleneckForProvider(providerRef, protocolKind);\n const jobId = `${agent.ref}-image-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n let result: any;\n try {\n result = await this.scheduleOnLimiter(limiter, { id: jobId }, () => generateImage(genArgs));\n } catch (error) {\n // #3204: a provider account's refusal (no credits, a spend limit) is classified like every other model call's;\n // any other failure reaches the caller exactly as before.\n if (readModelProviderAccountRefusal(error, providerRef) === undefined) throw error;\n const errorDetails = this.extractProviderErrorDetails(error);\n this.logger.error('Image generation refused by the provider account', { operation: 'GENERATE_IMAGE', providerRef, ...errorDetails });\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'GENERATE_IMAGE',\n message: `Failed to generate an image: ${errorDetails.errorMessage}`,\n }, providerRef);\n }\n\n const rawImages: any[] = Array.isArray(result?.images) && result.images.length > 0\n ? result.images\n : (result?.image ? [result.image] : []);\n const images = rawImages\n .filter((img) => img && typeof img.base64 === 'string')\n .map((img) => ({\n base64: img.base64 as string,\n mediaType: typeof img.mediaType === 'string' ? img.mediaType : 'image/png',\n }));\n\n const output: ImageProvider_GenerateImageOutput = { images };\n // #2935: the tokens the image model reported (AI SDK `generateImage().usage`), so the call is charged what it spent.\n // A model that reports none leaves `usage` absent and is charged an estimate (`chargeModelCall`); an all-undefined\n // report must not become a zero, which would read as a call that cost nothing.\n const imageUsage = result?.usage;\n const reportsTokens = [imageUsage?.inputTokens, imageUsage?.outputTokens, imageUsage?.totalTokens].some((count) => typeof count === 'number' && count > 0);\n return { output, ...(reportsTokens ? { usage: this.extractUsage(imageUsage) } : {}) };\n }\n\n private resolveAgentExecution(agent: FlowsActors_Agent): ResolvedAgentExecution {\n const providerRef = agent.config.providerRef;\n const operationKey = agent.config.operationKey as LLMProvider_OperationKey;\n const executionProfileRef = agent.config.executionProfileRef;\n\n // The CODING arm resolves first and by its own arm, not by the presence of\n // an `executionProfileRef`. Both transports use that field, so ordering by\n // it would route a coding agent into the CLI branch and fail obscurely.\n if (isCodingAgentConfiguration(agent.config)) {\n const codingConfig = agent.config;\n const acpExecutionProfileRef = codingConfig.executionProfileRef;\n const executionProtocolKind = ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL;\n if (!this.externalProvidersRegistry.isProviderEnabled(providerRef, executionProtocolKind)) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef,\n protocolKind: executionProtocolKind,\n executionProfileRef: acpExecutionProfileRef,\n message: 'Agent Client Protocol is not enabled for the selected provider',\n },\n });\n }\n\n const acpProfile = this.externalProvidersRegistry.getAgentClientProtocolProfile(providerRef);\n const acpExecutionProfile = this.externalProvidersRegistry.getAgentClientProtocolExecutionProfile(\n providerRef,\n acpExecutionProfileRef,\n );\n if (!acpProfile || !acpExecutionProfile) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef,\n executionProfileRef: acpExecutionProfileRef,\n message: 'ACP protocol metadata or execution profile not found in provider configuration',\n },\n });\n }\n\n return {\n transport: 'acp',\n providerRef,\n operationKey: codingConfig.operationKey,\n executionProfileRef: acpExecutionProfileRef,\n acpProfile,\n acpExecutionProfile,\n };\n }\n\n const semanticProtocolKind = ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER;\n if (!this.externalProvidersRegistry.isProviderEnabled(providerRef, semanticProtocolKind)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_PROVIDER_NOT_ENABLED,\n context: {\n providerRef,\n protocolKind: semanticProtocolKind,\n }\n });\n }\n\n const supportedLLMOperations = this.externalProvidersRegistry.getLLMSemanticOperationKeys(providerRef);\n if (supportedLLMOperations.length === 0) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_PROVIDER_NOT_FOUND,\n context: {\n providerRef,\n }\n });\n }\n\n if (!supportedLLMOperations.includes(operationKey)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_OPERATION_NOT_SUPPORTED,\n context: {\n providerRef,\n operationKey,\n }\n });\n }\n\n return {\n transport: 'api',\n providerRef,\n operationKey,\n llmProviderConfig: this.externalProvidersRegistry.getProviderConfiguration(\n providerRef,\n semanticProtocolKind,\n ) as LLMProvider_Configuration | undefined,\n };\n }\n\n /**\n * The system prompt and the instructions one call sends. `delivery` is how THIS call carries a conversation input:\n * the instructions are the current turn when the conversation travels as `messages`, and the rendered transcript when\n * the call has one text channel (`invocationInstructionsOf`). A conversation is already the bounded replay (#2750), so\n * the history reaches the model once, through that replay, and never also inside the compiled user prompt.\n */\n private async buildExecutionPrompts(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n delivery: ConversationDelivery,\n ): Promise<CompiledExecutionPrompts> {\n const rawInstructions = invocationInstructionsOf(request.input, delivery);\n\n if (agent.promptSpec) {\n const compiled = await this.buildCompiledPrompts(agent, request, rawInstructions);\n return {\n systemPrompt: compiled.systemPrompt,\n instructions: compiled.userPrompt,\n };\n }\n\n return {\n systemPrompt: this.buildSystemPrompt(agent, request),\n instructions: rawInstructions,\n };\n }\n\n /**\n * Resolve the AI-SDK provider client for an API-transport LLM call (shared by\n * the buffered and streaming API paths): fetch the provider API key\n * (fail-closed if missing) and build the SDK client (fail-closed if the\n * provider is not available).\n */\n private async resolveApiProviderClient(providerRef: string): Promise<any> {\n const apiKey = this.externalProvidersRegistry.getProviderApiKey(\n providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER\n );\n if (!apiKey) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef,\n protocolKind: ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n message: this.externalProvidersRegistry.describeMissingProviderApiKey(providerRef, ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER),\n }\n });\n }\n\n const aiProvider = await this.getAIProvider(providerRef, apiKey);\n if (!aiProvider) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n providerRef,\n message: 'AI SDK provider not available'\n }\n });\n }\n return aiProvider;\n }\n\n private async executeAgentViaApi(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n execution: Extract<ResolvedAgentExecution, { transport: 'api' }>,\n prompts: CompiledExecutionPrompts,\n outputModeration?: OutputModerationGuard,\n ): Promise<AgentExecutionResult> {\n const aiProvider = await this.resolveApiProviderClient(execution.providerRef);\n\n const limiter = this.getBottleneckForProvider(\n execution.providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER\n );\n const jobId = `${agent.ref}-api-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n\n this.logDebug('Scheduling API call through rate limiter', {\n agentRef: agent.ref,\n providerRef: execution.providerRef,\n operationKey: execution.operationKey,\n model: agent.config.model,\n jobId,\n currentQueueSize: limiter.queued(),\n currentRunning: limiter.running(),\n usesPromptCompiler: !!agent.promptSpec,\n });\n\n const modelFailovers: ModelCallFailover[] = [];\n const result = await this.scheduleOnLimiter(\n limiter,\n { id: jobId },\n () => this.executeOperation({\n providerClient: aiProvider,\n providerRef: execution.providerRef,\n config: agent.config,\n operationKey: execution.operationKey,\n systemPrompt: prompts.systemPrompt,\n instructions: prompts.instructions,\n input: request.input,\n llmProviderConfig: execution.llmProviderConfig,\n outputModeration,\n operationObservation: this.operationObservationOf(request),\n modelFailovers,\n })\n );\n\n return {\n ...result,\n ...this.apiTransportOf(execution.providerRef, agent.config.model, modelFailovers),\n };\n }\n\n /**\n * The transport an API call reports, and its model failovers (#2301): the provider and model that answered the final\n * step (the last hand-over's target, else the agent's own), and every hand-over in order.\n */\n private apiTransportOf(\n providerRef: string,\n model: string | undefined,\n modelFailovers: readonly ModelCallFailover[],\n ): Pick<AgentExecutionResult, 'transport' | 'modelFailovers'> {\n const served = modelFailovers.at(-1);\n return {\n transport: {\n kind: LLMProvider_ExecutionTransportKind.API,\n protocolKind: ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n providerRef: served?.toProviderRef ?? providerRef,\n model: served?.toModel ?? model,\n },\n ...(modelFailovers.length > 0 ? { modelFailovers: [...modelFailovers] } : {}),\n };\n }\n\n /**\n * Get AI SDK provider client configured with API key.\n *\n * Looks up the provider's `LLM_PROVIDER` runtime contract on the\n * backend provider registry, narrows by `kind: ProviderProtocolRuntimeKind.LLM`, and invokes the\n * `sdkFactory` declared on the contract. Per the framework principle\n * (provider behavior lives on the provider module), there is NO\n * `switch (providerRef)` here: adding a new LLM provider only requires\n * authoring its module with an `sdkFactory`.\n *\n * Returns the provider client (typically `{ languageModel(model): … }`)\n * or `null` when the provider has no LLM_PROVIDER binding (i.e. the\n * caller asked for an LLM client of a non-LLM provider).\n */\n private async getAIProvider(providerRef: string, apiKey: string): Promise<any> {\n try {\n const binding = this.backendProviderRegistryService.getProtocolBinding(\n providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n );\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.LLM) {\n return null;\n }\n const context = this.sdkFactoryContextOf(providerRef, binding.runtimeContract, 'LLM');\n // #3425: a service-account arm is handed a bearer token minted from the key, never the key; deployment parameters\n // (a project, a location) are read from their declared slots here, so the module never reads the environment.\n const resolved = await this.resolveAiSdkCredential(providerRef, ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER, binding.runtimeContract, apiKey);\n return await binding.runtimeContract.sdkFactory(resolved.credential, {\n ...context,\n ...(resolved.deploymentParameters === undefined ? {} : { deploymentParameters: resolved.deploymentParameters }),\n });\n } catch (error) {\n this.logger.error('Failed to initialize AI provider', { providerRef, ...projectCaughtErrorLogFields(error) });\n throw error;\n }\n }\n\n /**\n * The credential and deployment parameters an AI arm's `sdkFactory` is called with (#3425), through the one resolver\n * the embeddings service shares: the slot's value, or a bearer token minted from the service-account key in it, and\n * the declared parameters read from their slots. A key or parameter that cannot be used is a CONFIGURATION error, a\n * token endpoint that refused or could not be reached an EXTERNAL_SERVICE one; neither message quotes the key.\n */\n private async resolveAiSdkCredential(\n providerRef: string,\n protocolKind: ExternalProvider_ExchangeProtocol_Kind,\n arm: Parameters<typeof resolveProviderAiSdkCredential>[0]['arm'],\n apiKey: string,\n ): Promise<Awaited<ReturnType<typeof resolveProviderAiSdkCredential>>> {\n try {\n return await resolveProviderAiSdkCredential({\n providerRef,\n arm,\n secretValue: apiKey,\n readSlot: (envVarName) => this.externalProvidersRegistry.getProviderSecret(providerRef, protocolKind, envVarName),\n });\n } catch (error) {\n if (!(error instanceof ProviderClientCredentialsTokenError)) throw error;\n const configuration = error.failure === ProviderClientCredentialsTokenFailure.NOT_CONFIGURED;\n throw this.errorBuilder.buildError(configuration ? ErrorType.CONFIGURATION : ErrorType.EXTERNAL_SERVICE, undefined, {\n customMessageReference: configuration ? ErrorCustomMessageReference.CONFIGURATION : ErrorCustomMessageReference.EXTERNAL_SERVICE,\n context: { providerRef, protocolKind, message: error.message },\n });\n }\n }\n\n /**\n * The context an LLM or image arm's `sdkFactory` is called with: the base URL the engine resolved for it (#2518). A\n * fixed `baseUrl`, or `https://<host>` from the arm's declared host slot through `resolveProviderContractBaseUrl`, the\n * rule the document-extraction, content-safety and embeddings arms share, so a deployment host is admitted the same way\n * on every arm and a loopback double reaches a model only in development and test (#2991). An arm naming both sources\n * or neither, or a host that is unset or refused, is a CONFIGURATION error: the factory is never called with a guess.\n */\n private sdkFactoryContextOf(providerRef: string, contract: ProviderContractEndpointFields, contractLabel: string): ProviderSdkFactoryContext {\n const endpoint = resolveProviderContractBaseUrl({\n providerRef,\n contractLabel,\n contract,\n hostAdmission: () => ({\n declaredSlots: this.externalProvidersRegistry.getProviderSecretSlots(providerRef),\n environment: this.externalProvidersRegistry.getDeclaredApplicationEnvironment(),\n }),\n });\n if ('refusal' in endpoint) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { providerRef, message: endpoint.refusal },\n });\n }\n return { baseUrl: endpoint.baseUrl };\n }\n\n /**\n * The tool kinds shared by the profile and invocation policies. Reads and edits\n * are disjoint sets: an edit-only profile requested as read-only admits neither.\n * A display rank cannot express this intersection without granting new authority.\n * assurance-control: WILDO.SOFTWARE.AI_PRODUCED_CHANGE_CONTROL — a run may ask for less autonomy than its execution profile declares, never more.\n */\n private resolveEffectivePermissionCeiling(\n profile: AgentClientProtocol_ExecutionProfile,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n ): AgentClientProtocol_PermissionCeiling {\n const requested = (request.input as { requestedPermissionCeiling?: AgentClientProtocol_PermissionCeiling } | undefined)\n ?.requestedPermissionCeiling;\n if (\n requested === undefined\n || !Object.values(AgentClientProtocol_PermissionCeiling).includes(requested)\n ) {\n return profile.permissionCeiling;\n }\n const permitted = profile.permissionCeiling;\n if (requested === permitted) return permitted;\n if (requested === AgentClientProtocol_PermissionCeiling.PROMPT_ALWAYS\n || permitted === AgentClientProtocol_PermissionCeiling.PROMPT_ALWAYS) {\n return AgentClientProtocol_PermissionCeiling.PROMPT_ALWAYS;\n }\n if (permitted === AgentClientProtocol_PermissionCeiling.UNRESTRICTED) return requested;\n if (requested === AgentClientProtocol_PermissionCeiling.UNRESTRICTED) return permitted;\n if (permitted === AgentClientProtocol_PermissionCeiling.AUTO_ACCEPT_READS_AND_EDITS) return requested;\n if (requested === AgentClientProtocol_PermissionCeiling.AUTO_ACCEPT_READS_AND_EDITS) return permitted;\n // The only remaining current pair is READS versus EDITS, in either direction.\n return AgentClientProtocol_PermissionCeiling.PROMPT_ALWAYS;\n }\n\n /**\n * The environment gate for the ACP transport — the guard that keeps a\n * workspace-mutating agent out of production. Checked before the limiter and\n * before any spawn.\n * assurance-control: WILDO.SOFTWARE.AI_PRODUCED_CHANGE_CONTROL — a coding agent runs only in an application environment its execution profile admits, and never on a guessed one.\n */\n private validateAgentClientProtocolPolicy(\n execution: Extract<ResolvedAgentExecution, { transport: 'acp' }>,\n ): void {\n const declaredApplicationEnv = readDeclaredApplicationEnvironment(process.env);\n if (declaredApplicationEnv === undefined) {\n // The gate that keeps a workspace-mutating agent out of production cannot run on a guess (#982). It used to read an\n // unset variable as development, which admitted every profile that allows development — wherever it ran.\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n message: `ACP execution refused: ${APPLICATION_ENV_UNDECLARED_MESSAGE}`,\n },\n });\n }\n const applicationEnv = declaredApplicationEnv as string as APPLICATION_ENVIRONMENT;\n const platformEnvironmentId = process.env.PLATFORM_ENVIRONMENT_ID;\n const { acpExecutionProfile } = execution;\n\n if (!acpExecutionProfile.allowedApplicationEnvironments.includes(applicationEnv)) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n applicationEnv,\n allowedApplicationEnvironments: acpExecutionProfile.allowedApplicationEnvironments,\n message: 'ACP execution profile is not allowed in the current application environment',\n },\n });\n }\n\n if (\n acpExecutionProfile.allowedPlatformEnvironmentIds?.length\n && (!platformEnvironmentId || !acpExecutionProfile.allowedPlatformEnvironmentIds.includes(platformEnvironmentId))\n ) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n platformEnvironmentId,\n allowedPlatformEnvironmentIds: acpExecutionProfile.allowedPlatformEnvironmentIds,\n message: 'ACP execution profile is not allowed in the current platform environment',\n },\n });\n }\n }\n\n /**\n * Compose the prompt a subprocess-hosted agent receives on its single input\n * channel: the system prompt, then the instructions.\n */\n private buildSubprocessPromptInput(prompts: CompiledExecutionPrompts): string {\n if (!prompts.systemPrompt.trim()) {\n return prompts.instructions;\n }\n\n return [\n '[SYSTEM]',\n prompts.systemPrompt,\n '',\n '[TASK]',\n prompts.instructions,\n ].join('\\n');\n }\n\n /**\n * The child environment for a spawned agent: a minimal identity allowlist plus\n * exactly what the profile names.\n *\n * Never full `process.env` inheritance — the process that spawns the agent\n * holds platform secrets that must not reach it.\n */\n private buildSubprocessBaseEnvironment(\n inheritedEnvironmentVariables: readonly string[] | undefined,\n ): NodeJS.ProcessEnv {\n return buildAgentSubprocessEnvironment(inheritedEnvironmentVariables ?? []);\n }\n\n /**\n * The environment a coding agent is started with, BEFORE any secret is injected: the base allowlist plus the\n * provider's and the execution profile's inherited variables, refused when either names a declared secret (#3018).\n * One composition for the dispatch ({@link buildAgentClientProtocolEnvironment}) and for a host asking what the\n * agent will see ({@link readCodingAgentLaunchConfiguration}, #3262), so the two cannot drift.\n */\n private composeAgentClientProtocolInheritedEnvironment(\n execution: Extract<ResolvedAgentExecution, { transport: 'acp' }>,\n ): NodeJS.ProcessEnv {\n // UNION of what the AGENT needs and what the APPLICATION asks for.\n //\n // The two lists answer different questions and only one of them is policy.\n // Which variable an agent reads to locate its own credentials is PROVIDER\n // knowledge — an application cannot be expected to know that Claude Code\n // resolves its login through `CLAUDE_CONFIG_DIR` — so a provider-declared\n // variable must reach every profile, including the ones applications author\n // themselves. Before this, the contract's list was projected ONLY into the\n // synthesized `default` profile, which the dogfood application deliberately\n // never selects; the declaration was therefore inert exactly where it\n // mattered, and the agent failed to authenticate with `OAuth session expired\n // and could not be refreshed` — a message that is false and sends every\n // diagnosis at the credential rather than at the environment.\n const inheritedEnvironmentVariables = [\n ...(execution.acpProfile.inheritedEnvironmentVariables ?? []),\n ...(execution.acpExecutionProfile.inheritedEnvironmentVariables ?? []),\n ];\n // #3018: no variable the framework declares secret is forwarded into the agent, whichever list names it. Checked\n // here on the exact list the agent starts with, as well as where the configuration is read.\n // assurance-control: WILDO.SECRETS.CREDENTIAL_SCOPING — the dispatch refuses to start a coding agent whose inherited environment names a declared secret.\n this.externalProvidersRegistry.assertAgentInheritedEnvironmentVariablesAreNotSecrets(\n execution.providerRef,\n `the inherited environment of '${execution.providerRef}' execution profile '${execution.executionProfileRef}'`,\n inheritedEnvironmentVariables,\n );\n return this.buildSubprocessBaseEnvironment(inheritedEnvironmentVariables);\n }\n\n private buildAgentClientProtocolEnvironment(\n execution: Extract<ResolvedAgentExecution, { transport: 'acp' }>,\n ): NodeJS.ProcessEnv {\n const env = this.composeAgentClientProtocolInheritedEnvironment(execution);\n\n if (execution.acpExecutionProfile.authMode === AgentClientProtocol_AuthMode.SECRET_REF_ENV_INJECTION) {\n const secretEnvVarName = execution.acpExecutionProfile.secretEnvVarName;\n const secret = this.externalProvidersRegistry.getAgentClientProtocolExecutionProfileSecret(\n execution.providerRef,\n execution.executionProfileRef,\n );\n if (!secretEnvVarName || !secret) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n message: 'ACP execution profile declares secret injection but its secret could not be resolved',\n },\n });\n }\n env[secretEnvVarName] = secret;\n }\n\n return env;\n }\n\n /**\n * Whether the LLM provider's contract requests strict JSON Schema\n * enforcement on AI-SDK structured-output calls. Read from the runtime\n * contract (`structuredOutputs.strictJsonSchema`) — never branched on\n * `providerRef`. Today only OpenAI sets this; if more providers need\n * it, they declare the flag on their own module.\n */\n private llmProviderRequestsStrictJsonSchema(providerRef: string): boolean | null {\n const binding = this.backendProviderRegistryService.getProtocolBinding(\n providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n );\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.LLM) {\n return null;\n }\n const declared = binding.runtimeContract.structuredOutputs?.strictJsonSchema;\n // `null` means the provider declares no opinion, so no option is sent and the SDK default applies.\n // `false` is an OPINION and must be sent: omitting it lets the SDK default back to strict, which is\n // how a contract that reads `strictJsonSchema: false` still produced strict-mode request rejections.\n return declared === undefined ? null : declared;\n }\n\n /**\n * The limits a provider documents for its strict mode (#2344), declared beside `strictJsonSchema: true`\n * in its runtime contract, which makes them required there. Read only for a provider that requests\n * strict decoding; the derivation applies them and states none of its own.\n */\n private llmProviderStrictSchemaProfile(providerRef: string): StrictStructuredOutputProfile | undefined {\n const binding = this.backendProviderRegistryService.getProtocolBinding(\n providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n );\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.LLM) return undefined;\n const declared = binding.runtimeContract.structuredOutputs;\n return declared?.strictJsonSchema === true ? declared.strictSchemaProfile : undefined;\n }\n\n /**\n * The limits of a provider's NATIVE constrained decoding and its unconstrained path (#3146), read from its runtime\n * contract, never branched on `providerRef`. Absent for a provider that requests OpenAI-style strict mode, which has\n * its own derivation, and for one that declares nothing.\n */\n private llmProviderNativeConstrainedDecoding(providerRef: string): NativeConstrainedDecodingContract | undefined {\n const binding = this.backendProviderRegistryService.getProtocolBinding(\n providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n );\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.LLM) return undefined;\n const declared = binding.runtimeContract.structuredOutputs;\n return declared?.strictJsonSchema === true ? undefined : declared?.nativeConstrainedDecoding;\n }\n\n /**\n * Execute a CODING agent over an ACP session.\n *\n * Carries the SAME FOUR responsibilities as {@link executeAgentViaCLI}, and\n * they are listed here because the transport swap is exactly where one of\n * them would be quietly dropped:\n *\n * 1. rate limiting through the provider's Bottleneck limiter;\n * 2. the ENVIRONMENT GATE — the guard that keeps a workspace-mutating agent\n * out of production;\n * 3. prompt composition from the agent's compiled prompts and the request;\n * 4. result normalisation into the published coding-agent output contract.\n */\n /**\n * The agent-specific `_meta` for `session/new`, resolved from the AUTHORED\n * host-configuration posture.\n *\n * Fails CLOSED. If the profile asks for an isolation posture this provider\n * declares no translation for, the session is refused rather than opened with\n * whatever the agent defaults to — which, measured against Claude's adapter,\n * means the operator's entire personal configuration. The field used to be\n * authored, defaulted and documented as a safety posture while being read by\n * nothing at all; refusing is what makes it mean something.\n *\n * `HOST_INHERITED` needs no translation: inheriting everything is what an\n * agent does when told nothing.\n */\n private resolveAgentClientProtocolSessionMeta(\n execution: Extract<ResolvedAgentExecution, { transport: 'acp' }>,\n ): Record<string, unknown> | undefined {\n const posture = execution.acpExecutionProfile.hostConfigurationInheritance;\n const byPosture = execution.acpProfile.sessionMetaExtensionsByHostConfigurationInheritance;\n const translated = byPosture?.[posture];\n\n if (translated) {\n // Posture translation is authority, not a default. Merge unrelated metadata\n // recursively, but refuse replacing any translated leaf (including an array).\n // A shallow spread let a harmless sibling under `claudeCode` erase isolation.\n const isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n const merge = (protectedValues: Record<string, unknown>, authored: Record<string, unknown>, path = ''): Record<string, unknown> =>\n Object.fromEntries([...new Set([...Object.keys(protectedValues), ...Object.keys(authored)])].map((key) => {\n if (!Object.hasOwn(protectedValues, key)) return [key, authored[key]];\n if (!Object.hasOwn(authored, key)) return [key, protectedValues[key]];\n const protectedValue = protectedValues[key];\n const authoredValue = authored[key];\n const metadataPath = path ? `${path}.${key}` : key;\n if (isObject(protectedValue) && isObject(authoredValue)) {\n return [key, merge(protectedValue, authoredValue, metadataPath)];\n }\n if (isDeepStrictEqual(protectedValue, authoredValue)) return [key, protectedValue];\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n hostConfigurationInheritance: posture,\n metadataPath,\n message: 'Authored ACP session metadata conflicts with the provider translation of the requested host-configuration posture.',\n },\n });\n }));\n return merge(translated, execution.acpExecutionProfile.sessionMetaExtensions ?? {});\n }\n\n if (posture !== AgentClientProtocol_HostConfigurationInheritance.HOST_INHERITED) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n hostConfigurationInheritance: posture,\n message:\n 'ACP provider declares no translation for the authored host-configuration posture, '\n + 'so the requested isolation cannot be honoured and the session is refused.',\n },\n });\n }\n\n return execution.acpExecutionProfile.sessionMetaExtensions ?? execution.acpProfile.sessionMetaExtensions;\n }\n\n /**\n * What THIS agent's provider declares about escalating before it mutates.\n *\n * Read from the ACP runtime contract on the provider binding — never branched\n * on `providerRef`, and deliberately not taken from any projected provider\n * profile: this is a measured PROVIDER FACT about an agent's behaviour, not\n * application-authored policy, and it must not sit anywhere an application\n * configuration could merge over it.\n *\n * `undefined` means the provider has no ACP binding at all, which the caller\n * has already refused by the time this runs.\n */\n private resolveAgentClientProtocolPermissionEscalation(\n providerRef: string,\n ): AgentClientProtocolPermissionEscalationDeclaration | undefined {\n const binding = this.backendProviderRegistryService.getProtocolBinding(\n providerRef,\n ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL,\n );\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.AGENT_CLIENT_PROTOCOL) {\n return undefined;\n }\n return binding.runtimeContract.permissionEscalation;\n }\n\n /**\n * Can Wildo's in-flight guards fire for the session this run is about to open?\n *\n * Answered from the provider's declaration AND from the environment actually\n * composed for the child, because for a conditionally-escalating agent those\n * are two different facts: the agent escalates only if the pointer to its\n * permission configuration really arrives, and a declaration that it \"must be\n * supplied\" is not evidence that anything supplied it.\n *\n * The environment is inspected rather than trusted for the same reason the\n * runner judges a permission request rather than the agent's session mode:\n * the thing that decides behaviour is what the child receives.\n */\n private resolveAgentClientProtocolInFlightGuardAvailability(\n escalation: AgentClientProtocolPermissionEscalationDeclaration | undefined,\n childEnvironment: NodeJS.ProcessEnv,\n ): { behaviour?: AgentClientProtocol_PermissionEscalationBehaviour; canFire: boolean; missingConfigurationEnvironmentVariable?: string } {\n if (!escalation) {\n // No declaration reachable. Assume the guards CANNOT fire: this field is\n // required on the contract, so its absence means a provider shape this\n // build does not understand, and reporting an unverified \"yes\" is the one\n // answer that could make an operator trust a ceiling that is not there.\n return { canFire: false };\n }\n const supplied =\n escalation.behaviour === AgentClientProtocol_PermissionEscalationBehaviour.RAISES_ONLY_UNDER_HOST_CONFIGURATION\n ? childEnvironment[escalation.configurationEnvironmentVariableName] !== undefined\n : false;\n const canFire = agentClientProtocolInFlightGuardsCanFire(escalation.behaviour, supplied);\n return {\n behaviour: escalation.behaviour,\n canFire,\n ...(!canFire\n && escalation.behaviour === AgentClientProtocol_PermissionEscalationBehaviour.RAISES_ONLY_UNDER_HOST_CONFIGURATION\n ? { missingConfigurationEnvironmentVariable: escalation.configurationEnvironmentVariableName }\n : {}),\n };\n }\n\n private async executeAgentViaACP(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n hostContext?: AgentInvocationHostContext,\n ): Promise<AgentExecutionResult> {\n const execution = this.resolveAgentExecution(agent);\n if (execution.transport !== 'acp') {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n agentRef: agent.ref,\n providerRef: agent.config.providerRef,\n message: 'Coding agent did not resolve to an ACP execution',\n },\n });\n }\n\n const { acpExecutionProfile, acpProfile } = execution;\n\n // (2) Environment gate — BEFORE the limiter, before any spawn.\n this.validateAgentClientProtocolPolicy(execution);\n\n // The requested model must be one the transport declares. Validated here\n // rather than at the session, so a mis-pinned model fails before an agent\n // is started rather than after it has begun editing.\n const requestedModel = agent.config.model;\n if (!acpProfile.supportedModels.includes(requestedModel)) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n requestedModel,\n supportedModels: acpProfile.supportedModels,\n message: 'ACP profile does not declare support for the selected semantic model',\n },\n });\n }\n\n // The authored auth posture must be one the AGENT can actually use.\n //\n // `authModes` was consulted only when synthesizing the provider's `default`\n // execution profile, so an application authoring its own — which the dogfood\n // application does deliberately — could declare any mode and nothing\n // checked it. Both directions are silently wrong rather than loud: a profile\n // declaring HOST_MANAGED against a secret-injecting agent starts a run with\n // no credential, and one declaring SECRET_REF_ENV_INJECTION against a\n // host-managed agent injects a secret the agent ignores while the\n // application believes the run is credentialed by configuration.\n //\n // Normalised on both sides at projection time; comparing the contract's\n // hyphenated spelling against the enum's underscored one is a guard that\n // never fires.\n const supportedAuthModes = acpProfile.supportedAuthModes;\n if (supportedAuthModes && !supportedAuthModes.includes(acpExecutionProfile.authMode)) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n authoredAuthMode: acpExecutionProfile.authMode,\n supportedAuthModes: [...supportedAuthModes],\n message:\n 'The authored ACP execution profile declares an authentication mode this provider\\'s agent '\n + 'does not support, so the session is refused rather than started with a credential posture '\n + 'the agent will not honour.',\n },\n });\n }\n\n const workingDirectory = resolveTrustedWorkingDirectory({\n workspaceRootPath: hostContext?.workspaceRootPath,\n usesRelativePath:\n acpExecutionProfile.workingDirectoryPolicy === AgentClientProtocol_WorkingDirectoryPolicy.WORKSPACE_RELATIVE_PATH,\n relativePath: acpExecutionProfile.workingDirectoryRelativePath,\n });\n\n // (3) Prompt composition — the same compiled prompts every transport gets. A session has one prompt, so a\n // conversation input reaches it as the rendered transcript of its bounded replay.\n const prompts = await this.buildExecutionPrompts(agent, request, ConversationDelivery.SINGLE_PROMPT);\n const prompt = this.buildSubprocessPromptInput(prompts);\n\n // (1) Rate limiting, keyed on the ACP protocol so a coding session and an\n // HTTP completion against the same provider do not share one bucket.\n const limiter = this.getBottleneckForProvider(\n execution.providerRef,\n ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL,\n );\n const jobId = `${agent.ref}-acp-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n\n this.logDebug('Scheduling ACP coding session through rate limiter', {\n agentRef: agent.ref,\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n permissionCeiling: acpExecutionProfile.permissionCeiling,\n workingDirectory,\n jobId,\n });\n\n const sessionMetaExtensions = this.resolveAgentClientProtocolSessionMeta(execution);\n\n const effectivePermissionCeiling = this.resolveEffectivePermissionCeiling(acpExecutionProfile, request);\n const permissionEscalation = this.resolveAgentClientProtocolPermissionEscalation(execution.providerRef);\n\n return this.scheduleOnLimiter(limiter, { id: jobId }, async () => {\n const env = this.buildAgentClientProtocolEnvironment(execution);\n /*\n * Does this run's authored ceiling mean anything for THIS agent?\n *\n * Both of Wildo's in-flight controls — the permission ceiling and the\n * task's mutation scope — are enforced in the client's ANSWER to\n * `session/request_permission`. An agent that does not ask is bound by\n * neither. Measured: Codex never asks before an in-workspace write (its\n * safety model is a sandbox), and OpenCode does not either unless the host\n * points it at a permission configuration file.\n *\n * The agents stay ADMISSIBLE. Refusing a tool because its architecture\n * differs is exactly the hard ceremony the application-creation directive\n * rejects, and the dogfood lane's `UNRESTRICTED` profile — which asks for\n * no gate and gets none — runs unchanged through this branch.\n *\n * What is refused is a CONTRADICTION: a profile that authored a ceiling\n * narrower than UNRESTRICTED, i.e. that asked for some autonomy to be\n * withheld, against an agent from which nothing can be withheld. Running\n * it anyway would not be permissive, it would be false — the ceiling would\n * be a label, the mutation scope would never be consulted, and the only\n * account of what the run touched would be a change set taken afterwards\n * while the configuration said a gate was in place.\n *\n * The same shape as this transport's two existing refusals, and for the\n * same reason: `resolveAgentClientProtocolSessionMeta` refuses an isolation\n * posture the provider cannot express, and `modelDelivery` refuses a model\n * that could not reach the agent. A declared safety field that cannot be\n * honoured must refuse rather than be silently ignored; that is what makes\n * it mean something. The door is one word wide and always open —\n * `permissionCeiling: UNRESTRICTED` states plainly that this run has no\n * in-flight gate, which is the truth either way.\n */\n // assurance-control: WILDO.SOFTWARE.AI_PRODUCED_CHANGE_CONTROL — a ceiling narrower than unrestricted is refused for an agent its guards cannot hold (one that never asks, or OpenCode without its configuration pointer), so a ceiling is never a label.\n const guardAvailability = this.resolveAgentClientProtocolInFlightGuardAvailability(permissionEscalation, env);\n if (!guardAvailability.canFire && effectivePermissionCeiling !== AgentClientProtocol_PermissionCeiling.UNRESTRICTED) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n permissionCeiling: effectivePermissionCeiling,\n permissionEscalation: guardAvailability.behaviour,\n ...(guardAvailability.missingConfigurationEnvironmentVariable\n ? { missingConfigurationEnvironmentVariable: guardAvailability.missingConfigurationEnvironmentVariable }\n : {}),\n message:\n 'This agent does not raise a permission request before mutating, so the authored permission '\n + 'ceiling and the task mutation scope cannot be enforced in flight and the session is refused '\n + 'rather than run under a ceiling that would be a label. '\n + (guardAvailability.missingConfigurationEnvironmentVariable\n ? `Supply ${guardAvailability.missingConfigurationEnvironmentVariable} in the child environment `\n + '(name it in the execution profile\\'s `inheritedEnvironmentVariables`, pointing at a permission '\n + 'configuration OUTSIDE the application workspace), or author `permissionCeiling: UNRESTRICTED`.'\n : 'Author `permissionCeiling: UNRESTRICTED` to state that this run has no in-flight gate, or '\n + 'select an agent whose provider declares that it escalates before mutating.'),\n },\n });\n }\n // Stated at session open, beside the ceiling, so an operator watching a run\n // start learns whether anything stands between the agent and the workspace\n // — rather than learning it afterwards from a warning about a change set.\n this.logDebug('Opening ACP coding session', {\n agentRef: agent.ref,\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n permissionCeiling: effectivePermissionCeiling,\n permissionEscalation: guardAvailability.behaviour ?? null,\n inFlightPermissionGuardsCanFire: guardAvailability.canFire,\n });\n // DELIVER the model, through the channel THIS agent's provider declares.\n //\n // Until 2026-09-03 `requestedModel` was checked against the transport's\n // declared set and written into the transport metadata — and never reached\n // the spawned agent, so under HOST_MANAGED auth every session ran at the\n // OPERATOR's personal default model (measured: Opus, during a 529-overload\n // storm the agent definitions' declared model would have avoided).\n //\n // The first fix wrote `ANTHROPIC_MODEL` unconditionally from this\n // agent-NEUTRAL service, which is correct for exactly one adapter and a\n // silent no-op for every other: the same false result, one agent later.\n // So the channel is declared by the provider that knows its agent, and a\n // provider that declares none cannot have a model selected at all —\n // refused here rather than started with the choice quietly dropped.\n const modelDelivery = acpProfile.modelDelivery;\n // The model is VALIDATED as a semantic id and DELIVERED in the agent's own\n // spelling. Both halves matter: validation against `supportedModels` is\n // what refuses a mis-pinned model before an agent is spawned, and the\n // translation is what lets a multi-vendor agent — whose ids carry the\n // provider, `anthropic/claude-sonnet-5` — be addressed at all. Absent\n // means the two vocabularies coincide, which is the common case.\n const deliveredModel = acpProfile.modelTransportIds?.[requestedModel] ?? requestedModel;\n let modelSelection: { configId: string; model: string } | undefined;\n if (modelDelivery?.channel === 'environment-variable') {\n env[modelDelivery.environmentVariableName] = deliveredModel;\n } else if (modelDelivery?.channel === 'session-config-option') {\n // Set over ACP after the session opens; the runner fails the session if\n // the agent rejects it, before any prompt reaches the workspace.\n modelSelection = { configId: modelDelivery.configId, model: deliveredModel };\n } else {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n requestedModel,\n message:\n 'ACP provider declares no model-delivery channel, so the selected model cannot reach the '\n + 'agent and the session is refused rather than run at the agent\\'s own default.',\n },\n });\n }\n // A run that ANSWERS a parked session resumes it by id via `session/load`\n // instead of starting a fresh task; the input's prompt is then the answer.\n const continuationOfSessionId = (request.input as { continuationOfSessionId?: string } | undefined)\n ?.continuationOfSessionId;\n\n // (3b) The operator must be signed in to the agent (#1637). A signed-out agent completes the ACP\n // handshake and fails only on its first prompt, which used to be charged to the task as its\n // own failure. The provider declares how to read the login from local state (no tokens), and\n // it is read in the CHILD's environment — where the agent itself looks for its credentials.\n // Only a definite SIGNED_OUT refuses. An unreadable state proceeds, since a guard that guesses\n // \"signed out\" would block a working host — and so does a missing status command: the Claude and\n // Codex agents run through `npx` adapters that do not need `claude` / `codex` on PATH, so a host\n // whose CLI is absent (or only a shell alias) can still dispatch, and did before this check. An\n // application that starts its own agent command is running something the provider did not\n // describe, so its declaration does not apply.\n if (acpProfile.hostLogin && !acpExecutionProfile.command) {\n const login = await probeCodingAgentHostLoginAsync(acpProfile.hostLogin, { environment: env });\n if (login.state === CodingAgentHostLoginState.SIGNED_OUT) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n loginState: login.state,\n message: `${CODING_AGENT_NOT_SIGNED_IN_MESSAGE_PREFIX} (${execution.providerRef}): ${login.detail} ${login.remedy ?? ''}`.trim(),\n },\n });\n }\n }\n\n // (4) Open the live session, then drive it turn-by-turn.\n const agentSession = await startACPAgentSession({\n // The application may override how the agent is started, but normally\n // inherits it: the provider owns the package and its pinned version.\n command: acpExecutionProfile.command ?? acpProfile.agentCommand,\n args: acpExecutionProfile.command ? acpExecutionProfile.args : acpProfile.agentArgs,\n cwd: workingDirectory,\n env,\n supportedProtocolVersions: acpProfile.supportedProtocolVersions,\n // The invocation may request LESS autonomy than the profile allows; it\n // can never request more. Intersecting tool-kind policies prevents an\n // override from granting operations absent from the profile.\n //\n // Resolved ONCE, above, and reused here: the guard-availability refusal\n // just above decides on this exact value, and re-deriving it per use\n // would let the value that was CHECKED and the value the session RUNS\n // under drift apart — the whole class of defect this lane keeps meeting.\n permissionCeiling: effectivePermissionCeiling,\n // Agent-vocabulary mode ids from the provider contract. Absent is fine —\n // the ceiling is enforced by answering permission requests, never by the\n // agent's mode — but a map hardcoded in the runner silently matched\n // nothing for any agent but the one it was written for.\n ...(acpProfile.sessionModeIdsByPermissionCeiling?.[effectivePermissionCeiling]\n ? {\n preferredSessionModeIds:\n acpProfile.sessionModeIdsByPermissionCeiling[effectivePermissionCeiling],\n }\n : {}),\n ...(modelSelection ? { modelSelection } : {}),\n ...(hostContext?.isPermittedCodingLocation\n ? { isPermittedLocation: hostContext.isPermittedCodingLocation }\n : {}),\n ...(hostContext?.isPermittedCodingReadLocation\n ? { isPermittedReadLocation: hostContext.isPermittedCodingReadLocation }\n : {}),\n ...(sessionMetaExtensions ? { sessionMetaExtensions } : {}),\n ...(acpExecutionProfile.maximumRecordedEventBytes !== undefined\n ? { maxRecordedEventBytes: acpExecutionProfile.maximumRecordedEventBytes }\n : {}),\n ...(hostContext?.onCodingSessionEvent ? { onEvent: hostContext.onCodingSessionEvent } : {}),\n ...(continuationOfSessionId ? { resumeSessionId: continuationOfSessionId } : {}),\n });\n\n try {\n const ladder = await this.driveCodingTurnLadder({\n session: agentSession,\n firstPrompt: prompt,\n maxAutoContinuations: acpExecutionProfile.maxAutoContinuations,\n awaitingInputTtlMs: acpExecutionProfile.awaitingInputTtlMs,\n ...(acpExecutionProfile.turnTimeoutMs !== undefined ? { turnTimeoutMs: acpExecutionProfile.turnTimeoutMs } : {}),\n ...(hostContext?.codingSessionAbortSignal ? { abortSignal: hostContext.codingSessionAbortSignal } : {}),\n ...(hostContext?.classifyCodingTurnEnd ? { classify: hostContext.classifyCodingTurnEnd } : {}),\n ...(hostContext?.onCodingSessionStateChange ? { onStateChange: hostContext.onCodingSessionStateChange } : {}),\n });\n\n // (5) Result normalisation into the published contract.\n const output: CodingAgent_RunTaskOutput = {\n finalMessage: ladder.finalMessage,\n stopReason: ladder.stopReason,\n ...(ladder.rawStopReason ? { rawStopReason: ladder.rawStopReason } : {}),\n // Always emitted, including zero: absence would be indistinguishable\n // from \"no denials\", and under the strictest ceiling that is exactly the\n // distinction an operator needs.\n deniedPermissionCount: ladder.deniedPermissionCount,\n permissionDecisions: ladder.permissionDecisions,\n ...(ladder.reportedFileLocations.length > 0\n ? { reportedFileLocations: ladder.reportedFileLocations }\n : {}),\n // Absent means one turn — the single-turn shape every pre-ladder\n // consumer already assumes.\n ...(ladder.turnCount > 1 ? { turnCount: ladder.turnCount } : {}),\n ...(ladder.continuations.length > 0 ? { continuations: ladder.continuations } : {}),\n // Present ONLY when the run parked on a question — the field that stops\n // a suspended turn being read as a completed result.\n ...(ladder.suspension ? { suspension: ladder.suspension } : {}),\n };\n\n return {\n output,\n transport: {\n protocolKind: ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL as const,\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n model: requestedModel,\n negotiatedProtocolVersion: agentSession.negotiatedProtocolVersion,\n ...(agentSession.agentName ? { agentName: agentSession.agentName } : {}),\n ...(agentSession.agentVersion ? { agentVersion: agentSession.agentVersion } : {}),\n ...(agentSession.sessionModeId ? { sessionModeId: agentSession.sessionModeId } : {}),\n // Recorded on the run because the ceiling alone does not describe it.\n // A change set produced under a ceiling that could be enforced and one\n // produced under a ceiling that was inert look identical afterwards,\n // and this pair is the only thing that tells a later reader whether\n // anything stood between the agent and these files.\n ...(guardAvailability.behaviour ? { permissionEscalation: guardAvailability.behaviour } : {}),\n inFlightPermissionGuardsCanFire: guardAvailability.canFire,\n sessionId: agentSession.sessionId,\n },\n ...(ladder.usage ? { usage: ladder.usage } : {}),\n } satisfies AgentExecutionResult;\n } finally {\n // Closes on completion AND on park: a parked session is answered by a\n // fresh invocation that resumes it via `session/load`, never by holding\n // this child alive across the HTTP call that returned the question.\n agentSession.close();\n }\n });\n }\n\n /**\n * Install the host's language-model route (#3472), or remove it with `undefined`.\n *\n * Validated HERE, at installation, against the provider's ACP binding: a route naming an agent that cannot be\n * opened for a language-model session, or a model its binding does not offer, fails the host's startup instead of\n * failing the first of hundreds of calls.\n */\n public routeLanguageModelCallsOverAgentClientProtocol(route: LanguageModelAgentClientProtocolRoute | undefined): void {\n if (route === undefined) {\n this.languageModelRoute = undefined;\n return;\n }\n const execution = this.resolveLanguageModelRouteExecution(route);\n if (!execution.acpProfile.supportedModels.includes(route.model)) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { providerRef: route.acpProviderRef, model: route.model, supportedModels: execution.acpProfile.supportedModels, message: 'The language-model route names a model its ACP binding does not offer.' },\n });\n }\n if (this.readLanguageModelSessionDeclaration(route.acpProviderRef) === undefined) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { providerRef: route.acpProviderRef, message: 'The provider declares no `languageModelSession` on its ACP binding, so its agent cannot be opened for a language-model call.' },\n });\n }\n this.languageModelRoute = { route, limiter: new Bottleneck({ maxConcurrent: Math.max(1, route.maximumConcurrentSessions) }) };\n this.logger.info('Language-model calls are routed over the Agent Client Protocol', {\n acpProviderRef: route.acpProviderRef,\n model: route.model,\n routedProviderRefs: [...route.routedProviderRefs],\n maximumConcurrentSessions: route.maximumConcurrentSessions,\n });\n }\n\n /** The installed route, for a host that reports what its calls run on. */\n public readLanguageModelRoute(): LanguageModelAgentClientProtocolRoute | undefined {\n return this.languageModelRoute?.route;\n }\n\n private resolveLanguageModelRouteExecution(route: LanguageModelAgentClientProtocolRoute): Extract<ResolvedAgentExecution, { transport: 'acp' }> {\n const acpProfile = this.externalProvidersRegistry.getAgentClientProtocolProfile(route.acpProviderRef);\n const acpExecutionProfile = this.externalProvidersRegistry.getAgentClientProtocolExecutionProfile(route.acpProviderRef, route.executionProfileRef);\n if (!this.externalProvidersRegistry.isProviderEnabled(route.acpProviderRef, ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL) || !acpProfile || !acpExecutionProfile) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { providerRef: route.acpProviderRef, executionProfileRef: route.executionProfileRef, message: 'The language-model route names an ACP provider or execution profile that is not enabled.' },\n });\n }\n return {\n transport: 'acp',\n providerRef: route.acpProviderRef,\n operationKey: LLMProvider_OperationKey.GENERATE_STRUCTURED,\n executionProfileRef: route.executionProfileRef,\n acpProfile,\n acpExecutionProfile,\n } as unknown as Extract<ResolvedAgentExecution, { transport: 'acp' }>;\n }\n\n private readLanguageModelSessionDeclaration(providerRef: string) {\n const binding = this.backendProviderRegistryService.getProtocolBinding(providerRef, ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL);\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.AGENT_CLIENT_PROTOCOL) return undefined;\n return binding.runtimeContract.languageModelSession;\n }\n\n /**\n * Whether the installed route serves this call. A call it does not serve stays on the API, and the reason is logged\n * whenever a route IS installed for the agent's provider — an API call made despite the route has to say why.\n */\n private languageModelRouteServes(\n agent: FlowsActors_Agent,\n operationKey: LLMProvider_OperationKey,\n input: unknown,\n outputModeration: OutputModerationGuard | undefined,\n ): boolean {\n const installed = this.languageModelRoute;\n if (installed === undefined || !installed.route.routedProviderRefs.includes(agent.config.providerRef)) return false;\n const keptOnApi = (reason: string): false => {\n this.logger.info('A language-model call stays on the API despite the ACP route', { agentRef: agent.ref, operationKey, reason });\n return false;\n };\n if (!ROUTABLE_LANGUAGE_MODEL_OPERATIONS.has(operationKey)) return keptOnApi('the operation is not one a route serves');\n if (outputModeration !== undefined) return keptOnApi('the agent runs under an output-moderation guard, an API middleware');\n if (this.extractStructuredInputImages(input).length > 0) return keptOnApi('the input carries images');\n return true;\n }\n\n /**\n * One language-model call served by a locked-down ACP session (#3472).\n *\n * The session has no tool of the agent's own, its system prompt is the call's, and its only way to answer is the\n * host's `submit_result` tool, validated with the call's own schema. A turn that ends without an accepted submission\n * is reminded up to {@link ROUTED_CALL_REMINDER_TURNS} times; a call that still has none returns the API path's\n * failure contract (`structuredGenerationFailure`), so the caller's correction loop runs as it does on the API.\n */\n private async executeLanguageModelOperationViaACP(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n operationKey: LLMProvider_OperationKey,\n prompts: CompiledExecutionPrompts,\n ): Promise<AgentExecutionResult> {\n const installed = this.languageModelRoute!;\n const { route } = installed;\n const execution = this.resolveLanguageModelRouteExecution(route);\n const declaration = this.readLanguageModelSessionDeclaration(route.acpProviderRef)!;\n this.validateAgentClientProtocolPolicy(execution);\n\n const structured = operationKey === LLMProvider_OperationKey.GENERATE_STRUCTURED;\n const input = request.input as { schema?: unknown; includeRejectedAnswer?: unknown } | undefined;\n if (structured && !(input?.schema instanceof z.ZodType)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_STRUCTURED_SCHEMA_REQUIRED,\n context: { operation: 'GENERATE_STRUCTURED', transport: 'acp' },\n });\n }\n const schema: z.ZodTypeAny = structured ? (input!.schema as z.ZodTypeAny) : z.object({ text: z.string().min(1) });\n const answerInstruction = structured\n ? `Return your result by calling the ${ACP_RESULT_TOOL_NAME} tool with the WHOLE result as its input. Do not answer in text: only an accepted ${ACP_RESULT_TOOL_NAME} call counts.`\n : `Return your answer by calling the ${ACP_RESULT_TOOL_NAME} tool with {\"text\": \"<your whole answer>\"}. Do not answer in text: only an accepted ${ACP_RESULT_TOOL_NAME} call counts.`;\n const prompt = `${prompts.instructions}\\n\\n${answerInstruction}`;\n const jobId = `${agent.ref}-acp-language-model-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n\n // Through the one bound seam like every other model call (#2935): a routed call queued behind another caller's\n // runs in its OWN caller's frames, so its spend, cost attribution and logs never borrow that caller's.\n return this.scheduleOnLimiter(installed.limiter, { id: jobId }, async () => {\n mkdirSync(route.scratchDirectory, { recursive: true });\n const toolServer = await startAcpResultToolServer({\n schema,\n description: structured\n ? 'Submit the result the task asks for. Its input schema IS the result schema. A refusal names every issue; correct them and submit the whole result again.'\n : 'Submit your answer as {\"text\": \"...\"}.',\n maximumSubmissions: route.maximumSubmissions,\n });\n const env = this.buildAgentClientProtocolEnvironment(execution);\n const modelDelivery = execution.acpProfile.modelDelivery;\n const deliveredModel = execution.acpProfile.modelTransportIds?.[route.model] ?? route.model;\n if (modelDelivery?.channel === 'environment-variable') env[modelDelivery.environmentVariableName] = deliveredModel;\n const toolName = declaration.mcpToolNameTemplate.replace('{server}', ACP_RESULT_TOOL_SERVER_NAME).replace('{tool}', ACP_RESULT_TOOL_NAME);\n const sessionMeta = structuredClone(declaration.sessionMetaExtensions) as Record<string, unknown>;\n sessionMeta[declaration.systemPromptMetaKey] = prompts.systemPrompt;\n let cursor: Record<string, unknown> = sessionMeta;\n declaration.preApprovedToolsMetaPath.forEach((segment, index) => {\n if (index === declaration.preApprovedToolsMetaPath.length - 1) {\n cursor[segment] = [toolName];\n } else {\n const next = cursor[segment];\n cursor[segment] = next !== null && typeof next === 'object' && !Array.isArray(next) ? next : {};\n cursor = cursor[segment] as Record<string, unknown>;\n }\n });\n\n const startedAt = Date.now();\n let agentSession: ACPAgentSession | undefined;\n let usage: CodingAgent_Usage | undefined;\n try {\n agentSession = await startACPAgentSession({\n // The same resolution as a coding session: the execution profile's command when it authors one.\n command: execution.acpExecutionProfile.command ?? execution.acpProfile.agentCommand,\n args: execution.acpExecutionProfile.command ? execution.acpExecutionProfile.args : execution.acpProfile.agentArgs,\n cwd: route.scratchDirectory,\n env,\n supportedProtocolVersions: execution.acpProfile.supportedProtocolVersions,\n // Nothing of the agent's own is admitted: the host's tool is admitted by name, every other request refused.\n permissionCeiling: AgentClientProtocol_PermissionCeiling.PROMPT_ALWAYS,\n admitsHostToolCall: ({ toolCallTitle }) => toolCallTitle !== undefined && (toolCallTitle === toolName || toolCallTitle.includes(ACP_RESULT_TOOL_NAME)),\n ...(modelDelivery?.channel === 'session-config-option' ? { modelSelection: { configId: modelDelivery.configId, model: deliveredModel } } : {}),\n sessionMetaExtensions: sessionMeta,\n mcpServers: [{ type: 'http', name: ACP_RESULT_TOOL_SERVER_NAME, url: toolServer.url, headers: [] }],\n });\n let nextPrompt = prompt;\n for (let turn = 0; turn <= ROUTED_CALL_REMINDER_TURNS; turn += 1) {\n const remainingMs = route.callTimeoutMs - (Date.now() - startedAt);\n if (remainingMs <= 0) break;\n const turnResult = await agentSession.promptTurn(nextPrompt, { turnTimeoutMs: remainingMs });\n usage = this.mergeCodingUsage(usage, turnResult.usage);\n if (toolServer.acceptedResult() !== undefined || toolServer.submissionCount() >= route.maximumSubmissions) break;\n nextPrompt = `Your turn ended without an accepted ${ACP_RESULT_TOOL_NAME} call. ${answerInstruction}`;\n }\n } finally {\n agentSession?.close();\n await toolServer.close();\n }\n\n const transport = {\n protocolKind: ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL as const,\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n model: route.model,\n negotiatedProtocolVersion: agentSession!.negotiatedProtocolVersion,\n ...(agentSession!.agentName ? { agentName: agentSession!.agentName } : {}),\n ...(agentSession!.agentVersion ? { agentVersion: agentSession!.agentVersion } : {}),\n sessionId: agentSession!.sessionId,\n };\n const accepted = toolServer.acceptedResult();\n this.logDebug('Language-model call served over ACP', {\n agentRef: agent.ref,\n operationKey,\n model: route.model,\n accepted: accepted !== undefined,\n submissions: toolServer.submissionCount(),\n toolListed: toolServer.toolWasListed(),\n durationMs: Date.now() - startedAt,\n });\n\n if (accepted !== undefined) {\n const value = accepted.value;\n const output = operationKey === LLMProvider_OperationKey.GENERATE_STRUCTURED\n ? { object: value }\n : operationKey === LLMProvider_OperationKey.CHAT_COMPLETION\n ? { message: { role: LLMProvider_MessageRole.ASSISTANT, content: (value as { text: string }).text } }\n : { text: (value as { text: string }).text };\n return { output, transport, ...(usage ? { usage } : {}) } satisfies AgentExecutionResult;\n }\n\n if (!structured) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: {\n agentRef: agent.ref,\n operationKey,\n submissions: toolServer.submissionCount(),\n toolListed: toolServer.toolWasListed(),\n message: 'The ACP session ended without an accepted answer.',\n },\n });\n }\n // The API path's failure contract, so the caller's correction loop treats this exactly as a rejected API answer.\n const refusal = toolServer.lastRefusal();\n const structuredGenerationFailure = this.buildStructuredGenerationFailure(\n refusal !== undefined ? LLMProvider_StructuredGenerationFailureKind.INVALID_OBJECT_AFTER_COMPLETED_CALL : LLMProvider_StructuredGenerationFailureKind.NO_OBJECT_GENERATED,\n new Error(refusal !== undefined ? 'AcpResultRefused' : 'AcpNoResultSubmitted'),\n {\n ...(refusal !== undefined ? { cause: new z.ZodError([...refusal.issues]) } : {}),\n ...(refusal !== undefined ? { text: JSON.stringify(refusal.submitted) } : {}),\n },\n );\n return {\n output: {\n object: undefined,\n ...(input?.includeRejectedAnswer === true && refusal !== undefined ? { rejectedAnswer: JSON.stringify(refusal.submitted) } : {}),\n },\n structuredGenerationFailure,\n transport,\n ...(usage ? { usage } : {}),\n } satisfies AgentExecutionResult;\n });\n }\n\n private extractCLITextOutput(output: unknown): string {\n if (typeof output === 'string') {\n return output;\n }\n\n if (this.isRecord(output)) {\n if (typeof output.result === 'string') {\n return output.result;\n }\n if (typeof output.text === 'string') {\n return output.text;\n }\n if (typeof output.output === 'string') {\n return output.output;\n }\n if (typeof output.content === 'string') {\n return output.content;\n }\n }\n\n return JSON.stringify(output ?? '');\n }\n\n\n /**\n * Build system prompt from agent configuration\n *\n * If agent has promptSpec, uses the PromptCompiler for structured prompt building.\n * Otherwise, falls back to legacy skill-based prompt building.\n */\n private buildSystemPrompt(agent: FlowsActors_Agent, request: FlowsActors_Agent_Invocation<any, any, any>): string {\n const parts: string[] = [];\n\n if (agent.promptSpec.role) {\n parts.push(`Role: ${agent.promptSpec.role}`);\n }\n\n if (agent.promptSpec.persona) {\n parts.push(`Persona: ${agent.promptSpec.persona}`);\n }\n\n if (request.executionContext) {\n parts.push(`Context: ${JSON.stringify(request.executionContext)}`);\n }\n\n return parts.join('\\n\\n');\n }\n\n /**\n * Build prompts using the PromptCompiler when agent has promptSpec\n * Returns compiled system and user prompts\n */\n private async buildCompiledPrompts(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n instructions: string\n ): Promise<{ systemPrompt: string; userPrompt: string }> {\n if (!agent.promptSpec) {\n // Fall back to legacy mode\n return {\n systemPrompt: this.buildSystemPrompt(agent, request),\n userPrompt: instructions,\n };\n }\n\n this.logDebug('Building compiled prompts using PromptCompiler', {\n agentRef: agent.ref,\n hasInstructions: agent.promptSpec.instructions.length > 0,\n hasHints: !!agent.promptSpec.hints?.length,\n hasCuration: !!agent.promptSpec.curation,\n });\n\n // Build context items from execution context\n // Note: User input is NOT added here - it goes in the user prompt section, not context\n const contextItems: PromptIR_ContextItem[] = [];\n\n if (request.executionContext) {\n contextItems.push({\n id: 'exec_context',\n content: JSON.stringify(request.executionContext, null, 2),\n trust: PromptIR_TrustLevel.HIGH,\n sourceKind: PromptIR_ContextSourceKind.RELATIONSHIP,\n timestamp: new Date().toISOString(),\n });\n }\n\n // Compile using the prompt compiler - works directly with agent + invocation\n const compiled = await this.promptCompiler.compile(\n agent,\n request,\n contextItems,\n instructions\n );\n\n this.logDebug('Prompts compiled', {\n agentRef: agent.ref,\n format: compiled.format,\n systemPromptLength: compiled.systemPrompt.length,\n userPromptLength: compiled.userPrompt.length,\n tokenEstimates: compiled.tokenEstimates,\n });\n\n return {\n systemPrompt: compiled.systemPrompt,\n userPrompt: compiled.userPrompt,\n };\n }\n\n /**\n * Execute operation based on operation key\n * Dispatches to specific operation handlers\n */\n private async executeOperation({ providerClient, providerRef, config, operationKey, systemPrompt, instructions, input, llmProviderConfig, outputModeration, operationObservation, modelFailovers }: executeOperationParams): Promise<AgentOperationExecutionResult> {\n // A structured generation is STREAMED beneath every other wrap, so the account-refusal, observation and\n // moderation middlewares keep seeing a buffered call exactly as before (`withStreamedGenerationDeadlines`).\n const transportOf = (providerModel: any): any => operationKey === LLMProvider_OperationKey.GENERATE_STRUCTURED ? this.withStreamedGenerationDeadlines(providerModel) : providerModel;\n // #2301: the agent's declared alternatives sit beneath every engine middleware, each with its own transport wraps, so\n // a hand-over is invisible to the account-refusal, observation and moderation layers above.\n const transportModel = this.withDeclaredModelFailover({\n primary: transportOf(this.getModelFromProvider(providerClient, config.model)),\n providerRef,\n config,\n transportOf,\n ...(modelFailovers === undefined ? {} : { sink: modelFailovers }),\n });\n const model = this.moderatedModel(this.observedModel(this.accountRefusalIsFinal(transportModel), operationObservation), outputModeration, MODERATED_OUTPUT_KIND_OF_OPERATION[operationKey] ?? FlowsActors_ModeratedOutputKind.REPLY);\n // executeOperation is only reached on the LLM/text path (image agents\n // branch to executeImageAgent in executeAgent), so the config is the LLM arm.\n const baseOptions = this.buildBaseOptions(config as FlowsActors_Agent_LLMConfiguration);\n\n try {\n switch (operationKey) {\n case LLMProvider_OperationKey.GENERATE_TEXT:\n return await this.executeGenerateText({ model, systemPrompt, instructions, input, baseOptions });\n\n case LLMProvider_OperationKey.CHAT_COMPLETION:\n return await this.executeChatCompletion({ model, systemPrompt, instructions, input, baseOptions });\n\n case LLMProvider_OperationKey.CHAT_MULTIMODAL:\n return await this.executeChatMultimodal({ model, systemPrompt, instructions, input, baseOptions });\n\n case LLMProvider_OperationKey.GENERATE_STRUCTURED:\n return await this.executeGenerateStructured({\n model,\n systemPrompt,\n instructions,\n input,\n baseOptions,\n llmProviderConfig,\n providerRef,\n structuredGenerationExecutionMode: (config as FlowsActors_Agent_LLMConfiguration).structuredGenerationExecutionMode,\n maximumStructuredOutputLeafFields: (config as FlowsActors_Agent_LLMConfiguration).maximumStructuredOutputLeafFields,\n });\n\n case LLMProvider_OperationKey.STREAM_TEXT:\n return await this.executeStreamText({ model, systemPrompt, instructions, input, baseOptions });\n\n case LLMProvider_OperationKey.STREAM_STRUCTURED:\n return await this.executeStreamStructured({ model, systemPrompt, instructions, baseOptions });\n\n default:\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.AGENT_OPERATION_NOT_SUPPORTED,\n context: {\n // diagnostic (log-only)\n operationKey,\n supportedOperations: Object.values(LLMProvider_OperationKey),\n },\n }\n );\n }\n } catch (error) {\n // #2292: a withheld output is the application's policy, not a provider fault: it reaches the caller as itself.\n if (error instanceof AgentOutputWithheldError) throw error;\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n // Extract detailed provider error information\n const errorDetails = this.extractProviderErrorDetails(error);\n\n // Log detailed error information\n this.logger.error('Operation execution failed - provider error details', {\n operationKey,\n model: config.model,\n providerRef: (providerClient as any)?.providerRef || 'unknown',\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operationKey,\n model: config.model,\n message: `Failed to execute operation ${operationKey}: ${errorDetails.errorMessage}`,\n }, providerRef);\n }\n }\n\n /**\n * #3204: the model wrapped INNERMOST so a provider account's refusal (no credits, a spend limit) is final inside the\n * SDK's retry loop instead of being asked again with back-off (`MODEL_PROVIDER_ACCOUNT_REFUSAL_IS_FINAL`). A value\n * that is not a language model object is returned as it came, so the SDK's own resolution reports it.\n */\n private accountRefusalIsFinal(model: any): any {\n if (model === null || typeof model !== 'object' || typeof model.doGenerate !== 'function') return model;\n return wrapLanguageModel({ model, middleware: MODEL_PROVIDER_ACCOUNT_REFUSAL_IS_FINAL });\n }\n\n /**\n * The agent's model with the alternatives it declares behind it (#2301, `modelFailover`): `withModelCallFailover` over\n * the primary and each alternative, every alternative built like the agent's own model (its provider client through\n * `resolveApiProviderClient`, so its credential and its declared processing region apply, then `transportOf`, the same\n * transport wraps). Built lazily, at the first failure. One that cannot be reached or built is skipped with an ERROR\n * log; startup refuses it (`assertDeclaredFailoverProvidersCanServe`), so this is the mid-life case. Returns the primary\n * itself when the agent declares none.\n */\n private withDeclaredModelFailover(input: {\n readonly primary: any;\n readonly providerRef: string;\n readonly config: FlowsActors_Agent['config'];\n readonly transportOf: (providerModel: any) => any;\n readonly sink?: ModelCallFailover[];\n }): any {\n const alternatives: readonly FlowsActors_Agent_ModelAlternative[] = isLLMAgentConfiguration(input.config) ? input.config.modelFailover ?? [] : [];\n return withModelCallFailover({\n // The registry resolves an applicability to a concrete id before an agent runs, so `config.model` names the model\n // for every registered agent. A configuration handed in unregistered names it through the built model's own\n // `modelId`, which the AI SDK's language-model contract requires, so a hand-over record never names nothing (#3583).\n primary: { providerRef: input.providerRef, model: input.config.model ?? input.primary.modelId, languageModel: input.primary },\n declaresAlternatives: alternatives.length > 0,\n alternatives: async () => {\n const candidates: ModelCallCandidate[] = [];\n for (const alternative of alternatives) {\n try {\n const reachDefect = this.modelAlternativeReachDefect(alternative.providerRef);\n if (reachDefect !== undefined) throw new Error(reachDefect);\n const client = await this.resolveApiProviderClient(alternative.providerRef);\n candidates.push({\n providerRef: alternative.providerRef,\n model: alternative.model,\n languageModel: input.transportOf(this.getModelFromProvider(client, alternative.model)),\n });\n } catch (error) {\n this.logger.error('A declared model alternative cannot serve and was skipped', {\n providerRef: alternative.providerRef,\n model: alternative.model,\n error: describeCaughtError(error),\n });\n }\n }\n return candidates;\n },\n onFailover: (failover) => {\n input.sink?.push(failover);\n this.logger.warn('An agent model call failed over to a declared alternative model', { ...failover });\n },\n });\n }\n\n /**\n * Why a provider cannot serve as a declared model alternative on this runtime (#2301), or `undefined`. It must be\n * eligible for `AI_LLM` exactly as a selected provider is — registered, declared in this runtime's scope with the\n * capability, and loaded, which the application's data residency decides (a provider outside it is never loaded) —\n * enabled, credentialed, and carry an `LLM_PROVIDER` contract. Its processing region is bound at load, like any other.\n */\n private modelAlternativeReachDefect(providerRef: string): string | undefined {\n const protocolKind = ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER;\n if (!this.externalProvidersRegistry.getProvidersForEngineCapability(EngineCapability.AI_LLM).includes(providerRef)) {\n return `provider \"${providerRef}\" is not available for AI_LLM on this runtime (not loaded — a data residency refusal unloads a provider — or not declared with AI_LLM in this scope)`;\n }\n if (!this.externalProvidersRegistry.isProviderEnabled(providerRef, protocolKind)) return `provider \"${providerRef}\" is disabled`;\n if (!this.externalProvidersRegistry.getProviderApiKey(providerRef, protocolKind)) {\n return this.externalProvidersRegistry.describeMissingProviderApiKey(providerRef, protocolKind);\n }\n const binding = this.backendProviderRegistryService.getProtocolBinding(providerRef, protocolKind);\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.LLM) return `provider \"${providerRef}\" declares no LLM_PROVIDER contract`;\n return undefined;\n }\n\n /**\n * Why one declared model alternative cannot take this agent's calls (#2301), or `undefined`: what the provider must be\n * ({@link modelAlternativeReachDefect}), and what the model must serve. The model is judged on the facts the agent's own\n * model is judged on at registration: the catalog row, or a registry provider's declared model, for its reasoning\n * effort; and, where the catalog states the model's capabilities, the ones the agent's calls need (structured output,\n * tools, images). Facts nobody stated fail open, as they do for the agent's own model.\n */\n private describeModelAlternativeDefect(agent: FlowsActors_Agent, config: FlowsActors_Agent_LLMConfiguration, alternative: FlowsActors_Agent_ModelAlternative): string | undefined {\n if (config.executionProfileRef !== undefined) {\n return `declares modelFailover but runs on the execution profile \"${config.executionProfileRef}\"; a model alternative serves the API transport only`;\n }\n if (alternative.providerRef === config.providerRef && alternative.model === config.model) return `names its own model \"${alternative.model}\" as an alternative`;\n const reach = this.modelAlternativeReachDefect(alternative.providerRef);\n if (reach !== undefined) return reach;\n const catalogEntry = Object.hasOwn(LLM_MODEL_CATALOG, alternative.model) ? LLM_MODEL_CATALOG[alternative.model as LLM_Model] : undefined;\n if (catalogEntry !== undefined && catalogEntry.providerRef !== alternative.providerRef) {\n return `model \"${alternative.model}\" is served by \"${catalogEntry.providerRef}\", not by \"${alternative.providerRef}\"`;\n }\n let declaredFacts: Parameters<typeof validateReasoningEffortForModel>[2];\n if (!isLLMCatalogProvider(alternative.providerRef)) {\n const contract = this.externalProvidersRegistry.getProviderRuntimeContract(alternative.providerRef, ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER);\n declaredFacts = (contract?.kind === ProviderProtocolRuntimeKind.LLM ? contract.models?.find((declared) => declared.model === alternative.model) : undefined) ?? {};\n }\n const reasoning = validateReasoningEffortForModel(alternative.model, config.reasoningEffort, declaredFacts);\n if (reasoning !== null) return reasoning;\n const stated = catalogEntry?.ioCapabilities;\n if (stated !== undefined) {\n const needs: { readonly what: string; readonly anyOf: readonly LLM_Model_IO_Capability[] }[] = [];\n if (config.operationKey === LLMProvider_OperationKey.GENERATE_STRUCTURED || config.operationKey === LLMProvider_OperationKey.STREAM_STRUCTURED) {\n needs.push({ what: 'structured output', anyOf: [LLM_Model_IO_Capability.STRUCTURED_OUTPUTS, LLM_Model_IO_Capability.JSON_MODE] });\n }\n if (config.operationKey === LLMProvider_OperationKey.CHAT_MULTIMODAL) {\n needs.push({ what: 'images', anyOf: [LLM_Model_IO_Capability.MULTIMODAL_VISION] });\n }\n if ((agent.capabilities?.tools?.functionRefs?.length ?? 0) + (agent.capabilities?.tools?.mcpRefs?.length ?? 0) > 0) {\n needs.push({ what: 'tools', anyOf: [LLM_Model_IO_Capability.TOOL_USE, LLM_Model_IO_Capability.FUNCTION_CALLING] });\n }\n const missing = needs.filter((need) => !need.anyOf.some((capability) => stated.includes(capability))).map((need) => need.what);\n if (missing.length > 0) return `model \"${alternative.model}\" does not serve ${missing.join(', ')}, which this agent's calls need`;\n }\n return undefined;\n }\n\n /**\n * Refuses startup when an agent declares a model alternative that could not take its calls (#2301): see\n * {@link describeModelAlternativeDefect}. Without this the defect would surface only during the outage the declaration\n * exists for, as an alternative skipped with an ERROR log. The remedy is a configuration or environment edit. Agents\n * that declare no `modelFailover` are unaffected.\n */\n public assertDeclaredFailoverProvidersCanServe(): void {\n const defects: string[] = [];\n for (const agent of Object.values(this.flowsActorsRegistry.getRegistry().agents) as FlowsActors_Agent[]) {\n if (!isLLMAgentConfiguration(agent.config)) continue;\n for (const alternative of agent.config.modelFailover ?? []) {\n const defect = this.describeModelAlternativeDefect(agent, agent.config, alternative);\n if (defect !== undefined) defects.push(`agent \"${agent.ref}\", alternative ${alternative.providerRef}/${alternative.model}: ${defect}`);\n }\n }\n if (defects.length === 0) return;\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `A declared model alternative cannot take an agent's calls: ${defects.join('; ')}. `\n + 'Fix its provider configuration or credential, or remove it from the agent\\'s `modelFailover`.',\n defects,\n },\n });\n }\n\n /**\n * Get model instance from provider client\n */\n private getModelFromProvider(providerClient: any, modelName: string): any {\n if (providerClient && typeof providerClient.languageModel === 'function') {\n try {\n return providerClient.languageModel(modelName);\n } catch (error) {\n this.logger.error('Failed to get model via languageModel()', {\n modelName,\n ...projectCaughtErrorLogFields(error),\n });\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n modelName,\n message: `Failed to initialize model ${modelName} via languageModel() method`,\n originalError: describeCaughtError(error),\n stack: error instanceof Error ? error.stack : undefined,\n },\n }\n );\n }\n }\n\n if (typeof providerClient === 'function') {\n try {\n return providerClient(modelName);\n } catch (error) {\n this.logger.error('Failed to get model via function call', {\n modelName,\n ...projectCaughtErrorLogFields(error),\n });\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n modelName,\n message: `Failed to initialize model ${modelName} via provider function`,\n originalError: describeCaughtError(error),\n stack: error instanceof Error ? error.stack : undefined,\n },\n }\n );\n }\n }\n\n if (providerClient && typeof providerClient.model === 'function') {\n try {\n return providerClient.model(modelName);\n } catch (error) {\n this.logger.error('Failed to get model via model()', {\n modelName,\n ...projectCaughtErrorLogFields(error),\n });\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n modelName,\n message: `Failed to initialize model ${modelName} via model() method`,\n originalError: describeCaughtError(error),\n stack: error instanceof Error ? error.stack : undefined,\n },\n }\n );\n }\n }\n\n this.logger.error('Failed to get model from provider client', {\n providerType: typeof providerClient,\n providerKeys: providerClient ? Object.keys(providerClient).slice(0, 10) : [],\n hasLanguageModel: typeof providerClient?.languageModel === 'function',\n hasModel: typeof providerClient?.model === 'function',\n isFunction: typeof providerClient === 'function',\n });\n\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.AGENT_MODEL_INITIALIZATION_FAILED,\n context: {\n // diagnostic (log-only)\n modelName,\n providerType: typeof providerClient,\n hasLanguageModel: typeof providerClient?.languageModel === 'function',\n hasModel: typeof providerClient?.model === 'function',\n isFunction: typeof providerClient === 'function',\n },\n }\n );\n }\n\n /**\n * The provider model a structured-generation call runs on, answered by STREAMING under progress-based deadlines\n * (`streamedGenerationDeadlineMiddleware`). Applied INNERMOST, directly on the provider model: the account-refusal,\n * observation and output-moderation middlewares above it then still take their BUFFERED branch, so a withheld\n * answer is thrown with its usage exactly as before (their stream branches behave differently by design).\n *\n * A deadline is required: without one the call is unbounded. Measured 2026-08-20, a `top_down.market-analysis`\n * generation was dispatched and had still not returned TWELVE HOURS later; the Driver never received a result, the\n * Task-terminalization queue behind it never drained, and the next boot's startup drain inherited the stall.\n *\n * It used to be a 15-minute WALL CLOCK on a non-streaming request, which cannot tell a call still producing\n * tokens from one that hung. That held while OpenAI served the creation lane, and failed the day it moved to\n * Anthropic: a ~100 KB compliance-document candidate was still generating on Sonnet 5 when the clock expired, and\n * every retry spent another 15 minutes (reference run 42365624598, 2026-11-07). Streaming lets the bound be\n * \"nothing received for 5 minutes\", with a one-hour backstop, and the abort is the same `TimeoutError` the retry\n * policy already classifies as TIMEOUT. Both deadlines apply per SDK ATTEMPT (the middleware runs inside the SDK's\n * retry loop), where the old `abortSignal` spanned every retry of the call.\n */\n private withStreamedGenerationDeadlines(model: any): any {\n return wrapLanguageModel({\n model,\n middleware: streamedGenerationDeadlineMiddleware({\n idleMs: STREAMED_GENERATION_IDLE_DEADLINE_MS,\n totalMs: STREAMED_GENERATION_TOTAL_DEADLINE_MS,\n }),\n });\n }\n\n /**\n * The one prompt sent to auto-continue a coding agent past a self-imposed\n * pause. Named here rather than improvised at the call site so a run's\n * continuations are all identical and auditable, and so the wording — which\n * tells the agent to keep working AND to stop only when genuinely done or\n * genuinely blocked — lives in exactly one place.\n */\n private static readonly CODING_AUTO_CONTINUE_PROMPT =\n 'Continue with the task. Do not stop to ask whether to proceed — keep going until the task is '\n + 'genuinely complete. Only stop if you have finished, or if you need a decision or input that '\n + 'only the operator can provide, in which case state the specific question plainly.';\n\n /** Characters of an end-of-turn message kept on a continuation record for audit. */\n private static readonly CONTINUATION_MESSAGE_TAIL_CHARS = 500;\n\n /**\n * Drive a coding session turn-by-turn: continue a self-imposed pause, park a\n * genuine question, settle on completion — bounded by the profile's\n * continuation budget.\n *\n * The MECHANISM lives here; the JUDGMENT (`classify`) is the host's. The whole\n * loop fails toward settlement: any terminal stop reason, an exhausted budget,\n * or a classifier that is absent or throws all end the run with what the agent\n * has produced rather than hanging. A `NEEDS_INPUT` classification is the only\n * path that returns a `suspension`, and the caller must not read that as a\n * completed result.\n */\n private async driveCodingTurnLadder(params: {\n session: ACPAgentSession;\n firstPrompt: string;\n maxAutoContinuations: number;\n awaitingInputTtlMs: number;\n turnTimeoutMs?: number;\n abortSignal?: AbortSignal;\n classify?: AgentInvocationHostContext['classifyCodingTurnEnd'];\n onStateChange?: AgentInvocationHostContext['onCodingSessionStateChange'];\n }): Promise<{\n finalMessage: string;\n stopReason: CodingAgent_StopReason;\n rawStopReason?: string;\n usage?: CodingAgent_Usage;\n reportedFileLocations: string[];\n deniedPermissionCount: number;\n permissionDecisions: NonNullable<CodingAgent_RunTaskOutput['permissionDecisions']>;\n turnCount: number;\n continuations: CodingAgent_ContinuationRecord[];\n suspension?: CodingAgent_SessionSuspension;\n }> {\n const { session } = params;\n const reportedFileLocations: string[] = [];\n // Copied into the OUTPUT's mutable element shape here: the runner hands out\n // readonly records, and the published contract's field is mutable.\n const permissionDecisions: NonNullable<CodingAgent_RunTaskOutput['permissionDecisions']> = [];\n const continuations: CodingAgent_ContinuationRecord[] = [];\n let usage: CodingAgent_Usage | undefined;\n let deniedPermissionCount = 0;\n let turnIndex = 0;\n let autoContinuesUsed = 0;\n let prompt = params.firstPrompt;\n\n const emitState = (state: CodingSessionLadderState): void => {\n try {\n params.onStateChange?.(state);\n } catch {\n // A live-relay sink must never fail the run it observes.\n }\n };\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n turnIndex += 1;\n emitState({ phase: CodingSessionLadderPhase.RUNNING, turnIndex });\n\n const turn = await session.promptTurn(prompt, {\n ...(params.turnTimeoutMs !== undefined ? { turnTimeoutMs: params.turnTimeoutMs } : {}),\n ...(params.abortSignal ? { abortSignal: params.abortSignal } : {}),\n });\n\n // Aggregate every turn's evidence, whatever the ladder decides next.\n for (const path of turn.reportedFileLocations) {\n if (!reportedFileLocations.includes(path)) reportedFileLocations.push(path);\n }\n for (const decision of turn.permissionDecisions) {\n permissionDecisions.push({\n ...decision,\n locations: [...decision.locations],\n offeredOptionKinds: [...decision.offeredOptionKinds],\n });\n }\n deniedPermissionCount += turn.deniedPermissionCount;\n usage = this.mergeCodingUsage(usage, turn.usage);\n\n const settle = (suspension?: CodingAgent_SessionSuspension) => ({\n finalMessage: turn.finalMessage,\n stopReason: turn.stopReason,\n ...(turn.rawStopReason ? { rawStopReason: turn.rawStopReason } : {}),\n usage,\n reportedFileLocations,\n deniedPermissionCount,\n permissionDecisions,\n turnCount: turnIndex,\n continuations,\n ...(suspension ? { suspension } : {}),\n });\n\n // A non-voluntary stop (cancelled, max_tokens, refusal, or a reason this\n // version does not recognise) is terminal: there is nothing to continue.\n if (turn.stopReason !== CodingAgent_StopReason.END_TURN) {\n return settle();\n }\n\n // END_TURN: decide what it meant. No classifier → treat as complete AND\n // record nothing (the pre-ladder behaviour, preserved for every caller\n // that supplies none — a plain single turn carries no continuations).\n if (!params.classify) {\n return settle();\n }\n const classification = await this.classifyCodingTurnEndSafely(params.classify, turn.finalMessage, turnIndex);\n\n // A boundary is recorded only when the classifier was actually consulted,\n // so `continuations` is the audit trail of judgments, never a per-run\n // artefact that pollutes the single-turn shape.\n continuations.push({\n turnIndex,\n classification,\n agentMessageTail: turn.finalMessage.slice(-AgentsBackendService.CONTINUATION_MESSAGE_TAIL_CHARS),\n });\n\n if (classification === CodingAgent_EndOfTurnClassification.NEEDS_INPUT) {\n const suspension: CodingAgent_SessionSuspension = {\n sessionId: session.sessionId,\n question: turn.finalMessage,\n turnIndex,\n // Answerable across the child's death only if the agent persists sessions.\n resumable: session.capabilities.loadSession,\n parkedUntil: new Date(Date.now() + params.awaitingInputTtlMs).toISOString(),\n };\n emitState({ phase: CodingSessionLadderPhase.AWAITING_INPUT, turnIndex, question: turn.finalMessage });\n return settle(suspension);\n }\n\n const isSelfPause = classification === CodingAgent_EndOfTurnClassification.SELF_PAUSE;\n if (!isSelfPause || autoContinuesUsed >= params.maxAutoContinuations) {\n // TASK_COMPLETE, CLASSIFIER_UNAVAILABLE, or a self-pause past the budget:\n // settle with what the agent last produced.\n return settle();\n }\n\n autoContinuesUsed += 1;\n prompt = AgentsBackendService.CODING_AUTO_CONTINUE_PROMPT;\n }\n }\n\n /**\n * Run the host's end-of-turn classifier, mapping every failure to\n * `CLASSIFIER_UNAVAILABLE` so the ladder can settle rather than hang.\n *\n * The whole point of a separate method: the fail-open contract is one place,\n * and an unexpected classifier value (a host returning a string outside the\n * enum) degrades the same way a throw does.\n */\n private async classifyCodingTurnEndSafely(\n classify: NonNullable<AgentInvocationHostContext['classifyCodingTurnEnd']>,\n finalMessage: string,\n turnIndex: number,\n ): Promise<CodingAgent_EndOfTurnClassification> {\n try {\n const result = await classify({ finalMessage, turnIndex });\n if (Object.values(CodingAgent_EndOfTurnClassification).includes(result)) {\n return result;\n }\n this.logger.warn('Coding turn-end classifier returned an unrecognised value; treating the turn as complete', {\n turnIndex,\n received: String(result),\n });\n return CodingAgent_EndOfTurnClassification.CLASSIFIER_UNAVAILABLE;\n } catch (error) {\n // Fail OPEN. An auxiliary judgment must never make the autonomous lane hang\n // or discard a mutated workspace; the failure is recorded, not laundered.\n // The classifier is a model call, so its failure can be a vendor refusal quoting the turn it was asked about:\n // described like every model-call failure (#2368), never its message or JSON by value. A WildoBackendError (which\n // does not pass `instanceof Error`) reads by its `message`, so a missing config bound is still named (2026-09-04).\n this.logger.warn('Coding turn-end classifier failed; treating the turn as complete', {\n turnIndex,\n ...describeModelCallError(error),\n });\n return CodingAgent_EndOfTurnClassification.CLASSIFIER_UNAVAILABLE;\n }\n }\n\n /**\n * Combine per-turn usage into a session total: token counts SUM across turns;\n * the context-window pair and the COST are levels, so the latest turn's value\n * wins. Absence stays absence — a field nobody reported must not read as zero,\n * per the usage contract.\n *\n * Cost is a level because ACP reports it as the session's cumulative total, and\n * every turn of a coding run is a turn of ONE session (`promptTurn` on the same\n * runner). Summing it, as this did until #2232, counted a two-turn run's first\n * turn twice: four of app-creation-test-004's coding runs were two-turn. A turn\n * that reports no cost keeps the earlier turn's figure, which is the session's\n * total so far rather than nothing.\n *\n * spec-cite: ACP schema (`@agentclientprotocol/sdk` 1.5.0) — `UsageUpdate.cost` \"Cumulative session cost (optional)\";\n * the Claude Agent SDK's `total_cost_usd`, which the pinned adapter forwards, is likewise cumulative across turns\n * of a streaming-input session (`sdk.d.ts`, `SDKResultMessage.total_cost_usd`).\n */\n private mergeCodingUsage(\n accumulated: CodingAgent_Usage | undefined,\n turn: CodingAgent_Usage | undefined,\n ): CodingAgent_Usage | undefined {\n if (!turn) return accumulated;\n if (!accumulated) return turn;\n const merged: CodingAgent_Usage = { ...accumulated };\n for (const key of ['inputTokens', 'outputTokens', 'cachedReadTokens', 'cachedWriteTokens', 'totalTokens'] as const) {\n const a = accumulated[key];\n const b = turn[key];\n if (a !== undefined || b !== undefined) merged[key] = (a ?? 0) + (b ?? 0);\n }\n // The context window is a level, not a flow: the newest reading is current.\n if (turn.contextUsed !== undefined) merged.contextUsed = turn.contextUsed;\n if (turn.contextWindowSize !== undefined) merged.contextWindowSize = turn.contextWindowSize;\n // The session's cumulative cost: the latest turn that reported one is the total so far — unless it reported\n // a zero after a positive figure, which is a crashed result's zeroed value and not a cost (`latestCumulativeCost`).\n const cost = latestCumulativeCost(accumulated.cost, turn.cost);\n if (cost !== undefined) merged.cost = { amount: cost.amount, currency: cost.currency };\n return merged;\n }\n\n private buildBaseOptions(config: FlowsActors_Agent_LLMConfiguration): any {\n const baseOptions: any = {\n temperature: config.temperature,\n topP: config.topP,\n };\n\n // Only set maxOutputTokens if explicitly configured\n if (config.maxTokens !== undefined) {\n baseOptions.maxOutputTokens = config.maxTokens;\n }\n\n if (config.seed !== undefined) {\n baseOptions.seed = config.seed;\n }\n\n // Reasoning-effort control (Phase 3): the config enum values mirror the AI\n // SDK 7 top-level `reasoning` option exactly, so this is a direct pass-through.\n // The SDK maps it to each provider's native reasoning setting; non-reasoning\n // models ignore it. Omitted → provider default (pre-Phase-3 behavior).\n if (config.reasoningEffort !== undefined) {\n baseOptions.reasoning = config.reasoningEffort;\n }\n\n // The agent's system prompt is passed via the top-level `instructions:` option of EVERY\n // generateText/streamText call (see `executeGenerateText` and the chat builders below) — AI-SDK v7\n // (`ai@7`) rejects a `role:'system'` entry inside `messages`/`prompt`, and `buildChatMessages`\n // keeps the messages array system-free. Do NOT re-introduce a \"system in messages\" opt-in flag here:\n // a prior `baseOptions.allowSystemInMessages = true` was a SILENT NO-OP (that is not the real option\n // name — the v7 flag is the terse `l` param), which is exactly why every chat turn kept failing with\n // `AI_InvalidPromptError` until the system prompt was hoisted to `instructions:`.\n\n return baseOptions;\n }\n\n /**\n * Execute GENERATE_TEXT operation\n */\n private async executeGenerateText({ model, systemPrompt, instructions, input, baseOptions }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n /** The invocation input: a conversation in it is sent as `messages` (`textGenerationPromptOf`). */\n input?: unknown;\n baseOptions: any;\n }): Promise<AgentOperationExecutionResult> {\n try {\n const result = await generateText({\n model,\n ...this.textGenerationPromptOf(instructions, input),\n instructions: systemPrompt,\n ...baseOptions,\n });\n\n return {\n output: {\n text: result.text,\n },\n usage: this.extractUsage(result.usage),\n };\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Generate text operation failed - provider response', {\n operation: 'GENERATE_TEXT',\n hasSystemPrompt: !!systemPrompt,\n instructionsLength: instructions.length,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'GENERATE_TEXT',\n message: `Failed to generate text: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Execute CHAT_COMPLETION operation\n */\n private async executeChatCompletion({ model, systemPrompt, instructions, input, baseOptions }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n input: any;\n baseOptions: any;\n }): Promise<AgentOperationExecutionResult> {\n try {\n const messages = this.buildChatMessages(instructions, input);\n\n const result = await generateText({\n model,\n messages,\n // System prompt via the top-level option (AI-SDK v7 forbids it inside `messages`).\n instructions: systemPrompt,\n ...baseOptions,\n });\n\n return {\n output: {\n message: {\n role: LLMProvider_MessageRole.ASSISTANT,\n content: result.text,\n },\n },\n usage: this.extractUsage(result.usage),\n };\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Chat completion operation failed - provider response', {\n operation: 'CHAT_COMPLETION',\n hasSystemPrompt: !!systemPrompt,\n hasInputMessages: input && typeof input === 'object' && 'messages' in input,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'CHAT_COMPLETION',\n message: `Failed to complete chat: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Execute CHAT_MULTIMODAL operation\n */\n private async executeChatMultimodal({ model, systemPrompt, instructions, input, baseOptions }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n input: any;\n baseOptions: any;\n }): Promise<AgentOperationExecutionResult> {\n let messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string | Array<any> }> = [];\n\n try {\n if (input && typeof input === 'object' && 'messages' in input && Array.isArray(input.messages)) {\n // System prompt travels via the top-level `instructions:` option; drop any\n // `role:'system'` entries (AI-SDK v7 rejects them inside `messages`).\n messages = input.messages.filter((m: any) => m.role !== 'system');\n } else {\n messages.push({ role: 'user', content: instructions });\n }\n\n if (messages.length === 0) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.AGENT_MESSAGES_REQUIRED,\n context: {\n // diagnostic (log-only)\n operation: 'CHAT_MULTIMODAL',\n },\n }\n );\n }\n\n const result = await generateText({\n model,\n messages: this.normalizeSdkMessages(messages),\n // System prompt via the top-level option (AI-SDK v7 forbids it inside `messages`).\n instructions: systemPrompt,\n ...baseOptions,\n });\n\n return {\n output: {\n message: {\n role: LLMProvider_MessageRole.ASSISTANT,\n content: result.text,\n },\n },\n usage: this.extractUsage(result.usage),\n };\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Chat multimodal operation failed - provider response', {\n operation: 'CHAT_MULTIMODAL',\n hasSystemPrompt: !!systemPrompt,\n hasInputMessages: input && typeof input === 'object' && 'messages' in input,\n messagesCount: messages.length,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'CHAT_MULTIMODAL',\n message: `Failed to complete multimodal chat: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Read the OPTIONAL vision image parts off a GENERATE_STRUCTURED invocation\n * input (see `LLMProvider_GenerateStructuredInputSchema.images`). Returns `[]`\n * when none are present so the caller stays on the plain text-prompt path.\n * Defensive at the boundary: only well-formed `{ type: 'image', image }` parts\n * (non-empty string locator) survive; anything else is dropped rather than\n * handed to the SDK as a broken content part.\n */\n private extractStructuredInputImages(input: unknown): LLMProvider_ImageContent[] {\n if (!this.isRecord(input) || !Array.isArray(input.images)) {\n return [];\n }\n return (input.images as unknown[]).filter(\n (part): part is LLMProvider_ImageContent =>\n this.isRecord(part)\n && part.type === 'image'\n && typeof part.image === 'string'\n && part.image.length > 0,\n );\n }\n\n /**\n * Build the AI-SDK content argument for a structured-generation call.\n *\n * With no images this is a plain `{ prompt }` (text-only structured\n * generation — the historical behaviour, byte-identical). With images it\n * becomes a single multimodal user `{ messages: [...] }` whose content is the\n * instruction text followed by each image part, so the AI SDK feeds the pixels\n * to a vision-capable model (e.g. `gpt-4o`) and constrains the answer to the\n * requested schema. `system` is passed separately by the caller and is not\n * duplicated here.\n */\n private buildStructuredContentArgs(\n instructions: string,\n images: LLMProvider_ImageContent[],\n ): { prompt: string } | { messages: Array<{ role: 'user'; content: Array<Record<string, unknown>> }> } {\n if (images.length === 0) {\n return { prompt: instructions };\n }\n return {\n messages: [\n {\n role: 'user',\n content: [\n { type: 'text', text: instructions },\n ...images.map((part) => this.toSdkFilePart(part.image)),\n ],\n },\n ],\n };\n }\n\n /**\n * Translate our internal image locator (`LLMProvider_ImageContent.image` — a\n * data URI or URL) into an AI SDK v7 **file content part**.\n *\n * WHY: the SDK's `{ type: 'image', image }` content part was deprecated in v7\n * (it warns on every call and becomes a hard error in a future major). The v7\n * shape is `{ type: 'file', data, mediaType }`. This is the ONE translation\n * seam — our own `{ type: 'image', image }` domain vocabulary\n * ({@link LLMProvider_ImageContentSchema}) is intentionally kept; only the\n * SDK-facing emission changes.\n *\n * `mediaType` is required by the file part. We derive the concrete type from a\n * data URI when present (the case both internal producers actually emit —\n * they build `data:image/<fmt>;base64,…`); for a bare URL we sniff the\n * extension and fall back to the generic `image/*` the SDK itself suggests.\n */\n private toSdkFilePart(image: string): { type: 'file'; data: string; mediaType: string } {\n return { type: 'file', data: image, mediaType: this.deriveImageMediaType(image) };\n }\n\n /** Best-effort image media-type from a data URI or URL; generic `image/*` if unknown. */\n private deriveImageMediaType(image: string): string {\n const dataUri = /^data:(image\\/[^;]+)[;,]/i.exec(image);\n if (dataUri) return dataUri[1].toLowerCase();\n const ext = /\\.(png|jpe?g|gif|webp|bmp|svg|avif|tiff?)(?:[?#]|$)/i.exec(image);\n if (ext) {\n const e = ext[1].toLowerCase();\n if (e === 'jpg' || e === 'jpeg') return 'image/jpeg';\n if (e === 'svg') return 'image/svg+xml';\n if (e === 'tif' || e === 'tiff') return 'image/tiff';\n return `image/${e}`;\n }\n return 'image/*';\n }\n\n /**\n * Rewrite any legacy `{ type: 'image', image }` parts inside caller-supplied\n * CHAT_MULTIMODAL messages into v7 file parts, leaving every other part\n * untouched. Defensive: the internal producers route images through the\n * structured path above, but CHAT_MULTIMODAL forwards opaque caller `messages`\n * verbatim, so a caller passing the deprecated shape would otherwise leak it\n * to the SDK. Fail-open on unexpected shapes — never drop a caller's content.\n */\n private normalizeSdkMessages(\n messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string | Array<any> }>,\n ): Array<{ role: 'system' | 'user' | 'assistant'; content: string | Array<any> }> {\n return messages.map((message) => {\n if (!Array.isArray(message.content)) return message;\n const content = message.content.map((part) =>\n this.isRecord(part) && part.type === 'image' && typeof part.image === 'string'\n ? this.toSdkFilePart(part.image)\n : part,\n );\n return { ...message, content };\n });\n }\n\n /**\n * Execute GENERATE_STRUCTURED operation\n */\n private async executeGenerateStructured({\n model,\n systemPrompt,\n instructions,\n input,\n baseOptions,\n llmProviderConfig,\n providerRef,\n structuredGenerationExecutionMode,\n maximumStructuredOutputLeafFields,\n }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n input: any;\n baseOptions: any;\n llmProviderConfig?: LLMProvider_Configuration;\n providerRef: string;\n structuredGenerationExecutionMode?: StructuredGenerationExecutionMode;\n maximumStructuredOutputLeafFields?: number;\n }): Promise<AgentOperationExecutionResult> {\n try {\n if (!input || typeof input !== 'object' || !('schema' in input) || !input.schema) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.AGENT_STRUCTURED_SCHEMA_REQUIRED,\n context: {\n // diagnostic (log-only)\n operation: 'GENERATE_STRUCTURED',\n hasInput: !!input,\n inputType: typeof input,\n hasSchema: input && typeof input === 'object' && 'schema' in input,\n },\n }\n );\n }\n\n const schema = input.schema;\n const images = this.extractStructuredInputImages(input);\n if (\n structuredGenerationExecutionMode === StructuredGenerationExecutionMode.SINGLE_CALL_REQUIRED\n && (!Number.isSafeInteger(maximumStructuredOutputLeafFields) || (maximumStructuredOutputLeafFields ?? 0) <= 0)\n ) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: {\n operation: 'GENERATE_STRUCTURED',\n message: 'A single-call structured agent requires one positive immutable maximumStructuredOutputLeafFields value.',\n },\n });\n }\n const maxFields = maximumStructuredOutputLeafFields\n ?? llmProviderConfig?.maxStructuredDataFieldAllowed\n ?? DEFAULT_MAX_STRUCTURED_DATA_FIELD_ALLOWED;\n const isOpenAI = this.llmProviderRequestsStrictJsonSchema(providerRef);\n const strictSchemaProfile = isOpenAI === true ? this.llmProviderStrictSchemaProfile(providerRef) : undefined;\n const nativeConstrainedDecoding = isOpenAI === true ? undefined : this.llmProviderNativeConstrainedDecoding(providerRef);\n\n const shapePlan = planStructuredGenerationShape(schema, maxFields);\n\n this.logDebug('Checking if schema needs chunking', {\n leafFieldCount: shapePlan.leafFieldCount,\n maxFields,\n needsChunking: shapePlan.planKind === StructuredGenerationPlanKind.CHUNKED,\n unchunkableOverLimit: shapePlan.planKind === StructuredGenerationPlanKind.UNCHUNKABLE_OVER_LIMIT,\n isOpenAI,\n imageCount: images.length,\n });\n\n if (\n structuredGenerationExecutionMode === StructuredGenerationExecutionMode.SINGLE_CALL_REQUIRED\n && shapePlan.planKind !== StructuredGenerationPlanKind.SINGLE_CALL\n ) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: {\n operation: 'GENERATE_STRUCTURED',\n message: 'The registered agent requires one physical provider call, but the output schema requires chunking.',\n leafFieldCount: shapePlan.leafFieldCount,\n maxFields,\n },\n });\n }\n\n if (shapePlan.planKind === StructuredGenerationPlanKind.UNCHUNKABLE_OVER_LIMIT) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: {\n operation: 'GENERATE_STRUCTURED',\n message: 'The output schema exceeds the provider field limit and its root semantics cannot be preserved across chunks.',\n leafFieldCount: shapePlan.leafFieldCount,\n maxFields,\n },\n });\n }\n\n if (shapePlan.planKind === StructuredGenerationPlanKind.CHUNKED) {\n return await this.executeGenerateStructuredChunked({\n model,\n systemPrompt,\n instructions,\n images,\n schema,\n baseOptions,\n maxFields,\n leafFieldCount: shapePlan.leafFieldCount,\n schemaChunks: shapePlan.schemaChunks,\n isOpenAI,\n strictSchemaProfile,\n nativeConstrainedDecoding,\n });\n } else {\n return await this.executeGenerateStructuredSingle({\n model,\n systemPrompt,\n instructions,\n images,\n schema,\n baseOptions,\n isOpenAI,\n strictSchemaProfile,\n nativeConstrainedDecoding,\n includeRejectedAnswer: (input as { includeRejectedAnswer?: unknown }).includeRejectedAnswer === true,\n });\n }\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Generate structured operation failed - provider response', {\n operation: 'GENERATE_STRUCTURED',\n hasSchema: input && typeof input === 'object' && 'schema' in input,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'GENERATE_STRUCTURED',\n message: `Failed to generate structured data: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Execute structured generation with chunking - runs chunks in parallel\n */\n private async executeGenerateStructuredChunked({ model, systemPrompt, instructions, images, schema, baseOptions, maxFields, leafFieldCount, schemaChunks, isOpenAI, strictSchemaProfile, nativeConstrainedDecoding }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n images: LLMProvider_ImageContent[];\n schema: z.ZodSchema<any>;\n baseOptions: any;\n maxFields: number;\n leafFieldCount: number;\n schemaChunks: readonly z.ZodSchema[];\n isOpenAI: boolean | null;\n /** The provider's strict-mode limits, present when it requests strict decoding (#2344). */\n strictSchemaProfile?: StrictStructuredOutputProfile;\n /** The provider's native constrained-decoding limits and unconstrained path, when it declares them (#3146). */\n nativeConstrainedDecoding?: NativeConstrainedDecodingContract;\n }): Promise<AgentOperationExecutionResult> {\n try {\n this.logDebug('Chunking structured generation - parallel execution', {\n totalLeafFields: leafFieldCount,\n maxFields,\n chunks: schemaChunks.length,\n isOpenAI,\n });\n\n // Execute all chunks in parallel using Promise.all\n const chunkPromises = schemaChunks.map(async (chunkSchema, index) => {\n try {\n this.logDebug(`Starting structured chunk ${index + 1}/${schemaChunks.length}`);\n\n const prepared = this.prepareStructuredOutputSchema(chunkSchema, isOpenAI, strictSchemaProfile, nativeConstrainedDecoding, languageModelId(model));\n const chunkResult = await this.generateObjectHonouringStrictRefusal(prepared, (call) => generateObject({\n model,\n mode: \"json\",\n instructions: systemPrompt,\n schema: call.schema,\n ...this.buildStructuredContentArgs(instructions, images),\n ...this.structuredCallBaseOptions(baseOptions, call),\n ...call.providerOptions,\n }));\n\n this.logDebug(`Completed structured chunk ${index + 1}/${schemaChunks.length}`);\n\n return {\n index,\n object: chunkResult.object as Record<string, unknown>,\n usage: this.extractUsage(chunkResult.usage),\n failure: null as unknown,\n };\n } catch (error) {\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error(`Failed to generate structured chunk ${index + 1}/${schemaChunks.length} - provider response`, {\n operation: 'GENERATE_STRUCTURED',\n chunkIndex: index,\n totalChunks: schemaChunks.length,\n ...errorDetails,\n });\n\n // Same rule the single-call path states: a structured-generation failure carrying provider\n // usage IS a completed physical call, so throwing here discards billable truth. This site\n // used to throw, and it cost a live application its budget allocation PERMANENTLY -- the\n // discarded usage made the settlement ACCOUNTING_UNVERIFIABLE, which fail-closes every later\n // admission on that allocation, and a Work Cycle's allocation is bootstrapped once for the\n // application's life. The provider had reported exact usage on the very error we then called\n // unverifiable (6,680 input / 3,521 output tokens, with the cache-write split).\n //\n // Returning rather than throwing also keeps the SIBLING chunks' metering, which `Promise.all`\n // would otherwise drop on the floor along with this one.\n return {\n index,\n object: null,\n usage: this.extractUsage(\n typeof error === 'object' && error !== null && 'usage' in error\n ? (error as { usage: unknown }).usage\n : undefined,\n ),\n failure: error as unknown,\n };\n }\n });\n\n // Wait for all chunks to complete in parallel\n const chunkResultsWithMeta = await Promise.all(chunkPromises);\n\n // Sort by index to ensure consistent merge order, then extract objects\n const chunkResults = chunkResultsWithMeta\n .sort((a, b) => a.index - b.index)\n .flatMap(r => (r.object === null ? [] : [r.object]));\n\n // Aggregate usage from all chunks. A cache or reasoning split is summed only when EVERY chunk reported\n // it (#1598): a total over the chunks that happened to report would understate the split and read as exact.\n const { inputTokenDetails: exactInputTokenDetails, outputTokenDetails: exactOutputTokenDetails, ...totalUsage } =\n this.aggregateExtractedUsage(chunkResultsWithMeta.map((result) => result.usage));\n\n // Aggregate metering FIRST (above), then decide the outcome: a partially-failed chunked call is\n // still a set of completed, billable physical calls, and the Driver must be able to account for\n // every one of them before it classifies the missing object.\n // #2292 Phase 3: a chunk withheld by output moderation fails the whole answer as a withholding, metered over EVERY\n // chunk (siblings included) — the reason the chunks return their failure rather than throw.\n const withheldChunk = chunkResultsWithMeta.find((result) => result.failure instanceof AgentOutputWithheldError);\n if (withheldChunk !== undefined) {\n throw (withheldChunk.failure as AgentOutputWithheldError).withUsage({\n ...totalUsage,\n ...(exactInputTokenDetails === undefined ? {} : { inputTokenDetails: exactInputTokenDetails }),\n ...(exactOutputTokenDetails === undefined ? {} : { outputTokenDetails: exactOutputTokenDetails }),\n });\n }\n // #3204: a chunk the provider's ACCOUNT refused (no credits, a spend limit) is no answer the model failed to give.\n // Returned as a missing object it would read as the model's failure and be asked again; it fails the call as the\n // environment's refusal instead, whose remedy is a person's.\n const accountRefusedChunk = chunkResultsWithMeta.find((result) => result.failure !== null && readModelProviderAccountRefusal(result.failure) !== undefined);\n if (accountRefusedChunk !== undefined) {\n const errorDetails = this.extractProviderErrorDetails(accountRefusedChunk.failure);\n throw this.buildModelCallFailure(accountRefusedChunk.failure, errorDetails, {\n operation: 'GENERATE_STRUCTURED',\n message: `Failed to generate structured data with chunking: ${errorDetails.errorMessage}`,\n });\n }\n const failedChunk = chunkResultsWithMeta.find((result) => result.object === null);\n // `includeRejectedAnswer` is deliberately NOT honoured here: a failed chunk's text is one fragment of\n // the answer, and handing it to a retry as \"your previous answer\" would tell the model it wrote less\n // than it did. A chunked caller keeps the findings-only retry.\n if (failedChunk !== undefined) {\n const failureError = failedChunk.failure as { cause?: unknown; finishReason?: unknown; text?: unknown };\n return {\n output: { object: undefined },\n usage: {\n ...totalUsage,\n ...(exactInputTokenDetails === undefined ? {} : { inputTokenDetails: exactInputTokenDetails }),\n ...(exactOutputTokenDetails === undefined ? {} : { outputTokenDetails: exactOutputTokenDetails }),\n },\n structuredGenerationFailure: this.buildStructuredGenerationFailure(\n typeof failedChunk.failure === 'object' && failedChunk.failure !== null && 'usage' in failedChunk.failure\n ? LLMProvider_StructuredGenerationFailureKind.INVALID_OBJECT_AFTER_COMPLETED_CALL\n : LLMProvider_StructuredGenerationFailureKind.NO_OBJECT_GENERATED,\n failedChunk.failure,\n failureError,\n ),\n };\n }\n\n const mergedResult = this.mergeChunkedObjects(chunkResults);\n\n this.logDebug('All structured chunks completed and merged', {\n chunks: schemaChunks.length,\n totalUsage,\n });\n\n return {\n output: {\n object: mergedResult,\n },\n usage: {\n ...totalUsage,\n ...(exactInputTokenDetails === undefined ? {} : { inputTokenDetails: exactInputTokenDetails }),\n ...(exactOutputTokenDetails === undefined ? {} : { outputTokenDetails: exactOutputTokenDetails }),\n },\n };\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'GENERATE_STRUCTURED',\n message: `Failed to generate structured data with chunking: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Assemble the caller-facing reason a structured generation produced no object.\n *\n * Carries NO generated text — only `generatedTextLength`, which separates a truncated\n * completion from an empty one without disclosing content. `validationIssues` likewise\n * carries only an issue's code, path, what the SCHEMA expected, and — for a `custom` issue\n * alone — the sentence a refinement in this repository's own source wrote. Never Zod's\n * message for any other code, which is composed around the rejected value\n * (see {@link projectStructuredValidationIssues}).\n *\n * The chunked path calls this too. It used to throw a typed backend error instead, on the\n * reasoning that the reason \"already reaches the caller intact\" -- true of the REASON and false\n * of the USAGE, which is what the budget settles against. See the failure branch in\n * {@link executeGenerateStructuredChunked} for what that cost.\n */\n private buildStructuredGenerationFailure(\n kind: LLMProvider_StructuredGenerationFailureKind,\n error: unknown,\n providerError: { cause?: unknown; finishReason?: unknown; text?: unknown },\n ): LLMProvider_StructuredGenerationFailure {\n const errorName = error instanceof Error\n ? error.name\n : (typeof error === 'object' && error !== null && 'name' in error && typeof error.name === 'string'\n ? error.name\n : typeof error);\n const cause = providerError.cause;\n const validationCauseName = cause instanceof Error\n ? cause.name\n : (typeof cause === 'object' && cause !== null && 'name' in cause && typeof cause.name === 'string'\n ? cause.name\n : typeof cause);\n const validationIssues = projectStructuredValidationIssues(cause);\n // ROOT KEY NAMES, and only when the failure is `unrecognized_keys`.\n //\n // Zod 4 builds that issue at two sites and only one carries `keys` (v4/core/schemas.js:748 vs :1352);\n // the path taken here is the one that omits them, so the issue reports \"some unknown key exists at the\n // root\" and nothing more. That is undiagnosable: a single stray key discards a 40,000-character result\n // and there is no way to learn which key it was.\n //\n // The boundary this function holds is about VALUES: the rejected content must never reach a log. Root\n // KEY NAMES of a schema-driven generation are schema shape, are compared against a schema the reader\n // already has, and are emitted only on this one failure code -- never for `invalid_type`,\n // `invalid_format` or any issue whose path could name user content.\n const rootKeys = validationIssues.some((issue) => issue.code === 'unrecognized_keys')\n ? projectStructuredRootKeyNames(providerError.text)\n : undefined;\n return {\n kind,\n /*\n * NOT `describeCaughtError(error)`, which resolves to `error.message` — and an AI SDK\n * structured-generation error's message IS a JSON serialization of the whole error, carrying\n * `text` (the model's rejected output), `response.body` and the validation `value`.\n *\n * The rule was already written down one field over: `LLMProvider_StructuredValidationIssueSchema`\n * drops each issue's own `message` because \"a provider validation error retains the rejected\n * value in its message, so carrying it would copy private model output into any log, trace or\n * persisted failure record that receives this reason\". That is exactly this field — and the\n * envelope's own schema promises \"Contains NO generated text\", a promise this line broke for\n * every consumer, including `describeStructuredGenerationFailure`, whose docstring repeats it.\n *\n * Built from the two payload-free facts already resolved above. Nothing diagnostic is lost:\n * `errorName`, `validationCauseName`, `validationIssues`, `finishReason` and\n * `generatedTextLength` carry the whole picture, and the rejected text still reaches a caller\n * that explicitly opted in — on the OUTPUT, where this boundary does not apply.\n */\n message: `${errorName} (${kind})`,\n errorName,\n validationCauseName,\n ...(validationIssues.length > 0\n ? {\n validationIssues: validationIssues.map((issue) => ({\n code: issue.code,\n path: [...issue.path],\n ...(issue.keys ? { keys: [...issue.keys] } : {}),\n ...(issue.expected ? { expected: issue.expected } : {}),\n ...(issue.format ? { format: issue.format } : {}),\n ...(issue.pattern ? { pattern: issue.pattern } : {}),\n ...(issue.values ? { values: [...issue.values] } : {}),\n ...(issue.refinementMessage ? { refinementMessage: issue.refinementMessage } : {}),\n })),\n }\n : {}),\n ...(rootKeys && rootKeys.length > 0 ? { rootKeys: [...rootKeys] } : {}),\n ...(typeof providerError.finishReason === 'string' ? { finishReason: providerError.finishReason } : {}),\n generatedTextLength: typeof providerError.text === 'string' ? providerError.text.length : null,\n };\n }\n\n /**\n * The schema a structured call sends, and whether it is decoded STRICTLY (#2344).\n *\n * A provider whose contract requests strict JSON Schema (`structuredOutputs.strictJsonSchema: true`) is\n * sent the strict form derived from the Zod schema (`deriveStrictStructuredOutputSchema`): every\n * property required, every object closed, optional members as a `null` union. The Zod schema stays the\n * VALIDATOR, through `jsonSchema(…, { validate })`, after the answer is restored to its own shape, so\n * defaults, refinements and the paths of any rejection are exactly what they were. A schema with no\n * strict form is sent as it is with strict mode OFF, and the reason is logged.\n *\n * `restoreAnswerText` maps a REJECTED answer's text back to the original shape too: a retry patches\n * that text as \"your previous answer\", and the `null`s strict decoding wrote for absent members would\n * otherwise read as values the original schema refuses.\n *\n * A provider that instead declares NATIVE constrained decoding with complexity limits (Anthropic, #3146) is\n * prepared by `prepareForNativeConstrainedDecoding`: the schema is sent as it is, constrained or not depending on\n * whether it fits those limits, and nothing is derived or restored.\n */\n private prepareStructuredOutputSchema(\n schema: z.ZodSchema<any>,\n requestsStrictJsonSchema: boolean | null,\n strictSchemaProfile: StrictStructuredOutputProfile | undefined,\n nativeConstrainedDecoding?: NativeConstrainedDecodingContract,\n modelId?: string,\n ): PreparedStructuredOutputSchema {\n // The model answers in JSON (#3478): the schema it is decoded with, and described to it, is the JSON form of the one\n // declared, so a `z.date()` reads an RFC 3339 string and has a JSON Schema shape at all (a plain date has none).\n schema = jsonParsingSchemaOf(schema);\n const asSent = (strictJsonSchema: boolean | null) => (strictJsonSchema === null ? {} : { providerOptions: { openai: { strictJsonSchema } } });\n const lax = { schema, providerOptions: asSent(requestsStrictJsonSchema === null ? null : false) };\n if (requestsStrictJsonSchema !== true && nativeConstrainedDecoding !== undefined) {\n return this.prepareForNativeConstrainedDecoding(schema, nativeConstrainedDecoding, modelId);\n }\n if (requestsStrictJsonSchema !== true) {\n return { strict: undefined, lax: { schema, providerOptions: asSent(requestsStrictJsonSchema) }, decodedStrictly: false, restoreAnswerText: (text) => text };\n }\n if (strictSchemaProfile === undefined) {\n // The contract type makes the profile required beside `strictJsonSchema: true`; this is the door for\n // a caller that reached here without one, and it decodes as before rather than guessing limits.\n this.logger.warn('Strict structured output requested with no strict-mode profile; decoding without strict mode', { operation: 'GENERATE_STRUCTURED' });\n return { strict: undefined, lax, decodedStrictly: false, restoreAnswerText: (text) => text };\n }\n const derived = deriveStrictStructuredOutputSchema(schema, strictSchemaProfile);\n if (derived.kind === StrictStructuredOutputSchemaKind.UNREPRESENTABLE) {\n this.logger.warn('Structured output has no strict schema form; decoding without strict mode', {\n operation: 'GENERATE_STRUCTURED',\n reasons: derived.reasons.slice(0, 10),\n reasonCount: derived.reasons.length,\n });\n return { strict: undefined, lax, decodedStrictly: false, restoreAnswerText: (text) => text };\n }\n if (derived.narrowings.length > 0) {\n // At info, not debug: a narrowing is a place the model CANNOT write, and the module that finds it\n // promises it is reported, never hidden (#2344 review).\n this.logger.info('Strict structured output leaves members out of decoding', { operation: 'GENERATE_STRUCTURED', narrowings: derived.narrowings });\n }\n const prepared: PreparedStructuredOutputSchema = {\n strict: {\n schema: jsonSchema(derived.jsonSchema as Parameters<typeof jsonSchema>[0], {\n validate: (value) => {\n const parsed = schema.safeParse(derived.restore(value));\n return parsed.success ? { success: true, value: parsed.data } : { success: false, error: parsed.error };\n },\n }),\n providerOptions: asSent(true),\n },\n lax,\n decodedStrictly: true,\n restoreAnswerText: (text) => {\n if (!prepared.decodedStrictly) return text;\n try {\n return JSON.stringify(derived.restore(JSON.parse(text)));\n } catch {\n return text;\n }\n },\n };\n return prepared;\n }\n\n /**\n * How a structured call is sent to a provider whose NATIVE constrained decoding has complexity limits (#3146).\n *\n * Anthropic compiles the schema of a structured call into a decoding grammar and refuses one with more than 24\n * optional or 16 union-typed parameters. `HumanInputFormSchema` carries 32 optionals, so every form an\n * Anthropic-backed agent composed was refused. The composer now sends only the field types its questions admit\n * (`humanInputFormSchemaForFields`), in a vocabulary without validation constraints, which fits every combination\n * of question kinds (21 optional parameters at most, #3176): the unconstrained path is the fallback, not the plan,\n * since without the grammar the model may answer the wrong shape (measured: 5 of 20 free-text forms invalid).\n * A schema within the declared limits is sent constrained, with the\n * unconstrained path as its retry; one over them, or one that cannot be measured, goes straight to the unconstrained\n * path. A model that refuses the unconstrained path is sent the constrained call only: if the schema is over the\n * limits the provider's refusal is the answer, and the warning says why. The Zod schema is the validator in every\n * case, so no answer is accepted that it refuses; past the limits only decoding-time enforcement is given up.\n */\n private prepareForNativeConstrainedDecoding(\n schema: z.ZodSchema<any>,\n native: NativeConstrainedDecodingContract,\n modelId: string | undefined,\n ): PreparedStructuredOutputSchema {\n const constrained: PreparedStructuredOutputCall = { schema, providerOptions: { providerOptions: native.constrainedProviderOptions } };\n const complexity = measureConstrainedDecodingComplexity(schema);\n const overLimits = exceedsConstrainedDecodingLimits(complexity, native.limits);\n const measured = {\n operation: 'GENERATE_STRUCTURED',\n model: modelId ?? null,\n optionalParameters: complexity?.optionalParameters ?? null,\n unionTypedParameters: complexity?.unionTypedParameters ?? null,\n limits: native.limits,\n };\n /*\n * The same conversion the SDK applies to the Zod schema (`asSchema`), minus the keywords that only validate, and\n * validated by that same schema: the answer is held to every pattern and bound, after decoding instead of during it.\n */\n const sent = asSchema(schema);\n const relaxed: PreparedStructuredOutputCall = {\n schema: jsonSchema(async (): Promise<JSONSchema7> => withoutDecodingValidationConstraints(await sent.jsonSchema) as JSONSchema7, {\n validate: async (value) => {\n const parsed = await schema.safeParseAsync(value);\n return parsed.success ? { success: true, value: parsed.data } : { success: false, error: parsed.error };\n },\n }),\n providerOptions: { providerOptions: native.constrainedProviderOptions },\n };\n const path = native.unconstrainedPath;\n if (modelId !== undefined && path.refusedByModels.includes(modelId)) {\n if (overLimits) this.logger.warn('Structured output exceeds the provider\\'s constrained-decoding limits, and this model admits no unconstrained path; the provider is expected to refuse it', measured);\n // Its one fallback is the relaxed CONSTRAINED call (#3204): the model refuses the unconstrained path outright.\n return { strict: constrained, lax: relaxed, laxIsRelaxedConstrained: true, decodedStrictly: false, restoreAnswerText: (text) => text };\n }\n const unconstrained: PreparedStructuredOutputCall = { schema, providerOptions: { providerOptions: path.providerOptions }, withoutReasoning: path.forcesToolUse };\n if (overLimits) {\n // Relaxing removes no optional or union-typed parameter, so it cannot bring a schema over the COUNTED limits back under them.\n this.logger.info('Structured output exceeds the provider\\'s constrained-decoding limits; sending it unconstrained', measured);\n return { strict: undefined, lax: unconstrained, decodedStrictly: false, restoreAnswerText: (text) => text };\n }\n return { strict: constrained, relaxed, lax: unconstrained, decodedStrictly: false, restoreAnswerText: (text) => text };\n }\n\n /** The call's base options, without the agent's reasoning setting when the prepared call is sent without it (#3146). */\n private structuredCallBaseOptions(baseOptions: any, call: PreparedStructuredOutputCall): any {\n if (!call.withoutReasoning || baseOptions?.reasoning === undefined) return baseOptions;\n const { reasoning: _omitted, ...rest } = baseOptions;\n return rest;\n }\n\n /**\n * Run a structured call strictly when it was prepared that way, and once more WITHOUT strict mode when\n * the provider refuses the request because of the schema it was sent (`isStrictSchemaRequestRefusal`, or a\n * native constrained decoder's complexity refusal, `isConstrainedDecodingComplexityRefusal`, #3146).\n *\n * A native decoder's refusal over the grammar's SIZE is first answered with the RELAXED constrained call when one was\n * prepared (#3204): the same grammar without its validation-only keywords. Only a second complexity refusal reaches\n * `lax`. A refusal over a COUNTED limit goes straight to `lax`, since relaxing removes no counted parameter.\n *\n * The door beside the refusal (`design-philosophy.md`, \"Immutability needs a paired mutation path\"): a\n * strict schema the derivation judged representable that the provider still refuses must never stop\n * generation. It costs one request that produced nothing, and it is logged, so a schema the derivation\n * misjudges is visible rather than silent.\n */\n private async generateObjectHonouringStrictRefusal<T>(\n prepared: PreparedStructuredOutputSchema,\n call: (sent: PreparedStructuredOutputCall) => Promise<T>,\n ): Promise<T> {\n if (prepared.strict === undefined) return call(prepared.lax);\n try {\n return await call(prepared.strict);\n } catch (error) {\n if (!isStrictSchemaRequestRefusal(error) && !isConstrainedDecodingComplexityRefusal(error)) throw error;\n const describe = (refusal: unknown) => (refusal instanceof Error ? refusal.message.slice(0, 500) : String(refusal).slice(0, 500));\n prepared.decodedStrictly = false;\n if (prepared.relaxed !== undefined && isCompiledGrammarSizeRefusal(error)) {\n this.logger.warn('The provider refused the structured-output schema as too complex to compile; retrying it constrained without its validation-only keywords', {\n operation: 'GENERATE_STRUCTURED',\n errorMessage: describe(error),\n });\n try {\n return await call(prepared.relaxed);\n } catch (relaxedError) {\n if (!isConstrainedDecodingComplexityRefusal(relaxedError)) throw relaxedError;\n error = relaxedError;\n }\n }\n this.logger.warn(prepared.laxIsRelaxedConstrained === true\n ? 'The provider refused the structured-output schema it was sent; retrying it constrained without its validation-only keywords'\n : 'The provider refused the structured-output schema it was sent; retrying without constrained decoding', {\n operation: 'GENERATE_STRUCTURED',\n errorMessage: describe(error),\n });\n return call(prepared.lax);\n }\n }\n\n /**\n * Execute structured generation without chunking\n */\n private async executeGenerateStructuredSingle({ model, systemPrompt, instructions, images, schema, baseOptions, isOpenAI, strictSchemaProfile, nativeConstrainedDecoding, includeRejectedAnswer = false }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n images: LLMProvider_ImageContent[];\n schema: z.ZodSchema<any>;\n baseOptions: any;\n isOpenAI: boolean | null;\n /** The provider's strict-mode limits, present when it requests strict decoding (#2344). */\n strictSchemaProfile?: StrictStructuredOutputProfile;\n /** The provider's native constrained-decoding limits and unconstrained path, when it declares them (#3146). */\n nativeConstrainedDecoding?: NativeConstrainedDecodingContract;\n /** See `LLMProvider_GenerateStructuredInputSchema.includeRejectedAnswer`. */\n includeRejectedAnswer?: boolean;\n }): Promise<AgentOperationExecutionResult> {\n // Outside the `try`: the catch arms below read whether the call that threw decoded strictly, to map a\n // rejected answer's text back to the original schema's shape (#2344).\n const prepared = this.prepareStructuredOutputSchema(schema, isOpenAI, strictSchemaProfile, nativeConstrainedDecoding, languageModelId(model));\n try {\n this.logDebug('Generating structured normally', {\n hasSchema: !!schema,\n instructionsLength: instructions.length,\n hasSystemPrompt: !!systemPrompt,\n isOpenAI,\n imageCount: images.length,\n });\n\n const result = await this.generateObjectHonouringStrictRefusal(prepared, (call) => generateObject({\n model,\n mode: \"json\",\n instructions: systemPrompt,\n schema: call.schema,\n ...this.buildStructuredContentArgs(instructions, images),\n ...this.structuredCallBaseOptions(baseOptions, call),\n ...call.providerOptions,\n }));\n\n return {\n output: {\n object: result.object,\n },\n usage: this.extractUsage(result.usage),\n // The THIRD path that can hand a caller `{ object: undefined }`, and the one the\n // two catch arms below hide: `generateObject` RESOLVING with no object at all.\n // That is off-contract for the AI SDK — `object` is declared non-optional and\n // absence is signalled by throwing — but nothing here validates that, so leaving\n // it unattached would put a hole in the vocabulary's own invariant (every path\n // that returns no object says why), precisely where a caller has the least other\n // evidence: no error was raised, so `finishReason` and a validation cause do not\n // exist either. Attaching it costs one comparison on the success path and keeps\n // \"no `structuredGenerationFailure`\" meaning \"there IS an object\".\n ...(result.object === undefined\n ? {\n structuredGenerationFailure: {\n kind: LLMProvider_StructuredGenerationFailureKind.RESOLVED_WITHOUT_OBJECT,\n message: 'The structured-generation call resolved without raising, but carried no object.',\n generatedTextLength: null,\n } satisfies LLMProvider_StructuredGenerationFailure,\n }\n : {}),\n };\n } catch (error) {\n // #2292 Phase 3: a withheld answer is not an invalid object — it reaches the caller as itself, with its usage.\n if (error instanceof AgentOutputWithheldError) throw error;\n // Any structured-generation failure that carries provider usage represents a\n // completed physical call. Preserve its metering and let the Driver classify\n // the missing/invalid object; throwing here would discard billable truth.\n if (typeof error === 'object' && error !== null && 'usage' in error) {\n const providerError = error as { cause?: unknown; finishReason?: unknown; text?: unknown; usage: unknown };\n // Do not log the generated text: it can contain application-private\n // context. The error/cause and non-sensitive shape metadata are enough\n // to distinguish truncation, schema validation and provider refusal.\n // Previously this branch retained billing but erased the only reason a\n // real model result became `{ object: undefined }`, making live judge\n // failures impossible to diagnose.\n // The SAME facts go to the log line and to the caller. Logging them only was the\n // second half of the defect this branch already documents: the reason existed, but\n // exclusively inside the process's own log file, so a caller could report nothing\n // more specific than \"no object\" and an operator had to grep the companion log for\n // the line above to learn which schema paths the model had omitted.\n const structuredGenerationFailure = this.buildStructuredGenerationFailure(\n LLMProvider_StructuredGenerationFailureKind.INVALID_OBJECT_AFTER_COMPLETED_CALL,\n error,\n providerError,\n );\n this.logger.error('Structured generation completed without a valid object', {\n operation: 'GENERATE_STRUCTURED',\n errorName: structuredGenerationFailure.errorName,\n errorMessage: structuredGenerationFailure.message,\n validationCauseName: structuredGenerationFailure.validationCauseName,\n validationIssues: structuredGenerationFailure.validationIssues,\n finishReason: structuredGenerationFailure.finishReason,\n generatedTextLength: structuredGenerationFailure.generatedTextLength,\n });\n return {\n // The rejected TEXT rides on the output only for a caller that opted in, and never on the log line\n // above or on `structuredGenerationFailure`, which is telemetry every trace sink emits.\n output: {\n object: undefined,\n ...(includeRejectedAnswer && typeof providerError.text === 'string' ? { rejectedAnswer: prepared.restoreAnswerText(providerError.text) } : {}),\n },\n usage: this.extractUsage(error.usage),\n structuredGenerationFailure,\n };\n }\n // semantic-literal-boundary: AI SDK cross-realm error identity fallback\n const noObjectError = (\n typeof error === 'object'\n && error !== null\n && (\n // The SDK error's stable payload shape is retained even when bundlers or\n // mocked module realms erase its prototype/name marker.\n ('response' in error && 'finishReason' in error && 'text' in error)\n ||\n ('name' in error && error.name === 'AI_NoObjectGeneratedError')\n || (error as Record<PropertyKey, unknown>)[Symbol.for('vercel.ai.error.AI_NoObjectGeneratedError')] === true\n )\n )\n || error instanceof NoObjectGeneratedError\n || NoObjectGeneratedError.isInstance(error);\n if (noObjectError) {\n // No usage-bearing payload was recognised on the branch above, so no shape metadata\n // was recovered. The reason is still attached — a caller must be able to tell this\n // apart from the validated-and-rejected case, and specifically must NOT read the\n // absent `validationIssues` here as evidence that the schema was satisfied.\n return {\n output: {\n object: undefined,\n ...(includeRejectedAnswer && typeof (error as { text?: unknown }).text === 'string'\n ? { rejectedAnswer: prepared.restoreAnswerText((error as { text: string }).text) }\n : {}),\n },\n usage: this.extractUsage((error as NoObjectGeneratedError).usage),\n structuredGenerationFailure: this.buildStructuredGenerationFailure(\n LLMProvider_StructuredGenerationFailureKind.NO_OBJECT_GENERATED,\n error,\n error as { cause?: unknown; finishReason?: unknown; text?: unknown },\n ),\n };\n }\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Failed to generate structured data - provider response', {\n operation: 'GENERATE_STRUCTURED',\n hasSchema: !!schema,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'GENERATE_STRUCTURED',\n message: `Failed to generate structured data: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Execute STREAM_TEXT operation\n */\n private async executeStreamText({ model, systemPrompt, instructions, input, baseOptions }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n /** The invocation input: a conversation in it is sent as `messages` (`textGenerationPromptOf`). */\n input?: unknown;\n baseOptions: any;\n }): Promise<AgentOperationExecutionResult> {\n try {\n const result = await streamText({\n model,\n ...this.textGenerationPromptOf(instructions, input),\n instructions: systemPrompt,\n ...baseOptions,\n onError: SUPPRESS_SDK_STREAM_ERROR_PRINT,\n });\n\n let fullText = '';\n try {\n fullText = await this.drainBufferedStreamText(result);\n } catch (streamError) {\n // #2292 Phase 3: a withheld output reaches the caller as itself, with its usage, like a provider failure.\n if (streamError instanceof AgentModelCallFailedError || streamError instanceof AgentOutputWithheldError) throw streamError;\n // Described, never quoted by value (#2368): a stream failure comes from the model call and can carry the vendor's\n // answer. `describeModelCallError` keeps the name, a redacted message, the status and the frames.\n const streamFailure = describeModelCallError(streamError);\n this.logger.error('Failed to read text stream', {\n ...streamFailure,\n textLength: fullText.length,\n });\n throw this.buildModelCallFailure(streamError, streamFailure, {\n operation: 'STREAM_TEXT',\n message: `Failed to read text stream: ${String(streamFailure.errorMessage ?? streamFailure.errorName)}`,\n });\n }\n\n const usage = await result.usage;\n\n return {\n output: {\n textDelta: fullText,\n },\n usage: this.extractUsage(usage),\n };\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n this.rethrowModelCallFailure(error, 'STREAM_TEXT');\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Stream text operation failed - provider response', {\n operation: 'STREAM_TEXT',\n hasSystemPrompt: !!systemPrompt,\n instructionsLength: instructions.length,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'STREAM_TEXT',\n message: `Failed to stream text: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Execute STREAM_STRUCTURED operation\n */\n private async executeStreamStructured({ model, systemPrompt, instructions, baseOptions }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n baseOptions: any;\n }): Promise<AgentOperationExecutionResult> {\n try {\n const result = await streamText({\n model,\n prompt: instructions,\n instructions: systemPrompt,\n ...baseOptions,\n onError: SUPPRESS_SDK_STREAM_ERROR_PRINT,\n });\n\n let fullText = '';\n try {\n fullText = await this.drainBufferedStreamText(result);\n } catch (streamError) {\n // #2292 Phase 3: a withheld output reaches the caller as itself, with its usage, like a provider failure.\n if (streamError instanceof AgentModelCallFailedError || streamError instanceof AgentOutputWithheldError) throw streamError;\n const errorDetails = this.extractProviderErrorDetails(streamError);\n\n this.logger.error('Failed to read structured stream - provider response', {\n operation: 'STREAM_STRUCTURED',\n textLength: fullText.length,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(streamError, errorDetails, {\n operation: 'STREAM_STRUCTURED',\n message: `Failed to read structured stream: ${errorDetails.errorMessage}`,\n });\n }\n\n const usage = await result.usage;\n\n let parsedOutput: unknown = fullText;\n try {\n parsedOutput = JSON.parse(fullText);\n } catch (parseError) {\n // Described (#2368): V8's JSON parse error quotes the text it refused, which is the model's output.\n this.logDebug('Failed to parse structured stream as JSON, returning as text', {\n ...describeModelCallError(parseError),\n textLength: fullText.length,\n });\n }\n\n return {\n output: {\n object: parsedOutput,\n },\n usage: this.extractUsage(usage),\n };\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n this.rethrowModelCallFailure(error, 'STREAM_STRUCTURED');\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Stream structured operation failed - provider response', {\n operation: 'STREAM_STRUCTURED',\n hasSystemPrompt: !!systemPrompt,\n instructionsLength: instructions.length,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'STREAM_STRUCTURED',\n message: `Failed to stream structured data: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n // ==========================================================================\n // Honest token streaming (invokeAgentStreaming path)\n // --------------------------------------------------------------------------\n // NOTE: the `executeStreamText` / `executeStreamStructured` methods ABOVE are\n // the BUFFERED fallback for the `STREAM_*` operation keys when invoked through\n // the callback-less `invokeAgent` (there is no delta channel on that path, so\n // they assemble the full result). Real per-token delivery is the block below,\n // reached only via `invokeAgentStreaming`, which forwards each delta as it\n // arrives and never buffer-collapses.\n // ==========================================================================\n\n /**\n * Execute a streaming agent turn: resolve transport + prompts, then stream over\n * the API. Fails closed (typed {@link AgentStreamingUnsupportedError}) for the\n * CLI transport and for image agents — neither produces a token stream in v1.\n */\n private async executeAgentStreaming(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n handlers: AgentStreamHandlers,\n /** The organizations the turn works for, as `invokeAgentStreaming` derived them for its admission. */\n organizationScope: ModelCallOrganizationScope,\n toolContext?: FunctionToolExecutionContext,\n ): Promise<AgentExecutionResult> {\n if (isImageAgentConfiguration(agent.config)) {\n throw new AgentStreamingUnsupportedError('operation', 'Image agents do not produce a token stream.');\n }\n const execution = this.resolveAgentExecution(agent);\n // An ACP execution is refused just below, before the prompts are used; a stream is otherwise an API operation.\n const prompts = await this.buildExecutionPrompts(agent, request, execution.transport === 'acp' ? ConversationDelivery.SINGLE_PROMPT : CONVERSATION_DELIVERY_OF_OPERATION[execution.operationKey]);\n if (execution.transport === 'acp') {\n // A coding session DOES stream, but not tokens: it streams tool calls,\n // diffs and usage. Routing it through a token-delta handler would report\n // an agent's narration as if it were the model's output and drop\n // everything that matters. Coding progress is delivered through\n // `AgentInvocationHostContext.onCodingSessionEvent` instead.\n throw new AgentStreamingUnsupportedError('transport', 'Token streaming is not supported for the ACP coding transport; use invokeAgent and observe progress through onCodingSessionEvent.');\n }\n // #2292 R8: from here on the agent is seen with the guardrails the organizations this turn acts for tightened: its\n // own organization's, and each representing organization's its principal stands there through. The same scope its\n // suspensions were asked for (`invokeAgentStreaming`).\n agent = await this.agentUnderTurnPolicies(agent, organizationScope);\n // #3295: a resumed turn runs under at least the treatment it paused under, whatever organizations this call names.\n if (toolContext?.heldPersonalDataTreatment) {\n agent = { ...agent, contentGuardrails: effectiveAgentContentGuardrails(agent.contentGuardrails, [{ personalDataTreatment: toolContext.heldPersonalDataTreatment }]) };\n }\n // Refuses before any tool or MCP session is opened when the agent declares moderation nothing can serve.\n const operationObservation = this.operationObservationOf(request);\n const moderationOrigin = { toolContext, initiator: request.initiator, observation: operationObservation };\n // #3364 step 3: a turn that can read records gets a guard even when its agent declares no moderation, so an owner whose\n // rows reach the model can make the reply judged; until one does, it judges nothing and holds nothing.\n const outputModeration = this.outputModerationGuardOf(agent, moderationOrigin)\n ?? (toolContext ? this.ownerTightenableOutputModerationGuardOf(agent, moderationOrigin) : undefined);\n // A resumed turn is judged under at least what it paused under: the records its owners tightened it for are in the\n // paused messages it replays.\n if (toolContext?.heldOutputModeration) outputModeration?.tighten(toolContext.heldOutputModeration);\n const approvalGatedToolRoutes = new Map<string, HumanDecision_RouteKind>();\n const personalDataGuard = this.personalDataGuardOf(agent, toolContext);\n if (personalDataGuard) this.personalDataGuards.set(request, personalDataGuard);\n const toolResultScreen = this.toolResultScreenOf(agent, toolContext, operationObservation);\n // #2841: the tool events reach the operation observation on their way to the caller's handler.\n handlers = operationObservation.observeHandlers(handlers);\n // #2877: a record a tool returns is treated under the policy of the organization that owns it too.\n const recordOwnerPolicy = this.recordOwnerPolicyOf(request, agent, organizationScope, toolContext, operationObservation, outputModeration);\n const functionTools = this.resolveAgentTools(agent, toolContext, approvalGatedToolRoutes, personalDataGuard, toolResultScreen, recordOwnerPolicy);\n /*\n * MCP tools are DISCOVERED, which means a network call per declared server, bounded by that\n * server's discovery budget. A server that does not answer contributes nothing and the turn\n * proceeds — so this cannot fail the invocation, only shorten the tool list.\n */\n const { tools: mcpTools, sessions: mcpSessions } = await this.resolveAgentMcpTools(agent, toolContext, toolResultScreen, personalDataGuard);\n const tools = functionTools || Object.keys(mcpTools).length > 0\n ? { ...(functionTools ?? {}), ...mcpTools }\n : undefined;\n const toolApproval = this.buildToolApprovalConfiguration(approvalGatedToolRoutes, toolContext?.auth?.executionType, toolContext?.initiationKind);\n const toolApprovalSecret = toolApproval ? this.resolveToolApprovalSecretOrThrow(agent, new Set(approvalGatedToolRoutes.keys())) : undefined;\n try {\n const streamed = await this.executeAgentViaApiStreaming(agent, request, execution, prompts, handlers, tools, toolApproval, toolApprovalSecret, outputModeration);\n // #3364 step 3: a pause records the moderation its replies were judged under, owners' tightenings included.\n if (streamed.approvalSuspension && outputModeration?.judgesAnything) streamed.approvalSuspension.outputModerationAtPause = outputModeration.currentPolicy();\n return streamed;\n } finally {\n /*\n * Released in a `finally` so a thrown turn does not leak a session on somebody else's server.\n * `closeSession` swallows its own failures by contract — a server MAY refuse to let a client\n * end a session — so this can never turn a successful turn into a failed one, nor mask the\n * error of a failing one.\n */\n await Promise.all(mcpSessions.map((session) => this.mcpClient?.closeSession(session, null)));\n }\n }\n\n /**\n * Record one outbound MCP attempt on the audit trail.\n *\n * Fire-and-forget and feature-detected: an absent or failing audit sink must never fail the act it\n * was going to observe. A turn that produced its answer must not be turned into a failure because\n * the trail could not be written — the observation is evidence, not a gate.\n *\n * Emitted for the CALL path always, and for DISCOVERY only when the outbound guard refused the\n * target. That asymmetry is deliberate: a refused target is an attempted egress a reviewer wants\n * beside the calls that succeeded, whereas a server being unreachable or slow is availability, and\n * putting every timeout on the security trail would bury the rows that mean something. Those still\n * reach the log, at WARN, with the same server ref and host.\n */\n private recordMcpAttempt(input: {\n agentRef: string;\n mcpServerRef: string;\n destinationHost: string;\n outcome: McpOutcomeKind;\n toolName?: string;\n connectionOwnerScope?: string;\n credentialId?: string;\n credentialSetByUserId?: string;\n actingIdentity: { userId?: string; organizationId?: string };\n /**\n * The turn's verified auth, as the row's principal (#1595): a delegated turn's MCP call is the\n * delegating client's, and `initiatorUserId` alone would record it as the person acting first-party.\n */\n principal?: AuditPrincipalFacts;\n }): void {\n if (!this.auditLogs) return;\n void this.auditLogs.logMcpToolCall({\n mcpServerRef: input.mcpServerRef,\n destinationHost: input.destinationHost,\n toolName: input.toolName,\n outcome: input.outcome,\n connectionOwnerScope: input.connectionOwnerScope,\n credentialId: input.credentialId,\n ...(input.credentialSetByUserId === undefined ? {} : { credentialSetByUserId: input.credentialSetByUserId }),\n initiatorUserId: input.actingIdentity.userId,\n organizationId: input.actingIdentity.organizationId,\n agentRef: input.agentRef,\n }, undefined, input.principal).catch((error) => {\n this.logger.warn('Could not record an MCP tool attempt on the audit trail; the turn is unaffected', {\n agentRef: input.agentRef,\n mcpServerRef: input.mcpServerRef,\n ...projectCaughtErrorLogFields(error),\n });\n });\n }\n\n /**\n * Resolve an agent's `capabilities.tools.mcpRefs` into callable tools by DISCOVERING what each\n * declared server offers (#491).\n *\n * ## A server that cannot be reached contributes NOTHING, and the turn continues\n *\n * Fail-closed on the CLAIM, fail-open on the turn. Discovery happens here, at turn start, so a\n * server that is unreachable, whose credential is unavailable, or whose target is refused simply\n * adds no tools — and the model is never offered a capability it cannot use. That is the whole\n * correction #491 exists for, one level down: the agent card advertised MCP servers that resolved\n * to nothing, and the fix is not to advertise more carefully but to make what is offered be what\n * can actually be called.\n *\n * Every one of those is logged at WARN with the server ref and destination HOST. A server quietly\n * unreachable for a week must be visible as that, rather than as an agent that became less capable\n * for no stated reason.\n *\n * ## The tools are NOT the same kind of thing as a functionRef, and are named so\n *\n * A `functionRef` dispatches a LOCAL resource operation and owes that operation's declared roles\n * ACL and rate limit (#556). An MCP tool dispatches nothing locally — it leaves the trust boundary\n * — so those gates have no operation to apply to. What it owes instead is enforced where a caller\n * cannot skip it: the outbound target guard and the timeouts live inside the client, the credential\n * comes from a resolver service, and the endpoint was refused at registration if it was plaintext.\n *\n * The `mcp_<serverRef>_<toolName>` prefix keeps the two planes distinguishable in a trace and\n * prevents a third-party tool name from colliding with a declared `functionRef`.\n *\n * Returns the open sessions so the caller can release them; see `executeAgentStreaming`.\n */\n private async resolveAgentMcpTools(\n agent: FlowsActors_Agent,\n toolContext?: FunctionToolExecutionContext,\n /** #2292: screens each MCP result for prompt injection before the model reads it; absent when the agent declares none. */\n toolResultScreen?: ToolResultScreen,\n /**\n * #2292 R8: the turn's personal-data treatment, declared or set by an organization's policy. An MCP result has no\n * schema the engine can read, so under a treatment its model is sent it withheld whole, like a function tool that\n * does not declare its result; an error result keeps its kind only.\n */\n personalDataGuard?: PersonalDataGuard,\n ): Promise<{ tools: Record<string, any>; sessions: McpSession[] }> {\n const mcpRefs = agent.capabilities?.tools?.mcpRefs;\n const empty = { tools: {} as Record<string, any>, sessions: [] as McpSession[] };\n if (!mcpRefs?.length || !toolContext) return empty;\n if (toolContext.autonomousTrigger === AutonomousTurnTrigger.INBOUND_DELIVERY) {\n // #1611: an MCP tool's effect is declared nowhere the engine can read (the list is discovered from\n // the server at turn start), so none can be shown to be a read, and a turn running on inbound content\n // is offered no tool that might write unreviewed. Withheld whole, and said so.\n this.logger.info('MCP tools are withheld from a turn started by an inbound delivery: their effects cannot be classified', {\n agentRef: agent.ref, mcpRefs,\n });\n return empty;\n }\n if (!this.mcpClient || !this.mcpCredentialResolver) {\n // Declared, and this deployment bound no MCP services. Reported rather than silently empty:\n // the agent is about to be less capable than its declaration says, and nothing else would say so.\n this.logger.warn('Agent declares MCP servers but this deployment binds no MCP client; the agent will run without those tools', {\n agentRef: agent.ref,\n mcpRefs,\n });\n return empty;\n }\n\n const actingIdentity = {\n userId: toolContext.auth?.initiatorIds?.userId,\n organizationId: toolContext.organizationId,\n };\n\n const tools: Record<string, any> = {};\n const sessions: McpSession[] = [];\n\n for (const ref of mcpRefs) {\n const server = this.flowsActorsRegistry.getMcpServer(ref);\n if (!server) {\n // The registry refuses this at initialization, so reaching it means the agent was registered\n // afterwards through the public `registerAgent`. Skipped rather than thrown: a turn is the\n // wrong place to fail an application's configuration.\n this.logger.warn('Agent declares an MCP server the application never declared; skipping', { agentRef: agent.ref, mcpRef: ref });\n continue;\n }\n\n const credential = await this.mcpCredentialResolver.resolve(server, actingIdentity);\n if (credential.kind !== McpCredentialOutcomeKind.RESOLVED) {\n this.logger.warn('No credential for a declared MCP server; the agent will run without its tools', {\n agentRef: agent.ref,\n mcpServerRef: ref,\n outcome: credential.kind,\n // Slot NAMES only: a connection exists under a slot the provider no longer declares, so the\n // remedy is to reconnect rather than to connect (#624).\n ...(credential.kind === McpCredentialOutcomeKind.STORED_UNDER_RETIRED_SLOT ? { retiredSecretSlugs: credential.retiredSecretSlugs } : {}),\n });\n continue;\n }\n\n // The session spends the credential's connection on every request, so the connection's vendor budget (#1938) is\n // the one a provider operation on that connection also spends.\n // #2973: metered for this turn, so a turn a re-read trigger's delivery started spends that lane's share.\n // Only the delivery the turn came through decides the lane, so a turn with none spends as an ordinary call.\n const arrivedThrough = toolContext?.auth?.arrivedThrough;\n const connection = credential.connection && arrivedThrough ? { ...credential.connection, meteredFor: { arrivedThrough } } : credential.connection;\n const discovery = await this.mcpClient.openSession(server, credential.token, connection);\n if (discovery.kind !== McpOutcomeKind.OK) {\n this.logger.warn('An MCP server contributed no tools to this turn', {\n agentRef: agent.ref,\n mcpServerRef: discovery.mcpServerRef,\n destinationHost: discovery.destinationHost,\n outcome: discovery.kind,\n detail: discovery.detail,\n });\n // A refused TARGET is an attempted egress a guard blocked — a security event, and the row a\n // reviewer wants beside the calls that succeeded. Everything else here is availability.\n if (discovery.kind === McpOutcomeKind.REFUSED_TARGET) {\n // Discovery runs at turn start, outside any tool call, so the agent frame is opened here for this\n // one row: the refused egress was the AGENT's, and the row must say so (#1595).\n runWithAgentActorFrame(agentActorForToolCall(agent, toolContext), () => this.recordMcpAttempt({\n agentRef: agent.ref,\n mcpServerRef: discovery.mcpServerRef,\n destinationHost: discovery.destinationHost,\n outcome: discovery.kind,\n connectionOwnerScope: credential.source,\n credentialId: credential.credentialId,\n credentialSetByUserId: credential.credentialSetByUserId,\n actingIdentity,\n principal: toolContext.auth,\n }));\n }\n continue;\n }\n\n sessions.push(discovery.session);\n for (const descriptor of discovery.session.tools) {\n // A third-party server's names are whatever it chose, and one name the model's provider refuses fails\n // the WHOLE request, so the name is mapped into the set every model API accepts (#1080).\n const toolName = toPortableModelToolName(`mcp_${ref}_${descriptor.name}`);\n if (toolName in tools) {\n // Two names that differ only in characters the mapping replaces (`a.b` / `a_b`) arrive under one\n // key. Letting the second overwrite the first would bind the model's call to a tool it was not\n // described, so the first is kept and the second is reported.\n this.logger.warn('Two MCP tools map to the same model-facing name; the second is not offered to the model', {\n agentRef: agent.ref,\n mcpServerRef: ref,\n toolName,\n skippedToolName: descriptor.name,\n });\n continue;\n }\n tools[toolName] = tool({\n description: descriptor.description ?? descriptor.title ?? `${server.displayName}: ${descriptor.name}`,\n // The server's own JSON Schema, passed to the model unchanged. Re-deriving it as Zod would\n // be a second description of somebody else's contract, and the two would drift.\n inputSchema: jsonSchema(descriptor.inputSchema as never),\n // #2292: an MCP server's answer is content somebody else wrote, the clearest case for screening. Its error\n // results below are returned AS results, so they are screened too. Under a personal-data treatment the answer\n // cannot be classified field by field (no schema), so the model is sent it withheld whole, and an error result\n // its kind only; neither is screened, since neither carries anything the server wrote. The person and the\n // conversation's tool trace keep what the server returned.\n ...(personalDataGuard ? {\n toModelOutput: async ({ output }: { output: unknown }) => ({\n type: 'json' as const,\n value: (isMcpErrorResult(output) ? { error: output.error } : personalDataGuard.withholdWhole()) as never,\n }),\n } : toolResultScreen ? {\n toModelOutput: async ({ toolCallId, output }: { toolCallId: string; output: unknown }) =>\n await toolResultScreen.forModel(toolCallId, toolName, output) as never,\n } : {}),\n // Runs inside the agent frame, like a function tool: anything this call records — the MCP\n // attempt row below, any write a future MCP plane makes locally — names the agent (#1595).\n execute: async (args: any) => runWithAgentActorFrame(agentActorForToolCall(agent, toolContext, toolName), async () => {\n let outcome: Awaited<ReturnType<McpClientBackendService['callTool']>>;\n try {\n outcome = await this.mcpClient!.callTool(discovery.session, descriptor.name, args ?? {}, credential.token);\n } catch (error) {\n // The client answers rather than throws; a throw is a defect, and its text could carry the server's words.\n // A screened or treated agent's model is told the kind only, as for a function tool.\n if (toolResultScreen || personalDataGuard) throw guardedToolError(error);\n throw error;\n }\n /*\n * Every ATTEMPT is recorded, not only what worked. Recording successes alone would hide\n * exactly what a reviewer looks for first — the refusals, the timeouts, and the tools\n * that answered with their own error.\n */\n this.recordMcpAttempt({\n agentRef: agent.ref,\n mcpServerRef: server.ref,\n destinationHost: mcpServerDestinationHost(server.url),\n outcome: outcome.kind,\n toolName: descriptor.name,\n connectionOwnerScope: credential.source,\n credentialId: credential.credentialId,\n credentialSetByUserId: credential.credentialSetByUserId,\n actingIdentity,\n principal: toolContext.auth,\n });\n if (outcome.kind === McpOutcomeKind.OK) return outcome.content;\n /*\n * Returned to the MODEL as a result rather than thrown, and the difference is deliberate.\n * A thrown tool error becomes an SDK tool-error result the model narrates as prose, which\n * is how an ACL denial once got narrated as \"I don't have permission to write to that\n * list\" and sent an investigator at the list. A typed value the model can read lets it\n * retry or route around — which is the whole reason these five kinds are kept apart.\n */\n this.logger.warn('An MCP tool call did not succeed; the model is told and may route around it', {\n agentRef: agent.ref,\n mcpServerRef: outcome.mcpServerRef,\n destinationHost: outcome.destinationHost,\n toolName: descriptor.name,\n outcome: outcome.kind,\n detail: outcome.detail,\n });\n return { error: outcome.kind, detail: outcome.detail };\n }),\n });\n }\n }\n\n return { tools, sessions };\n }\n\n /**\n * #2292 R8: `agent` as one call sees it, its declared guardrails tightened by the agent policy of every\n * organization the call acts for. The runtime that opened the turn has usually resolved those policies already (a frame\n * covering at least these organizations, its unreadable reading included); otherwise they are read here. Either way they are MERGED with the declaration,\n * so nothing carried can loosen it. A policy that cannot be read refuses the call: an organization that asked for its\n * agents to be stricter is never read as having asked for nothing. A call acting for no organization applies none to the\n * agent; the records it reads are treated under their owners' policies at the model boundary (#2877, `recordOwnerPolicyOf`).\n */\n private async agentUnderTurnPolicies(agent: FlowsActors_Agent, scope: ModelCallOrganizationScope): Promise<FlowsActors_Agent> {\n if (!isLLMAgentConfiguration(agent.config)) return agent;\n if (scope.unreadable !== undefined) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: `Agent '${agent.ref}' cannot run: ${scope.unreadable}. It is not run untightened.` },\n });\n }\n const organizationIds = organizationIdsOfCallScope(scope);\n if (organizationIds.length === 0) return agent;\n const lookup = agentPoliciesInFrame(organizationIds) ?? await readAgentPolicies(this.repositoriesRegistry, organizationIds);\n if (lookup.unreadable !== undefined) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: `Agent '${agent.ref}' cannot run: ${lookup.unreadable}. It is not run untightened.` },\n });\n }\n if (lookup.policies.length === 0) return agent;\n return { ...agent, contentGuardrails: effectiveAgentContentGuardrails(agent.contentGuardrails, lookup.policies) };\n }\n\n /**\n * #2292: the screen this agent's tool results go through before its model reads them, or `undefined` when it declares no\n * prompt-injection screening. Refuses the invocation when it declares screening and no classifier can serve it:\n * running unscreened is the outcome the declaration exists to prevent.\n */\n private toolResultScreenOf(\n agent: FlowsActors_Agent,\n toolContext?: FunctionToolExecutionContext,\n /** #2841: the invocation's operation observation, told each verdict the screen reaches. */\n observation?: AgentOperationObservationRecorder,\n ): ToolResultScreen | undefined {\n if (!agent.contentGuardrails?.promptInjection) return undefined;\n // assurance-control: WILDO.SECURITY.FAIL_CLOSED, WILDO.AI.UNTRUSTED_CONTENT_SCREENING — an agent that declares\n // prompt-injection screening does not run where nothing can screen, and a result that could not be screened reaches\n // its model only as a withheld notice\n const contentSafety = this.contentSafety;\n // The one predicate the boot report also runs (`reportUnservableAgentContentGuardrails`), so the two cannot disagree.\n const unavailable = contentGuardrailClassifierGapOf(contentSafety, { kind: ClassifierBackedContentGuardrail.PROMPT_INJECTION })?.reason;\n if (unavailable !== undefined || !contentSafety) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: `Agent '${agent.ref}' screens its tool results for prompt injection (contentGuardrails.promptInjection, declared or set by an organization's policy), and they cannot be screened: ${unavailable}. It is not run.` },\n });\n }\n observation?.screensToolResults();\n return new ToolResultScreen(\n (text) => contentSafety.screenForPromptInjection(text),\n (record) => this.recordToolResultWithholding(agent, toolContext, record),\n observation?.observeScreening,\n );\n }\n\n /**\n * #2292 Phase 3: the model this call runs on — wrapped with the output-moderation middleware when the agent declares\n * moderation, as it is. Below the SDK, so a withheld tool call is never executed and never put before an approver.\n */\n private moderatedModel(model: any, outputModeration: OutputModerationGuard | undefined, generateOutputKind: FlowsActors_ModeratedOutputKind): any {\n if (!outputModeration) return model;\n return wrapLanguageModel({ model, middleware: outputModeration.middleware(generateOutputKind) });\n }\n\n /**\n * #2292 Phase 3: this agent's output moderation for one invocation, or `undefined` when it declares none. Refuses the\n * invocation, before any model call, when it declares moderation and nothing can serve it: no content-safety service,\n * no provider-call recorder (a judgement nobody can show happened), or no provider that moderates output in every\n * category the policy names.\n */\n private outputModerationGuardOf(\n agent: FlowsActors_Agent,\n origin: {\n toolContext?: FunctionToolExecutionContext;\n initiator?: ExecutionContext_InitiatorIds;\n /** #2841: the invocation's operation observation, told each judgement and the withholding the guard applies. */\n observation?: AgentOperationObservationRecorder;\n },\n ): OutputModerationGuard | undefined {\n const policy = agent.contentGuardrails?.outputModeration?.blockAtOrAbove;\n if (!policy) return undefined;\n // assurance-control: WILDO.SECURITY.FAIL_CLOSED, WILDO.AI.OUTPUT_MODERATION — an agent that declares output moderation\n // does not run where nothing can judge its output, and an output that could not be judged is withheld\n const categories = outputModerationCategories(policy);\n const contentSafety = this.contentSafety;\n // The one predicate the boot report also runs (`reportUnservableAgentContentGuardrails`), so the two cannot disagree.\n const unavailable = contentGuardrailClassifierGapOf(contentSafety, { kind: ClassifierBackedContentGuardrail.OUTPUT_MODERATION, categories })?.reason;\n if (unavailable !== undefined || !contentSafety) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: `Agent '${agent.ref}' moderates its output (contentGuardrails.outputModeration, declared or set by an organization's policy), and its output cannot be judged: ${unavailable}. It is not run.` },\n });\n }\n origin.observation?.moderatesOutput();\n return new OutputModerationGuard(\n policy,\n this.moderateOutputWhereServable(),\n (withholding) => {\n origin.observation?.observeOutputWithholding(withholding);\n this.recordOutputWithholding(agent, origin, withholding);\n },\n agent.disclosure?.reasoning === true,\n origin.observation?.observeModerationJudgement,\n );\n }\n\n /**\n * #3364 step 3: the output moderation of a turn whose agent declares none, which an organization whose rows reach the\n * model tightens (`OutputModerationGuard.tighten`). It judges nothing, and holds nothing, until one does. It does not\n * refuse the turn where nothing can judge: whether anything will be asked is unknown until the rows are read, and what\n * is asked then and cannot be judged is withheld (`OUTPUT_NOT_MODERATED`) by `moderateOutputWhereServable`.\n */\n private ownerTightenableOutputModerationGuardOf(\n agent: FlowsActors_Agent,\n origin: { toolContext?: FunctionToolExecutionContext; initiator?: ExecutionContext_InitiatorIds; observation?: AgentOperationObservationRecorder },\n ): OutputModerationGuard {\n return new OutputModerationGuard(\n {},\n this.moderateOutputWhereServable(),\n (withholding) => {\n origin.observation?.observeOutputWithholding(withholding);\n this.recordOutputWithholding(agent, origin, withholding);\n },\n agent.disclosure?.reasoning === true,\n origin.observation?.observeModerationJudgement,\n );\n }\n\n /**\n * #3364 step 3: judge a text in these categories, or answer NOT_MODERATED (with the reason) when no classifier can serve\n * them here. Asked at every judgement because an owner's policy can add categories mid-turn that the declared ones did\n * not need, through the predicate the boot report and the guard builder share (`contentGuardrailClassifierGapOf`).\n */\n private moderateOutputWhereServable(): (text: string, categories: readonly ContentSafety_HarmCategory[]) => Promise<ContentSafetyModerationResult> {\n return async (text, categories) => {\n const contentSafety = this.contentSafety;\n const unavailable = contentGuardrailClassifierGapOf(contentSafety, { kind: ClassifierBackedContentGuardrail.OUTPUT_MODERATION, categories })?.reason;\n if (unavailable !== undefined || !contentSafety) {\n return { outcome: ContentSafetyModerationOutcome.NOT_MODERATED, reason: `the output cannot be judged in ${categories.join(', ')}: ${unavailable ?? 'no content-safety service'}` };\n }\n return contentSafety.moderateOutput(text, categories);\n };\n }\n\n /**\n * #2292 Phase 3: one audit row per withheld output — OUTPUT_WITHHELD when it reached the policy, OUTPUT_MODERATION_FAILED\n * when it could not be judged. A conversational turn is routed to its organization and attributed to its principal (the\n * tool context); a buffered call (a flow step, a deliberation, the question-form composer) carries no principal and is\n * routed to the organization its initiator names, when it names one. Fire-and-forget: the output is already withheld.\n */\n private recordOutputWithholding(\n agent: FlowsActors_Agent,\n origin: { toolContext?: FunctionToolExecutionContext; initiator?: ExecutionContext_InitiatorIds },\n withholding: OutputWithholding,\n ): void {\n const auditLogs = this.auditLogs;\n const toolContext = origin.toolContext;\n const organizationId = toolContext ? toolContext.organizationId : origin.initiator?.organizationId;\n const initiatorUserId = toolContext ? toolContext.auth?.initiatorIds?.userId : origin.initiator?.userId;\n const fields = {\n agentRef: agent.ref,\n outputKind: withholding.outputKind,\n ...(withholding.toolName ? { toolName: withholding.toolName } : {}),\n ...(withholding.toolCallId ? { toolCallId: withholding.toolCallId } : {}),\n ...(withholding.providerRef ? { providerRef: withholding.providerRef } : {}),\n ...(toolContext?.executionId ? { executionId: toolContext.executionId } : {}),\n ...(initiatorUserId ? { initiatorUserId } : {}),\n ...(organizationId ? { organizationId } : {}),\n };\n this.logger.warn('An agent\\'s output was withheld by its output moderation', { ...fields, code: withholding.code });\n if (!auditLogs) return;\n const written = withholding.code === FlowsActors_ExecutionErrorCode.OUTPUT_WITHHELD\n ? auditLogs.logAgentOutputWithheld({ ...fields, flaggedCategories: [...(withholding.flaggedCategories ?? [])] }, toolContext?.auth)\n : auditLogs.logAgentOutputModerationFailed({ ...fields, ...(withholding.failureReason ? { failureReason: withholding.failureReason } : {}) }, toolContext?.auth);\n written.catch((error) => {\n this.logger.warn('Could not record a withheld output on the audit trail; the call is unaffected', { ...fields, error: describeCaughtError(error) });\n });\n }\n\n /**\n * #2292: one audit row per withheld tool result — CONTENT_QUARANTINED for an attack, CONTENT_SCREENING_FAILED when it\n * could not be screened. Ids and names only, routed to the turn's organization, attributed to the turn's principal.\n * Fire-and-forget like the MCP attempt row: the withholding already happened, and a missing audit sink must not undo\n * it or fail the turn.\n */\n private recordToolResultWithholding(agent: FlowsActors_Agent, toolContext: FunctionToolExecutionContext | undefined, record: ToolResultScreeningRecord): void {\n const auditLogs = this.auditLogs;\n const fields = {\n agentRef: agent.ref,\n contentSource: FlowsActors_ScreenedContentSource.TOOL_RESULT,\n toolName: record.toolName,\n toolCallId: record.toolCallId,\n ...(record.result.providerRef ? { providerRef: record.result.providerRef } : {}),\n ...(toolContext?.executionId ? { executionId: toolContext.executionId } : {}),\n ...(toolContext?.auth?.initiatorIds?.userId ? { initiatorUserId: toolContext.auth.initiatorIds.userId } : {}),\n ...(toolContext?.organizationId ? { organizationId: toolContext.organizationId } : {}),\n };\n this.logger.warn('An agent tool result was withheld from its model by its content guardrail', { ...fields, outcome: record.result.outcome });\n if (!auditLogs) return;\n const written = record.result.outcome === ContentSafetyScreeningOutcome.NOT_SCREENED\n ? auditLogs.logAgentContentScreeningFailed({ ...fields, failureReason: record.result.reason }, toolContext?.auth)\n : auditLogs.logAgentContentQuarantined(fields, toolContext?.auth);\n written.catch((error) => {\n this.logger.warn('Could not record a withheld tool result on the audit trail; the turn is unaffected', { ...fields, error: describeCaughtError(error) });\n });\n }\n\n /**\n * #2292: the guard that applies this agent's declared personal-data treatment to what its tools send the model, over the\n * conversation's placeholder table when the turn carries one (a conversation loads it from its row and stores it again),\n * else a table for this invocation. `undefined` when the agent declares no treatment.\n */\n private personalDataGuardOf(agent: FlowsActors_Agent, toolContext?: FunctionToolExecutionContext): PersonalDataGuard | undefined {\n const declared = agent.contentGuardrails?.personalData;\n if (!declared) return undefined;\n // assurance-control: WILDO.PRIVACY.DATA_MINIMIZATION, WILDO.PRIVACY.THIRD_PARTY_PROCESSING — a guarded agent's model\n // provider is sent personal fields only as the declared treatment, and each call records what was withheld\n // R7: the treatment is recorded per call (what was not sent in clear). A process that cannot record it does not run a\n // guarded agent: an unrecorded treatment is one nobody can show was applied.\n if (!this.providerCallRecorder) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: `Agent '${agent.ref}' treats personal data (contentGuardrails.personalData, declared or set by an organization's policy), and this process records no provider calls, so the treatment could not be recorded. It is not run.` },\n });\n }\n const table = toolContext?.personalDataPlaceholders ?? new PersonalDataPlaceholderTable();\n if (toolContext && !toolContext.personalDataPlaceholders) toolContext.personalDataPlaceholders = table;\n const registry = toolContext?.services.resourcesRegistry;\n return new PersonalDataGuard(declared.treatment, table, (resourceType) => registry?.tryGetResourceConfiguration(resourceType as never) as never);\n }\n\n /**\n * #2877, #3364: what a tool result's rows need to be treated under the policy of the organization that OWNS each one\n * (`treatRecordsResultByOwner`): its personal-data treatment and machine-reader placeholders per row, its screening\n * through an owner screen when the call screens nothing, and its output moderation by tightening `outputModeration`. The call's own organizations (its scope) are already applied to the agent; the others\n * are read here, once per call, from the turn's frame when it covers them. A row needing a treatment on a call that has\n * no guard is treated by a `REMOVE` guard created on first use over the call's table, and recorded on the call's trace\n * like a declared one. `undefined` when the call has no tool context, so offers no tool.\n *\n * Unlike a declared guard (`personalDataGuardOf`), the owner guard does not refuse a process without a provider-call\n * recorder: it appears mid-turn, after the model was called, and it only ever withholds. A turn is never run\n * untreated for want of the recorder; it can only send less, and the call's trace still names what was withheld.\n */\n private recordOwnerPolicyOf(\n request: object,\n agent: FlowsActors_Agent,\n scope: ModelCallOrganizationScope,\n toolContext?: FunctionToolExecutionContext,\n /** #2841: the invocation's operation observation, told each verdict the owner screen reaches. */\n observation?: AgentOperationObservationRecorder,\n /** #3364 step 3: the call's output moderation, tightened by each owner whose rows reach the model. */\n outputModeration?: OutputModerationGuard,\n ): (RecordOwnerPolicyContext & { readonly createdOwnerGuard: () => PersonalDataGuard | undefined }) | undefined {\n if (!toolContext) return undefined;\n const registry = toolContext.services.resourcesRegistry;\n const configurationOf = (resourceType: string) => registry?.tryGetResourceConfiguration(resourceType as never) as { resourcePrimaryScope?: ResourcePrimaryScope } | undefined;\n const lookups = new Map<string, Promise<AgentPolicyLookup>>();\n let ownerGuard: PersonalDataGuard | undefined;\n let ownerScreen: ToolResultScreen | undefined;\n const coveredOrganizationIds = organizationIdsOfCallScope(scope);\n // What the tools act in, which confines what they read; the call's scope can name more (a case's tenant).\n const acting = toolContext.auth?.initiatorIds?.organizationId;\n const actingOrganizationId = typeof acting === 'string' && acting.length > 0 ? acting : undefined;\n return {\n coveredOrganizationIds,\n ...(actingOrganizationId ? { actingOrganizationId } : {}),\n // The set retrieval narrows to: the acting tenant, else the caller's organization-wide memberships.\n possibleOwnerOrganizationIds: () => (actingOrganizationId ? [actingOrganizationId] : resolveCallerOrganizationIds((toolContext.auth ?? {}) as never)),\n // The organization row is its own scope root: its owner is its id. Every other organization-owned row names it.\n ownerOf: organizationNamedByRecord,\n // #3369: counted on the call's operation record, so the population is measured rather than assumed.\n rowsOwnerNotDerived: (call, rows) => {\n observation?.observeRowsOwnerNotDerived(call.toolCallId, rows);\n this.logger.info('A tool returned rows naming no organization that nothing could attribute; they reached the model under the strictest agent policy', {\n agentRef: agent.ref, toolName: call.toolName, rows,\n });\n },\n readPolicies: (organizationIds) => {\n const key = organizationIds.join('\\u0000');\n let lookup = lookups.get(key);\n if (!lookup) {\n const framed = agentPoliciesInFrame(organizationIds);\n lookup = framed ? Promise.resolve(framed) : readAgentPolicies(this.repositoriesRegistry, organizationIds);\n lookups.set(key, lookup);\n }\n return lookup;\n },\n // An unregistered resource is treated as organization-owned (fail closed); a registered one by its declared scope.\n isOrganizationOwned: (resourceType) => (configurationOf(resourceType)?.resourcePrimaryScope ?? ResourcePrimaryScope.ORGANIZATIONS) === ResourcePrimaryScope.ORGANIZATIONS,\n ownerGuard: () => {\n if (!ownerGuard) {\n const table = toolContext.personalDataPlaceholders ?? new PersonalDataPlaceholderTable();\n ownerGuard = new PersonalDataGuard(RedactionType.REMOVE, table, (resourceType) => configurationOf(resourceType) as never);\n if (!this.personalDataGuards.get(request)) this.personalDataGuards.set(request, ownerGuard);\n }\n return ownerGuard;\n },\n createdOwnerGuard: () => ownerGuard,\n // assurance-control: WILDO.AI.OUTPUT_MODERATION — a reply drawn from an organization's records is judged under that organization's output policy too\n rowsReachedModelFrom: (tightenings) => {\n // One entry at a time, so the lower severity wins whatever the order: entries of several owners, or a policy that\n // names a category twice, would let the LAST win through a single `Object.fromEntries` (#3364 review N1).\n for (const tightening of tightenings) {\n for (const entry of tightening.outputModeration ?? []) outputModeration?.tighten({ [entry.category]: entry.blockAtOrAbove });\n }\n },\n // #3364: a row whose owner screens is screened even when the call does not. Withholdings are recorded as the call's\n // own screen records them. Where nothing can screen, the screen answers NOT_SCREENED and the rows are withheld.\n // assurance-control: WILDO.AI.UNTRUSTED_CONTENT_SCREENING, WILDO.SECURITY.FAIL_CLOSED — a row whose owner asked for screening reaches the model only screened clean\n ownerScreen: () => {\n if (!ownerScreen) {\n const contentSafety = this.contentSafety;\n const unavailable = contentGuardrailClassifierGapOf(contentSafety, { kind: ClassifierBackedContentGuardrail.PROMPT_INJECTION })?.reason;\n observation?.screensToolResults();\n ownerScreen = new ToolResultScreen(\n unavailable !== undefined || !contentSafety\n ? async () => ({ outcome: ContentSafetyScreeningOutcome.NOT_SCREENED, reason: `the organization that owns these records screens them, and they cannot be screened: ${unavailable ?? 'no content-safety service'}` })\n : (text) => contentSafety.screenForPromptInjection(text),\n (record) => this.recordToolResultWithholding(agent, toolContext, record),\n observation?.observeScreening,\n );\n }\n return ownerScreen;\n },\n };\n }\n\n /**\n * Resolve an agent's declarative `capabilities.tools.functionRefs` into AI-SDK\n * `tool(...)` definitions, closing each over the caller's `toolContext` so the\n * tool executes as the user. Returns `undefined` when the agent declares no\n * tools or no context was supplied (grounding disabled). Unknown refs are\n * skipped with a debug log rather than failing the whole invocation.\n *\n * assurance-control: WILDO.AI.AGENT_AUTHORITY_CONFINEMENT — every tool is closed over its caller's context, so it acts with the caller's authority and no more.\n */\n private resolveAgentTools(\n agent: FlowsActors_Agent,\n toolContext?: FunctionToolExecutionContext,\n /** Populated with the identifier-safe name of every tool that requires a human decision, and its gate's route. */\n approvalGatedToolRoutes: Map<string, HumanDecision_RouteKind> = new Map(),\n /** #2292: the agent's personal-data treatment, applied at the MODEL boundary of every tool it is offered. */\n personalDataGuard?: PersonalDataGuard,\n /** #2292: screens each result for prompt injection before the model reads it; absent when the agent declares none. */\n toolResultScreen?: ToolResultScreen,\n /** #2877: treats each returned row under its owning organization's policy too (`recordOwnerPolicyOf`). */\n recordOwnerPolicy?: RecordOwnerPolicyContext & { readonly createdOwnerGuard: () => PersonalDataGuard | undefined },\n ): Record<string, any> | undefined {\n const functionRefs = agent.capabilities?.tools?.functionRefs;\n if (!functionRefs?.length || !toolContext) return undefined;\n\n const tools: Record<string, any> = {};\n /** #3369: what each tool call's dispatches reached, by `toolCallId`, read when its result is sent to the model. */\n const observedOwners = new Map<string, ToolCallRecordOwners>();\n for (const ref of functionRefs) {\n const functionTool: FunctionTool | undefined = this.flowsActorsRegistry.getFunctionTool(ref);\n if (!functionTool) {\n this.logDebug('Agent declares an unknown function tool; skipping', { agentRef: agent.ref, functionRef: ref });\n continue;\n }\n // #1611: a turn whose input came from outside (an autonomous turn started by an inbound delivery) is\n // offered only tools that read, or that a reviewer must approve. Withheld, not denied: the model is\n // never shown a write it could be talked into asking for.\n if (!isFunctionToolOfferedToTurn(functionTool, toolContext.autonomousTrigger, toolContext.initiationKind)) {\n this.logger.info(functionTool.presentsRecords\n ? 'A tool that shows records is withheld from a turn no conversation draws for a person (A2A, autonomous)'\n : 'A write tool is withheld from a turn started by an inbound delivery; declare it READ or gate it on a reviewer to offer it', {\n agentRef: agent.ref, functionRef: ref,\n });\n continue;\n }\n // Provider tool names must be identifier-safe; functionRefs use dots. Shared with the\n // approval-modification path, which must reverse it — see `modelToolNameForFunctionRef`.\n const toolName = modelToolNameForFunctionRef(ref);\n if (toolName in tools) {\n // The mapping is not injective. The approval path resolves a name back to the FIRST declared ref\n // that maps to it, so keeping the first here is what keeps the two directions agreeing.\n this.logger.warn('Two declared function refs map to the same model-facing name; the second is not offered to the model', {\n agentRef: agent.ref,\n functionRef: ref,\n toolName,\n });\n continue;\n }\n // #2292: a tool that does not say what its result carries could return anything. An agent that DECLARES a treatment\n // is never offered one (startup refuses it). An agent an organization's policy put under a treatment still is (#2292\n // R8): the tool runs and the person sees its result, but its MODEL is sent the result withheld whole\n // (`treatToolOutputForModel`), never in clear — rather than the tool silently disappearing from the agent.\n const personalDataOutput = functionTool.personalDataOutput;\n if (personalDataGuard && !personalDataOutput) {\n this.logger.info('A tool that does not declare what its result carries reaches this guarded agent\\'s model only withheld whole', {\n agentRef: agent.ref, functionRef: ref,\n });\n }\n // #2848: the ARGUMENTS of every tool that can change something are checked, whatever its result declares. Keyed on\n // the resource the arguments describe (`argumentsResource`), else the records the tool returns; a guarded write\n // naming neither accepts no placeholder at all, and a withheld marker is refused everywhere. See `argumentsAToolRunsWith`.\n tools[toolName] = tool({\n description: functionTool.description,\n // Under TOKENIZE a personal field also accepts a placeholder, which its own type (an email, a date) would refuse\n // before the value could be put back; the arguments are re-identified and validated against the tool's own schema\n // in `execute`.\n inputSchema: sdkInputSchemaOfFunctionTool(functionTool, personalDataGuard),\n // #2292: what the MODEL is sent of the result: treated for personal data, then screened for prompt injection, in\n // that order so the classifier reads placeholders. Applied only where model messages are built, so the person, the\n // conversation's tool trace and the cards keep what the tool returned.\n // A tool returning the person's own answer is not third-party content and is not screened.\n // #2877: a tool returning records is always given a model-side view, so a row an organization outside the call's\n // scope owns is treated under that organization's policy even on a call that declares no treatment.\n ...(personalDataGuard || (recordOwnerPolicy && (personalDataOutput?.kind === FunctionToolPersonalDataOutputKind.RECORDS_OF_RESOURCE\n || personalDataOutput?.kind === FunctionToolPersonalDataOutputKind.TREATED_BY_TOOL))\n || (toolResultScreen && !functionTool.returnsThePersonsOwnWords) ? {\n toModelOutput: async ({ toolCallId, output }: { toolCallId: string; output: unknown }) => {\n // #2761: the engine wrote this result and it quotes nothing a record or a third party holds, so it reaches the\n // model as it is: withholding or screening it would hide the very sentence it exists to deliver.\n if (isFunctionToolRefusalResult(output)) return { type: 'json' as const, value: output as never };\n const observed = observedOwners.get(toolCallId);\n const ownerToolCall = {\n toolCallId,\n toolName,\n callScreensResult: toolResultScreen !== undefined && !functionTool.returnsThePersonsOwnWords,\n unattributedRows: unattributedRowOwnershipOf(functionTool),\n ...(observed ? { observedOwners: observed } : {}),\n };\n const modelSide = recordOwnerPolicy && personalDataOutput?.kind === FunctionToolPersonalDataOutputKind.RECORDS_OF_RESOURCE\n ? await treatRecordsResultByOwner(output, personalDataOutput.resourceType, personalDataGuard, recordOwnerPolicy, ownerToolCall)\n : recordOwnerPolicy && personalDataOutput?.kind === FunctionToolPersonalDataOutputKind.TREATED_BY_TOOL\n ? await treatToolTreatedResultByPossibleOwners(output, personalDataOutput.treat, personalDataGuard, recordOwnerPolicy, ownerToolCall)\n : personalDataGuard ? treatToolOutputForModel(output, personalDataOutput, personalDataGuard) : output;\n if (!toolResultScreen || functionTool.returnsThePersonsOwnWords) return { type: 'json' as const, value: modelSide as never };\n return await toolResultScreen.forModel(toolCallId, toolName, modelSide) as never;\n },\n } : {}),\n /**\n * OBSERVE the failure, then re-throw it unchanged.\n *\n * The AI SDK catches whatever a tool throws and turns it into a tool-error RESULT that is fed\n * back to the model, which then narrates it to the user in prose. That is the right runtime\n * behaviour — the model can apologise, retry or ask a question — but it means a failing tool\n * produces NO server-side record of any kind: not an error, not a warning, not a debug line.\n * The only trace is whatever the model chose to say, and the model is guessing: an\n * `authorizations_access_denied` on the CREATE was narrated as \"I don't have permission to\n * write to that list\", which points an investigator at the list rather than at the ACL.\n *\n * That cost a full debugging session against a live stack — the failure could not be\n * attributed from the logs at all, because there were none. An app author hitting the same\n * thing has strictly less to work with, since the engine internals are not theirs to read.\n *\n * Re-throwing is what keeps this observation-only: the SDK still receives the same error, so\n * the model still sees the same tool result and the conversation is unchanged.\n */\n //\n // The call runs inside the AGENT FRAME (#1595). Every `ExecutionContext` the tool builds — through\n // a framework factory, by hand from `toolContext.auth`, or through an `*AsSystem` helper — adopts\n // it, so every audit row the tool causes names this agent and this execution without the tool\n // doing anything. Opened HERE, once per call, rather than threaded through the tool context,\n // because a hand-written tool that forgot to copy it would record the agent's write as the\n // user's own.\n // assurance-control: WILDO.AUDIT.CONTEXT_ATTRIBUTION — an agent's tool calls are attributed to the agent on every audit row\n execute: async (args: any, callOptions: { toolCallId: string }) => runWithAgentActorFrame(agentActorForToolCall(agent, toolContext, ref), async () => {\n try {\n // #2877: once a row was withheld from this call's model, its writes are checked as a guarded call's are, so a\n // withheld marker is never stored.\n const effectiveArgs = await argumentsAToolExecutesWith(functionTool, personalDataGuard ?? recordOwnerPolicy?.createdOwnerGuard(), args);\n toolContext.onFunctionToolExecuting?.(callOptions.toolCallId);\n if (!recordOwnerPolicy) return await functionTool.execute(effectiveArgs, toolContext);\n // #3369: the owners of the rows this call's dispatches return, so a row the tool returns without its\n // organization is still attributed (`treatRecordsResultByOwner`).\n const { result, owners } = await observingRecordOwners(() => functionTool.execute(effectiveArgs, toolContext));\n observedOwners.set(callOptions.toolCallId, owners);\n return result;\n } catch (error) {\n this.logger.warn('Agent function tool execution failed; the model will be told, so nothing else records this', {\n agentRef: agent.ref,\n functionRef: ref,\n toolName,\n ...projectCaughtErrorLogFields(error),\n });\n // #2761: a refusal only the PERSON can resolve, in the application, is returned as a typed result carrying the\n // engine's own sentence, not re-thrown for the model to narrate in its own words. Checked before the guarded\n // re-throw: the result names no record value, only what the person must do.\n const refusal = functionToolRefusalOf(error);\n if (refusal) return refusal;\n // #2292: an error's text can quote a record's value (a duplicate email, a conflicting name), and the SDK sends it\n // to the model as it is. A guarded agent's model is told only what kind of failure it was; a placeholder\n // refusal, which names no value, is passed on so the model can correct the call.\n // A screened agent's model is told the kind too: an error's text can carry what a third party wrote, and an error\n // result is not screened.\n if ((personalDataGuard || recordOwnerPolicy?.createdOwnerGuard() || toolResultScreen) && !(error instanceof PersonalDataPlaceholderRefusal)) throw guardedToolError(error);\n throw error;\n }\n }),\n });\n // ⚠️ The SDK's tool-level `needsApproval` is DELIBERATELY not set — it is deprecated\n // (\"tool approval is handled on a generateText / streamText level now\"), so the gate is\n // declared here and applied at the CALL site via `toolApproval`. Keeping the translation in\n // one place also means an app author never writes the SDK's vocabulary.\n // `resolveFunctionToolApprovalGate` is the one reader of `requiresHumanApproval` and `humanApproval`\n // (#1594), so the gate the model is held to and the route a pause is given cannot disagree about\n // whether a tool is gated.\n const approvalGate = resolveFunctionToolApprovalGate(functionTool);\n if (approvalGate) approvalGatedToolRoutes.set(toolName, approvalGate.route);\n }\n return Object.keys(tools).length > 0 ? tools : undefined;\n }\n\n /**\n * The approval-signing key, or `undefined` when this runtime holds no tool-approval key (#2893).\n *\n * PUBLIC because there are two moments that need this exact key and only one of them is a turn:\n * the tool loop SIGNS an approval request when it suspends, and — since approve-with-modifications\n * (#566) — a resume RE-SIGNS it after an approver authored different arguments. A second\n * derivation in the resume path would be a second key the day either expression moved, and the\n * failure would present as a forged approval rather than as the configuration skew it is.\n *\n * Returns rather than throws, because the two callers owe different answers: a TURN that cannot\n * sign must be refused outright (see below), while a MODIFICATION that cannot be re-signed must\n * leave the pause standing so the approver can still approve the call as proposed.\n */\n public resolveToolApprovalSigningKey(): string | undefined {\n const purposeKey = applicationSymmetricKeyOf(this.appConfig, CryptoKey_Purpose.TOOL_APPROVAL_SIGNING);\n return purposeKey ? deriveToolApprovalSigningKey(purposeKey) : undefined;\n }\n\n /**\n * The HMAC secret that signs approval requests — REQUIRED once any tool is approval-gated.\n *\n * Fails CLOSED, and the asymmetry is the reason. Without a secret the SDK still suspends and still\n * resumes, so everything looks like it works; what silently disappears is the binding between an\n * approval and the tool call it approved, which is what stops a client forging one. The tools an\n * author bothered to gate are precisely those where a forged approval is worst, so degrading to\n * unsigned approvals would remove the protection exactly where it was asked for.\n *\n * Refusing the TURN (rather than the tool) is deliberate: silently dropping the gated tool from an\n * agent's toolset would leave the agent quietly less capable with no signal, which is harder to\n * diagnose than a startup-shaped failure naming the missing configuration.\n *\n * ## Where the key comes from\n *\n * Its own key purpose, `CryptoKey_Purpose.TOOL_APPROVAL_SIGNING` (#2893), minted by the platform and delivered to the\n * backend and the minions, which both run agents: a resume must verify what a suspension signed, wherever each ran.\n *\n * It used to be derived from the application's primary secret. That made the key whatever the bearer credential was,\n * so anyone holding the credential could forge approvals, and a minion (which holds its own credential under the same\n * name) signed with a key the backend could not verify. Before that, a bespoke `WILDO_TOOL_APPROVAL_SECRET` was read\n * that no deployment ever set, so the gate refused every turn. A delivered purpose key has neither defect.\n *\n * The approval secret is still the purpose key's HMAC over a versioned label ({@link deriveToolApprovalSigningKey}), so\n * the key is never handed to the SDK verbatim. Deliberately NOT offered as an override-if-set: a second source would\n * mean two backends that disagree about whether an approval is valid, and the failure would look like a forged\n * approval rather than a configuration skew.\n */\n private resolveToolApprovalSecretOrThrow(agent: FlowsActors_Agent, approvalGatedToolNames: Set<string>): string {\n const signingKey = this.resolveToolApprovalSigningKey();\n if (signingKey) return signingKey;\n\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `Agent \"${agent.ref}\" declares human-approval tools (${[...approvalGatedToolNames].join(', ')}) but this runtime holds no tool-approval key (security.symmetricKeys.tool_approval_signing), so approvals cannot be signed. Approval decisions would be unsigned and therefore forgeable by a client, so the turn is refused rather than run with the gate weakened.`,\n agentRef: agent.ref,\n },\n });\n }\n\n /**\n * The SDK call-level approval configuration for a resolved tool set, or `undefined` when no\n * declared tool is approval-gated.\n *\n * `'user-approval'` is the status that SUSPENDS the tool loop and emits a\n * `tool-approval-request`; the other statuses (`approved` / `denied` / `not-applicable`) decide\n * without a human and are not what a `requiresHumanApproval` declaration means. The SDK still reports\n * an `approved` / `denied` decision as a `tool-approval-request`, marked `isAutomatic`, which the stream\n * reader must not take for a pause (#3254, `streamTextToDeltas`).\n */\n private buildToolApprovalConfiguration(\n approvalGatedToolRoutes: Map<string, HumanDecision_RouteKind>,\n /** The turn's principal. `undefined` is treated as unable to answer — fail closed. */\n executionType?: ExecutionContext_ExecutionType,\n /** The door that opened the turn, from the row (#1594). Only an AUTONOMOUS machine turn may pause, on a reviewer route. */\n initiationKind?: FlowsActors_InitiationKind | null,\n ): Record<string, ToolApprovalDecision> | undefined {\n if (approvalGatedToolRoutes.size === 0) return undefined;\n\n // A call that nobody could answer must be DENIED, never suspended (D-HITL-3, now the predicate\n // `admitsDecisionSuspension`, decided PER TOOL because the route is the tool's). Suspending such a\n // turn is not a safe default: it parks the execution waiting for a decision nobody is routed.\n //\n // Denial is also the better OUTCOME, not merely the safe one: the SDK reports the refusal to\n // the model, which answers explaining that the action needs human approval. The caller gets a\n // usable reply instead of a turn that never returns.\n const denied: ToolApprovalDecision = { type: 'denied', reason: 'This action requires approval from a person, and this caller is not one. Ask a user to perform it, or run it through an interactive session.' };\n return Object.fromEntries([...approvalGatedToolRoutes].map(([name, routeKind]) => [\n name,\n admitsDecisionSuspension({ executionType, initiationKind, routeKind }) ? 'user-approval' : denied,\n ]));\n }\n\n /** API-transport streaming — mirrors executeAgentViaApi but forwards deltas + tool events. */\n private async executeAgentViaApiStreaming(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n execution: Extract<ResolvedAgentExecution, { transport: 'api' }>,\n prompts: CompiledExecutionPrompts,\n handlers: AgentStreamHandlers,\n tools?: Record<string, any>,\n toolApproval?: Record<string, ToolApprovalDecision>,\n toolApprovalSecret?: string,\n outputModeration?: OutputModerationGuard,\n ): Promise<AgentExecutionResult> {\n const aiProvider = await this.resolveApiProviderClient(execution.providerRef);\n const limiter = this.getBottleneckForProvider(\n execution.providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n );\n const jobId = `${agent.ref}-api-stream-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n\n this.logDebug('Scheduling streaming API call through rate limiter', {\n agentRef: agent.ref,\n providerRef: execution.providerRef,\n operationKey: execution.operationKey,\n model: agent.config.model,\n toolCount: tools ? Object.keys(tools).length : 0,\n jobId,\n });\n\n const modelFailovers: ModelCallFailover[] = [];\n const result = await this.scheduleOnLimiter(\n limiter,\n { id: jobId },\n () => this.streamOperation({\n providerClient: aiProvider,\n providerRef: execution.providerRef,\n modelFailovers,\n config: agent.config,\n operationKey: execution.operationKey,\n systemPrompt: prompts.systemPrompt,\n instructions: prompts.instructions,\n input: request.input,\n handlers,\n tools,\n toolApproval,\n toolApprovalSecret,\n outputModeration,\n operationObservation: this.operationObservationOf(request),\n personalDataGuard: this.personalDataGuards.get(request),\n }),\n );\n\n return {\n ...result,\n ...this.apiTransportOf(execution.providerRef, agent.config.model, modelFailovers),\n };\n }\n\n /**\n * Dispatch a streaming operation by key. Only text-producing operations\n * (GENERATE_TEXT / CHAT_COMPLETION and their THINKING variants) stream; other\n * keys throw {@link AgentStreamingUnsupportedError}. The output shape matches\n * the buffered executors so `normalizeOperationOutput` is identical.\n */\n private async streamOperation({ providerClient, providerRef, modelFailovers, config, operationKey, systemPrompt, instructions, input, handlers, tools, toolApproval, toolApprovalSecret, outputModeration, operationObservation, personalDataGuard }: streamOperationParams): Promise<{ output: unknown; usage?: any; approvalSuspension?: AgentApprovalSuspension }> {\n // A conversational stream's text is the reply; tool inputs and shown reasoning are named by the middleware itself.\n // #2301: a declared alternative takes a step whose stream the provider failed to OPEN (`withModelCallFailover`).\n const providerModel = this.withDeclaredModelFailover({\n primary: this.getModelFromProvider(providerClient, config.model),\n providerRef,\n config,\n transportOf: (alternativeModel) => alternativeModel,\n ...(modelFailovers === undefined ? {} : { sink: modelFailovers }),\n });\n const model = this.moderatedModel(this.observedModel(this.accountRefusalIsFinal(providerModel), operationObservation), outputModeration, FlowsActors_ModeratedOutputKind.REPLY);\n const baseOptions = this.buildBaseOptions(config as FlowsActors_Agent_LLMConfiguration);\n\n try {\n switch (operationKey) {\n case LLMProvider_OperationKey.GENERATE_TEXT: {\n const { text, usage, approvalSuspension } = await this.streamTextToDeltas({ model, ...this.textGenerationPromptOf(instructions, input), instructions: systemPrompt, baseOptions, tools, toolApproval, toolApprovalSecret, personalDataGuard }, handlers);\n return { output: { text }, usage, approvalSuspension };\n }\n\n case LLMProvider_OperationKey.CHAT_COMPLETION: {\n const messages = this.buildChatMessages(instructions, input);\n // System prompt goes via the top-level `instructions:` option (AI-SDK v7\n // forbids it inside `messages`), exactly like the GENERATE_TEXT branch above.\n const { text, usage, approvalSuspension } = await this.streamTextToDeltas({ model, messages, instructions: systemPrompt, baseOptions, tools, toolApproval, toolApprovalSecret, personalDataGuard }, handlers);\n return { output: { message: { role: LLMProvider_MessageRole.ASSISTANT, content: text } }, usage, approvalSuspension };\n }\n\n default:\n throw new AgentStreamingUnsupportedError('operation', `Operation ${operationKey} does not produce a token stream; use invokeAgent (buffered) instead.`);\n }\n } catch (error) {\n if (error instanceof AgentStreamingUnsupportedError) throw error;\n if (error instanceof AgentOutputWithheldError) throw error;\n this.rethrowModelCallFailure(error, operationKey);\n if (isWildoBackendError(error)) throw error;\n const errorDetails = this.extractProviderErrorDetails(error);\n this.logger.error('Streaming operation failed - provider response', { operationKey, ...errorDetails });\n throw this.buildModelCallFailure(error, errorDetails, { operationKey, message: `Failed to stream operation ${operationKey}: ${errorDetails.errorMessage}` });\n }\n }\n\n /**\n * Run AI-SDK `streamText` and iterate its `fullStream`, forwarding text deltas\n * through `handlers.onDelta` and tool-call/result lifecycle events through\n * `handlers.onToolEvent` as they arrive (honest streaming — no buffering). When\n * `tools` are supplied a bounded multi-step loop is enabled\n * (`stopWhen: stepCountIs(MAX_TOOL_STEPS)`) so the model can call a tool and\n * continue. A throwing handler is swallowed (debug-logged) so a consumer error\n * never breaks the stream. Returns the assembled text + normalized usage, or throws\n * {@link AgentModelCallFailedError} when the provider failed the call (an `error` part, #2191).\n */\n private async streamTextToDeltas(\n args: {\n model: any; prompt?: string; instructions?: string; messages?: any[]; baseOptions: any;\n tools?: Record<string, any>; toolApproval?: Record<string, ToolApprovalDecision>; toolApprovalSecret?: string;\n /** #2855: see `streamOperationParams.personalDataGuard`. */\n personalDataGuard?: PersonalDataGuard;\n },\n handlers: AgentStreamHandlers,\n ): Promise<{ text: string; usage?: any; approvalSuspension?: AgentApprovalSuspension }> {\n const { baseOptions, tools, toolApproval, toolApprovalSecret, personalDataGuard, ...streamArgs } = args;\n /*\n * #2855: what each MODEL STEP is sent of a tool call a PERSON authored (an approver's edit): its\n * personal arguments treated by this invocation's guard, its mark removed. The SDK executes the approved call from the\n * messages BEFORE the first step and never from a step's prompt, so the person's values run and the model reads only\n * the treatment. Through `prepareStep`, whose messages carry forward to later steps (treated once, counted once); with\n * no tools nothing executes from the messages, and they are treated before the call. `promptMessages` below stays the\n * untreated array, so a second pause stores the call as it runs, mark included, and its resume is treated again.\n */\n const modelMessagesOf = (messages: any[]): any[] => modelCopyOfPersonAuthoredToolCalls(messages, personalDataGuard);\n const callArgs = !tools && Array.isArray(streamArgs.messages) ? { ...streamArgs, messages: modelMessagesOf(streamArgs.messages) } : streamArgs;\n\n // ── Usage must be accumulated AS STEPS FINISH, not read only at the end ────────────────────\n //\n // On an ABORTED stream AI-SDK ends `fullStream` normally (an `abort` part) but **rejects**\n // `result.usage`. Reading only that terminal promise therefore threw here, which skipped\n // the runtime's usage report upstream (then `reportUsage` into A2A's `turnTotalTokens`, then `reportTurnUsage`\n // into the one usage port, #1855; the charge is now this service's own, #2935), and meant `recordTurnTokens` was\n // NEVER called — so a cancelled turn moved the tenant's token budget by zero while the\n // provider had really generated (and charged for) output. That made cancellation an\n // unmetered-spend path a caller could drive on demand: start a turn, hang up, repeat.\n //\n // Per-step usage is known the moment each step completes, so it survives an abort. Only the\n // IN-FLIGHT step's partial output is unrecoverable — a small, bounded, honest gap rather than\n // losing the whole turn's consumption.\n //\n // Each step's FULL extracted usage is kept (#1598), so the per-step total keeps the cache and reasoning\n // splits too; `aggregateExtractedUsage` sums a split only when every step reported it.\n const stepUsages: ReturnType<AgentsBackendService['extractUsage']>[] = [];\n\n const result = await streamText({\n ...callArgs,\n ...baseOptions,\n onStepFinish: (step: any) => {\n stepUsages.push(this.extractUsage(step?.usage));\n },\n // The SDK's default `onError` prints the raw failure to stderr and nothing else. The `error`\n // PART below is what makes the call fail, and `streamOperation` logs it with the provider's\n // details, so the default would only add an unstructured duplicate (#2191).\n onError: SUPPRESS_SDK_STREAM_ERROR_PRINT,\n // AFTER `baseOptions` on purpose: the signal is per-INVOCATION, whereas\n // `baseOptions` is derived from the agent's static config, so it must not be\n // overridable by configuration.\n ...(handlers.abortSignal ? { abortSignal: handlers.abortSignal } : {}),\n // Human-in-the-loop. `toolApproval` suspends the loop on a gated call; the secret HMAC-signs\n // the request so a replayed approval cannot be forged by a client. The caller guarantees they\n // travel together — see the fail-closed check where the configuration is built.\n ...(toolApproval ? { toolApproval, experimental_toolApprovalSecret: toolApprovalSecret } : {}),\n ...(tools\n ? {\n tools,\n stopWhen: stepCountIs(MAX_TOOL_STEPS),\n // Sanitize the CONTINUATION prompt of the multi-step tool loop: extended-thinking models\n // emit an empty-text assistant `reasoning` part that the provider's prompt validation\n // rejects when it is fed back for the next step, killing every step after the first.\n // `prepareStep`'s `messages` override is the SDK-supported seam for this and carries\n // forward to later steps. See `stripEmptyReasoningParts`.\n // #3192: the same seam tells the model a reviewer changed a call. Read from these raw messages, because the\n // override below removes the mark: the instructions carry forward, so the step that reads the mark states it.\n prepareStep: ({ messages, instructions }: { messages: any[]; instructions?: any }) => {\n const stated = withReviewerEditStatements(instructions, reviewerEditStatementsOf(messages));\n return { messages: stripEmptyReasoningParts(modelMessagesOf(messages)), ...(stated === undefined ? {} : { instructions: stated }) };\n },\n }\n : {}),\n });\n\n let full = '';\n let approvalSuspension: AgentApprovalSuspension | undefined;\n /** The FIRST `error` part — the provider's failure. Later parts are its consequences. */\n let providerFailure: { error: unknown } | undefined;\n for await (const part of result.fullStream) {\n // A provider failure arrives as a PART, never as a throw (#2191). Recorded outside the handler\n // `try` below on purpose: that `try` swallows consumer errors, and this is not one. The stream is\n // drained to its end rather than abandoned, so every finished step still reports its usage.\n if (part.type === 'error') {\n providerFailure ??= { error: (part as { error?: unknown }).error };\n continue;\n }\n try {\n if (part.type === 'text-delta') {\n full += part.text;\n handlers.onDelta(part.text);\n } else if (part.type === 'tool-call') {\n handlers.onToolEvent?.({ phase: FlowsActors_ToolCallPhase.CALL, toolCallId: part.toolCallId, toolName: part.toolName, input: part.input });\n } else if (part.type === 'tool-result') {\n // A PRELIMINARY result is a streaming tool's partial output; the final one follows with the same id.\n if (!(part as { preliminary?: boolean }).preliminary) {\n handlers.onToolEvent?.({ phase: FlowsActors_ToolCallPhase.RESULT, toolCallId: part.toolCallId, toolName: part.toolName, input: part.input, output: part.output });\n }\n } else if (part.type === 'tool-error') {\n handlers.onToolEvent?.({ phase: FlowsActors_ToolCallPhase.ERROR, toolCallId: part.toolCallId, toolName: part.toolName, input: part.input, error: part.error });\n } else if (part.type === 'tool-output-denied') {\n // The call was refused and never ran: by the person it was waiting on, or by the approval configuration when no\n // person could be asked (#3254, an automatic denial). Without this the call stayed at CALL (#2524).\n handlers.onToolEvent?.({ phase: FlowsActors_ToolCallPhase.DENIED, toolCallId: part.toolCallId, toolName: part.toolName });\n } else if (part.type === 'reasoning-delta') {\n handlers.onReasoningDelta?.(part.text);\n } else if (part.type === 'source') {\n handlers.onSource?.(toFlowsActorsSource(part));\n } else if (part.type === 'tool-approval-request' && (part as { isAutomatic?: boolean }).isAutomatic !== true) {\n // The tool loop has STOPPED and is waiting for a human. This is a terminal outcome of the\n // turn, not an error: the model produced no further text and will not until the decision\n // is replayed. Captured here rather than inferred from `finishReason`, because the part\n // carries the `approvalId` the resume must echo — and the SDK binds that id to the tool\n // call with an HMAC signature, so it cannot be reconstructed after the fact.\n //\n // Only a request a PERSON must answer (#3254). The SDK also reports a decision the configuration already made\n // (`buildToolApprovalConfiguration`'s `{ type: 'denied' }` for a principal no person waits on) as a request,\n // marked `isAutomatic`, followed by its own response and a `tool-output-denied`, and the loop carries on: the\n // model reads the refusal and answers. Taking that for a pause parked an A2A organization client's turn on a\n // call already refused, and raised a decision no answer could apply.\n // spec-cite: ai 7.0.142 `dist/index.d.ts`, the approval request's `isAutomatic` (\"Flag indicating whether the tool was automatically approved or denied.\"), and `docs/03-agents/06-tool-approvals.mdx`, \"Handle Manual Approvals\", which collects only `part.type === 'tool-approval-request' && !part.isAutomatic`.\n approvalSuspension = {\n approvalId: (part as any).approvalId,\n toolCallId: (part as any).toolCall?.toolCallId ?? (part as any).toolCallId,\n toolName: (part as any).toolCall?.toolName ?? (part as any).toolName,\n toolArgs: (part as any).toolCall?.input ?? (part as any).input,\n sdkModelMessages: [],\n };\n }\n } catch (cbError) {\n this.logDebug('Streaming handler threw (non-fatal)', {\n ...projectCaughtErrorLogFields(cbError),\n });\n }\n }\n\n // ── A provider failure FAILS the call ──────────────────────────────────────────────────────\n //\n // Returning here, as this method did until #2191, handed back `{ text: '' }` for a call the\n // provider refused, and the caller recorded a COMPLETED turn with no message. Throwing reaches the\n // failure arm every caller already has. A CANCELLED call is left to the caller's own signal check:\n // the SDK replaces the remainder of an aborted stream with an `abort` part, and a cancellation is\n // not a provider failure even if a failing chunk raced it.\n //\n // Usage is the per-step total, never `result.usage`: after a later step's call fails the SDK\n // resolves the terminal total as an EMPTY usage (no `finish` part was seen), which would meter a\n // tool loop's finished steps as zero. No finished step → no usage at all (see the error's JSDoc).\n // #2292 Phase 3: the output-moderation middleware ends a withheld step with its own error part, after the step's\n // `finish` usage. Checked FIRST: it is the application's policy, not a provider failure, and carries the step's usage.\n if (providerFailure?.error instanceof AgentOutputWithheldError) {\n throw providerFailure.error.withUsage(stepUsages.length > 0 ? this.aggregateExtractedUsage(stepUsages) : undefined);\n }\n if (providerFailure && !handlers.abortSignal?.aborted) {\n throw new AgentModelCallFailedError(providerFailure.error, stepUsages.length > 0 ? this.aggregateExtractedUsage(stepUsages) : undefined);\n }\n\n // Guarded: `result.usage` rejects on a stream aborted before ANY step finished. An unguarded\n // read here is what turned cancellation into an unmetered path.\n let terminalUsage: unknown;\n try {\n terminalUsage = await result.usage;\n } catch (usageError) {\n this.logDebug('Stream usage unavailable (aborted, or the provider omitted it) — metering the per-step total instead', {\n ...projectCaughtErrorLogFields(usageError),\n });\n }\n const usage = this.selectStreamTurnUsage(terminalUsage, stepUsages);\n\n // The resume payload is the WHOLE conversation the model was in when it stopped: the prompt this call was given,\n // then every step's response messages. The runtime resumes with `[...payload, approval response]`, which is the\n // SDK's own manual-approval recipe (ai 7, `docs/03-agents/06-tool-approvals.mdx`, \"Handle Manual Approvals\":\n // `messages.push(...result.responseMessages)` onto the messages the call was given).\n //\n // #3145: this stored `(await result.response).messages` alone, which is wrong twice. `response` is the LAST step's\n // metadata, so a turn that read something before the gated call lost that step; and response messages never carry\n // the prompt, so the resumed call opened on an assistant tool call with no user message before it. An answered\n // question then ended \"your message didn't come through\", and an approved call ran with the request that asked\n // for it gone. Read AFTER the stream drains, so the assistant turn carrying the approval request is included.\n if (approvalSuspension) {\n try {\n const promptMessages = streamArgs.messages ?? (streamArgs.prompt !== undefined ? [{ role: 'user', content: streamArgs.prompt }] : []);\n approvalSuspension.sdkModelMessages = [...promptMessages, ...((await result.responseMessages) ?? [])];\n } catch (messagesError) {\n this.logDebug('Could not capture resume messages for a suspended turn', {\n ...projectCaughtErrorLogFields(messagesError),\n });\n }\n }\n\n return {\n text: full,\n usage,\n approvalSuspension,\n };\n }\n\n /**\n * Choose what a streamed turn meters: the SDK's terminal total, or the sum of the steps that finished.\n *\n * The terminal total is authoritative when it carries numbers, because it is the provider's own account of the\n * whole turn. It carries none on a turn that was cut short, and ai@7 signals that in TWO ways, not one (#2252):\n *\n * - no step finished → `result.usage` REJECTS (`terminalUsage` arrives here `undefined`);\n * - a step finished, then the stream was aborted → `result.usage` RESOLVES to the empty usage, every field\n * `undefined`, because the total is only ever set by a `finish` part and an aborted stream emits none.\n * (ai@7.0.142 `dist/index.js`, the `eventProcessor` flush: it rejects only when no step was recorded or a\n * no-output error was seen, and otherwise resolves `recordedTotalUsage ?? createNullLanguageModelUsage()`.)\n *\n * Keying the choice on rejection alone, as this method did until #2252, preferred the empty total in the second\n * case and metered a cancelled tool loop as zero tokens while the provider charged for its finished steps — the\n * caller-driveable unmetered-spend path the per-step accumulation exists to close. So the test is whether the\n * total REPORTS usage (`tokenUsageComplete`, i.e. both token counts are numbers), not whether it settled.\n *\n * Rejected: keying on `abortSignal.aborted`. A turn can finish and THEN be cancelled, and its terminal total is\n * then complete and right; the content of the total is what decides, not the cancellation that raced it.\n *\n * A complete terminal total is still not trusted as COMPLETE when a finished step reported no usage: the SDK\n * sums step usage treating a missing count as 0, so its total would claim completeness for a turn one of whose\n * steps was never metered. The per-step sum carries the same counts and says it is incomplete.\n *\n * With no finished step and no terminal total the result is all-zero and marked incomplete, exactly what\n * `extractUsage(undefined)` reports.\n */\n private selectStreamTurnUsage(\n terminalUsage: unknown,\n stepUsages: readonly ReturnType<AgentsBackendService['extractUsage']>[],\n ): ReturnType<AgentsBackendService['extractUsage']> {\n const terminal = terminalUsage === undefined ? undefined : this.extractUsage(terminalUsage);\n if (terminal?.tokenUsageComplete && stepUsages.every((step) => step.tokenUsageComplete)) return terminal;\n if (stepUsages.length > 0) return this.aggregateExtractedUsage(stepUsages);\n return terminal ?? this.aggregateExtractedUsage(stepUsages);\n }\n\n /**\n * What a text-generation call (GENERATE_TEXT, STREAM_TEXT) sends as its prompt: a conversation input as `messages`, so the\n * bounded replay keeps each turn's role and reaches the model once, and any other input as the single `prompt`. The\n * instructions of a conversation are only its current turn (`invocationInstructionsOf`), which is the last message.\n */\n private textGenerationPromptOf(instructions: string, input: unknown): { prompt: string } | { messages: ReturnType<AgentsBackendService['buildChatMessages']> } {\n return invocationConversationOf(input) ? { messages: this.buildChatMessages(instructions, input) } : { prompt: instructions };\n }\n\n /**\n * Build the AI-SDK `messages` array for a chat turn: a caller-supplied\n * `input.messages` conversation, or a single user turn from `instructions`.\n *\n * The array is deliberately SYSTEM-FREE. AI-SDK v7 (`ai@7.x`) rejects a\n * `role:'system'` entry inside `messages` (\"System messages are not allowed in\n * the prompt or messages fields. Use the instructions option instead.\"). The\n * agent's system prompt must be passed by the CALLER via the top-level\n * `instructions:` option of `generateText` / `streamText` (as `executeGenerateText`\n * does), NEVER pushed in here. Any `role:'system'` entry a caller left in\n * `input.messages` is filtered out so the array stays v7-valid (and a new array is\n * returned — the caller's `input.messages` is never mutated). Shared by the\n * buffered chat executor and the streaming path. Throws VALIDATION when no\n * messages result.\n */\n private buildChatMessages(\n instructions: string,\n input: any,\n ): Array<{ role: 'system' | 'user' | 'assistant'; content: string | Array<any> }> {\n let messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string | Array<any> }> = [];\n\n if (input && typeof input === 'object' && 'messages' in input && Array.isArray(input.messages)) {\n // System prompt travels via the top-level `instructions:` option, so drop any\n // `role:'system'` entries here (they would be rejected by AI-SDK v7).\n messages = input.messages.filter((m: any) => m.role !== 'system');\n } else {\n messages.push({ role: 'user', content: instructions });\n }\n\n if (messages.length === 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_MESSAGES_REQUIRED,\n context: { operation: 'CHAT_COMPLETION' }, // diagnostic (log-only)\n });\n }\n return messages;\n }\n\n /**\n * Sum several physical results' extracted usage into one (the chunks of a chunked structured call, the steps\n * of an aborted stream). Prompt, completion and total are summed; completeness holds only if every part was\n * complete. Each cache or reasoning dimension is summed only when EVERY part reported it (#1598 I6): a\n * split known for some parts only would be an understatement presented as exact, so it is left absent and\n * the cost calculator prices the whole as uncached input / plain output instead. With no parts the result is\n * all-zero and marked incomplete, which is what `extractUsage(undefined)` reports too.\n */\n private aggregateExtractedUsage(parts: readonly ReturnType<AgentsBackendService['extractUsage']>[]): ReturnType<AgentsBackendService['extractUsage']> {\n const sum = (read: (part: ReturnType<AgentsBackendService['extractUsage']>) => number | undefined): number | undefined =>\n parts.length > 0 && parts.every((part) => read(part) !== undefined)\n ? parts.reduce((total, part) => total + read(part)!, 0)\n : undefined;\n const noCacheTokens = sum((part) => part.inputTokenDetails?.noCacheTokens);\n const cacheReadTokens = sum((part) => part.inputTokenDetails?.cacheReadTokens);\n const cacheWriteTokens = sum((part) => part.inputTokenDetails?.cacheWriteTokens);\n const textTokens = sum((part) => part.outputTokenDetails?.textTokens);\n const reasoningTokens = sum((part) => part.outputTokenDetails?.reasoningTokens);\n return {\n promptTokens: parts.reduce((total, part) => total + part.promptTokens, 0),\n completionTokens: parts.reduce((total, part) => total + part.completionTokens, 0),\n totalTokens: parts.reduce((total, part) => total + part.totalTokens, 0),\n // No parts is no report at all, never a complete one.\n tokenUsageComplete: parts.length > 0 && parts.every((part) => part.tokenUsageComplete),\n // The three input categories travel together, as the calculator reads them: all or none.\n ...(noCacheTokens !== undefined && cacheReadTokens !== undefined && cacheWriteTokens !== undefined\n ? { inputTokenDetails: { noCacheTokens, cacheReadTokens, cacheWriteTokens } }\n : {}),\n ...(textTokens !== undefined || reasoningTokens !== undefined\n ? { outputTokenDetails: { ...(textTokens === undefined ? {} : { textTokens }), ...(reasoningTokens === undefined ? {} : { reasoningTokens }) } }\n : {}),\n };\n }\n\n /**\n * Extract usage information from AI SDK usage object\n * Handles different usage object structures across providers\n */\n private extractUsage(usage: any): AgentModelCallUsage {\n // AI SDK usage object structure varies by provider\n // Common properties: promptTokens, completionTokens, totalTokens\n const observedPromptTokens = usage?.promptTokens ?? usage?.inputTokens;\n const observedCompletionTokens = usage?.completionTokens ?? usage?.outputTokens;\n const tokenUsageComplete = typeof observedPromptTokens === 'number' && typeof observedCompletionTokens === 'number';\n const promptTokens = observedPromptTokens ?? 0;\n const completionTokens = observedCompletionTokens ?? 0;\n const totalTokens = usage?.totalTokens ?? (promptTokens + completionTokens);\n\n const details = usage?.inputTokenDetails;\n // AI SDK 7 `LanguageModelUsage.outputTokenDetails` (#1598): OpenAI, Google, xAI and Perplexity report the\n // reasoning split; Anthropic and Mistral do not. Only a NUMBER is kept, so an unreported split stays absent.\n const outputDetails = usage?.outputTokenDetails;\n const textTokens = typeof outputDetails?.textTokens === 'number' ? outputDetails.textTokens : undefined;\n const reasoningTokens = typeof outputDetails?.reasoningTokens === 'number' ? outputDetails.reasoningTokens : undefined;\n return {\n promptTokens,\n completionTokens,\n totalTokens,\n tokenUsageComplete,\n ...(details && typeof details === 'object'\n ? {\n inputTokenDetails: {\n ...(details.noCacheTokens === undefined ? {} : { noCacheTokens: details.noCacheTokens }),\n ...(details.cacheReadTokens === undefined ? {} : { cacheReadTokens: details.cacheReadTokens }),\n ...(details.cacheWriteTokens === undefined ? {} : { cacheWriteTokens: details.cacheWriteTokens }),\n },\n }\n : {}),\n ...(textTokens !== undefined || reasoningTokens !== undefined\n ? {\n outputTokenDetails: {\n ...(textTokens === undefined ? {} : { textTokens }),\n ...(reasoningTokens === undefined ? {} : { reasoningTokens }),\n },\n }\n : {}),\n };\n }\n\n /**\n * Re-throw a {@link AgentModelCallFailedError} unchanged, logging the provider's own failure first.\n *\n * Every operation's `catch` calls this before its generic wrapping. Wrapping would rebuild the error\n * as an INTERNAL backend error and drop the usage it carries, which the failure paths meter, and the\n * typed class, which is how the conversational runtime tells a provider failure apart in its log.\n */\n private rethrowModelCallFailure(error: unknown, operation: string): void {\n if (!(error instanceof AgentModelCallFailedError)) return;\n this.logger.error('The model call failed on the stream; the invocation fails with its reason', {\n operation,\n ...this.extractProviderErrorDetails(error.providerError),\n });\n throw error;\n }\n\n /**\n * Drain a BUFFERED stream's text, failing on a provider failure instead of returning what arrived.\n *\n * `textStream` is the obvious reader and the wrong one: it keeps text deltas and DROPS the `error`\n * part, so a mid-stream provider failure (an `overloaded_error` event after the response began)\n * came back as a successful, truncated or empty text (#2191). Reading `fullStream` keeps the part.\n *\n * A refusal before any output also rejects `result.usage`; on that path the error carries no usage,\n * because the provider ran nothing. A failure after output began still resolves it, with what was used.\n */\n private async drainBufferedStreamText(result: { fullStream: AsyncIterable<any>; usage: PromiseLike<unknown> }): Promise<string> {\n let text = '';\n let providerFailure: { error: unknown } | undefined;\n for await (const part of result.fullStream) {\n if (part?.type === 'text-delta') text += part.text;\n else if (part?.type === 'error') providerFailure ??= { error: part.error };\n }\n if (providerFailure) {\n let usage: AgentModelCallUsage | undefined;\n try {\n usage = this.extractUsage(await result.usage);\n } catch {\n usage = undefined;\n }\n // #2292 Phase 3: a withheld output is not a provider failure (see `streamTextToDeltas`).\n if (providerFailure.error instanceof AgentOutputWithheldError) throw providerFailure.error.withUsage(usage);\n throw new AgentModelCallFailedError(providerFailure.error, usage);\n }\n return text;\n }\n\n /**\n * The error a failed model call throws: every provider-call failure site in this service builds it here (#3204).\n *\n * A provider ACCOUNT's refusal (no credits left, a spend or usage limit, billing — `readModelProviderAccountRefusal`)\n * is the environment's condition, never an internal fault: it answers `EXTERNAL_SERVICE` (502) with the stable\n * reference `MODEL_PROVIDER_ACCOUNT_REFUSED`. Its context names the reason, the provider and the provider's own message\n * for the log; the wire carries the reason only (least disclosure: the requester may be an application's end user),\n * and the operator reads the rest in the log and on the companion's creation loop. Every other failure stays\n * `INTERNAL`, exactly as before. Measured on run 42073501412: an OpenAI\n * account out of credits answered 429 on every structured generation and the companion reported each as a critical\n * INTERNAL 500, so the drive stopped `loop-refused` and the run read `stalled`.\n */\n private buildModelCallFailure(\n error: unknown,\n errorDetails: Record<string, unknown>,\n context: Record<string, unknown>,\n providerRef?: string,\n ): WildoError_Backend {\n const refusal = readModelProviderAccountRefusal(error, providerRef);\n if (refusal !== undefined) {\n return this.errorBuilder.buildError(ErrorType.EXTERNAL_SERVICE, undefined, {\n customMessageReference: ErrorCustomMessageReference.MODEL_PROVIDER_ACCOUNT_REFUSED,\n context: { ...context, ...errorDetails, ...refusal, message: describeModelProviderAccountRefusal(refusal) },\n });\n }\n return this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: { ...context, ...errorDetails },\n });\n }\n\n /**\n * What a failed model call records of the vendor's answer (#2368): see `describeModelCallError`. The vendor's body,\n * response headers and `data` are never recorded by value: a refusal can quote the prompt content it refused, and these\n * details are logged and spread into the thrown error's context, where erasure does not reach. What is kept is named\n * field by field there: the status, the vendor's type and code, its redacted message, token counts, operational headers.\n */\n private extractProviderErrorDetails(error: unknown): Record<string, unknown> {\n return describeModelCallError(error);\n }\n\n // ================================\n // Agent Validation\n // ================================\n\n /**\n * The organizations a BUFFERED call works for (`invokeAgent`, a structured call on another agent's model): the scope its\n * agent's suspensions (#2843) and its content guardrails (#2292 R8) are both read for. Built once, at the entry point,\n * and handed to the execution, so an organization that suspended an agent, or tightened it, is asked about the same\n * calls.\n *\n * Four sources, each engine-set, never a caller's or a model's:\n *\n * 1. the organization the call names (an `invokeAgent` initiator's, a structured call's explicit attribution);\n * 2. the work frame's tenant, merged field by field with the call's explicit attribution as its cost record is\n * (`resolveModelCallAttribution`);\n * 3. the tenant of the case that attribution names, read from the case row by the provider-call recorder\n * (`caseTenantOf`), as the tenant a call's cost is recorded against is. An actor run carries no tenant of its own:\n * its frame names its run and its case (`actorRunWorkAttribution`), so this is how an application's own actor run on\n * a case is asked;\n * 4. the organization of the run's requester, from the spend frame. A flow run's frame names no tenant, and its\n * `agent.call` step names none, so without this a flow step was asked only for the application's suspensions and\n * ran with the agent's declared guardrails, whatever its organization had decided (#2843 review H1). The flow\n * service opens that frame only for a requester acting in the run's organization (`inFlowRunSpendFrame`), and a\n * conversational turn opens it for its authenticated principal, so it names the organization the work is done in.\n *\n * The call is made for the first one present, in the order the cost record decides its tenant (the case's row, then the\n * named organization, then the frame's), then the requester's. Every other one present is applied as well rather than\n * outranked: a suspension only refuses and a policy only tightens, so one more organization's can never let through\n * what one of them stops. Where they disagree (a case row of another tenant than its frame says) the call is refused or\n * tightened by both, which is the fail-closed reading. Rejected: picking one winner, which would let the loser's\n * suspension silently not apply.\n *\n * A case row whose read FAILED is not \"no tenant\": that organization may have suspended the agent, so the scope carries\n * `unreadable` and the call is refused, as an unreadable suspension or policy refuses it. A row that was not found (a\n * create still in its transaction, a deleted row), or has no tenant (an application-scoped work unit), gives none.\n *\n * A call none of the four names (a deliberation the dev companion runs, an application's own call outside any request,\n * turn, flow or case) works for no organization: only the application's suspensions refuse it, and no organization's\n * policy tightens it.\n *\n * A buffered call carries no role entries, so the representing organization is the one its attribution names (a\n * machine acting for a firm), when it represents one of the organizations above.\n */\n private async buildCallOrganizationScope(\n namedOrganizationId: string | undefined,\n explicitAttribution?: ModelCallAttributionInput,\n ): Promise<ModelCallOrganizationScope> {\n const attribution = resolveModelCallAttribution(explicitAttribution, getCurrentWorkAttributionFrame()).attribution;\n const requesterOrganizationId = getCurrentModelSpendFrame()?.auth?.initiatorIds?.organizationId;\n const caseTenant = attribution.caseRef && this.providerCallRecorder ? await this.providerCallRecorder.caseTenantOf(attribution.caseRef) : undefined;\n const caseOrganizationId = caseTenant?.kind === CaseTenantReadingKind.TENANT ? caseTenant.organizationId : undefined;\n const present = [caseOrganizationId, namedOrganizationId, attribution.organizationId, requesterOrganizationId]\n .filter((id): id is string => typeof id === 'string' && id.length > 0);\n const organizationIds = [...new Set(present)];\n const organizationId = organizationIds[0];\n const via = attribution.viaOrganization;\n return {\n ...(organizationId ? { organizationId } : {}),\n alsoWorkedForOrganizationIds: organizationIds.slice(1),\n representingOrganizationIds: via && organizationIds.includes(via.organizationId) ? [via.representingOrganizationId] : [],\n ...(caseTenant?.kind === CaseTenantReadingKind.UNREADABLE\n ? { unreadable: `the organization of case '${attribution.caseRef!.resourceType}/${attribution.caseRef!.resourceId}' could not be read: ${caseTenant.detail}` }\n : {}),\n };\n }\n\n /**\n * The organizations a STREAMING call works for (a conversational turn): the turn's organization (its tool context's, else\n * its initiator's), derived further exactly as a buffered call's is (`buildCallOrganizationScope`: the case's tenant, the\n * work frame's, the turn principal's), plus each organization the principal represents in the turn's organization through\n * its role entries (#2618). One scope for the turn's suspensions and its guardrails, so the two cannot disagree about\n * which organizations a turn acts for.\n */\n private async buildStreamingCallOrganizationScope(\n toolContext: FunctionToolExecutionContext | undefined,\n initiatorOrganizationId: string | undefined,\n explicitAttribution?: ModelCallAttributionInput,\n ): Promise<ModelCallOrganizationScope> {\n const turnOrganizationId = toolContext?.organizationId ?? initiatorOrganizationId;\n const derived = await this.buildCallOrganizationScope(turnOrganizationId, explicitAttribution);\n const throughRoles = resolveRepresentingOrganizationIdsInOrganization(toolContext?.auth?.initiatorRoles, turnOrganizationId);\n return { ...derived, representingOrganizationIds: [...new Set([...(derived.representingOrganizationIds ?? []), ...throughRoles])] };\n }\n\n /**\n * The admission every model call passes, at each of this service's three entry points (`invokeAgent`,\n * `invokeAgentStreaming`, `generateStructuredOnAgentModel`), before anything is sent to a model. Every door reaches one\n * of them: an A2A turn, an autonomous turn, a Slack/Teams message, an in-app turn, a flow's `agent.call` step, the form\n * composer, and an application's own call.\n *\n * 1. The agent's declared `status` must be ACTIVE (`AGENT_NOT_ACTIVE`): the deploy-time switch.\n * 2. #2843: the agent must not be suspended, for the whole application or for an organization the call acts for (its\n * own, and each representing organization). A suspended agent is refused with `AGENT_SUSPENDED` (CONFLICT: the\n * caller may call it, the agent's current state forbids it); a suspension that cannot be read refuses the call too,\n * as `INFRASTRUCTURE` (retryable). Each refusal is recorded (`SUSPENDED_AGENT_CALL_REFUSED`), naming the door of the\n * conversation or flow run the call was made in.\n *\n * Two decisions, taken by the practice a kill switch follows (a flag or a disabled credential takes effect on the next\n * request; nothing reaches into a request already being served):\n *\n * - **A call already running is not stopped.** A model call in another process cannot be reached from here, and one in\n * this process ends after its bounded tool steps (`MAX_TOOL_STEPS`). What a suspension guarantees is that the NEXT call\n * is refused, including a turn's resume after an approval, which is a new call. Stopping a running turn stays its\n * owner's (`cancelTurn`).\n * - **Queued autonomous occurrences are not skipped ahead of time.** Each one that comes due opens its turn, and that\n * turn's first model call is refused here: the turn ends FAILED with `AGENT_SUSPENDED`, nothing reaches a model, and\n * the refusal is recorded with the door `autonomous`. No queue or schedule state is changed, so resuming the agent\n * needs nothing else: the next occurrence runs.\n *\n * assurance-control: WILDO.AI.HUMAN_OVERSIGHT, WILDO.SECURITY.FAIL_CLOSED — an agent an administrator suspended is refused before its model is called, at every door, and an unreadable suspension refuses the call.\n */\n private async validateAgentStatus(agent: FlowsActors_Agent, scope: ModelCallOrganizationScope): Promise<void> {\n if (agent.status !== FlowsActors_Agent_Status.ACTIVE) {\n throw this.errorBuilder.buildError( ErrorType.VALIDATION, undefined,\n { customMessageReference: ErrorCustomMessageReference.AGENT_NOT_ACTIVE,\n context: { agentRef: agent.ref, status: agent.status }}); // diagnostic (log-only)\n }\n // Only in a process that boots an application (`enforceAgentSuspensions`): the dev companion and the platform's\n // services answer to no application's suspensions.\n if (!this.resolveSuspendingApplicationId) return;\n const lookup: AgentSuspensionLookup = scope.unreadable !== undefined\n ? { kind: AgentSuspensionLookupKind.UNREADABLE, detail: scope.unreadable }\n : await this.readSuspensionOf(agent.ref, organizationIdsOfCallScope(scope));\n if (lookup.kind === AgentSuspensionLookupKind.ADMITTED) return;\n const door = getCurrentModelSpendFrame()?.door;\n this.recordSuspendedAgentCallRefusal(agent.ref, lookup, scope.organizationId);\n if (lookup.kind === AgentSuspensionLookupKind.UNREADABLE) {\n this.logger.error('An agent\\'s suspensions could not be read; the call is refused rather than run', { agentRef: agent.ref, door, detail: lookup.detail });\n throw this.errorBuilder.buildError(ErrorType.INFRASTRUCTURE, undefined, {\n customMessageReference: ErrorCustomMessageReference.INFRASTRUCTURE,\n context: {\n agentRef: agent.ref,\n ...(door ? { door } : {}),\n // Read back by `agentSuspensionRefusalOf`.\n agentSuspensionRefusalReason: AgentSuspensionRefusalReason.SUSPENSION_UNREADABLE,\n message: `Whether agent '${agent.ref}' is suspended could not be read, so its model was not called.`,\n },\n });\n }\n this.logger.warn('A suspended agent was called; the call is refused before its model runs', {\n agentRef: agent.ref, door, suspensionScope: lookup.scope, ...(lookup.organizationId ? { suspendedForOrganizationId: lookup.organizationId } : {}),\n });\n throw this.errorBuilder.buildError(ErrorType.CONFLICT, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_SUSPENDED,\n context: {\n agentRef: agent.ref,\n code: ErrorCustomMessageReference.AGENT_SUSPENDED,\n suspensionScope: lookup.scope,\n ...(door ? { door } : {}),\n agentSuspensionRefusalReason: AgentSuspensionRefusalReason.SUSPENDED,\n message: lookup.scope === AgentSuspensionScope.APPLICATION\n ? `Agent '${agent.ref}' is suspended for the whole application, so its model was not called.`\n : `Agent '${agent.ref}' is suspended for this organization, so its model was not called.`,\n },\n });\n }\n\n /**\n * #3313: what {@link validateAgentStatus} would answer for a call of `agentRef` for `organizationIds`, asked of a call\n * that has not been made, so a person's approval can be refused while its decision still stands. It only reads: no call\n * was refused, so it writes no `SUSPENDED_AGENT_CALL_REFUSED` row and logs nothing. The call itself is still checked when\n * it is made, and may be for more organizations (a case's tenant): this is the same reading, not a replacement for it.\n */\n public async readCallAdmission(agentRef: string, organizationIds: readonly string[]): Promise<AgentCallAdmission> {\n if (this.flowsActorsRegistry.getAgent(agentRef)?.status !== FlowsActors_Agent_Status.ACTIVE) return AgentCallAdmission.AGENT_NOT_ACTIVE;\n if (!this.resolveSuspendingApplicationId) return AgentCallAdmission.ADMITTED;\n const lookup = await this.readSuspensionOf(agentRef, organizationIds);\n if (lookup.kind === AgentSuspensionLookupKind.SUSPENDED) return AgentCallAdmission.SUSPENDED;\n return lookup.kind === AgentSuspensionLookupKind.UNREADABLE ? AgentCallAdmission.UNREADABLE : AgentCallAdmission.ADMITTED;\n }\n\n /**\n * #2843: how this process names the application whose suspensions it answers to, set by `enforceAgentSuspensions` at\n * the application's boot. Unset in a process that boots no application (the dev companion, a platform service): there\n * the admission reads no suspension.\n */\n private resolveSuspendingApplicationId: (() => Promise<string>) | undefined;\n\n /**\n * #2843: start refusing suspended agents. Called once by the application's startup (`StartApplicationBackendService`),\n * before it serves anything, never by a process that boots no application. The application's id is resolved per call\n * (the identity service memoizes it), so a call checked before the identity is primed is still checked.\n */\n public enforceAgentSuspensions(resolveApplicationId: () => Promise<string>): void {\n this.resolveSuspendingApplicationId = resolveApplicationId;\n }\n\n /** #2843: the call's suspensions; an application id that cannot be resolved refuses it like an unreadable record. */\n private async readSuspensionOf(agentRef: string, organizationIds: readonly string[]): Promise<AgentSuspensionLookup> {\n let applicationId: string;\n try {\n applicationId = await this.resolveSuspendingApplicationId!();\n } catch (error) {\n return { kind: AgentSuspensionLookupKind.UNREADABLE, detail: `the application whose suspensions apply could not be resolved: ${describeCaughtError(error)}` };\n }\n return readAgentSuspension(this.repositoriesRegistry, agentRef, { applicationId, organizationIds });\n }\n\n /**\n * #2843: one `SUSPENDED_AGENT_CALL_REFUSED` row per refused call, as the principal of the conversation or flow run it was\n * made in (its spend frame), else for the organization it was made for. Fire-and-forget: the refusal stands whether or\n * not it could be recorded, and a failed write is logged.\n */\n private recordSuspendedAgentCallRefusal(agentRef: string, lookup: Exclude<AgentSuspensionLookup, { kind: AgentSuspensionLookupKind.ADMITTED }>, callOrganizationId: string | undefined): void {\n if (typeof this.auditLogs?.logSuspendedAgentCallRefused !== 'function') return;\n const frame = getCurrentModelSpendFrame();\n const suspended = lookup.kind === AgentSuspensionLookupKind.SUSPENDED ? lookup : undefined;\n void this.auditLogs.logSuspendedAgentCallRefused({\n agentRef,\n reason: suspended ? AgentSuspensionRefusalReason.SUSPENDED : AgentSuspensionRefusalReason.SUSPENSION_UNREADABLE,\n ...(suspended ? { suspensionScope: suspended.scope } : {}),\n ...(suspended?.organizationId ? { suspendedForOrganizationId: suspended.organizationId } : {}),\n ...(frame ? { door: frame.door } : {}),\n }, frame?.auth, callOrganizationId).catch((error: unknown) => {\n this.logger.warn('A refused call to a suspended agent could not be recorded (non-fatal)', { agentRef, ...projectCaughtErrorLogFields(error) });\n });\n }\n\n /**\n * Validate that everything an agent DECLARES resolves — function tools in the registry and MCP\n * servers in the application's declaration — and that any explicitly-required function refs are\n * declared by the agent. Returns false on any gap rather than throwing, so callers can decide how\n * to degrade.\n *\n * ## Why `mcpRefs` are checked here as well (#491)\n *\n * `FlowsActorsRegistryService.initialize` already REFUSES an agent whose `mcpRefs` name no\n * declared server, so on the ordinary path this is redundant — and it is kept anyway, because\n * `registerAgent` is PUBLIC and the refusal is not on it. An agent registered after initialization\n * bypasses that gate entirely today, so this is the only site that would notice.\n *\n * The refusal is deliberately NOT moved onto `registerAgent`: addon load order is not guaranteed,\n * and a per-registration check would refuse a coherent application for the order its addons\n * happened to load in. Two sites answering the same question at two different moments is the\n * correct shape here — one fails the boot, one degrades an invocation.\n */\n public validateAgentCapabilities(agentRef: string, requiredCapabilities: string[]): boolean {\n const agent = this.flowsActorsRegistry.getAgentOrThrow(agentRef);\n const declaredFunctionRefs = agent.capabilities?.tools?.functionRefs ?? [];\n const declaredMcpRefs = agent.capabilities?.tools?.mcpRefs ?? [];\n\n // Every tool the agent declares must resolve in the registry.\n const unresolved = declaredFunctionRefs.filter((ref) => !this.flowsActorsRegistry.hasFunctionTool(ref));\n // And every MCP server it names must be one the application declared.\n const unresolvedMcpRefs = declaredMcpRefs.filter((ref) => !this.flowsActorsRegistry.hasMcpServer(ref));\n // Every explicitly-required capability must be declared by the agent.\n const missingRequired = requiredCapabilities.filter((ref) => !declaredFunctionRefs.includes(ref));\n\n const isValid = unresolved.length === 0 && unresolvedMcpRefs.length === 0 && missingRequired.length === 0;\n this.logDebug('Agent capabilities validated', { agentRef, requiredCapabilities, unresolved, unresolvedMcpRefs, missingRequired, isValid });\n return isValid;\n }\n\n // ================================\n // Agent Discovery\n // ================================\n\n public getAvailableAgents(): FlowsActors_Agent[] {\n const registry = this.flowsActorsRegistry.getRegistry();\n return Object.values(registry.agents).filter((agent: FlowsActors_Agent) => agent.status === FlowsActors_Agent_Status.ACTIVE);\n }\n\n public getAgentsBySkillType(skillType: string): FlowsActors_Agent[] {\n return this.getAvailableAgents().filter(agent => agent.promptSpec.skillType === skillType);\n }\n\n /**\n * Whether the operator is signed in to a provider's coding agent, read from the agent's own status\n * command (no model call) — the same check that refuses a dispatch to a signed-out agent (#1637).\n * `null` when the provider declares no coding agent or no way to read its login.\n *\n * Read in the AGENT's environment — the base set plus the provider's declared variables — never this\n * process's: `claude auth status` reports `loggedIn: true` from an `ANTHROPIC_API_KEY` the dispatched\n * agent never receives, so reading with the full environment showed \"signed in\" for an agent every\n * dispatch refused. An application's execution profile may widen the set further; the provider's\n * declaration is the part every dispatch shares. Public so a host (the companion) can show the state\n * before anything is dispatched; asynchronous so a slow status command never stalls it.\n */\n public async readCodingAgentHostLogin(providerRef: string): Promise<{ providerRef: string; state: CodingAgentHostLoginState; detail: string; remedy: string | null } | null> {\n const profile = this.externalProvidersRegistry.getAgentClientProtocolProfile(providerRef);\n if (!profile?.hostLogin) return null;\n const environment = buildAgentSubprocessEnvironment(profile.inheritedEnvironmentVariables ?? []);\n return { providerRef, ...(await probeCodingAgentHostLoginAsync(profile.hostLogin, { environment })) };\n }\n\n /**\n * What a coding agent of this provider and execution profile is STARTED with, for a host that must reason about the\n * agent's own network route (#3262): its environment (the dispatch's own composition, without the injected secret,\n * which says nothing about the route) and its resolved ACP session metadata (where, for Claude Code, the\n * host-configuration posture becomes the `settingSources` whose settings files add to that environment).\n *\n * `null` when the provider declares no ACP profile or the profile is unknown. Throws what the dispatch would throw on\n * the same configuration (a declared secret in the inherited list, conflicting isolation metadata).\n */\n public readCodingAgentLaunchConfiguration(providerRef: string, executionProfileRef: string): { environment: NodeJS.ProcessEnv; sessionMeta: Record<string, unknown> | undefined } | null {\n const acpProfile = this.externalProvidersRegistry.getAgentClientProtocolProfile(providerRef);\n const acpExecutionProfile = this.externalProvidersRegistry.getAgentClientProtocolExecutionProfile(providerRef, executionProfileRef);\n if (!acpProfile || !acpExecutionProfile) return null;\n const execution: Extract<ResolvedAgentExecution, { transport: 'acp' }> = {\n transport: 'acp',\n providerRef,\n operationKey: CodingAgent_OperationKey.RUN_CODING_TASK,\n executionProfileRef,\n acpProfile,\n acpExecutionProfile,\n };\n return { environment: this.composeAgentClientProtocolInheritedEnvironment(execution), sessionMeta: this.resolveAgentClientProtocolSessionMeta(execution) };\n }\n\n public getAgent(agentRef: string): FlowsActors_Agent | undefined {\n return this.flowsActorsRegistry.getAgent(agentRef);\n }\n\n public getAgentOrThrow(agentRef: string): FlowsActors_Agent {\n return this.flowsActorsRegistry.getAgentOrThrow(agentRef);\n }\n\n // ================================\n // Debug Methods\n // ================================\n\n public getDebugInfo(): { totalAgents: number; activeAgents: number; agentsByProvider: Record<string, number>; agentsBySkillType: Record<string, number> } {\n const allAgents = Object.values(this.flowsActorsRegistry.getRegistry().agents) as FlowsActors_Agent[];\n\n const activeAgents = allAgents.filter(a => a.status === FlowsActors_Agent_Status.ACTIVE);\n\n const agentsByProvider: Record<string, number> = {};\n const agentsBySkillType: Record<string, number> = {};\n\n allAgents.forEach(agent => {\n const provider = agent.config.providerRef;\n agentsByProvider[provider] = (agentsByProvider[provider] || 0) + 1;\n\n const skillType = agent.promptSpec.skillType;\n agentsBySkillType[skillType] = (agentsBySkillType[skillType] || 0) + 1;\n });\n\n return { totalAgents: allAgents.length, activeAgents: activeAgents.length, agentsByProvider, agentsBySkillType, };\n }\n}\n\n/**\n * #2292: a tool's result as a guarded agent's model may read it, by what the tool declares its result carries. A result\n * the tool does not classify is withheld whole: it could carry anything.\n */\nfunction treatToolOutputForModel(output: unknown, declaration: FunctionTool['personalDataOutput'], guard: PersonalDataGuard): unknown {\n switch (declaration?.kind) {\n case FunctionToolPersonalDataOutputKind.RECORDS_OF_RESOURCE:\n return treatRecordsResult(output, guard, declaration.resourceType);\n case FunctionToolPersonalDataOutputKind.TREATED_BY_TOOL:\n return declaration.treat(output, guard);\n case FunctionToolPersonalDataOutputKind.NOT_FROM_RECORDS:\n return output;\n default:\n return guard.withholdWhole();\n }\n}\n\n/**\n * #2292 R8: whether an MCP tool's result is the error result `resolveAgentMcpTools` returns (`{ error, detail }`, the\n * error an outcome kind). A server answer that happens to have that shape is read as one too, and the model is then sent\n * only an outcome kind: never anything the server wrote.\n */\nfunction isMcpErrorResult(output: unknown): output is { error: McpOutcomeKind; detail?: unknown } {\n if (typeof output !== 'object' || output === null || Array.isArray(output)) return false;\n const keys = Object.keys(output);\n return keys.every((key) => key === 'error' || key === 'detail')\n && (Object.values(McpOutcomeKind) as unknown[]).includes((output as { error?: unknown }).error);\n}\n\n/**\n * #2761: the refusals a function tool's call can meet that only the PERSON can resolve, and only in the application. Each\n * is returned to the model as a typed result (`{ error, detail }`) carrying the engine's sentence, never re-thrown: a thrown\n * tool error reaches the model as an SDK tool-error result it narrates in its own words, so the person would be told\n * whatever the model made of an `AUTHORIZATION / STEP_UP_REQUIRED` string. The refusal itself stands; the model cannot\n * satisfy it and is told so.\n *\n * The case that motivated it: a chat turn (Slack, Teams) acts with an authority rebuilt from the member's chat link, which\n * carries no `lastAuthenticatedAt`, so under a user type's `authPolicy.stepUpAuth` every write its tools attempt is\n * refused. The same holds for an in-application turn whose authentication has aged past the policy: the tool runs on the\n * server, so no client is there to answer the step-up challenge.\n */\nexport enum AgentFunctionToolRefusalKind {\n /** The operation needs a recent authentication (the step-up gate, `ErrorCustomMessageReference.STEP_UP_REQUIRED`). */\n STEP_UP_REQUIRED = 'STEP_UP_REQUIRED',\n /**\n * An organization this request reaches through a relationship requires a second factor of its own\n * (`ErrorCustomMessageReference.STEP_UP_REQUIRED_BY_GRANTING_ORGANIZATION`).\n */\n GRANTING_ORGANIZATION_SECOND_FACTOR_REQUIRED = 'GRANTING_ORGANIZATION_SECOND_FACTOR_REQUIRED',\n}\n\n/**\n * The sentence the model is given for each refusal, for the model to relay. Written for the person, and true on every\n * surface a turn runs from: a chat member must open the application, and an in-application user must confirm there too.\n */\nconst AGENT_FUNCTION_TOOL_REFUSAL_DETAIL: Record<AgentFunctionToolRefusalKind, string> = {\n [AgentFunctionToolRefusalKind.STEP_UP_REQUIRED]:\n 'This action needs the person to confirm it is them first, and that cannot be done from here. Tell them to open the application, confirm their identity there, then ask again. Do not retry the call.',\n [AgentFunctionToolRefusalKind.GRANTING_ORGANIZATION_SECOND_FACTOR_REQUIRED]:\n 'An organization this action reaches requires the person to sign in with a second factor, and that cannot be done from here. Tell them to open the application, complete the second factor there, then ask again. Do not retry the call.',\n};\n\n/** #2761: what a function tool returns to the model for a refusal only the person can resolve. */\nexport interface AgentFunctionToolRefusalResult {\n readonly error: AgentFunctionToolRefusalKind;\n readonly detail: string;\n}\n\n/** #2761: the typed result for an error that is such a refusal, or `undefined` for any other error (which is re-thrown). */\nexport function functionToolRefusalOf(error: unknown): AgentFunctionToolRefusalResult | undefined {\n if (!isWildoBackendError(error) || error.type !== ErrorType.AUTHORIZATION) return undefined;\n const kind = error.customMessageReference === ErrorCustomMessageReference.STEP_UP_REQUIRED\n ? AgentFunctionToolRefusalKind.STEP_UP_REQUIRED\n : error.customMessageReference === ErrorCustomMessageReference.STEP_UP_REQUIRED_BY_GRANTING_ORGANIZATION\n ? AgentFunctionToolRefusalKind.GRANTING_ORGANIZATION_SECOND_FACTOR_REQUIRED\n : undefined;\n return kind === undefined ? undefined : { error: kind, detail: AGENT_FUNCTION_TOOL_REFUSAL_DETAIL[kind] };\n}\n\n/** #2761: whether a function tool's output is a refusal result the engine wrote (exactly `{ error, detail }`, both known). */\nfunction isFunctionToolRefusalResult(output: unknown): output is AgentFunctionToolRefusalResult {\n if (typeof output !== 'object' || output === null || Array.isArray(output)) return false;\n const keys = Object.keys(output);\n if (keys.length !== 2 || !keys.includes('error') || !keys.includes('detail')) return false;\n const { error, detail } = output as { error?: unknown; detail?: unknown };\n return (Object.values(AgentFunctionToolRefusalKind) as unknown[]).includes(error)\n && detail === AGENT_FUNCTION_TOOL_REFUSAL_DETAIL[error as AgentFunctionToolRefusalKind];\n}\n\n/** #2292: what a guarded agent's model is told about a failed tool call — its kind, never its text. */\nfunction guardedToolError(error: unknown): Error {\n const kind = isWildoBackendError(error) ? [error.type, error.customMessageReference].filter(Boolean).join(' / ') : 'error';\n return new Error(`The tool call failed (${kind}). Its details are not shown to you, because they can quote record values this agent may not see.`);\n}\n\n/**\n * The usage a failed model call carries, whichever failure it is: a provider failure ({@link AgentModelCallFailedError})\n * or an output its moderation withheld ({@link AgentOutputWithheldError}, #2292). One reader for every failure path that\n * meters — the failure trace, the conversational runtime's usage report — so a failure class cannot silently stop being\n * metered.\n */\nexport function modelCallUsageOfFailure(error: unknown): AgentModelCallUsage | undefined {\n if (error instanceof AgentModelCallFailedError || error instanceof AgentOutputWithheldError) return error.usage;\n return undefined;\n}\n\n/** #3313: what the admission of a model call would answer, read without making the call (`readCallAdmission`). */\nexport enum AgentCallAdmission {\n /** The call would be admitted. */\n ADMITTED = 'admitted',\n /** The agent's declared status is not active. */\n AGENT_NOT_ACTIVE = 'agent_not_active',\n /** An administrator suspended the agent for the application or an organization the call acts for. */\n SUSPENDED = 'suspended',\n /** A suspension record could not be read, and the call would be refused for it. */\n UNREADABLE = 'unreadable',\n}\n\n/**\n * #2843: why a call was refused for its agent's suspension, read back from the error `validateAgentStatus` threw, or\n * `undefined` for any other error. A caller (a conversational turn) tells the person \"this assistant is suspended\"\n * instead of \"it failed\".\n */\nexport function agentSuspensionRefusalOf(error: unknown): { reason: AgentSuspensionRefusalReason; scope?: AgentSuspensionScope } | undefined {\n if (!isWildoBackendError(error)) return undefined;\n const context = error.context as Record<string, unknown> | undefined;\n const reason = context?.agentSuspensionRefusalReason;\n if (!Object.values(AgentSuspensionRefusalReason).includes(reason as AgentSuspensionRefusalReason)) return undefined;\n const scope = context?.suspensionScope;\n return {\n reason: reason as AgentSuspensionRefusalReason,\n ...(Object.values(AgentSuspensionScope).includes(scope as AgentSuspensionScope) ? { scope: scope as AgentSuspensionScope } : {}),\n };\n}\n\n/**\n * #2935: the reason a model call was refused by its organization's model allowance before it ran\n * (`AgentsBackendService` refuses a flow's call this way), or `undefined` for any other error, a provider's failure\n * included. What lets a caller report a spent allowance as such rather than as a broken step.\n */\nexport function modelSpendRefusalOf(error: unknown): { reason: A2ATokenBudgetDenialReason } | undefined {\n if (!isWildoBackendError(error)) return undefined;\n const reason = (error.context as Record<string, unknown> | undefined)?.modelSpendRefusalReason;\n return Object.values(A2ATokenBudgetDenialReason).includes(reason as A2ATokenBudgetDenialReason)\n ? { reason: reason as A2ATokenBudgetDenialReason }\n : undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agents.backend.service.js","sourceRoot":"","sources":["../../../../src/flows-actors/services/agents.backend.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACzD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAkC,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5F,OAAO,UAAU,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AACjE,OAAO,EAAE,cAAc,EAAmB,MAAM,uEAAuE,CAAC;AAExH,OAAO,EAAE,qBAAqB,EAA2C,MAAM,iFAAiF,CAAC;AACjK,OAAO,EAAE,4BAA4B,EAAE,MAAM,2EAA2E,CAAC;AACzH,OAAO,EAAE,kCAAkC,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,6EAA6E,CAAC;AAE3M,OAAO,EAAE,wBAAwB,EAAE,MAAM,kFAAkF,CAAC;AAE5H,OAA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,CAAC,QAAQ,CAAC,MAAoC,CAAC;QAC7F,CAAC,CAAC,EAAE,MAAM,EAAE,MAAoC,EAAE;QAClD,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC","sourcesContent":["import 'reflect-metadata';\nimport { mkdirSync } from 'node:fs';\nimport { isDeepStrictEqual } from 'node:util';\nimport { AsyncResource } from 'node:async_hooks';\nimport { injectable, inject, optional } from 'inversify';\nimport { z } from 'zod';\nimport { ExecutionContext_ExecutionType, jsonParsingSchemaOf } from '@wildo-ai/saas-models';\nimport Bottleneck from 'bottleneck';\nimport { mcpServerDestinationHost } from '@wildo-ai/saas-models';\nimport { McpOutcomeKind, type McpSession } from '~wildo-backend-lib/flows-actors/models/mcp-client.backend.definitions';\nimport type { AuditLogsBackendService } from '~wildo-backend-lib/compliance/audit-trails/services/audit-logs.backend.service';\nimport { CaseTenantReadingKind, type ProviderCallRecorderBackendService } from '~wildo-backend-lib/flows-actors/services/provider-call-recorder.backend.service';\nimport { deriveToolApprovalSigningKey } from '~wildo-backend-lib/flows-actors/utils/tool-approval-signing.backend.utils';\nimport { CONVERSATION_DELIVERY_OF_OPERATION, ConversationDelivery, invocationConversationOf, invocationInstructionsOf } from '~wildo-backend-lib/flows-actors/utils/invocation-instructions.backend.utils';\nimport type { McpClientBackendService } from '~wildo-backend-lib/flows-actors/services/mcp-client.backend.service';\nimport { McpCredentialOutcomeKind } from '~wildo-backend-lib/flows-actors/services/mcp-credential-resolver.backend.service';\nimport type { McpCredentialResolverBackendService } from '~wildo-backend-lib/flows-actors/services/mcp-credential-resolver.backend.service';\nimport { SAAS_SERVICE_TYPES } from '~wildo-backend-lib/inject/models/service-types';\nimport { LoggerService } from '~wildo-backend-lib/monitoring/logger/services/logger.service';\nimport { ErrorBuilderBackendService } from '~wildo-backend-lib/errors/services/error-builder.backend.service';\nimport { describeCaughtError, projectCaughtErrorLogFields } from '~wildo-backend-lib/errors/utils/error-log-level-classification.backend.utils';\nimport { IMAGE_MODEL_PROVIDER_ACCOUNT_REFUSAL_IS_FINAL, MODEL_PROVIDER_ACCOUNT_REFUSAL_IS_FINAL, describeModelCallError, readModelProviderAccountRefusal } from '~wildo-backend-lib/flows-actors/utils/model-call-error-description.backend.utils';\nimport { FlowsActorsRegistryService } from './flows-actors-registry.service';\nimport { ExternalProvidersRegistryBackendService, RuntimeAgentClientProtocolProfile } from '~wildo-backend-lib/external-providers/services/external-providers-registry.backend.service';\nimport { BackendProviderRegistryBackendService } from '~wildo-backend-lib/external-providers/services/backend-provider-registry.backend.service';\nimport { resolveProviderContractBaseUrl, type ProviderContractEndpointFields } from '~wildo-backend-lib/external-providers/services/provider-http-access.backend';\nimport { ProviderClientCredentialsTokenError, ProviderClientCredentialsTokenFailure } from '~wildo-backend-lib/external-providers/services/provider-client-credentials-token.backend';\nimport { resolveProviderAiSdkCredential } from '~wildo-backend-lib/external-providers/services/provider-service-account-token.backend';\nimport { PromptCompilerBackendService } from './prompt-compiler.backend.service';\nimport {\n FlowsActors_Agent,\n type FlowsActors_OutputModerationPolicy,\n RedactionType,\n ResourcePrimaryScope,\n FlowsActors_Agent_Status,\n FlowsActors_Agent_Invocation,\n type FlowsActors_Agent_LLMConfiguration,\n type FlowsActors_Agent_ImageConfiguration,\n isImageAgentConfiguration,\n isCodingAgentConfiguration,\n EngineCapability,\n type FlowsActors_Agent_ModelAlternative,\n PromptIR_ContextItem,\n PromptIR_TrustLevel,\n PromptIR_ContextSourceKind,\n ErrorType,\n ErrorCustomMessageReference,\n isWildoBackendError,\n PersonalDataCategory,\n sortPersonalDataCategories,\n AgentCallOutcome,\n AgentTraceabilityLevel,\n type AgentCallTrace,\n type AgentCallTraceError,\n type AgentOperationObservation,\n type AgentTraceabilityPolicy,\n type AgentTraceContext,\n type AgentCallTraceSink,\n StructuredGenerationExecutionMode,\n FlowsActors_Agent_Skill_Type,\n isLLMAgentConfiguration,\n FlowsActors_SourceKind,\n FlowsActors_ToolCallPhase,\n type FlowsActors_Source,\n FlowsActors_ScreenedContentSource,\n effectiveAgentContentGuardrails,\n resolveRepresentingOrganizationIdsInOrganization,\n AgentSuspensionRefusalReason,\n AgentSuspensionScope,\n A2A_TOKEN_BUDGET_FEATURE_ID,\n A2ATokenBudgetDenialReason,\n ModelSpendDoor,\n modelSpendDoorPayerFallsBackToAttributedWork,\n} from '@wildo-ai/saas-models';\nimport { APPLICATION_ENV_UNDECLARED_MESSAGE, readDeclaredApplicationEnvironment } from '~wildo-backend-lib/config/models/app-env-config.backend.schemas';\nimport {\n APPLICATION_ENVIRONMENT,\n LLMProvider_ExecutionArtifactMetadata,\n LLMProvider_ExecutionTransportMetadata,\n LLMProvider_ExecutionTransportKind,\n LLMProvider_ExecutionTransportMetadataSchema,\n LLMProvider_UsageSchema,\n LLMProvider_StructuredGenerationFailureKind,\n LLMProvider_StructuredGenerationFailureSchema,\n type LLMProvider_StructuredGenerationFailure,\n ExternalProvider_ExchangeProtocol_Kind,\n ExternalProvider_RateLimitConfigurationSchema,\n LLMProvider_Configuration,\n LLMProvider_OperationKey,\n LLMProvider_GenerateStructuredInputSchema,\n LLMProvider_GenerateStructuredOutputSchema,\n LLMProvider_MessageRole,\n type LLMProvider_ImageContent,\n type ImageProvider_OperationKey,\n CodingAgent_OperationKey,\n AgentClientProtocol_AuthMode,\n AgentClientProtocol_PermissionCeiling,\n AgentClientProtocol_WorkingDirectoryPolicy,\n AgentClientProtocol_PermissionEscalationBehaviour,\n agentClientProtocolInFlightGuardsCanFire,\n type AgentClientProtocol_ExecutionProfile,\n type CodingAgent_RunTaskOutput,\n AgentClientProtocol_HostConfigurationInheritance,\n CodingAgent_UsageSchema,\n AgentClientProtocol_ExecutionTransportMetadataSchema,\n type AgentClientProtocol_ExecutionTransportMetadata,\n type ImageProvider_GenerateImageOutput,\n CodingAgent_EndOfTurnClassification,\n CodingAgent_StopReason,\n type CodingAgent_ContinuationRecord,\n type CodingAgent_SessionSuspension,\n type CodingAgent_Usage,\n ProviderProtocolRuntimeKind,\n isLLMCatalogProvider,\n LLM_MODEL_CATALOG,\n LLM_Model_IO_Capability,\n type LLM_Model,\n validateReasoningEffortForModel,\n CODING_AGENT_NOT_SIGNED_IN_MESSAGE_PREFIX,\n CodingAgentHostLoginState,\n ContentSafetyScreeningOutcome,\n ContentSafetyModerationOutcome,\n type ContentSafety_HarmCategory,\n} from '@wildo-ai/external-connectors-models';\nimport { buildAgentSubprocessEnvironment, probeCodingAgentHostLoginAsync } from '@wildo-ai/external-connectors-private/backend-runtime';\nimport type { NativeConstrainedDecodingContract, ProviderSdkFactoryContext, StrictStructuredOutputProfile } from '@wildo-ai/external-connectors-private/backend-runtime';\nimport { asSchema, generateText, streamText, generateObject, generateImage, NoObjectGeneratedError, tool, jsonSchema, stepCountIs, wrapImageModel, wrapLanguageModel, type JSONSchema7 } from 'ai';\nimport { STREAMED_GENERATION_IDLE_DEADLINE_MS, STREAMED_GENERATION_TOTAL_DEADLINE_MS, streamedGenerationDeadlineMiddleware } from '../utils/streamed-generation-deadline.backend.utils';\nimport {\n latestCumulativeCost,\n startACPAgentSession,\n type ACPAgentSession,\n} from '~wildo-backend-lib/flows-actors/utils/acp-session-runner.backend.utils';\nimport {\n ACP_RESULT_TOOL_NAME,\n ACP_RESULT_TOOL_SERVER_NAME,\n startAcpResultToolServer,\n} from '~wildo-backend-lib/flows-actors/utils/acp-result-tool-server.backend.utils';\nimport { executeBoundedSubprocess, resolveTrustedWorkingDirectory } from '~wildo-backend-lib/flows-actors/utils/bounded-subprocess.backend.utils';\nimport type { FunctionTool, FunctionToolExecutionContext } from '~wildo-backend-lib/flows-actors/models/function-tools.backend.definitions';\nimport { FunctionToolPersonalDataOutputKind, argumentsAToolExecutesWith, sdkInputSchemaOfFunctionTool, isFunctionToolOfferedToTurn, modelToolNameForFunctionRef, resolveFunctionToolApprovalGate } from '~wildo-backend-lib/flows-actors/models/function-tools.backend.definitions';\nimport {\n PersonalDataGuard,\n PersonalDataPlaceholderRefusal,\n PersonalDataPlaceholderTable,\n modelCopyOfPersonAuthoredToolCalls,\n reviewerEditStatementsOf,\n withReviewerEditStatements,\n treatRecordsResult,\n} from '~wildo-backend-lib/flows-actors/content-guardrails/personal-data-guard.backend.utils';\nimport { ToolResultScreen, type ToolResultScreeningRecord } from '~wildo-backend-lib/flows-actors/content-guardrails/tool-result-screen.backend.utils';\nimport { ClassifierBackedContentGuardrail, contentGuardrailClassifierGapOf } from '~wildo-backend-lib/flows-actors/content-guardrails/classifier-availability.backend.utils';\nimport { AgentOperationObservationRecorder } from '~wildo-backend-lib/flows-actors/services/agent-operation-observation.backend.utils';\nimport { getCurrentWorkAttributionFrame } from '~wildo-backend-lib/runtime/models/work-attribution.als.backend';\nimport { getCurrentModelSpendFrame } from '~wildo-backend-lib/runtime/models/model-spend-frame.als.backend';\nimport type { ModelCallSpendMeter } from '~wildo-backend-lib/flows-actors/a2a/services/a2a-token-budget.backend.service';\nimport { estimateModelCallTokens, modelCallUsageIsPartial, reportedModelCallTokens } from '~wildo-backend-lib/flows-actors/services/model-call-token-estimate.backend.utils';\nimport { agentPoliciesInFrame, readAgentPolicies, turnPolicyOrganizationIds, type AgentPolicyLookup } from '~wildo-backend-lib/flows-actors/content-guardrails/agent-policy.backend';\nimport { treatRecordsResultByOwner, treatToolTreatedResultByPossibleOwners, unattributedRowOwnershipOf, type RecordOwnerPolicyContext } from '~wildo-backend-lib/flows-actors/content-guardrails/record-owner-policy.backend';\nimport { observingRecordOwners, organizationNamedByRecord, type ToolCallRecordOwners } from '~wildo-backend-lib/flows-actors/content-guardrails/tool-call-record-owners.backend';\nimport { resolveCallerOrganizationIds } from '~wildo-backend-lib/security/authorizations/scope-root-collection-confinement.backend';\nimport { AgentSuspensionLookupKind, readAgentSuspension, type AgentSuspensionLookup } from '~wildo-backend-lib/flows-actors/agent-suspension/agent-suspension.backend';\nimport type { RepositoriesRegistryHandlerBackendService } from '~wildo-backend-lib/base-classes/services/repositories/repositories-registry-handler.backend.service';\nimport {\n AgentOutputWithheldError,\n OutputModerationGuard,\n type OutputWithholding,\n} from '~wildo-backend-lib/flows-actors/content-guardrails/output-moderation.backend.utils';\nimport { type ContentSafetyBackendService, type ContentSafetyModerationResult } from '~wildo-backend-lib/external-providers/services/content-safety.backend.service';\nimport {\n AutonomousTurnTrigger,\n FlowsActors_ExecutionErrorCode,\n FlowsActors_ModeratedOutputKind,\n admitsDecisionSuspension,\n outputModerationCategories,\n resolveModelCallAttribution,\n type ExecutionContext_InitiatorIds,\n type ModelCallAttributionInput,\n type FlowsActors_InitiationKind,\n type HumanDecision_RouteKind,\n describeModelProviderAccountRefusal,\n type ModelProviderAccountRefusal,\n type WildoError_Backend,\n} from '@wildo-ai/saas-models';\nimport { toPortableModelToolName } from '~wildo-backend-lib/flows-actors/models/model-tool-name.backend.utils';\nimport { userInputToContextItem } from '~wildo-backend-lib/flows-actors/utils/prompt-ir-adapters.backend.utils';\nimport { runWithAgentActorFrame } from '~wildo-backend-lib/runtime/models/agent-actor-frame.als.backend';\nimport type { AuditAgentActor } from '@wildo-ai/saas-models';\nimport type { AuditPrincipalFacts } from '~wildo-backend-lib/compliance/audit-trails/utils/audit-actor.backend.utils';\nimport {\n DEFAULT_MAX_STRUCTURED_DATA_FIELD_ALLOWED,\n planStructuredGenerationShape,\n StructuredGenerationPlanKind,\n} from '~wildo-backend-lib/flows-actors/utils/structured-generation-plan.backend.utils';\nimport {\n StrictStructuredOutputSchemaKind,\n deriveStrictStructuredOutputSchema,\n exceedsConstrainedDecodingLimits,\n isCompiledGrammarSizeRefusal,\n isConstrainedDecodingComplexityRefusal,\n isStrictSchemaRequestRefusal,\n measureConstrainedDecodingComplexity,\n withoutDecodingValidationConstraints,\n} from '~wildo-backend-lib/flows-actors/utils/strict-structured-output-schema.backend.utils';\nimport { CryptoKey_Purpose } from '@wildo-ai/saas-models';\nimport type { AppConfigurationService } from '~wildo-backend-lib/config/services/app-configuration.backend.service';\nimport { applicationSymmetricKeyOf } from '~wildo-backend-lib/security/crypto-keys/application-symmetric-keys.backend';\nimport { withModelCallFailover, type ModelCallCandidate, type ModelCallFailover } from '~wildo-backend-lib/flows-actors/utils/model-call-failover.backend.utils';\n\n\n\ninterface executeOperationParams {\n providerClient: any;\n providerRef: string;\n config: FlowsActors_Agent['config'];\n operationKey: LLMProvider_OperationKey;\n systemPrompt: string;\n instructions: string;\n input: any;\n llmProviderConfig?: LLMProvider_Configuration;\n /** #2292 Phase 3: the agent's output moderation, when it declares one. The model is wrapped with its middleware. */\n outputModeration?: OutputModerationGuard;\n /** #2841: the invocation's operation observation; the model is wrapped innermost with its middleware. */\n operationObservation?: AgentOperationObservationRecorder;\n /** #2301: where each hand-over to a declared alternative model is written, for the invocation's trace. */\n modelFailovers?: ModelCallFailover[];\n}\n\n/**\n * #2292 Phase 3: what a BUFFERED operation's result is, as output moderation names it. Total over the operation keys, so a\n * new operation is a compile error here rather than a call whose output escapes moderation. A structured answer is judged\n * by its string leaves; a reply as it is.\n */\nconst MODERATED_OUTPUT_KIND_OF_OPERATION: Readonly<Record<LLMProvider_OperationKey, FlowsActors_ModeratedOutputKind>> = {\n [LLMProvider_OperationKey.GENERATE_TEXT]: FlowsActors_ModeratedOutputKind.REPLY,\n [LLMProvider_OperationKey.CHAT_COMPLETION]: FlowsActors_ModeratedOutputKind.REPLY,\n [LLMProvider_OperationKey.CHAT_MULTIMODAL]: FlowsActors_ModeratedOutputKind.REPLY,\n [LLMProvider_OperationKey.STREAM_TEXT]: FlowsActors_ModeratedOutputKind.REPLY,\n [LLMProvider_OperationKey.GENERATE_STRUCTURED]: FlowsActors_ModeratedOutputKind.STRUCTURED_OUTPUT,\n [LLMProvider_OperationKey.STREAM_STRUCTURED]: FlowsActors_ModeratedOutputKind.STRUCTURED_OUTPUT,\n};\n\n/**\n * The organizations one model call works for (#2843, #2292 R8): whose suspensions refuse it, and whose agent policies\n * tighten its guardrails. Built ONCE per call, at its entry point, by `AgentsBackendService.buildCallOrganizationScope`\n * (a streaming turn through `buildStreamingCallOrganizationScope`, which wraps it), and handed to both the admission and\n * the execution, so the organizations a call is refused for and those it is tightened for cannot differ.\n */\ninterface ModelCallOrganizationScope {\n /** The organization the call is made for: the one its refusal or moderation row is recorded in. */\n readonly organizationId?: string;\n /**\n * Every other organization whose work the call is: the case's tenant, the run's requester's organization, when they\n * differ from `organizationId`. Each one's suspensions and policies apply too: a suspension only refuses and a policy\n * only tightens, so applying one more organization's can never let through what one of them stops.\n */\n readonly alsoWorkedForOrganizationIds?: readonly string[];\n /** The organizations a principal acting in `organizationId` represents there (#2618). */\n readonly representingOrganizationIds?: readonly string[];\n /**\n * Why an organization the call may work for could not be known: the case it works on could not be read. The call is\n * refused, as for an unreadable suspension or policy: that organization may have suspended the agent or tightened it.\n */\n readonly unreadable?: string;\n}\n\n/** Every organization a call's scope names, its own first, each once. */\nfunction organizationIdsOfCallScope(scope: ModelCallOrganizationScope): string[] {\n return turnPolicyOrganizationIds(scope.organizationId, [...(scope.alsoWorkedForOrganizationIds ?? []), ...(scope.representingOrganizationIds ?? [])]);\n}\n\ninterface CompiledExecutionPrompts {\n systemPrompt: string;\n instructions: string;\n}\n\n/**\n * What a single operation helper (`executeGenerateText`, `executeGenerateStructured`, …)\n * hands back to {@link AgentsBackendService.executeOperation}.\n *\n * Named rather than written inline at each helper because it grew a THIRD member:\n * a structured generation can legitimately complete with no object, and the reason it\n * did has to survive the four hops between the helper that learns it and the caller\n * that reports it. An inline `{ output; usage? }` at every signature silently drops any\n * fourth field at the first hop that re-declares the shape — which is exactly how the\n * approval suspension was lost once already (see the warning in\n * {@link AgentsBackendService.finalizeInvocationSuccess}).\n */\ninterface AgentOperationExecutionResult {\n output: unknown;\n usage?: any;\n /**\n * Present ONLY when a structured generation returned `{ object: undefined }`. Every\n * other outcome — success, or a provider fault that throws — leaves it absent.\n */\n structuredGenerationFailure?: LLMProvider_StructuredGenerationFailure;\n}\n\ninterface AgentExecutionResult extends AgentOperationExecutionResult {\n output: unknown;\n usage?: unknown;\n /**\n * #2301: each hand-over of a model call to an alternative the agent declared, in order. Absent when every call was\n * answered by the agent's own model. The last one names the model that answered the final step.\n */\n modelFailovers?: readonly ModelCallFailover[];\n /**\n * How the call was physically executed.\n *\n * A UNION, because a coding run is not an LLM call with a different wire\n * format and its metadata is owned by the coding-agent family. Before this was\n * widened, the ACP executor returned through a double cast and finalization\n * parsed the result with the LLM schemas — which would have thrown on the\n * first real dispatch, in a path no test and no live probe had exercised.\n */\n transport?: LLMProvider_ExecutionTransportMetadata | AgentClientProtocol_ExecutionTransportMetadata;\n /**\n * Present when the turn SUSPENDED at a human-in-the-loop approval boundary rather than\n * completing. A caller that ignores it treats a paused turn as a finished one — which would\n * record a terminal status for work that has not happened.\n */\n approvalSuspension?: AgentApprovalSuspension;\n}\n\n/**\n * A host's decision to run language-model calls on an ACP agent instead of an API key (#3472).\n *\n * The development companion installs one at startup: its creation lane makes hundreds of structured calls per run,\n * and on a metered API key that cost exploded, while every developer using Wildo already runs a coding agent on their\n * own subscription. With a route installed, a language-model agent whose provider is in `routedProviderRefs` has its\n * text and structured calls served by a locked-down session of the route's ACP agent, and its result returned through\n * the host's `submit_result` tool (`acp-result-tool-server.backend.utils.ts`). Everything above the call — prompts,\n * schemas, validators, the correction loop — is unchanged; only the transport and the model differ.\n *\n * What stays on the API, by construction: image generation (no ACP agent generates images), a call whose input\n * carries images (not yet measured over ACP), streaming calls, and an agent under an output-moderation guard (the\n * guard is an API middleware). Each is logged when it happens, so a call that still spends API tokens says why.\n */\nexport interface LanguageModelAgentClientProtocolRoute {\n /** The provider whose ACP binding serves the calls, e.g. `anthropic` (Claude Code through its adapter). */\n readonly acpProviderRef: string;\n /** The ACP execution profile of that provider the sessions start under (its auth posture, its environment). */\n readonly executionProfileRef: string;\n /** The model every routed call runs on, a member of the ACP binding's `models`. */\n readonly model: string;\n /** Language-model agents on these providers are routed; every other agent keeps its own transport. */\n readonly routedProviderRefs: readonly string[];\n /** The working directory of every session: a scratch directory, never an application workspace. */\n readonly scratchDirectory: string;\n /** How many routed sessions may run at once. Each is an agent process. */\n readonly maximumConcurrentSessions: number;\n /** The longest one routed call may take, all its turns together. */\n readonly callTimeoutMs: number;\n /** Refused submissions after which a call stops asking and reports the last refusal. */\n readonly maximumSubmissions: number;\n}\n\n/** The operations a route serves: a prompt in, one result out. */\nconst ROUTABLE_LANGUAGE_MODEL_OPERATIONS: ReadonlySet<LLMProvider_OperationKey> = new Set([\n LLMProvider_OperationKey.GENERATE_STRUCTURED,\n LLMProvider_OperationKey.GENERATE_TEXT,\n LLMProvider_OperationKey.CHAT_COMPLETION,\n]);\n\n/** Turns a routed call may add after one that ended without an accepted result, to ask for the submission. */\nconst ROUTED_CALL_REMINDER_TURNS = 2;\n\n/**\n * Backend-only authority supplied by the installed host for an Agent call.\n *\n * A spawned agent operates in a real filesystem workspace, but that workspace is\n * neither provider configuration nor task data: profiles are portable and task\n * callers must never choose process working directories. The host that owns\n * the installed application resolves the physical root and passes it here only\n * for the invocation that needs it. API-backed Agents intentionally require no\n * host context.\n */\nexport interface AgentInvocationHostContext {\n workspaceRootPath?: string;\n /**\n * Narrows what a CODING agent may touch, beyond the profile's permission\n * ceiling. Supplied by the host that owns the task's mutation scope; returning\n * false denies, whatever the ceiling permits. Host authority, not authored\n * configuration — a portable profile cannot know a task's scope.\n */\n isPermittedCodingLocation?: (absolutePath: string) => boolean;\n /**\n * Optional read boundary for ACP client callbacks and declared non-mutating tool locations. Research supplies its evidence\n * store; ordinary coding leaves this absent so a narrow write scope still permits source reading.\n * Host authority only: a task prompt or portable execution profile cannot broaden it.\n */\n isPermittedCodingReadLocation?: (absolutePath: string) => boolean;\n /**\n * Live progress from a coding session. Best-effort by contract: the runner\n * swallows anything this throws, because a progress sink must never be able\n * to fail the run it observes.\n */\n onCodingSessionEvent?: (event: { readonly kind: string; readonly payload: unknown }) => void;\n /** Operator-initiated cancellation of a coding session. Cooperative first, kill second. */\n codingSessionAbortSignal?: AbortSignal;\n /**\n * Judge what a coding agent's END-OF-TURN message actually meant, so the turn\n * ladder can auto-continue a self-imposed pause and park a genuine question.\n *\n * The JUDGMENT is host authority, not engine mechanism: it is an auxiliary LLM\n * call, and the host (the companion) owns model resolution and the deliberation\n * infrastructure. The engine owns the LADDER — when to call this, how many\n * continuations to allow, how to record the result — and it FAILS OPEN: if this\n * is absent, throws, or times out, the turn is treated as complete. An\n * autonomous coding lane must never hang, or discard a mutated workspace, on an\n * auxiliary call. Absence therefore reproduces the pre-ladder single-turn\n * behaviour exactly, which is why every non-coding caller can ignore it.\n */\n classifyCodingTurnEnd?: (input: {\n readonly finalMessage: string;\n readonly turnIndex: number;\n }) => Promise<CodingAgent_EndOfTurnClassification>;\n /**\n * Whether this host can hold a coding session PARKED on a question the agent asked (#3710): it reads\n * `output.suspension`, shows the question and resumes the session with the answer. When true the agent is offered\n * the protocol's question channel (form elicitation) and a turn that uses it parks; when absent the agent cannot ask\n * and nothing parks. A question is never inferred from the agent's prose: see `driveCodingTurnLadder`.\n */\n parksCodingAgentQuestions?: boolean;\n /**\n * Live phase transitions for a coding session — distinct from\n * {@link onCodingSessionEvent}, which relays the agent's own frames. This fires\n * when the LADDER changes state: a new turn starting, or the session parking on\n * a question. Best-effort, like the event sink: never allowed to fail the run.\n */\n onCodingSessionStateChange?: (state: CodingSessionLadderState) => void;\n}\n\n/** The ladder phases a live coding session transitions through. */\nexport enum CodingSessionLadderPhase {\n /** A turn is executing. */\n RUNNING = 'running',\n /** The session parked on a question and is waiting for an operator answer. */\n AWAITING_INPUT = 'awaiting_input',\n}\n\n/** A phase transition in the turn ladder, surfaced to the host for live relay. */\nexport interface CodingSessionLadderState {\n readonly phase: CodingSessionLadderPhase;\n /** 1-based index of the turn this state refers to. */\n readonly turnIndex: number;\n /** The agent's question, present only when `phase` is `AWAITING_INPUT`. */\n readonly question?: string;\n}\n\n/** True when an execution result carries a CODING transport rather than an LLM one. */\nfunction isAgentClientProtocolTransport(\n transport: LLMProvider_ExecutionTransportMetadata | AgentClientProtocol_ExecutionTransportMetadata | undefined,\n): transport is AgentClientProtocol_ExecutionTransportMetadata {\n return transport?.protocolKind === ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL;\n}\n\ntype ResolvedAgentExecution =\n | {\n transport: 'api';\n providerRef: string;\n operationKey: LLMProvider_OperationKey;\n llmProviderConfig?: LLMProvider_Configuration;\n }\n | {\n transport: 'acp';\n providerRef: string;\n operationKey: CodingAgent_OperationKey;\n executionProfileRef: string;\n acpProfile: RuntimeAgentClientProtocolProfile;\n acpExecutionProfile: AgentClientProtocol_ExecutionProfile;\n };\n\n/**\n * The provider's declaration of whether its agent escalates before mutating.\n *\n * Structurally identical to the `permissionEscalation` member of the ACP runtime\n * contract, and declared locally rather than imported because that contract type\n * lives in the provider-module package, which this engine package does not\n * depend on. The narrowing below is by the enum member, so a contract that grew\n * a fourth behaviour would fail this file's exhaustiveness rather than fall into\n * a silent default.\n */\ntype AgentClientProtocolPermissionEscalationDeclaration =\n | { behaviour: typeof AgentClientProtocol_PermissionEscalationBehaviour.RAISES_BEFORE_MUTATION }\n | {\n behaviour: typeof AgentClientProtocol_PermissionEscalationBehaviour.RAISES_ONLY_UNDER_HOST_CONFIGURATION;\n configurationEnvironmentVariableName: string;\n }\n | { behaviour: typeof AgentClientProtocol_PermissionEscalationBehaviour.NEVER_RAISES };\n\n\n/**\n * Thrown by {@link AgentsBackendService.invokeAgentStreaming} when honest token\n * streaming is not available for the requested agent:\n * - `'transport'` — the agent uses the CLI transport (v1 streams over the API\n * transport only; the session-oriented CLI runtime is a future workstream);\n * - `'operation'` — the operation is non-text (structured / multimodal / image),\n * which has no token-delta stream.\n * Callers may catch this to fall back to the buffered {@link AgentsBackendService.invokeAgent}.\n */\nexport class AgentStreamingUnsupportedError extends Error {\n constructor(public readonly reason: 'transport' | 'operation', message: string) {\n super(message);\n this.name = 'AgentStreamingUnsupportedError';\n }\n}\n\n/**\n * The usage a model call reported, as {@link AgentsBackendService} normalizes it — the shape the\n * invocation carries on `executionContext.usage` (parsed there by `LLMProvider_UsageSchema`).\n */\nexport interface AgentModelCallUsage {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n tokenUsageComplete: boolean;\n inputTokenDetails?: { noCacheTokens?: number; cacheReadTokens?: number; cacheWriteTokens?: number };\n /** The output split (#1598): absent `reasoningTokens` means the provider did not report it, never zero. */\n outputTokenDetails?: { textTokens?: number; reasoningTokens?: number };\n}\n\n/**\n * Thrown when the model provider FAILED a streamed call — refused it (an HTTP 4xx such as Anthropic's\n * `400 Your credit balance is too low`), broke off mid-stream (an `overloaded_error` event), or failed a\n * later step of the tool loop.\n *\n * ## Why this exists (#2191)\n *\n * AI-SDK v7 does not THROW a provider failure out of `streamText`. It delivers it as an `error` PART on\n * `fullStream` — exactly as it delivers a cancellation as an `abort` part — and `fullStream` then ends\n * cleanly. `textStream` drops the part altogether. So a reader that only handles the part types it\n * expects sees an empty, successful stream, and the turn was recorded COMPLETED with no assistant\n * message: an exhausted, revoked or misconfigured key read as \"the model chose not to act\", the client\n * never received `AGENT_FAILED`, and the reason existed only in a stack the SDK printed to stderr.\n *\n * Every reader of an AI-SDK stream in this service therefore turns an `error` part into this error,\n * which every invocation path already treats as a failed call: the failure trace carries its message,\n * the provider-call record its {@link code} (the HTTP status), and the conversational runtime records\n * the turn FAILED. It is NOT a backend error built by the error builder — `isWildoBackendError` does not\n * match it — so a caller that needs the distinction tests `instanceof AgentModelCallFailedError`.\n *\n * Not every `error` part is the provider's: the SDK reports its own failures the same way (an invalid\n * prompt, a forged tool-approval signature on a resume, a stream that ended with no output). Only a\n * failure carrying an HTTP status is a provider REFUSAL, which is why {@link statusCode} is optional\n * and the runtime words its log line by it.\n *\n * ## The usage it carries\n *\n * Steps that FINISHED before the failure really consumed provider tokens (a tool loop whose second\n * model call is refused already paid for its first). Throwing would otherwise drop that consumption on\n * the floor — the same unmetered-spend shape the aborted-stream fix closed — so the per-step total\n * rides on the error and the failure paths meter it. When NO step finished (the call was refused\n * outright) `usage` is ABSENT, not zero: zero would read downstream as \"the provider reported a token\n * count\" (the provider-call evidence counts it) and as \"a metered call reported nothing\" (the token\n * budget warns that spend escaped it), and neither is true of a call the provider never ran.\n */\nexport class AgentModelCallFailedError extends Error {\n /** The provider's HTTP status when the failure was an HTTP refusal (`APICallError.statusCode`). */\n public readonly statusCode?: number;\n /**\n * `HTTP_<status>` for a provider refusal, absent otherwise. Read by the agent-call trace (`error.code`),\n * which is the only part of the error the provider-call record keeps, so a 400 credit refusal and a 529\n * overload stay distinguishable there.\n */\n public readonly code?: string;\n /**\n * The failure exactly as the SDK delivered it on the stream — usually an `APICallError`. NOT ENUMERABLE (#2368): the\n * engine's log normalizer serializes every own enumerable key of an error, and this one holds the prompt\n * (`requestBodyValues`), the vendor's body and headers and the request URL, so a caller logging this error would\n * record all of them by value. Read it by name; describe it with `describeModelCallError`.\n */\n declare public readonly providerError: unknown;\n /**\n * The provider ACCOUNT's refusal behind the failure (#3204): no credits left, a spend or usage limit, billing. Present\n * only then; the message then says which provider and what to do, in the shape every layer reads back\n * (`describeModelProviderAccountRefusal`).\n */\n public readonly accountRefusal?: ModelProviderAccountRefusal;\n\n constructor(\n providerError: unknown,\n /** What the steps that finished before the failure consumed; absent when none finished. */\n public readonly usage?: AgentModelCallUsage,\n ) {\n const statusCode = AgentModelCallFailedError.statusCodeOf(providerError);\n // The vendor's message, redacted (#2368): a refusal can quote the prompt content it refused, and this message is\n // logged and carried on the failure. `describeModelCallError` keeps its quoted identifiers and limits, never a value.\n const described = String(describeModelCallError(providerError).errorMessage ?? 'no message');\n const accountRefusal = readModelProviderAccountRefusal(providerError);\n super(accountRefusal !== undefined ? describeModelProviderAccountRefusal(accountRefusal) : statusCode !== undefined\n ? `The model provider refused the call (HTTP ${statusCode}): ${described}`\n : `The model call failed on the stream: ${described}`);\n this.name = 'AgentModelCallFailedError';\n Object.defineProperty(this, 'providerError', { value: providerError, enumerable: false, writable: false, configurable: false });\n this.statusCode = statusCode;\n this.code = statusCode !== undefined ? `HTTP_${statusCode}` : undefined;\n if (accountRefusal !== undefined) this.accountRefusal = accountRefusal;\n }\n\n /**\n * The HTTP status of an `APICallError`, or of the LAST attempt when the SDK gave up retrying (a retryable\n * 429/529 arrives as a `RetryError` whose own object carries no status, only `lastError`).\n */\n private static statusCodeOf(error: unknown): number | undefined {\n if (!error || typeof error !== 'object') return undefined;\n const own = (error as { statusCode?: unknown }).statusCode;\n if (typeof own === 'number') return own;\n const last = (error as { lastError?: { statusCode?: unknown } }).lastError?.statusCode;\n return typeof last === 'number' ? last : undefined;\n }\n}\n\n/**\n * `streamText`'s `onError`, passed by every reader in this service. The SDK's default prints the raw\n * failure to stderr; here the `error` PART itself fails the call and is logged with the provider's\n * details (see {@link AgentModelCallFailedError}), so printing it again would only duplicate it without\n * structure. Named so each call site states why it is silent rather than repeating an empty arrow.\n */\nconst SUPPRESS_SDK_STREAM_ERROR_PRINT = (): void => undefined;\n\n/** Max agent↔tool round-trips per streaming turn (bounds tool-call loops). */\nconst MAX_TOOL_STEPS = 6;\n\n/**\n * Strip assistant `reasoning` content parts that carry NO text, for the multi-step\n * tool-loop continuation.\n *\n * WHY: extended-thinking models (e.g. Sonnet-5) emit an assistant `reasoning` part whose `text` is\n * EMPTY — the thinking itself lives in the provider-encrypted `providerOptions.anthropic.signature`.\n * When the AI-SDK v7 tool loop re-feeds that assistant message to the model for the NEXT step, the\n * provider prompt validation rejects the empty-text part\n * (`AI_TypeValidationError: … expected 'reasoning' | 'reasoning-file' | 'tool-call'`) — so the second\n * step never runs: a read→create chain dies after the first tool and the reply comes back empty.\n *\n * WHAT: drop ONLY the text-less reasoning parts. Reasoning parts that DO carry text round-trip fine\n * and are preserved, as are text / tool-call / tool-result parts — so nothing user-visible and no\n * tool causality is lost. An assistant message left with no parts at all is dropped entirely (an\n * empty content array is itself invalid).\n *\n * Pure + total: returns a NEW array only when something changed, never mutates the caller's\n * messages, and passes through any non-array content untouched.\n */\nexport function stripEmptyReasoningParts(messages: readonly any[] | undefined): any[] {\n if (!Array.isArray(messages)) return [];\n const isTextlessReasoning = (part: any): boolean =>\n !!part && typeof part === 'object' && part.type === 'reasoning'\n && (typeof part.text !== 'string' || part.text.length === 0);\n\n const result: any[] = [];\n for (const message of messages) {\n if (!message || message.role !== 'assistant' || !Array.isArray(message.content)) {\n result.push(message);\n continue;\n }\n if (!message.content.some(isTextlessReasoning)) {\n result.push(message);\n continue;\n }\n const content = message.content.filter((part: any) => !isTextlessReasoning(part));\n // An assistant message whose parts were ALL text-less reasoning has nothing left to send.\n if (content.length === 0) continue;\n result.push({ ...message, content });\n }\n return result;\n}\n\n/**\n * A source part of the model stream, as the conversation keeps it (#2524): the SDK's `sourceType` read into the model\n * vocabulary, and only the fields a person is shown. Read by shape — the part crossed a provider boundary.\n */\nfunction toFlowsActorsSource(part: unknown): FlowsActors_Source {\n const bag = (part ?? {}) as { sourceType?: unknown; url?: unknown; title?: unknown; mediaType?: unknown; filename?: unknown };\n const text = (value: unknown): string | undefined => (typeof value === 'string' && value.length > 0 ? value : undefined);\n const title = text(bag.title);\n if (bag.sourceType === FlowsActors_SourceKind.DOCUMENT) {\n const mediaType = text(bag.mediaType);\n const filename = text(bag.filename);\n return { kind: FlowsActors_SourceKind.DOCUMENT, ...(title ? { title } : {}), ...(mediaType ? { mediaType } : {}), ...(filename ? { filename } : {}) };\n }\n const url = text(bag.url);\n return { kind: FlowsActors_SourceKind.URL, ...(title ? { title } : {}), ...(url ? { url } : {}) };\n}\n\n/**\n * One phase of a tool call, surfaced to the streaming caller as it happens (#2524).\n *\n * All three phases carry the SDK's `toolCallId`, so a caller can join a call to its result or its error. The result and\n * the error used to arrive with the tool's name only — nothing to join on, nothing to show — and the conversational\n * runtime dropped both.\n */\n/** #2292: see `AgentsBackendService.personalDataGuards`. Keyed by the invocation's request object; nothing outlives it. */\nconst PERSONAL_DATA_GUARD_BY_INVOCATION = new WeakMap<object, PersonalDataGuard>();\n/** #2841: see `AgentsBackendService.operationObservationOf`. Keyed by the invocation's request object; nothing outlives it. */\nconst AGENT_OPERATION_OBSERVATION_BY_INVOCATION = new WeakMap<object, AgentOperationObservationRecorder>();\n\nexport interface FunctionToolStreamEvent {\n phase: FlowsActors_ToolCallPhase;\n toolCallId: string;\n toolName: string;\n /** What the agent passed. Every phase. */\n input?: unknown;\n /** What the tool returned. RESULT only. */\n output?: unknown;\n /** What the tool threw. ERROR only. */\n error?: unknown;\n}\n\n/** Callbacks a streaming invocation forwards to the caller. */\nexport interface AgentStreamHandlers {\n onDelta: (delta: string) => void;\n onToolEvent?: (event: FunctionToolStreamEvent) => void;\n /**\n * The model's REASONING, as it streams (#2524). Forwarded for every model that emits it; whether a person is shown\n * it is the caller's decision (`FlowsActors_Agent.disclosure.reasoning`), never this layer's.\n */\n onReasoningDelta?: (delta: string) => void;\n /** A source the model cited, as the provider reported it (#2524). */\n onSource?: (source: FlowsActors_Source) => void;\n /**\n * Cooperative cancellation for the model call.\n *\n * Carried HERE rather than as a new parameter because `handlers` is already threaded\n * unchanged through every hop of the streaming path\n * (`invokeAgentStreaming` → `executeAgentViaApiStreaming` → `streamOperation` →\n * `streamTextToDeltas` → `streamText`). Adding a positional argument at four levels\n * is exactly the arity hazard that has already produced one silent `undefined` in this\n * codebase; riding the object that is passed anyway changes no call signature.\n *\n * Semantically it belongs: this interface is the stream's control surface, and\n * \"stop streaming\" is part of controlling a stream.\n *\n * When absent the model call is simply uncancellable — the previous behaviour.\n */\n abortSignal?: AbortSignal;\n}\n\ninterface streamOperationParams {\n providerClient: any;\n /** The provider the agent names: the first candidate of a declared model failover (#2301). */\n providerRef: string;\n /** #2301: where each hand-over to a declared alternative model is written, for the invocation's trace. */\n modelFailovers?: ModelCallFailover[];\n config: FlowsActors_Agent['config'];\n operationKey: LLMProvider_OperationKey;\n systemPrompt: string;\n instructions: string;\n input: any;\n handlers: AgentStreamHandlers;\n tools?: Record<string, any>;\n /** #2292 Phase 3: the agent's output moderation, when it declares one. The model is wrapped with its middleware. */\n outputModeration?: OutputModerationGuard;\n /** #2841: the invocation's operation observation; the model is wrapped innermost with its middleware. */\n operationObservation?: AgentOperationObservationRecorder;\n /**\n * Call-level tool-approval configuration (human-in-the-loop), keyed by identifier-safe tool name.\n *\n * Rides the params OBJECT rather than a positional argument, for the reason already recorded on\n * `abortSignal` above: this value crosses four levels, and adding a positional parameter at four\n * levels is the arity hazard that has already produced one silent `undefined` here.\n */\n toolApproval?: Record<string, ToolApprovalDecision>;\n /**\n * Secret used to HMAC-sign approval requests and verify them on replay.\n *\n * REQUIRED whenever `toolApproval` is present — without it a client can forge an approval for\n * exactly the tools someone marked dangerous enough to gate. The caller fails closed rather than\n * passing `toolApproval` with no secret.\n */\n toolApprovalSecret?: string;\n /**\n * #2855: the invocation's personal-data guard, when the agent runs under a treatment: every model step is sent the\n * person-authored tool calls of its messages treated by it (`modelCopyOfPersonAuthoredToolCalls`).\n */\n personalDataGuard?: PersonalDataGuard;\n}\n\n/**\n * A turn that SUSPENDED at a human-in-the-loop approval boundary instead of completing.\n *\n * Not an error and not a terminal failure: the tool loop stopped, the model is waiting, and the run\n * state below is everything needed to resume once a human decides. `sdkModelMessages` is the SDK's\n * own resume payload — opaque to us by design.\n */\nexport interface AgentApprovalSuspension {\n approvalId: string;\n toolCallId: string;\n toolName: string;\n toolArgs?: Record<string, unknown>;\n sdkModelMessages: Record<string, unknown>[];\n /** #3364 step 3: the output moderation the turn was judged under when it paused, when it judged anything. */\n outputModerationAtPause?: FlowsActors_OutputModerationPolicy;\n}\n\n/**\n * The per-tool approval decision handed to the model SDK.\n *\n * semantic-literal-boundary: `'user-approval'` and `'denied'` are the model SDK's own\n * `ToolApprovalStatus` vocabulary, not Wildo's. This type is the thin adapter where they are\n * produced; they must not spread past {@link AgentsBackendService.buildToolApprovalConfiguration}.\n */\ntype ToolApprovalDecision = 'user-approval' | { type: 'denied'; reason: string };\n\n// ── Who may leave a gated call waiting for a person (#1611) ──\n// It is decided by ONE predicate,\n// `admitsDecisionSuspension` (saas-models, #1611), per tool, from the turn's principal, the door that\n// opened it and the route the tool's gate declares. It used to be an allow-list of one execution type\n// here (`USER_REQUEST`), which made every machine turn deny every gated call; the predicate keeps that\n// floor and admits exactly one more case — an organization machine whose turn was opened by the\n// autonomous entry point, pausing on a REVIEWER route (ROLE or ASSIGNEE), which a person in the\n// organization can answer.\n//\n// Why this stays an ALLOW-list inside the predicate rather than a deny-list of machines: the execution\n// vocabulary has nine members, and every case below is one where nobody can give the decision —\n//\n// - `ORGANIZATION_MACHINE` on an A2A turn, and `APPLICATION_MACHINE` — the caller is a machine waiting\n// for a reply, and nobody is routed its decisions;\n// - `INTERNALLY_INITIATED_REQUEST`, `WEBHOOK_CALLBACK`, `INBOUND_DELIVERY` — system-initiated; an\n// inbound-triggered turn that must ask goes through the autonomous entry point instead;\n// - `PUBLIC_EXECUTION`, `ANONYMOUS_SESSION` — no accountable identity, so no audit record of an approver;\n// - `CONSUMABLE_TOKEN` — a one-off credential not established to sustain a response channel.\n//\n// A deny-list would let the NEXT execution type inherit \"suspend\", and a principal that cannot answer\n// suspending is a turn waiting on a decision nobody is routed; the allow-list fails that closed.\n\n\n/**\n * Project only structural validation metadata from nested SDK/Zod errors.\n * Provider validation errors retain the rejected value in their message, so\n * logging `cause.message` would copy private model output into ordinary logs.\n * The one exception is a `custom` issue's message, which Zod never composes —\n * see {@link projectStructuredIssueRefinementMessage} for why that is the same\n * boundary rather than a hole in it.\n */\n/**\n * The TOP-LEVEL key names of a structured generation, for `unrecognized_keys` diagnosis only.\n *\n * Returns names, never values, and never recurses: a nested key could be a map keyed by user content,\n * whereas the root of a schema-driven generation is schema shape. Any parse failure yields nothing rather\n * than leaking a fragment of the raw text through an error message.\n */\nfunction projectStructuredRootKeyNames(text: unknown): readonly string[] | undefined {\n if (typeof text !== 'string' || text.length === 0) return undefined;\n try {\n const parsed: unknown = JSON.parse(text);\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined;\n return Object.keys(parsed).slice(0, 64);\n } catch {\n return undefined;\n }\n}\n\n/**\n * What one issue's SCHEMA expected — `expected`, `format`, `pattern`, `values` — read off the issue's own\n * fields and never off its message, which is where the rejected value lives. Each is schema shape: a type\n * name, a format name, the schema's regex, an enum's members. Without them a retry is told only WHERE it\n * failed, and on 2026-09-13 a model repeated the same `invalid_type` three times for want of \"array\".\n */\nfunction projectStructuredIssueExpectation(issue: object): {\n readonly expected?: string;\n readonly format?: string;\n readonly pattern?: string;\n readonly values?: readonly string[];\n} {\n const candidate = issue as { expected?: unknown; format?: unknown; pattern?: unknown; values?: unknown };\n const values = Array.isArray(candidate.values)\n ? candidate.values.filter((value) => ['string', 'number', 'boolean'].includes(typeof value)).map(String)\n : undefined;\n return {\n ...(typeof candidate.expected === 'string' ? { expected: candidate.expected } : {}),\n ...(typeof candidate.format === 'string' ? { format: candidate.format } : {}),\n ...(typeof candidate.pattern === 'string' ? { pattern: candidate.pattern } : {}),\n ...(values && values.length > 0 ? { values } : {}),\n };\n}\n\n/**\n * The authored message of a `custom` issue, and of NO OTHER CODE.\n *\n * `code: \"custom\"` is the one code Zod never raises by itself: it exists because a `.refine()` or\n * `.superRefine()` in this repository's own source called `addIssue`, so the message is the schema\n * author's sentence rather than Zod's rendering of the rejected value. That is what makes it safe to\n * carry under the same boundary as `expected` and `keys` — and it is the whole content the issue has,\n * since a cross-field refinement has no leaf schema to report an `expected` from.\n *\n * The code check is the guarantee, not a filter: widen it to any other code and this function starts\n * copying a message Zod composed around the input, which is the disclosure\n * {@link projectStructuredValidationIssues} exists to prevent.\n */\nfunction projectStructuredIssueRefinementMessage(code: string, issue: object): { readonly refinementMessage?: string } {\n if (code !== 'custom') return {};\n const message = (issue as { message?: unknown }).message;\n return typeof message === 'string' && message.length > 0 ? { refinementMessage: message } : {};\n}\n\nfunction projectStructuredValidationIssues(\n error: unknown,\n): ReadonlyArray<{\n readonly code: string;\n readonly path: readonly (string | number)[];\n readonly keys?: readonly string[];\n readonly expected?: string;\n readonly format?: string;\n readonly pattern?: string;\n readonly values?: readonly string[];\n readonly refinementMessage?: string;\n}> {\n let current = error;\n for (let depth = 0; depth < 4 && typeof current === 'object' && current !== null; depth += 1) {\n const record = current as { cause?: unknown; issues?: unknown };\n if (Array.isArray(record.issues)) {\n return record.issues.flatMap((issue) => {\n if (typeof issue !== 'object' || issue === null) return [];\n const candidate = issue as { code?: unknown; path?: unknown };\n if (typeof candidate.code !== 'string' || !Array.isArray(candidate.path)) return [];\n const path = candidate.path.filter((segment): segment is string | number => typeof segment === 'string' || typeof segment === 'number');\n // `unrecognized_keys` additionally carries the offending KEY NAMES, and those are projected. A key\n // a model invented against a strict object is schema shape, not model content -- the boundary this\n // function exists to hold is about VALUES, which are never included. Without the names the issue is\n // undiagnosable: it reports only that some unknown key exists at the root, which cost several live\n // runs on 2026-08-21 before the key could be identified any other way.\n const rawKeys = (issue as { keys?: unknown }).keys;\n const keys = Array.isArray(rawKeys)\n ? rawKeys.filter((key): key is string => typeof key === 'string')\n : undefined;\n return [{\n code: candidate.code,\n path,\n ...(keys && keys.length > 0 ? { keys } : {}),\n ...projectStructuredIssueExpectation(issue),\n ...projectStructuredIssueRefinementMessage(candidate.code, issue),\n }];\n });\n }\n current = record.cause;\n }\n return [];\n}\n\n/**\n * The agent frame one tool call runs in (#1595): which agent, in which conversational execution and\n * actors system, calling which tool. Identifiers only — never the call's arguments or a digest of them.\n *\n * `agentExecutionId` is absent when the agent was invoked outside any conversational execution (an\n * application calling `invokeAgent` with its own tool context): the frame names the agent it knows\n * rather than invent an execution. `decisionRef` names the human decision whose answer let this call run —\n * set on the tool context by the resume of an approval-gated turn (#1594), absent on every ordinary call.\n */\nfunction agentActorForToolCall(\n agent: FlowsActors_Agent,\n toolContext: FunctionToolExecutionContext | undefined,\n /** Absent for work the agent does outside any one tool call — MCP discovery at turn start. */\n toolName?: string,\n): AuditAgentActor {\n return {\n agentRef: agent.ref,\n ...(toolContext?.executionId ? { agentExecutionId: toolContext.executionId } : {}),\n ...(toolContext?.systemRef ? { systemRef: toolContext.systemRef } : {}),\n ...(toolName ? { toolName } : {}),\n ...(toolContext?.decisionRef ? { decisionRef: toolContext.decisionRef } : {}),\n };\n}\n\n/** One way of sending a structured call: the schema `generateObject` receives and the provider options beside it. */\ninterface PreparedStructuredOutputCall {\n /** The Zod schema as it is, or the strict JSON Schema validated through it. */\n readonly schema: z.ZodSchema<any> | ReturnType<typeof jsonSchema>;\n /** AI-SDK `providerOptions`, keyed by the SDK's provider id: OpenAI's strict flag, or a provider's declared path (#3146). */\n readonly providerOptions: { readonly providerOptions?: Readonly<Record<string, Readonly<Record<string, unknown>>>> };\n /**\n * Sent without the agent's reasoning setting (#3146): the call forces a tool, which a provider may refuse beside\n * manual extended thinking, and a forced tool call produces no reasoning anyway.\n */\n readonly withoutReasoning?: boolean;\n}\n\n/** The id of an AI-SDK language model (`LanguageModel.modelId`), or `undefined` for a model object that carries none. */\nfunction languageModelId(model: unknown): string | undefined {\n const modelId = (model as { modelId?: unknown } | null | undefined)?.modelId;\n return typeof modelId === 'string' ? modelId : undefined;\n}\n\n/** How a structured call is sent, strictly when it can be (#2344). See `prepareStructuredOutputSchema`. */\ninterface PreparedStructuredOutputSchema {\n /**\n * The CONSTRAINED call, tried first: the derived strict form for a provider that requests one, or the schema as it\n * is for a provider whose native constrained decoding admits it (#3146). Absent when there is none.\n */\n readonly strict: PreparedStructuredOutputCall | undefined;\n /**\n * The constrained call once more with the schema's validation-only keywords removed (#3204), tried when the provider\n * refused `strict` as too complex to compile, before `lax`. Present only for a provider whose native constrained\n * decoding has limits: there, giving up decoding-time patterns keeps the answer's shape, and giving up the grammar\n * entirely does not.\n */\n readonly relaxed?: PreparedStructuredOutputCall;\n /**\n * The schema as it is, unconstrained: strict mode off where the provider has an opinion, or the provider's declared\n * unconstrained path where its native decoding has limits. Sent when `strict` is absent or was refused. For a model\n * that admits no unconstrained path it is the relaxed constrained call, the only fallback that model accepts.\n */\n readonly lax: PreparedStructuredOutputCall;\n /** Set when `lax` is the relaxed constrained call (a model with no unconstrained path, #3204), so the log names it. */\n readonly laxIsRelaxedConstrained?: boolean;\n /** Whether the call that answered (or threw) decoded strictly. Cleared when a refusal falls back to `lax`. */\n decodedStrictly: boolean;\n /** A rejected answer's text in the ORIGINAL schema's shape, for a retry that patches it. */\n readonly restoreAnswerText: (text: string) => string;\n}\n\n@injectable()\nexport class AgentsBackendService {\n\n protected logDebug: (message: string, context?: Record<string, unknown>) => void;\n\n // Bottleneck instances per provider for rate limiting LLM calls\n private readonly bottleneckInstances: Map<string, Bottleneck> = new Map();\n\n /** The installed language-model route and its own limiter, when a host installed one (#3472). */\n private languageModelRoute: { readonly route: LanguageModelAgentClientProtocolRoute; readonly limiter: Bottleneck } | undefined;\n\n constructor(\n @inject(SAAS_SERVICE_TYPES.Logger) private readonly logger: LoggerService,\n @inject(SAAS_SERVICE_TYPES.ErrorBuilderService) private readonly errorBuilder: ErrorBuilderBackendService,\n @inject(SAAS_SERVICE_TYPES.FlowsActorsRegistryService) private readonly flowsActorsRegistry: FlowsActorsRegistryService,\n @inject(SAAS_SERVICE_TYPES.ExternalProvidersRegistryService) private readonly externalProvidersRegistry: ExternalProvidersRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.BackendProviderRegistryService) private readonly backendProviderRegistryService: BackendProviderRegistryBackendService,\n @inject(SAAS_SERVICE_TYPES.PromptCompilerService) private readonly promptCompiler: PromptCompilerBackendService,\n @inject(SAAS_SERVICE_TYPES.AgentCallTraceSink) @optional() private readonly agentTraceSink?: AgentCallTraceSink,\n @inject(SAAS_SERVICE_TYPES.AgentTraceabilityPolicy) @optional() private readonly agentTracePolicy?: AgentTraceabilityPolicy,\n /**\n * OPTIONAL, because an application that declares no MCP server needs neither bound — and an\n * agent with no `mcpRefs` never reaches them. Absence degrades to \"this agent gets its\n * `functionRefs` and nothing else\", which is exactly what it got before #491.\n */\n @inject(SAAS_SERVICE_TYPES.McpClientService) @optional() private readonly mcpClient?: McpClientBackendService,\n @inject(SAAS_SERVICE_TYPES.McpCredentialResolverService) @optional() private readonly mcpCredentialResolver?: McpCredentialResolverBackendService,\n /**\n * OPTIONAL, and feature-detected at every emission. An audit sink that is absent must never fail\n * the act it was going to observe — the same stance the file-scanning lane takes, and the reason\n * an observation is fire-and-forget rather than awaited into the turn's critical path.\n */\n @inject(SAAS_SERVICE_TYPES.AuditLogsService) @optional() private readonly auditLogs?: AuditLogsBackendService,\n /**\n * OPTIONAL for the same reason: a host that binds no recorder still makes its calls. When bound, it\n * is called for EVERY physical call, before the traceability gate below (see\n * `ProviderCallRecorderBackendService` for why the record cannot share that gate).\n */\n @inject(SAAS_SERVICE_TYPES.ProviderCallRecorder) @optional() private readonly providerCallRecorder?: ProviderCallRecorderBackendService,\n /**\n * #2292: the classifier an agent declaring `contentGuardrails.promptInjection` screens its tool results through.\n * OPTIONAL like the two above, and appended LAST (DI positions are order-sensitive); an agent that declares\n * screening refuses to run without it.\n */\n @inject(SAAS_SERVICE_TYPES.ContentSafetyService) @optional() private readonly contentSafety?: ContentSafetyBackendService,\n /**\n * #2292 R8: reads the agent policy of each organization a turn acts for. OPTIONAL and appended LAST: a process\n * with no repository handler holds no tenant rows, so no organization can have tightened anything there.\n */\n @inject(SAAS_SERVICE_TYPES.RepositoriesRegistryHandlerService) @optional() private readonly repositoriesRegistry?: RepositoriesRegistryHandlerBackendService,\n /**\n * #2935: the model-spend meter every call this service makes is charged through, and asked before, when the work it\n * is made in pays per call (a flow's step). OPTIONAL and appended LAST: a host that binds no budget service (a minimal\n * test container) has no allowance to charge or enforce. The engine's own container binds it everywhere, the dev\n * companion's included; a companion call charges nothing because it is made for no organization (no frame, no\n * attribution).\n */\n @inject(SAAS_SERVICE_TYPES.A2ATokenBudgetService) @optional() private readonly modelSpend?: ModelCallSpendMeter,\n /**\n * Where the tool-approval key is read (#2893). OPTIONAL and appended LAST: without it no approval-gated tool can run,\n * which is the fail-closed answer {@link resolveToolApprovalSecretOrThrow} gives.\n */\n @inject(SAAS_SERVICE_TYPES.AppConfigService) @optional() private readonly appConfig?: AppConfigurationService,\n ) {\n this.logDebug = this.logger.debugByType('AgentsBackend');\n this.logger.setDebugTypeLogging('AgentsBackend', false);\n\n this.logDebug('Agents backend service created');\n }\n\n // ================================\n // Structured Data Chunking Utilities\n // ================================\n\n\n private mergeChunkedObjects<T extends Record<string, unknown>>(chunks: T[]): T {\n if (chunks.length === 0) {\n return {} as T;\n }\n if (chunks.length === 1) {\n return chunks[0];\n }\n\n // Deep merge nested objects instead of shallow merge\n const result = { ...chunks[0] } as any;\n\n for (let i = 1; i < chunks.length; i++) {\n const chunk = chunks[i];\n for (const key in chunk) {\n if (chunk.hasOwnProperty(key)) {\n const chunkValue = chunk[key];\n const resultValue = result[key];\n\n // If both values are plain objects, deep merge them\n if (\n chunkValue !== null &&\n typeof chunkValue === 'object' &&\n !Array.isArray(chunkValue) &&\n resultValue !== null &&\n typeof resultValue === 'object' &&\n !Array.isArray(resultValue) &&\n resultValue.constructor === Object &&\n chunkValue.constructor === Object\n ) {\n result[key] = this.mergeChunkedObjects([resultValue, chunkValue]);\n } else {\n // Otherwise, use the chunk value (last one wins for conflicts)\n result[key] = chunkValue;\n }\n }\n }\n }\n\n return result as T;\n }\n\n // ================================\n // Bottleneck Rate Limiting\n // ================================\n\n\n /**\n * Schedule `job` on a provider's limiter, running it in the async context of the CALLER that scheduled it (#2935 review).\n *\n * Bottleneck runs a job from inside its own submission and drain chain, so without the bind a job scheduled while\n * another job is in flight, queued or not, can inherit THAT caller's `AsyncLocalStorage` frames. Measured with the\n * engine's Bottleneck: with one slot, turn B's job queued behind turn A's ran with A's frames; with ten free slots\n * and no queueing at all, B scheduled within a millisecond of A still ran with A's frames. Every frame read inside a\n * model call leaked that way: the spend frame (B's nested agent would be charged to A's organization, and refused\n * under A's requester when A is a flow), the work-attribution frame (B's provider-call cost recorded against A's\n * case), the turn-policy frame (B's guardrails tightened, or loosened, by A's organizations), the agent-actor and\n * relationship-provenance frames, and a database session frame. The last four predate the spend frame; one bind fixes\n * them all. `AsyncResource.bind` captures the context at the call, so the job runs as its own caller whatever drains\n * it.\n */\n private scheduleOnLimiter<T>(limiter: Bottleneck, options: Bottleneck.JobOptions, job: () => Promise<T>): Promise<T> {\n return limiter.schedule(options, AsyncResource.bind(job));\n }\n\n private getBottleneckForProvider(\n providerRef: string,\n protocolKind: ExternalProvider_ExchangeProtocol_Kind = ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER\n ): Bottleneck {\n const limiterKey = `${providerRef}:${protocolKind}`;\n if (this.bottleneckInstances.has(limiterKey)) {\n const existingLimiter = this.bottleneckInstances.get(limiterKey)!;\n this.logDebug('Returning existing bottleneck instance for provider', { providerRef, protocolKind });\n return existingLimiter;\n }\n\n this.logDebug('Creating new bottleneck instance for provider', { providerRef, protocolKind });\n const config = this.externalProvidersRegistry.getProviderConfiguration(providerRef, protocolKind);\n\n const rateLimitConfig = config && 'rateLimitConfig' in config && config.rateLimitConfig\n ? ExternalProvider_RateLimitConfigurationSchema.parse(config.rateLimitConfig)\n : ExternalProvider_RateLimitConfigurationSchema.parse({});\n\n // Create bottleneck options\n const bottleneckOptions: Record<string, number | undefined> = {\n maxConcurrent: rateLimitConfig.maxConcurrent ?? 10,\n minTime: rateLimitConfig.minTime,\n reservoir: rateLimitConfig.reservoir,\n reservoirRefreshInterval: rateLimitConfig.reservoirRefreshInterval,\n reservoirRefreshAmount: rateLimitConfig.reservoirRefreshAmount,\n };\n\n // Remove undefined values\n Object.keys(bottleneckOptions).forEach(key => {\n if (bottleneckOptions[key] === undefined) {\n delete bottleneckOptions[key];\n }\n });\n\n // Create and store bottleneck instance\n const limiter = new Bottleneck(bottleneckOptions);\n\n // Add event listeners for rate limiting visibility\n this.setupBottleneckEventListeners(limiter, limiterKey);\n\n this.bottleneckInstances.set(limiterKey, limiter);\n\n this.logDebug('Bottleneck instance created for provider', {\n providerRef,\n protocolKind,\n maxConcurrent: bottleneckOptions.maxConcurrent,\n minTime: bottleneckOptions.minTime,\n reservoir: bottleneckOptions.reservoir\n });\n\n return limiter;\n }\n\n /**\n * Setup event listeners on bottleneck instance to track rate limiting behavior\n */\n private setupBottleneckEventListeners(limiter: Bottleneck, providerRef: string): void {\n // Track when jobs are queued (delayed due to rate limiting)\n limiter.on('queued', (info: any) => {\n const jobId = info?.options?.id || 'unknown';\n this.logDebug('API call queued (rate limited - will be delayed)', {\n providerRef,\n jobId,\n queued: limiter.queued(),\n running: limiter.running(),\n done: limiter.done(),\n });\n });\n\n // Track when jobs start running (immediate or after queuing)\n limiter.on('executing', (info: any) => {\n const jobId = info?.options?.id || 'unknown';\n this.logDebug('API call executing (running now)', {\n providerRef,\n jobId,\n queued: limiter.queued(),\n running: limiter.running(),\n done: limiter.done(),\n });\n });\n\n // Track when jobs complete\n limiter.on('done', (info: any) => {\n const jobId = info?.options?.id || 'unknown';\n this.logDebug('API call completed through rate limiter', {\n providerRef,\n jobId,\n queued: limiter.queued(),\n running: limiter.running(),\n done: limiter.done(),\n });\n });\n\n // Track when jobs are dropped (queue full or other reasons)\n limiter.on('dropped', (info: any) => {\n const jobId = info?.options?.id || 'unknown';\n this.logger.warn('API call dropped by rate limiter (queue full or limit exceeded)', {\n providerRef,\n jobId,\n queued: limiter.queued(),\n running: limiter.running(),\n });\n });\n\n // Track when reservoir is depleted\n limiter.on('depleted', () => {\n this.logDebug('Rate limiter reservoir depleted (waiting for refresh)', {\n providerRef,\n queued: limiter.queued(),\n running: limiter.running(),\n });\n });\n\n // Track errors in the limiter\n limiter.on('error', (error: any) => {\n this.logger.error('Rate limiter error', {\n providerRef,\n ...projectCaughtErrorLogFields(error),\n stack: error instanceof Error ? error.stack : undefined,\n });\n });\n }\n\n // ================================\n // Agent Invocation\n // ================================\n\n /**\n * @wildo_source:part:start saas.backend.flows-actors.invoke-agent facet:layer:backend facet:family:flows-actors\n *\n * Run ONE agent, once, and await its complete answer. This is the seam an\n * application calls to use its `AI_LLM` capability from its own backend code\n * (a service, a custom resource operation, a batch job).\n *\n * Inject it by DI symbol:\n * `@inject(SAAS_SERVICE_TYPES.AgentsBackendService) private readonly agentsService: AgentsBackendService`\n * — import both from `@wildo-ai/saas-backend-lib`.\n *\n * The engine owns everything around the call: it resolves the agent by\n * `request.agentRef` (unknown ref → throws), refuses a non-`ACTIVE` agent,\n * compiles `promptSpec` into a provider-shaped system prompt, resolves the\n * provider client + API key (fail-closed if unconfigured), schedules the call\n * through that provider's rate limiter, normalizes the output to the\n * operation's wrapped shape, and emits the usage/latency trace. You supply an\n * invocation and read `result.output`.\n *\n * **Function tools do NOT run on this path.** An agent's declared\n * `capabilities.tools.functionRefs` are resolved and executed only by the\n * STREAMING/conversational path ({@link invokeAgentStreaming}). A one-shot\n * agent must therefore receive everything it needs in `request.input` — fetch\n * the data yourself first. Declaring tools here is silently inert, not an error.\n *\n * @param request the invocation envelope (`agentRef` + `input` + empty `output` seed).\n * @param traceContext optional correlation for the agent-call trace sink.\n * @param hostContext backend-owned physical execution context, required only\n * once the selected declared transport is CLI.\n * @returns the same envelope with `output` normalized and `executionContext` enriched.\n * @throws a typed backend error — unknown/inactive agent, an agent an administrator suspended (`AGENT_SUSPENDED`, a\n * CONFLICT, read back with `agentSuspensionRefusalOf`, #2843), missing provider key,\n * missing `input.schema` on a structured call, or a provider failure. A provider failure\n * delivered on a STREAMED operation (`STREAM_TEXT`, `STREAM_STRUCTURED`) throws\n * `AgentModelCallFailedError` instead (exported from `@wildo-ai/saas-backend-lib`, not a\n * backend error: test it with `instanceof`), carrying the provider's error, its HTTP\n * `statusCode` when it refused, and the `usage` of the steps that finished first. Inside a flow run, or\n * outside any turn or flow for work attributed to an organization (your own operation or handler, #2957), a\n * `FEATURE_LIMIT_EXCEEDED` backend error when the organization's model allowance is spent, or `INFRASTRUCTURE`\n * when it cannot be checked, before the model is called (#2935).\n *\n * Every call is charged to the model allowance of the work it is made in (#2935): the conversational turn or flow\n * run around it, else the organization its work is attributed to, whose allowance is also asked before the call\n * (#2957). A call whose provider reported no usage is charged an estimate. Application code needs to do nothing for\n * this, except pass `attribution` when its work is attributed to no organization otherwise.\n */\n public async invokeAgent(\n request: FlowsActors_Agent_Invocation<any, any, any>,\n traceContext?: AgentTraceContext,\n hostContext?: AgentInvocationHostContext,\n ): Promise<FlowsActors_Agent_Invocation<any, any, any>> {\n /** @wildo_source:part:end saas.backend.flows-actors.invoke-agent */\n const startTime = Date.now();\n const callTimestamp = new Date(startTime).toISOString();\n\n this.logDebug('Invoking agent', { agentRef: request.agentRef,hasInput: !!request.input,hasExecutionContext: !!request.executionContext });\n\n const agent = this.flowsActorsRegistry.getAgentOrThrow(request.agentRef);\n\n const organizationScope = await this.buildCallOrganizationScope(request.initiator?.organizationId, traceContext?.attribution);\n await this.validateAgentStatus(agent, organizationScope);\n await this.admitModelSpend(request.agentRef, traceContext);\n\n try {\n const result = await this.executeAgent(agent, request, organizationScope, hostContext);\n this.logDebug('Agent invocation completed', {agentRef: request.agentRef,executionTime: Date.now() - startTime,hasOutput: !!result.output });\n return await this.finalizeInvocationSuccess(request, agent, result, startTime, callTimestamp, traceContext);\n } catch (error) {\n await this.traceInvocationFailure(request, agent, error, startTime, callTimestamp, traceContext);\n throw error;\n }\n }\n\n /**\n * Streaming counterpart of {@link invokeAgent}: runs the agent over the API\n * transport and forwards each token delta through `streamHandlers.onDelta` as\n * it arrives (honest token streaming — no buffer-collapse). The returned\n * invocation carries the fully-assembled, normalized output + enriched\n * `executionContext`, identical in shape to `invokeAgent`, so persistence and\n * tracing are unchanged.\n *\n * Only text-producing operations over the API transport stream. CLI-transport\n * agents and non-text operations (structured / multimodal / image) throw\n * {@link AgentStreamingUnsupportedError}; callers may catch it to fall back to\n * the buffered `invokeAgent`.\n */\n public async invokeAgentStreaming(\n request: FlowsActors_Agent_Invocation<any, any, any>,\n streamHandlers: AgentStreamHandlers,\n toolContext?: FunctionToolExecutionContext,\n traceContext?: AgentTraceContext,\n ): Promise<FlowsActors_Agent_Invocation<any, any, any>> {\n const startTime = Date.now();\n const callTimestamp = new Date(startTime).toISOString();\n\n this.logDebug('Invoking agent (streaming)', { agentRef: request.agentRef, hasToolContext: !!toolContext });\n\n const agent = this.flowsActorsRegistry.getAgentOrThrow(request.agentRef);\n // The organizations the turn works for, the same scope its guardrails are tightened for (`executeAgentStreaming`).\n const organizationScope = await this.buildStreamingCallOrganizationScope(toolContext, request.initiator?.organizationId, traceContext?.attribution);\n await this.validateAgentStatus(agent, organizationScope);\n await this.admitModelSpend(request.agentRef, traceContext);\n\n try {\n const result = await this.executeAgentStreaming(agent, request, streamHandlers, organizationScope, toolContext);\n this.logDebug('Agent streaming invocation completed', { agentRef: request.agentRef, executionTime: Date.now() - startTime });\n return await this.finalizeInvocationSuccess(request, agent, result, startTime, callTimestamp, traceContext);\n } catch (error) {\n await this.traceInvocationFailure(request, agent, error, startTime, callTimestamp, traceContext);\n throw error;\n }\n }\n\n /**\n * A structured answer from ANOTHER agent's provider and model, under instructions of the engine's own (#2720).\n *\n * Some engine steps serve an agent's turn without being that agent: composing the form through which a question the\n * agent raised is asked of a person is one. Such a step runs on the agent's provider and resolved model, because the\n * provider key and the spend are what the application chose for that agent. Its usage is recorded against the\n * work-attribution frame it runs in, so the CALLER runs it inside the frame of the work it serves: the composer's\n * caller re-opens the paused turn's frame (`runWithWorkAttributionFrame`). It has its own instructions and no tools.\n *\n * Nothing is registered. The derived agent exists for this one call, under a ref that says whose model it borrowed\n * (`<agentRef>#<purpose>`), so the trace names it and the application's agent catalog never lists it.\n *\n * Only an LLM agent on the API transport can serve: a coding agent, an image agent and a CLI transport have no\n * structured call. The error says so, and the caller's own fallback decides what happens next.\n *\n * @returns the object the provider produced, re-parsed with `schema`.\n */\n public async generateStructuredOnAgentModel<T extends z.ZodTypeAny>(params: {\n /** The agent whose provider and model the call borrows. */\n agentRef: string;\n /** What the call is for, appended to the derived agent's ref and named in its trace. */\n purpose: string;\n /** The derived agent's role, in place of the borrowed agent's own. */\n role: string;\n instructions: readonly string[];\n prompt: string;\n schema: T;\n traceContext?: AgentTraceContext;\n }): Promise<z.infer<T>> {\n const agent = this.flowsActorsRegistry.getAgentOrThrow(params.agentRef);\n // The organizations the call works for (`buildCallOrganizationScope`): the explicit attribution's, the work frame's, the\n // case's tenant, and the run's requester's. A flow's `agent.call` step names none itself; its run's organization comes\n // from its spend frame. The borrowed agent's suspensions are asked for each (#2843), the call is made for the first,\n // so its guardrails are that organization's and an output-moderation row it leaves is routed there (#2292).\n // Engine-derived throughout, never a caller's.\n const organizationScope = await this.buildCallOrganizationScope(params.traceContext?.attribution?.organizationId, params.traceContext?.attribution);\n await this.validateAgentStatus(agent, organizationScope);\n if (!isLLMAgentConfiguration(agent.config)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: { agentRef: agent.ref, message: 'Only a language-model agent can serve a structured call on its model.' },\n });\n }\n const derived: FlowsActors_Agent = {\n ...agent,\n ref: `${agent.ref}#${params.purpose}`,\n config: { ...agent.config, operationKey: LLMProvider_OperationKey.GENERATE_STRUCTURED },\n operationDefinition: {\n ...agent.operationDefinition,\n operationKey: LLMProvider_OperationKey.GENERATE_STRUCTURED,\n inputSchema: LLMProvider_GenerateStructuredInputSchema,\n outputSchema: LLMProvider_GenerateStructuredOutputSchema,\n },\n promptSpec: { role: params.role, skillType: FlowsActors_Agent_Skill_Type.GENERATION, instructions: [...params.instructions] },\n capabilities: undefined,\n } as FlowsActors_Agent;\n if (this.resolveAgentExecution(derived).transport !== 'api') {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: { agentRef: agent.ref, message: 'A structured call needs the agent to run on the API transport.' },\n });\n }\n await this.admitModelSpend(derived.ref, params.traceContext);\n\n const startTime = Date.now();\n const callTimestamp = new Date(startTime).toISOString();\n const request = {\n agentRef: derived.ref,\n initiator: organizationScope.organizationId ? { organizationId: organizationScope.organizationId } : {},\n invocationContext: [],\n input: { prompt: params.prompt, schema: params.schema },\n output: { object: {} },\n executionContext: { callTimestamp },\n artifactBindings: [],\n } as unknown as FlowsActors_Agent_Invocation<any, any, any>;\n try {\n const result = await this.executeAgent(derived, request, organizationScope);\n const finalized = await this.finalizeInvocationSuccess(request, derived, result, startTime, callTimestamp, params.traceContext);\n return params.schema.parse((finalized.output as { object: unknown }).object) as z.infer<T>;\n } catch (error) {\n await this.traceInvocationFailure(request, derived, error, startTime, callTimestamp, params.traceContext);\n throw error;\n }\n }\n\n /**\n * Shared success finalizer for buffered + streaming invocations: enrich the\n * execution context (timing / usage / transport), normalize the output for the\n * agent's operation, and emit the best-effort policy-gated success trace. Every\n * caller of invokeAgent* — companion, backend flows, minions, workers — gets\n * the trace for free; the sink decides where it lands. See\n * `agent-call-trace-sink.backend.ts`.\n */\n private async finalizeInvocationSuccess(\n request: FlowsActors_Agent_Invocation<any, any, any>,\n agent: FlowsActors_Agent,\n result: AgentExecutionResult,\n startTime: number,\n callTimestamp: string,\n traceContext?: AgentTraceContext,\n ): Promise<FlowsActors_Agent_Invocation<any, any, any>> {\n const executionTime = Date.now() - startTime;\n const finishedAt = new Date().toISOString();\n const executionContext = {\n ...request.executionContext,\n callDuration: executionTime,\n executionTime,\n finishedAt,\n // Parsed by the envelope actually received. A coding run reports context\n // and cost the LLM usage schema does not model, and an ACP transport\n // record is not a member of the LLM transport union — running either\n // through the LLM schemas throws, and it throws AFTER the workspace has\n // been mutated.\n ...(result.usage\n ? {\n usage: isAgentClientProtocolTransport(result.transport)\n ? CodingAgent_UsageSchema.parse(result.usage)\n : LLMProvider_UsageSchema.parse(result.usage),\n }\n : {}),\n ...(result.transport\n ? {\n transport: isAgentClientProtocolTransport(result.transport)\n ? AgentClientProtocol_ExecutionTransportMetadataSchema.parse(result.transport)\n : LLMProvider_ExecutionTransportMetadataSchema.parse(result.transport),\n }\n : {}),\n // A structured generation that produced no object carries the reason it did not.\n // It rides on `executionContext` beside `usage` because that is the envelope the\n // whole invocation contract already publishes for provider-learned facts — and\n // because the trace sink receives this same object as its `context`, so the reason\n // reaches traceability without a second wiring. Parsed rather than spread so a\n // malformed reason cannot silently enter the published contract.\n ...(result.structuredGenerationFailure\n ? { structuredGenerationFailure: LLMProvider_StructuredGenerationFailureSchema.parse(result.structuredGenerationFailure) }\n : {}),\n // #2301: each hand-over of a model call to a declared alternative (who failed, who served, why). It reaches the trace\n // sink with this context; the provider-call record below names the provider and model that answered.\n ...(result.modelFailovers && result.modelFailovers.length > 0 ? { modelFailovers: result.modelFailovers.map((failover) => ({ ...failover })) } : {}),\n };\n const output = this.normalizeOperationOutput(agent.config.operationKey, result.output);\n const servedBy = result.modelFailovers?.at(-1);\n await this.emitAgentCallTrace(\n {\n agentRef: request.agentRef,\n provider: servedBy?.toProviderRef ?? agent.config.providerRef,\n model: servedBy?.toModel ?? agent.config.model,\n callTimestamp,\n outcome: AgentCallOutcome.SUCCESS,\n input: request.input,\n output,\n context: executionContext,\n ...this.personalDataTraceOf(request),\n },\n traceContext,\n this.operationObservationOf(request).snapshot({ failed: false, awaitingDecision: result.approvalSuspension !== undefined }),\n );\n // Carry the approval suspension onto the returned invocation.\n //\n // ⚠️ This method REBUILDS the result rather than spreading it, so anything the execution layer\n // learned that is not `output`/`executionContext` is dropped here by construction. That is what\n // happened to the suspension: it was threaded correctly through the stream reader, the operation\n // and the transport, and then silently lost at this fifth hop — the turn reported COMPLETED with\n // empty text while the tool sat unapproved, which is exactly the outcome the whole feature\n // exists to prevent. The unit pins could not see it because they stub `invokeAgentStreaming` and\n // never reach this method; only the live lane did.\n //\n // Deliberately kept as an explicit field rather than switching to `...result`: this rebuild is\n // intentional (the invocation is the caller's request plus its answer, not the internal\n // execution record), and spreading would leak transport internals onto a public shape.\n return { ...request, output, executionContext, ...(result.approvalSuspension ? { approvalSuspension: result.approvalSuspension } : {}) };\n }\n\n /** Shared failure tracer for buffered + streaming invocations. */\n private async traceInvocationFailure(\n request: FlowsActors_Agent_Invocation<any, any, any>,\n agent: FlowsActors_Agent,\n error: unknown,\n startTime: number,\n callTimestamp: string,\n traceContext?: AgentTraceContext,\n ): Promise<void> {\n await this.emitAgentCallTrace(\n {\n agentRef: request.agentRef,\n provider: agent.config.providerRef,\n model: agent.config.model,\n callTimestamp,\n outcome: AgentCallOutcome.FAILURE,\n input: request.input,\n context: {\n ...request.executionContext,\n executionTime: Date.now() - startTime,\n // A provider failure after finished steps still cost tokens, and the provider-call record\n // prices what the trace carries (#2191). Absent for every other failure, as before.\n ...(modelCallUsageOfFailure(error) ? { usage: LLMProvider_UsageSchema.parse(modelCallUsageOfFailure(error)) } : {}),\n },\n error: this.buildAgentCallTraceError(error),\n ...this.personalDataTraceOf(request),\n },\n traceContext,\n this.operationObservationOf(request).snapshot({ failed: true, error }),\n );\n }\n\n /**\n * #2292: the guard each invocation's tools treated through, by the invocation's request object, so its counts reach the\n * trace on success AND on failure (a failed call still sent its model what the guard let through). Module-level and\n * read through a getter: it holds no state of this instance, and a service built without its constructor reaches it.\n */\n private get personalDataGuards(): WeakMap<object, PersonalDataGuard> {\n return PERSONAL_DATA_GUARD_BY_INVOCATION;\n }\n\n /** #2292: what a call's model was not sent in clear, as its trace carries it; nothing for an unguarded call. */\n private personalDataTraceOf(request: object): { personalData?: AgentCallTrace['personalData'] } {\n const guard = this.personalDataGuards.get(request);\n if (!guard) return {};\n const categories = Object.keys(guard.counts.byCategory).filter((category) => category.length > 0) as PersonalDataCategory[];\n return { personalData: { treatment: guard.treatment, fieldsWithheld: guard.counts.fields, categoriesWithheld: [...sortPersonalDataCategories(categories)] } };\n }\n\n /**\n * #2841: what this invocation is observed doing, for its operation record — created on first use, by the invocation's\n * request object, like its personal-data guard, so every hop that already holds the request (the guards' construction,\n * the stream, the trace emitter) reads the same observation without a new positional argument.\n */\n private operationObservationOf(request: object): AgentOperationObservationRecorder {\n let observation = AGENT_OPERATION_OBSERVATION_BY_INVOCATION.get(request);\n if (!observation) {\n observation = new AgentOperationObservationRecorder();\n AGENT_OPERATION_OBSERVATION_BY_INVOCATION.set(request, observation);\n }\n return observation;\n }\n\n /**\n * #2841: the model the call runs on, wrapped INNERMOST with the observation's middleware, which reads the model id the\n * provider reports from each response. Innermost so a response output moderation withholds still reports its model.\n */\n private observedModel(model: any, observation: AgentOperationObservationRecorder | undefined): any {\n if (!observation) return model;\n return wrapLanguageModel({ model, middleware: observation.middleware() });\n }\n\n /**\n * #2935: ask the model-spend gate before a call, as the payer of the work it is made in (the ambient spend frame). Only\n * a payer whose door is asked per call (a flow's step) can be refused; the refusal is recorded by the gate, and the\n * call fails here with the budget's error, BEFORE anything reaches the provider and before a trace exists (a refused\n * call was not a provider call, so it leaves no provider-call record).\n *\n * #2957: with NO payer (a call an application's own code makes in no turn, no flow and no operation: an inbound\n * handler, a job), the gate is asked for the organization the call would be charged to\n * ({@link organizationOfAttributedWork}, the derivation {@link chargeModelCall} uses), through the door\n * `organization_work`. So the allowance that refuses is the allowance that would have been charged, and an organization\n * whose allowance is spent cannot keep spending through its application's own backend code. A call attributed to no\n * organization, outside any operation, is asked nothing and charged nothing: it is the host's own spend (the dev\n * companion, platform tooling).\n *\n * #2957: a call made inside a RESOURCE OPERATION has the operation's principal as its payer (`resource_operation`, opened\n * by the services registry). That door falls back to the work the call was made for\n * (`modelSpendDoorPayerFallsBackToAttributedWork`), so the work's organization is derived for it too and handed to the\n * gate, which charges and refuses the principal's own allowance, else that organization's, else the application's, and\n * refuses a call none of them can pay for.\n *\n * - spent: `FEATURE_LIMIT_EXCEEDED` (HTTP 403, the plan-limit error), naming the limit and its counts;\n * - not verifiable (the plan or the counter could not be read): `INFRASTRUCTURE` (503, retryable), as the A2A door\n * answers an unverifiable allowance;\n * - no allowance can be named (`PAYER_UNRESOLVED`): `CONFIGURATION`, because the application made a model call from an\n * operation whose principal, work and application pay for nothing. Its remedy is the call site's: name the\n * organization the work is for (`traceContext.attribution`), or run it as a principal that pays.\n *\n * assurance-control: WILDO.AI.MODEL_SPEND_LIMIT — a model call made in work whose door is asked per call (a flow's step), or made in no turn and no flow for an organization, is refused before the model runs once its organization's allowance is spent or unverifiable.\n */\n private async admitModelSpend(agentRef: string, traceContext: AgentTraceContext | undefined): Promise<void> {\n if (!this.modelSpend) return;\n const payer = getCurrentModelSpendFrame();\n const decision = payer && !modelSpendDoorPayerFallsBackToAttributedWork(payer.door)\n ? await this.modelSpend.admitModelCall(payer)\n : await this.modelSpend.admitModelCall(payer, await this.organizationOfAttributedWork(traceContext));\n if (decision.kind === 'ok') return;\n if (decision.reason === A2ATokenBudgetDenialReason.PAYER_UNRESOLVED) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n featureId: A2A_TOKEN_BUDGET_FEATURE_ID,\n reason: decision.reason,\n door: payer?.door ?? ModelSpendDoor.ORGANIZATION_WORK,\n agentRef,\n modelSpendRefusalReason: decision.reason,\n message: 'This model call was made from an operation whose principal, work and application name no model allowance, so the model was not called. Name the organization the work is for in the call\\'s attribution, or make the call as a principal that pays.',\n },\n });\n }\n const spent = decision.reason === A2ATokenBudgetDenialReason.ALLOWANCE_EXHAUSTED;\n throw this.errorBuilder.buildError(spent ? ErrorType.FEATURE_LIMIT_EXCEEDED : ErrorType.INFRASTRUCTURE, undefined, {\n customMessageReference: spent ? ErrorCustomMessageReference.FEATURE_LIMIT_EXCEEDED : ErrorCustomMessageReference.INFRASTRUCTURE,\n context: {\n featureId: A2A_TOKEN_BUDGET_FEATURE_ID,\n reason: decision.reason,\n door: payer?.door ?? ModelSpendDoor.ORGANIZATION_WORK,\n agentRef,\n // Read back by `modelSpendRefusalOf`, so a caller (a flow's step) can tell a spend refusal from a provider failure.\n modelSpendRefusalReason: decision.reason,\n ...(typeof decision.allowanceTokens === 'number' ? { allowanceTokens: decision.allowanceTokens } : {}),\n ...(typeof decision.consumedTokens === 'number' ? { consumedTokens: decision.consumedTokens } : {}),\n message: spent\n ? 'The organization\\'s model allowance for this period is spent, so the model was not called.'\n : 'The organization\\'s model allowance could not be checked, so the model was not called.',\n },\n });\n }\n\n /**\n * #2957: the organization a call's WORK is attributed to, read before the call, for a call with no payer or a payer\n * whose door falls back to its work (a resource operation): the call site's explicit attribution, else the ambient\n * work frame (`resolveModelCallAttribution`), with a named work-unit case's own tenant winning\n * (`ProviderCallRecorderBackendService.organizationOfAttribution`, which never throws). The same derivation\n * {@link chargeModelCall} makes after the call, so the allowance asked and the allowance charged cannot differ.\n * `undefined` when the call is attributed to no organization.\n */\n private async organizationOfAttributedWork(traceContext: AgentTraceContext | undefined): Promise<string | undefined> {\n const attribution = resolveModelCallAttribution(traceContext?.attribution, getCurrentWorkAttributionFrame()).attribution;\n if (!attribution.caseRef || !this.providerCallRecorder) return attribution.organizationId;\n return this.providerCallRecorder.organizationOfAttribution(attribution);\n }\n\n /**\n * #2935: charge one model call to the payer of the work it was made in: the spend frame (a turn's or a flow run's door\n * and principal), else the organization the call's cost record names (the call site's explicit attribution, else the\n * ambient work frame, with a named work-unit case's own tenant winning, as the provider-call recorder derives it), else\n * nobody (a call made for no organization). The ONE place a model call's tokens reach an\n * allowance, for every entry point of this service, on success and on failure.\n *\n * The tokens are the provider's reported total, else the sum of the counters it reported, else a coding transport's\n * `contextUsed` (a lower bound). A successful call whose report the provider marked incomplete is charged the larger\n * of what it reported and the estimate. A call that SUCCEEDED and reported none is charged an estimate from what it\n * sent and returned (`estimateModelCallTokens`, decided at that module): never nothing, never refused. A call\n * that FAILED and reported none is charged nothing: the provider answered with an error before any step finished, and\n * a provider does not bill a request it refused. A failure after finished steps carries their usage, and is charged it.\n *\n * Never throws: metering must not fail a call that already ran.\n *\n * assurance-control: WILDO.AI.MODEL_SPEND_LIMIT — every model call the agent service makes is charged to the allowance of the work it was made in, a call that reported no usage at an estimate.\n */\n private chargeModelCall(trace: AgentCallTrace, traceContext: AgentTraceContext | undefined): void {\n const meter = this.modelSpend;\n if (!meter) return;\n try {\n const reportedTokens = reportedModelCallTokens(trace.context);\n const succeeded = trace.outcome === AgentCallOutcome.SUCCESS;\n // A call that succeeded ran, so it is charged at least one token even when it sent and returned nothing readable.\n const estimateOf = (): number => Math.max(1, estimateModelCallTokens(trace.input, trace.output));\n // No report: the estimate. A report the provider marked incomplete (an image model counting its input, not its\n // output): the larger of the two, so a partial count is never the whole charge.\n const estimated = succeeded && (reportedTokens === undefined || modelCallUsageIsPartial(trace.context));\n const totalTokens = reportedTokens === undefined\n ? (succeeded ? estimateOf() : 0)\n : (estimated ? Math.max(reportedTokens, estimateOf()) : reportedTokens);\n if (!(totalTokens > 0)) return;\n // Read synchronously: the frames belong to the call being charged.\n const payer = getCurrentModelSpendFrame();\n const attribution = resolveModelCallAttribution(traceContext?.attribution, getCurrentWorkAttributionFrame()).attribution;\n const charge = (attributedOrganizationId: string | undefined): void => meter.recordModelCallSpend({\n payer, attributedOrganizationId, totalTokens, estimated, agentRef: trace.agentRef,\n });\n // With no payer, or a payer whose door falls back to its work (#2957: a resource operation), the organization is the\n // one the call's cost record names: a named case's own tenant wins over the frame's\n // (`ProviderCallRecorderBackendService.organizationOfAttribution`, the recorder's own derivation). A work unit's\n // operation frame carries the case and no tenant, so without this the call would be charged to nobody.\n // `organizationOfAttributedWork` is the same derivation, asked before the call (#2957).\n const chargedFromWork = !payer || modelSpendDoorPayerFallsBackToAttributedWork(payer.door);\n if (!chargedFromWork || !attribution.caseRef || !this.providerCallRecorder) {\n charge(attribution.organizationId);\n return;\n }\n void this.providerCallRecorder.organizationOfAttribution(attribution).then(charge, (error: unknown) => {\n this.logger.warn('A model call could not be charged to its allowance (non-fatal)', { agentRef: trace.agentRef, ...projectCaughtErrorLogFields(error) });\n });\n } catch (error) {\n this.logger.warn('A model call could not be charged to its allowance (non-fatal)', { agentRef: trace.agentRef, ...projectCaughtErrorLogFields(error) });\n }\n }\n\n /**\n * Emit one agent-call trace to the configured sink — best-effort and gated by\n * the resolved policy level (per-call `levelOverride` wins; default `NONE` →\n * skip, so output is byte-identical when traceability is off). A sink failure\n * is swallowed (debug-logged): tracing must never turn a successful agent call\n * into a failed one.\n */\n private async emitAgentCallTrace(\n trace: AgentCallTrace,\n traceContext?: AgentTraceContext,\n /** #2841: what the invocation was observed doing, for its operation record beside the provider-call record. */\n operation?: AgentOperationObservation,\n ): Promise<void> {\n // #2935: the call's spend, synchronously and before any await, so it reads the frames of the call it is charging.\n this.chargeModelCall(trace, traceContext);\n // The provider-call RECORD first, ungated: evidence of the call must not depend on whether an\n // observability provider raised the traceability level. The recorder never throws. Its attribution\n // (#1598) is the call site's explicit `traceContext.attribution`, else the ambient work frame. The operation\n // (#2841) is not part of the trace: sinks receive the trace as before, and only the recorder's store receives it.\n // assurance-control: WILDO.AI.OPERATION_RECORD — the invocation's observation reaches the recorder (when the container\n // binds one) on success and on failure, before and whatever the traceability level.\n await this.providerCallRecorder?.record(trace, traceContext?.attribution ? { attribution: traceContext.attribution } : undefined, operation);\n const sink = this.agentTraceSink;\n if (!sink) {\n return;\n }\n const level = traceContext?.levelOverride ?? this.agentTracePolicy?.level ?? AgentTraceabilityLevel.NONE;\n if (level === AgentTraceabilityLevel.NONE) {\n return;\n }\n try {\n await sink.recordAgentCall({ trace, level, context: traceContext });\n } catch (err) {\n this.logDebug('Agent-call trace sink failed (non-fatal)', {\n agentRef: trace.agentRef,\n ...projectCaughtErrorLogFields(err),\n });\n }\n }\n\n /** Build the JSON-serializable trace error shape from a thrown value. */\n private buildAgentCallTraceError(error: unknown): AgentCallTraceError {\n if (error instanceof Error) {\n const code = (error as Error & { code?: string }).code;\n return {\n name: error.name,\n message: error.message,\n ...(code ? { code } : {}),\n };\n }\n // A non-Error, non-string throw still carries information — a JSON-RPC error object, a refusal\n // shape. Serialize it (bounded) rather than replacing it with a sentence that says nothing.\n if (typeof error === 'string') return { message: error };\n try {\n const serialized = JSON.stringify(error);\n if (serialized && serialized !== '{}') return { message: `Non-Error thrown: ${serialized.slice(0, 500)}` };\n } catch { /* circular or hostile — fall through to the sentinel */ }\n return { message: 'Unknown agent invocation error' };\n }\n\n /**\n * Normalize executor outputs to the shared transport-neutral LLM contract.\n *\n * The current execution helpers naturally produce provider/raw payloads such as\n * plain strings or plain objects. Downstream consumers, however, already rely on\n * the wrapped shared schemas (`{ text }`, `{ object }`, `{ message }`, etc.).\n * Centralizing the normalization here fixes the runtime boundary once instead of\n * forcing every caller to guess the provider-shaped payload.\n */\n private normalizeOperationOutput(\n operationKey: LLMProvider_OperationKey | ImageProvider_OperationKey | CodingAgent_OperationKey,\n output: unknown,\n ): unknown {\n // Image outputs (`{ images }`) are already shaped by executeImageAgent, and\n // coding outputs (`{ finalMessage, stopReason, … }`) by the ACP executor —\n // both are produced in their published shape rather than as a raw provider\n // payload, so both fall through the `default` arm unchanged. Only the LLM\n // arms need wrapping, because only they receive a bare string or object.\n switch (operationKey) {\n case LLMProvider_OperationKey.GENERATE_TEXT:\n if (this.isRecord(output) && typeof output.text === 'string') {\n return output;\n }\n return { text: typeof output === 'string' ? output : JSON.stringify(output ?? '') };\n\n case LLMProvider_OperationKey.CHAT_COMPLETION:\n case LLMProvider_OperationKey.CHAT_MULTIMODAL:\n if (this.isRecord(output) && this.isRecord(output.message)) {\n return output;\n }\n return {\n message: {\n role: LLMProvider_MessageRole.ASSISTANT,\n content: typeof output === 'string' ? output : JSON.stringify(output ?? ''),\n },\n };\n\n case LLMProvider_OperationKey.GENERATE_STRUCTURED:\n if (this.isRecord(output) && 'object' in output) {\n return output;\n }\n return { object: output };\n\n case LLMProvider_OperationKey.STREAM_TEXT:\n if (this.isRecord(output) && typeof output.textDelta === 'string') {\n return output;\n }\n return { textDelta: typeof output === 'string' ? output : JSON.stringify(output ?? '') };\n\n case LLMProvider_OperationKey.STREAM_STRUCTURED:\n if (this.isRecord(output) && ('object' in output || 'partialObject' in output)) {\n return output;\n }\n return { object: output };\n\n default:\n return output;\n }\n }\n\n private isRecord(value: unknown): value is Record<string, any> {\n return typeof value === 'object' && value !== null;\n }\n\n /**\n * Execute agent with LLM provider using @ai-sdk\n */\n private async executeAgent(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n /** The organizations the call works for, as its entry point derived them for its admission. */\n organizationScope: ModelCallOrganizationScope,\n hostContext?: AgentInvocationHostContext,\n ): Promise<AgentExecutionResult> {\n this.logDebug('Executing agent', {\n agentRef: agent.ref,\n operationKey: agent.config.operationKey,\n providerRef: agent.config.providerRef,\n model: agent.config.model,\n executionProfileRef: agent.config.executionProfileRef,\n });\n\n // Modality dispatch: an image agent routes to the IMAGE_PROVIDER path.\n // AUDIO/VIDEO modalities are reserved — their configs have no arm yet, so\n // they cannot reach here; if one ever does, `executeImageAgent`'s provider\n // resolution fail-closes. The LLM/text + CLI path below is unchanged.\n if (isImageAgentConfiguration(agent.config)) {\n return this.executeImageAgent(agent, request);\n }\n\n // A coding agent routes to the ACP session transport. It produces no\n // artifact modality — its product is a changed workspace — so it is\n // dispatched by its own arm rather than by an artifact-modality branch.\n if (isCodingAgentConfiguration(agent.config)) {\n return this.executeAgentViaACP(agent, request, hostContext);\n }\n\n const execution = this.resolveAgentExecution(agent);\n\n if (execution.transport === 'acp') {\n // Unreachable in practice: a coding agent is dispatched by its arm above,\n // before prompts are compiled. Kept so the transport union is handled\n // exhaustively here rather than falling into the API branch, which is\n // what an unhandled member would silently do. It compiles its own prompts.\n return this.executeAgentViaACP(agent, request, hostContext);\n }\n\n // #2292 R8: the guardrails as the organizations this call works for tightened them: the scope its admission was asked\n // for, so a call is tightened by exactly the organizations whose suspensions it answered to.\n const guarded = await this.agentUnderTurnPolicies(agent, organizationScope);\n const outputModeration = this.outputModerationGuardOf(guarded, { initiator: request.initiator, observation: this.operationObservationOf(request) });\n // Compiled once the route is decided, because the route decides how a conversation reaches the model: a routed call\n // has one prompt, an API call the operation's own channel (`CONVERSATION_DELIVERY_OF_OPERATION`).\n if (this.languageModelRouteServes(guarded, execution.operationKey, request.input, outputModeration)) {\n const routedPrompts = await this.buildExecutionPrompts(agent, request, ConversationDelivery.SINGLE_PROMPT);\n return this.executeLanguageModelOperationViaACP(guarded, request, execution.operationKey, routedPrompts);\n }\n const prompts = await this.buildExecutionPrompts(agent, request, CONVERSATION_DELIVERY_OF_OPERATION[execution.operationKey]);\n return this.executeAgentViaApi(guarded, request, execution, prompts, outputModeration);\n }\n\n /**\n * Execute an IMAGE-modality agent via an `IMAGE_PROVIDER` transport.\n *\n * Mirrors the LLM API path (provider-enabled check → apiKey → SDK client →\n * rate-limited call) but resolves the `IMAGE_PROVIDER` binding and calls the\n * AI-SDK `experimental_generateImage` against `client.imageModel(model)`.\n * Image-generation parameters come from the image config arm (`size` /\n * `quality` / `background` / `outputFormat` / `n`), NOT LLM sampling.\n *\n * Usage is the image model's own token report when it makes one (#2935);\n * transport metadata is not populated (the shared `executionContext` schema\n * is LLM-shaped). The best-effort agent-call trace still records\n * provider/model/input/output.\n */\n private async executeImageAgent(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n ): Promise<AgentExecutionResult> {\n const config = agent.config as FlowsActors_Agent_ImageConfiguration;\n const providerRef = config.providerRef;\n const protocolKind = ExternalProvider_ExchangeProtocol_Kind.IMAGE_PROVIDER;\n\n if (!this.externalProvidersRegistry.isProviderEnabled(providerRef, protocolKind)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_PROVIDER_NOT_ENABLED,\n // CLIENT-VISIBLE since 2026-09-18: both are allow-listed in `sanitizeErrorForClient`, because a\n // refusal that does not name the provider it refused cannot be acted on (#1304).\n context: { providerRef, protocolKind },\n });\n }\n\n const apiKey = this.externalProvidersRegistry.getProviderApiKey(providerRef, protocolKind);\n if (!apiKey) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { providerRef, protocolKind, message: this.externalProvidersRegistry.describeMissingProviderApiKey(providerRef, protocolKind) },\n });\n }\n\n const binding = this.backendProviderRegistryService.getProtocolBinding(providerRef, protocolKind);\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.IMAGE) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: { providerRef, message: 'Image runtime contract not available for provider' },\n });\n }\n\n // #3425: a service-account image arm (Vertex Imagen) is handed a token minted from the key, never the key, with its\n // deployment parameters read from their declared slots, through the resolver the LLM and embeddings arms share.\n const imageContext = this.sdkFactoryContextOf(providerRef, binding.runtimeContract, 'image');\n const resolvedImageCredential = await this.resolveAiSdkCredential(providerRef, protocolKind, binding.runtimeContract, apiKey);\n const client: any = await binding.runtimeContract.sdkFactory(resolvedImageCredential.credential, {\n ...imageContext,\n ...(resolvedImageCredential.deploymentParameters === undefined ? {} : { deploymentParameters: resolvedImageCredential.deploymentParameters }),\n });\n if (typeof client?.imageModel !== 'function') {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_IMAGE_GENERATION_NOT_SUPPORTED,\n context: { providerRef }, // diagnostic (log-only)\n });\n }\n\n const input = request.input as { prompt?: unknown; referenceImages?: unknown } | undefined;\n const prompt = typeof input?.prompt === 'string' ? input.prompt : String(request.input ?? '');\n if (prompt.length === 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_IMAGE_PROMPT_REQUIRED,\n context: { agentRef: agent.ref }, // diagnostic (log-only)\n });\n }\n\n const providerOptions: Record<string, any> = {};\n const openaiOptions: Record<string, any> = {};\n if (config.quality) openaiOptions.quality = config.quality;\n if (config.background) openaiOptions.background = config.background;\n if (config.outputFormat) openaiOptions.output_format = config.outputFormat;\n if (Object.keys(openaiOptions).length > 0) providerOptions.openai = openaiOptions;\n\n // `any` on the args object sidesteps the SDK's strict `${number}x${number}`\n // size template-literal type (our `size` is an enum incl. `auto`); the\n // rest of this service uses the same `any` pragmatism for model/options.\n const genArgs: any = {\n // #3204: a refused account is final inside the SDK's retry loop, as for a language model.\n model: wrapImageModel({ model: client.imageModel(config.model), middleware: IMAGE_MODEL_PROVIDER_ACCOUNT_REFUSAL_IS_FINAL }),\n prompt,\n ...(config.n !== undefined ? { n: config.n } : {}),\n ...(config.size !== undefined ? { size: config.size } : {}),\n ...(config.seed !== undefined ? { seed: config.seed } : {}),\n ...(Object.keys(providerOptions).length > 0 ? { providerOptions } : {}),\n };\n\n const limiter = this.getBottleneckForProvider(providerRef, protocolKind);\n const jobId = `${agent.ref}-image-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n let result: any;\n try {\n result = await this.scheduleOnLimiter(limiter, { id: jobId }, () => generateImage(genArgs));\n } catch (error) {\n // #3204: a provider account's refusal (no credits, a spend limit) is classified like every other model call's;\n // any other failure reaches the caller exactly as before.\n if (readModelProviderAccountRefusal(error, providerRef) === undefined) throw error;\n const errorDetails = this.extractProviderErrorDetails(error);\n this.logger.error('Image generation refused by the provider account', { operation: 'GENERATE_IMAGE', providerRef, ...errorDetails });\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'GENERATE_IMAGE',\n message: `Failed to generate an image: ${errorDetails.errorMessage}`,\n }, providerRef);\n }\n\n const rawImages: any[] = Array.isArray(result?.images) && result.images.length > 0\n ? result.images\n : (result?.image ? [result.image] : []);\n const images = rawImages\n .filter((img) => img && typeof img.base64 === 'string')\n .map((img) => ({\n base64: img.base64 as string,\n mediaType: typeof img.mediaType === 'string' ? img.mediaType : 'image/png',\n }));\n\n const output: ImageProvider_GenerateImageOutput = { images };\n // #2935: the tokens the image model reported (AI SDK `generateImage().usage`), so the call is charged what it spent.\n // A model that reports none leaves `usage` absent and is charged an estimate (`chargeModelCall`); an all-undefined\n // report must not become a zero, which would read as a call that cost nothing.\n const imageUsage = result?.usage;\n const reportsTokens = [imageUsage?.inputTokens, imageUsage?.outputTokens, imageUsage?.totalTokens].some((count) => typeof count === 'number' && count > 0);\n return { output, ...(reportsTokens ? { usage: this.extractUsage(imageUsage) } : {}) };\n }\n\n private resolveAgentExecution(agent: FlowsActors_Agent): ResolvedAgentExecution {\n const providerRef = agent.config.providerRef;\n const operationKey = agent.config.operationKey as LLMProvider_OperationKey;\n const executionProfileRef = agent.config.executionProfileRef;\n\n // The CODING arm resolves first and by its own arm, not by the presence of\n // an `executionProfileRef`. Both transports use that field, so ordering by\n // it would route a coding agent into the CLI branch and fail obscurely.\n if (isCodingAgentConfiguration(agent.config)) {\n const codingConfig = agent.config;\n const acpExecutionProfileRef = codingConfig.executionProfileRef;\n const executionProtocolKind = ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL;\n if (!this.externalProvidersRegistry.isProviderEnabled(providerRef, executionProtocolKind)) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef,\n protocolKind: executionProtocolKind,\n executionProfileRef: acpExecutionProfileRef,\n message: 'Agent Client Protocol is not enabled for the selected provider',\n },\n });\n }\n\n const acpProfile = this.externalProvidersRegistry.getAgentClientProtocolProfile(providerRef);\n const acpExecutionProfile = this.externalProvidersRegistry.getAgentClientProtocolExecutionProfile(\n providerRef,\n acpExecutionProfileRef,\n );\n if (!acpProfile || !acpExecutionProfile) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef,\n executionProfileRef: acpExecutionProfileRef,\n message: 'ACP protocol metadata or execution profile not found in provider configuration',\n },\n });\n }\n\n return {\n transport: 'acp',\n providerRef,\n operationKey: codingConfig.operationKey,\n executionProfileRef: acpExecutionProfileRef,\n acpProfile,\n acpExecutionProfile,\n };\n }\n\n const semanticProtocolKind = ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER;\n if (!this.externalProvidersRegistry.isProviderEnabled(providerRef, semanticProtocolKind)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_PROVIDER_NOT_ENABLED,\n context: {\n providerRef,\n protocolKind: semanticProtocolKind,\n }\n });\n }\n\n const supportedLLMOperations = this.externalProvidersRegistry.getLLMSemanticOperationKeys(providerRef);\n if (supportedLLMOperations.length === 0) {\n throw this.errorBuilder.buildError(ErrorType.NOT_FOUND, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_PROVIDER_NOT_FOUND,\n context: {\n providerRef,\n }\n });\n }\n\n if (!supportedLLMOperations.includes(operationKey)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_OPERATION_NOT_SUPPORTED,\n context: {\n providerRef,\n operationKey,\n }\n });\n }\n\n return {\n transport: 'api',\n providerRef,\n operationKey,\n llmProviderConfig: this.externalProvidersRegistry.getProviderConfiguration(\n providerRef,\n semanticProtocolKind,\n ) as LLMProvider_Configuration | undefined,\n };\n }\n\n /**\n * The system prompt and the instructions one call sends. `delivery` is how THIS call carries a conversation input:\n * the instructions are the current turn when the conversation travels as `messages`, and the rendered transcript when\n * the call has one text channel (`invocationInstructionsOf`). A conversation is already the bounded replay (#2750), so\n * the history reaches the model once, through that replay, and never also inside the compiled user prompt.\n */\n private async buildExecutionPrompts(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n delivery: ConversationDelivery,\n ): Promise<CompiledExecutionPrompts> {\n const rawInstructions = invocationInstructionsOf(request.input, delivery);\n\n if (agent.promptSpec) {\n const compiled = await this.buildCompiledPrompts(agent, request, rawInstructions);\n return {\n systemPrompt: compiled.systemPrompt,\n instructions: compiled.userPrompt,\n };\n }\n\n return {\n systemPrompt: this.buildSystemPrompt(agent, request),\n instructions: rawInstructions,\n };\n }\n\n /**\n * Resolve the AI-SDK provider client for an API-transport LLM call (shared by\n * the buffered and streaming API paths): fetch the provider API key\n * (fail-closed if missing) and build the SDK client (fail-closed if the\n * provider is not available).\n */\n private async resolveApiProviderClient(providerRef: string): Promise<any> {\n const apiKey = this.externalProvidersRegistry.getProviderApiKey(\n providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER\n );\n if (!apiKey) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef,\n protocolKind: ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n message: this.externalProvidersRegistry.describeMissingProviderApiKey(providerRef, ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER),\n }\n });\n }\n\n const aiProvider = await this.getAIProvider(providerRef, apiKey);\n if (!aiProvider) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n providerRef,\n message: 'AI SDK provider not available'\n }\n });\n }\n return aiProvider;\n }\n\n private async executeAgentViaApi(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n execution: Extract<ResolvedAgentExecution, { transport: 'api' }>,\n prompts: CompiledExecutionPrompts,\n outputModeration?: OutputModerationGuard,\n ): Promise<AgentExecutionResult> {\n const aiProvider = await this.resolveApiProviderClient(execution.providerRef);\n\n const limiter = this.getBottleneckForProvider(\n execution.providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER\n );\n const jobId = `${agent.ref}-api-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n\n this.logDebug('Scheduling API call through rate limiter', {\n agentRef: agent.ref,\n providerRef: execution.providerRef,\n operationKey: execution.operationKey,\n model: agent.config.model,\n jobId,\n currentQueueSize: limiter.queued(),\n currentRunning: limiter.running(),\n usesPromptCompiler: !!agent.promptSpec,\n });\n\n const modelFailovers: ModelCallFailover[] = [];\n const result = await this.scheduleOnLimiter(\n limiter,\n { id: jobId },\n () => this.executeOperation({\n providerClient: aiProvider,\n providerRef: execution.providerRef,\n config: agent.config,\n operationKey: execution.operationKey,\n systemPrompt: prompts.systemPrompt,\n instructions: prompts.instructions,\n input: request.input,\n llmProviderConfig: execution.llmProviderConfig,\n outputModeration,\n operationObservation: this.operationObservationOf(request),\n modelFailovers,\n })\n );\n\n return {\n ...result,\n ...this.apiTransportOf(execution.providerRef, agent.config.model, modelFailovers),\n };\n }\n\n /**\n * The transport an API call reports, and its model failovers (#2301): the provider and model that answered the final\n * step (the last hand-over's target, else the agent's own), and every hand-over in order.\n */\n private apiTransportOf(\n providerRef: string,\n model: string | undefined,\n modelFailovers: readonly ModelCallFailover[],\n ): Pick<AgentExecutionResult, 'transport' | 'modelFailovers'> {\n const served = modelFailovers.at(-1);\n return {\n transport: {\n kind: LLMProvider_ExecutionTransportKind.API,\n protocolKind: ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n providerRef: served?.toProviderRef ?? providerRef,\n model: served?.toModel ?? model,\n },\n ...(modelFailovers.length > 0 ? { modelFailovers: [...modelFailovers] } : {}),\n };\n }\n\n /**\n * Get AI SDK provider client configured with API key.\n *\n * Looks up the provider's `LLM_PROVIDER` runtime contract on the\n * backend provider registry, narrows by `kind: ProviderProtocolRuntimeKind.LLM`, and invokes the\n * `sdkFactory` declared on the contract. Per the framework principle\n * (provider behavior lives on the provider module), there is NO\n * `switch (providerRef)` here: adding a new LLM provider only requires\n * authoring its module with an `sdkFactory`.\n *\n * Returns the provider client (typically `{ languageModel(model): … }`)\n * or `null` when the provider has no LLM_PROVIDER binding (i.e. the\n * caller asked for an LLM client of a non-LLM provider).\n */\n private async getAIProvider(providerRef: string, apiKey: string): Promise<any> {\n try {\n const binding = this.backendProviderRegistryService.getProtocolBinding(\n providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n );\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.LLM) {\n return null;\n }\n const context = this.sdkFactoryContextOf(providerRef, binding.runtimeContract, 'LLM');\n // #3425: a service-account arm is handed a bearer token minted from the key, never the key; deployment parameters\n // (a project, a location) are read from their declared slots here, so the module never reads the environment.\n const resolved = await this.resolveAiSdkCredential(providerRef, ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER, binding.runtimeContract, apiKey);\n return await binding.runtimeContract.sdkFactory(resolved.credential, {\n ...context,\n ...(resolved.deploymentParameters === undefined ? {} : { deploymentParameters: resolved.deploymentParameters }),\n // #3780: a signing arm's SDK signs each request with these; its credential argument is empty.\n ...(resolved.requestSigningCredentials === undefined ? {} : { requestSigningCredentials: resolved.requestSigningCredentials }),\n });\n } catch (error) {\n this.logger.error('Failed to initialize AI provider', { providerRef, ...projectCaughtErrorLogFields(error) });\n throw error;\n }\n }\n\n /**\n * The credential and deployment parameters an AI arm's `sdkFactory` is called with (#3425), through the one resolver\n * the embeddings service shares: the slot's value, or a bearer token minted from the service-account key in it, and\n * the declared parameters read from their slots. A key or parameter that cannot be used is a CONFIGURATION error, a\n * token endpoint that refused or could not be reached an EXTERNAL_SERVICE one; neither message quotes the key.\n */\n private async resolveAiSdkCredential(\n providerRef: string,\n protocolKind: ExternalProvider_ExchangeProtocol_Kind,\n arm: Parameters<typeof resolveProviderAiSdkCredential>[0]['arm'],\n apiKey: string,\n ): Promise<Awaited<ReturnType<typeof resolveProviderAiSdkCredential>>> {\n try {\n return await resolveProviderAiSdkCredential({\n providerRef,\n arm,\n secretValue: apiKey,\n readSlot: (envVarName) => this.externalProvidersRegistry.getProviderSecret(providerRef, protocolKind, envVarName),\n });\n } catch (error) {\n if (!(error instanceof ProviderClientCredentialsTokenError)) throw error;\n const configuration = error.failure === ProviderClientCredentialsTokenFailure.NOT_CONFIGURED;\n throw this.errorBuilder.buildError(configuration ? ErrorType.CONFIGURATION : ErrorType.EXTERNAL_SERVICE, undefined, {\n customMessageReference: configuration ? ErrorCustomMessageReference.CONFIGURATION : ErrorCustomMessageReference.EXTERNAL_SERVICE,\n context: { providerRef, protocolKind, message: error.message },\n });\n }\n }\n\n /**\n * The context an LLM or image arm's `sdkFactory` is called with: the base URL the engine resolved for it (#2518). A\n * fixed `baseUrl`, or `https://<host>` from the arm's declared host slot through `resolveProviderContractBaseUrl`, the\n * rule the document-extraction, content-safety and embeddings arms share, so a deployment host is admitted the same way\n * on every arm and a loopback double reaches a model only in development and test (#2991). An arm naming both sources\n * or neither, or a host that is unset or refused, is a CONFIGURATION error: the factory is never called with a guess.\n */\n private sdkFactoryContextOf(providerRef: string, contract: ProviderContractEndpointFields, contractLabel: string): ProviderSdkFactoryContext {\n const endpoint = resolveProviderContractBaseUrl({\n providerRef,\n contractLabel,\n contract,\n hostAdmission: () => ({\n declaredSlots: this.externalProvidersRegistry.getProviderSecretSlots(providerRef),\n environment: this.externalProvidersRegistry.getDeclaredApplicationEnvironment(),\n }),\n });\n if ('refusal' in endpoint) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { providerRef, message: endpoint.refusal },\n });\n }\n return { baseUrl: endpoint.baseUrl };\n }\n\n /**\n * The tool kinds shared by the profile and invocation policies. Reads and edits\n * are disjoint sets: an edit-only profile requested as read-only admits neither.\n * A display rank cannot express this intersection without granting new authority.\n * assurance-control: WILDO.SOFTWARE.AI_PRODUCED_CHANGE_CONTROL — a run may ask for less autonomy than its execution profile declares, never more.\n */\n private resolveEffectivePermissionCeiling(\n profile: AgentClientProtocol_ExecutionProfile,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n ): AgentClientProtocol_PermissionCeiling {\n const requested = (request.input as { requestedPermissionCeiling?: AgentClientProtocol_PermissionCeiling } | undefined)\n ?.requestedPermissionCeiling;\n if (\n requested === undefined\n || !Object.values(AgentClientProtocol_PermissionCeiling).includes(requested)\n ) {\n return profile.permissionCeiling;\n }\n const permitted = profile.permissionCeiling;\n if (requested === permitted) return permitted;\n if (requested === AgentClientProtocol_PermissionCeiling.PROMPT_ALWAYS\n || permitted === AgentClientProtocol_PermissionCeiling.PROMPT_ALWAYS) {\n return AgentClientProtocol_PermissionCeiling.PROMPT_ALWAYS;\n }\n if (permitted === AgentClientProtocol_PermissionCeiling.UNRESTRICTED) return requested;\n if (requested === AgentClientProtocol_PermissionCeiling.UNRESTRICTED) return permitted;\n if (permitted === AgentClientProtocol_PermissionCeiling.AUTO_ACCEPT_READS_AND_EDITS) return requested;\n if (requested === AgentClientProtocol_PermissionCeiling.AUTO_ACCEPT_READS_AND_EDITS) return permitted;\n // The only remaining current pair is READS versus EDITS, in either direction.\n return AgentClientProtocol_PermissionCeiling.PROMPT_ALWAYS;\n }\n\n /**\n * The environment gate for the ACP transport — the guard that keeps a\n * workspace-mutating agent out of production. Checked before the limiter and\n * before any spawn.\n * assurance-control: WILDO.SOFTWARE.AI_PRODUCED_CHANGE_CONTROL — a coding agent runs only in an application environment its execution profile admits, and never on a guessed one.\n */\n private validateAgentClientProtocolPolicy(\n execution: Extract<ResolvedAgentExecution, { transport: 'acp' }>,\n ): void {\n const declaredApplicationEnv = readDeclaredApplicationEnvironment(process.env);\n if (declaredApplicationEnv === undefined) {\n // The gate that keeps a workspace-mutating agent out of production cannot run on a guess (#982). It used to read an\n // unset variable as development, which admitted every profile that allows development — wherever it ran.\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n message: `ACP execution refused: ${APPLICATION_ENV_UNDECLARED_MESSAGE}`,\n },\n });\n }\n const applicationEnv = declaredApplicationEnv as string as APPLICATION_ENVIRONMENT;\n const platformEnvironmentId = process.env.PLATFORM_ENVIRONMENT_ID;\n const { acpExecutionProfile } = execution;\n\n if (!acpExecutionProfile.allowedApplicationEnvironments.includes(applicationEnv)) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n applicationEnv,\n allowedApplicationEnvironments: acpExecutionProfile.allowedApplicationEnvironments,\n message: 'ACP execution profile is not allowed in the current application environment',\n },\n });\n }\n\n if (\n acpExecutionProfile.allowedPlatformEnvironmentIds?.length\n && (!platformEnvironmentId || !acpExecutionProfile.allowedPlatformEnvironmentIds.includes(platformEnvironmentId))\n ) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n platformEnvironmentId,\n allowedPlatformEnvironmentIds: acpExecutionProfile.allowedPlatformEnvironmentIds,\n message: 'ACP execution profile is not allowed in the current platform environment',\n },\n });\n }\n }\n\n /**\n * Compose the prompt a subprocess-hosted agent receives on its single input\n * channel: the system prompt, then the instructions.\n */\n private buildSubprocessPromptInput(prompts: CompiledExecutionPrompts): string {\n if (!prompts.systemPrompt.trim()) {\n return prompts.instructions;\n }\n\n return [\n '[SYSTEM]',\n prompts.systemPrompt,\n '',\n '[TASK]',\n prompts.instructions,\n ].join('\\n');\n }\n\n /**\n * The child environment for a spawned agent: a minimal identity allowlist plus\n * exactly what the profile names.\n *\n * Never full `process.env` inheritance — the process that spawns the agent\n * holds platform secrets that must not reach it.\n */\n private buildSubprocessBaseEnvironment(\n inheritedEnvironmentVariables: readonly string[] | undefined,\n ): NodeJS.ProcessEnv {\n return buildAgentSubprocessEnvironment(inheritedEnvironmentVariables ?? []);\n }\n\n /**\n * The environment a coding agent is started with, BEFORE any secret is injected: the base allowlist plus the\n * provider's and the execution profile's inherited variables, refused when either names a declared secret (#3018).\n * One composition for the dispatch ({@link buildAgentClientProtocolEnvironment}) and for a host asking what the\n * agent will see ({@link readCodingAgentLaunchConfiguration}, #3262), so the two cannot drift.\n */\n private composeAgentClientProtocolInheritedEnvironment(\n execution: Extract<ResolvedAgentExecution, { transport: 'acp' }>,\n ): NodeJS.ProcessEnv {\n // UNION of what the AGENT needs and what the APPLICATION asks for.\n //\n // The two lists answer different questions and only one of them is policy.\n // Which variable an agent reads to locate its own credentials is PROVIDER\n // knowledge — an application cannot be expected to know that Claude Code\n // resolves its login through `CLAUDE_CONFIG_DIR` — so a provider-declared\n // variable must reach every profile, including the ones applications author\n // themselves. Before this, the contract's list was projected ONLY into the\n // synthesized `default` profile, which the dogfood application deliberately\n // never selects; the declaration was therefore inert exactly where it\n // mattered, and the agent failed to authenticate with `OAuth session expired\n // and could not be refreshed` — a message that is false and sends every\n // diagnosis at the credential rather than at the environment.\n const inheritedEnvironmentVariables = [\n ...(execution.acpProfile.inheritedEnvironmentVariables ?? []),\n ...(execution.acpExecutionProfile.inheritedEnvironmentVariables ?? []),\n ];\n // #3018: no variable the framework declares secret is forwarded into the agent, whichever list names it. Checked\n // here on the exact list the agent starts with, as well as where the configuration is read.\n // assurance-control: WILDO.SECRETS.CREDENTIAL_SCOPING — the dispatch refuses to start a coding agent whose inherited environment names a declared secret.\n this.externalProvidersRegistry.assertAgentInheritedEnvironmentVariablesAreNotSecrets(\n execution.providerRef,\n `the inherited environment of '${execution.providerRef}' execution profile '${execution.executionProfileRef}'`,\n inheritedEnvironmentVariables,\n );\n return this.buildSubprocessBaseEnvironment(inheritedEnvironmentVariables);\n }\n\n private buildAgentClientProtocolEnvironment(\n execution: Extract<ResolvedAgentExecution, { transport: 'acp' }>,\n ): NodeJS.ProcessEnv {\n const env = this.composeAgentClientProtocolInheritedEnvironment(execution);\n\n if (execution.acpExecutionProfile.authMode === AgentClientProtocol_AuthMode.SECRET_REF_ENV_INJECTION) {\n const secretEnvVarName = execution.acpExecutionProfile.secretEnvVarName;\n const secret = this.externalProvidersRegistry.getAgentClientProtocolExecutionProfileSecret(\n execution.providerRef,\n execution.executionProfileRef,\n );\n if (!secretEnvVarName || !secret) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n message: 'ACP execution profile declares secret injection but its secret could not be resolved',\n },\n });\n }\n env[secretEnvVarName] = secret;\n }\n\n return env;\n }\n\n /**\n * Whether the LLM provider's contract requests strict JSON Schema\n * enforcement on AI-SDK structured-output calls. Read from the runtime\n * contract (`structuredOutputs.strictJsonSchema`) — never branched on\n * `providerRef`. Today only OpenAI sets this; if more providers need\n * it, they declare the flag on their own module.\n */\n private llmProviderRequestsStrictJsonSchema(providerRef: string): boolean | null {\n const binding = this.backendProviderRegistryService.getProtocolBinding(\n providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n );\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.LLM) {\n return null;\n }\n const declared = binding.runtimeContract.structuredOutputs?.strictJsonSchema;\n // `null` means the provider declares no opinion, so no option is sent and the SDK default applies.\n // `false` is an OPINION and must be sent: omitting it lets the SDK default back to strict, which is\n // how a contract that reads `strictJsonSchema: false` still produced strict-mode request rejections.\n return declared === undefined ? null : declared;\n }\n\n /**\n * The limits a provider documents for its strict mode (#2344), declared beside `strictJsonSchema: true`\n * in its runtime contract, which makes them required there. Read only for a provider that requests\n * strict decoding; the derivation applies them and states none of its own.\n */\n private llmProviderStrictSchemaProfile(providerRef: string): StrictStructuredOutputProfile | undefined {\n const binding = this.backendProviderRegistryService.getProtocolBinding(\n providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n );\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.LLM) return undefined;\n const declared = binding.runtimeContract.structuredOutputs;\n return declared?.strictJsonSchema === true ? declared.strictSchemaProfile : undefined;\n }\n\n /**\n * The limits of a provider's NATIVE constrained decoding and its unconstrained path (#3146), read from its runtime\n * contract, never branched on `providerRef`. Absent for a provider that requests OpenAI-style strict mode, which has\n * its own derivation, and for one that declares nothing.\n */\n private llmProviderNativeConstrainedDecoding(providerRef: string): NativeConstrainedDecodingContract | undefined {\n const binding = this.backendProviderRegistryService.getProtocolBinding(\n providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n );\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.LLM) return undefined;\n const declared = binding.runtimeContract.structuredOutputs;\n return declared?.strictJsonSchema === true ? undefined : declared?.nativeConstrainedDecoding;\n }\n\n /**\n * Execute a CODING agent over an ACP session.\n *\n * Carries the SAME FOUR responsibilities as {@link executeAgentViaCLI}, and\n * they are listed here because the transport swap is exactly where one of\n * them would be quietly dropped:\n *\n * 1. rate limiting through the provider's Bottleneck limiter;\n * 2. the ENVIRONMENT GATE — the guard that keeps a workspace-mutating agent\n * out of production;\n * 3. prompt composition from the agent's compiled prompts and the request;\n * 4. result normalisation into the published coding-agent output contract.\n */\n /**\n * The agent-specific `_meta` for `session/new`, resolved from the AUTHORED\n * host-configuration posture.\n *\n * Fails CLOSED. If the profile asks for an isolation posture this provider\n * declares no translation for, the session is refused rather than opened with\n * whatever the agent defaults to — which, measured against Claude's adapter,\n * means the operator's entire personal configuration. The field used to be\n * authored, defaulted and documented as a safety posture while being read by\n * nothing at all; refusing is what makes it mean something.\n *\n * `HOST_INHERITED` needs no translation: inheriting everything is what an\n * agent does when told nothing.\n */\n private resolveAgentClientProtocolSessionMeta(\n execution: Extract<ResolvedAgentExecution, { transport: 'acp' }>,\n ): Record<string, unknown> | undefined {\n const posture = execution.acpExecutionProfile.hostConfigurationInheritance;\n const byPosture = execution.acpProfile.sessionMetaExtensionsByHostConfigurationInheritance;\n const translated = byPosture?.[posture];\n\n if (translated) {\n // Posture translation is authority, not a default. Merge unrelated metadata\n // recursively, but refuse replacing any translated leaf (including an array).\n // A shallow spread let a harmless sibling under `claudeCode` erase isolation.\n const isObject = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === 'object' && !Array.isArray(value);\n const merge = (protectedValues: Record<string, unknown>, authored: Record<string, unknown>, path = ''): Record<string, unknown> =>\n Object.fromEntries([...new Set([...Object.keys(protectedValues), ...Object.keys(authored)])].map((key) => {\n if (!Object.hasOwn(protectedValues, key)) return [key, authored[key]];\n if (!Object.hasOwn(authored, key)) return [key, protectedValues[key]];\n const protectedValue = protectedValues[key];\n const authoredValue = authored[key];\n const metadataPath = path ? `${path}.${key}` : key;\n if (isObject(protectedValue) && isObject(authoredValue)) {\n return [key, merge(protectedValue, authoredValue, metadataPath)];\n }\n if (isDeepStrictEqual(protectedValue, authoredValue)) return [key, protectedValue];\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n hostConfigurationInheritance: posture,\n metadataPath,\n message: 'Authored ACP session metadata conflicts with the provider translation of the requested host-configuration posture.',\n },\n });\n }));\n return merge(translated, execution.acpExecutionProfile.sessionMetaExtensions ?? {});\n }\n\n if (posture !== AgentClientProtocol_HostConfigurationInheritance.HOST_INHERITED) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n hostConfigurationInheritance: posture,\n message:\n 'ACP provider declares no translation for the authored host-configuration posture, '\n + 'so the requested isolation cannot be honoured and the session is refused.',\n },\n });\n }\n\n return execution.acpExecutionProfile.sessionMetaExtensions ?? execution.acpProfile.sessionMetaExtensions;\n }\n\n /**\n * What THIS agent's provider declares about escalating before it mutates.\n *\n * Read from the ACP runtime contract on the provider binding — never branched\n * on `providerRef`, and deliberately not taken from any projected provider\n * profile: this is a measured PROVIDER FACT about an agent's behaviour, not\n * application-authored policy, and it must not sit anywhere an application\n * configuration could merge over it.\n *\n * `undefined` means the provider has no ACP binding at all, which the caller\n * has already refused by the time this runs.\n */\n private resolveAgentClientProtocolPermissionEscalation(\n providerRef: string,\n ): AgentClientProtocolPermissionEscalationDeclaration | undefined {\n const binding = this.backendProviderRegistryService.getProtocolBinding(\n providerRef,\n ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL,\n );\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.AGENT_CLIENT_PROTOCOL) {\n return undefined;\n }\n return binding.runtimeContract.permissionEscalation;\n }\n\n /**\n * Can Wildo's in-flight guards fire for the session this run is about to open?\n *\n * Answered from the provider's declaration AND from the environment actually\n * composed for the child, because for a conditionally-escalating agent those\n * are two different facts: the agent escalates only if the pointer to its\n * permission configuration really arrives, and a declaration that it \"must be\n * supplied\" is not evidence that anything supplied it.\n *\n * The environment is inspected rather than trusted for the same reason the\n * runner judges a permission request rather than the agent's session mode:\n * the thing that decides behaviour is what the child receives.\n */\n private resolveAgentClientProtocolInFlightGuardAvailability(\n escalation: AgentClientProtocolPermissionEscalationDeclaration | undefined,\n childEnvironment: NodeJS.ProcessEnv,\n ): { behaviour?: AgentClientProtocol_PermissionEscalationBehaviour; canFire: boolean; missingConfigurationEnvironmentVariable?: string } {\n if (!escalation) {\n // No declaration reachable. Assume the guards CANNOT fire: this field is\n // required on the contract, so its absence means a provider shape this\n // build does not understand, and reporting an unverified \"yes\" is the one\n // answer that could make an operator trust a ceiling that is not there.\n return { canFire: false };\n }\n const supplied =\n escalation.behaviour === AgentClientProtocol_PermissionEscalationBehaviour.RAISES_ONLY_UNDER_HOST_CONFIGURATION\n ? childEnvironment[escalation.configurationEnvironmentVariableName] !== undefined\n : false;\n const canFire = agentClientProtocolInFlightGuardsCanFire(escalation.behaviour, supplied);\n return {\n behaviour: escalation.behaviour,\n canFire,\n ...(!canFire\n && escalation.behaviour === AgentClientProtocol_PermissionEscalationBehaviour.RAISES_ONLY_UNDER_HOST_CONFIGURATION\n ? { missingConfigurationEnvironmentVariable: escalation.configurationEnvironmentVariableName }\n : {}),\n };\n }\n\n private async executeAgentViaACP(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n hostContext?: AgentInvocationHostContext,\n ): Promise<AgentExecutionResult> {\n const execution = this.resolveAgentExecution(agent);\n if (execution.transport !== 'acp') {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n agentRef: agent.ref,\n providerRef: agent.config.providerRef,\n message: 'Coding agent did not resolve to an ACP execution',\n },\n });\n }\n\n const { acpExecutionProfile, acpProfile } = execution;\n\n // (2) Environment gate — BEFORE the limiter, before any spawn.\n this.validateAgentClientProtocolPolicy(execution);\n\n // The requested model must be one the transport declares. Validated here\n // rather than at the session, so a mis-pinned model fails before an agent\n // is started rather than after it has begun editing.\n const requestedModel = agent.config.model;\n if (!acpProfile.supportedModels.includes(requestedModel)) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n requestedModel,\n supportedModels: acpProfile.supportedModels,\n message: 'ACP profile does not declare support for the selected semantic model',\n },\n });\n }\n\n // The authored auth posture must be one the AGENT can actually use.\n //\n // `authModes` was consulted only when synthesizing the provider's `default`\n // execution profile, so an application authoring its own — which the dogfood\n // application does deliberately — could declare any mode and nothing\n // checked it. Both directions are silently wrong rather than loud: a profile\n // declaring HOST_MANAGED against a secret-injecting agent starts a run with\n // no credential, and one declaring SECRET_REF_ENV_INJECTION against a\n // host-managed agent injects a secret the agent ignores while the\n // application believes the run is credentialed by configuration.\n //\n // Normalised on both sides at projection time; comparing the contract's\n // hyphenated spelling against the enum's underscored one is a guard that\n // never fires.\n const supportedAuthModes = acpProfile.supportedAuthModes;\n if (supportedAuthModes && !supportedAuthModes.includes(acpExecutionProfile.authMode)) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n authoredAuthMode: acpExecutionProfile.authMode,\n supportedAuthModes: [...supportedAuthModes],\n message:\n 'The authored ACP execution profile declares an authentication mode this provider\\'s agent '\n + 'does not support, so the session is refused rather than started with a credential posture '\n + 'the agent will not honour.',\n },\n });\n }\n\n const workingDirectory = resolveTrustedWorkingDirectory({\n workspaceRootPath: hostContext?.workspaceRootPath,\n usesRelativePath:\n acpExecutionProfile.workingDirectoryPolicy === AgentClientProtocol_WorkingDirectoryPolicy.WORKSPACE_RELATIVE_PATH,\n relativePath: acpExecutionProfile.workingDirectoryRelativePath,\n });\n\n // (3) Prompt composition — the same compiled prompts every transport gets. A session has one prompt, so a\n // conversation input reaches it as the rendered transcript of its bounded replay.\n const prompts = await this.buildExecutionPrompts(agent, request, ConversationDelivery.SINGLE_PROMPT);\n const prompt = this.buildSubprocessPromptInput(prompts);\n\n // (1) Rate limiting, keyed on the ACP protocol so a coding session and an\n // HTTP completion against the same provider do not share one bucket.\n const limiter = this.getBottleneckForProvider(\n execution.providerRef,\n ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL,\n );\n const jobId = `${agent.ref}-acp-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n\n this.logDebug('Scheduling ACP coding session through rate limiter', {\n agentRef: agent.ref,\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n permissionCeiling: acpExecutionProfile.permissionCeiling,\n workingDirectory,\n jobId,\n });\n\n const sessionMetaExtensions = this.resolveAgentClientProtocolSessionMeta(execution);\n\n const effectivePermissionCeiling = this.resolveEffectivePermissionCeiling(acpExecutionProfile, request);\n const permissionEscalation = this.resolveAgentClientProtocolPermissionEscalation(execution.providerRef);\n\n return this.scheduleOnLimiter(limiter, { id: jobId }, async () => {\n const env = this.buildAgentClientProtocolEnvironment(execution);\n /*\n * Does this run's authored ceiling mean anything for THIS agent?\n *\n * Both of Wildo's in-flight controls — the permission ceiling and the\n * task's mutation scope — are enforced in the client's ANSWER to\n * `session/request_permission`. An agent that does not ask is bound by\n * neither. Measured: Codex never asks before an in-workspace write (its\n * safety model is a sandbox), and OpenCode does not either unless the host\n * points it at a permission configuration file.\n *\n * The agents stay ADMISSIBLE. Refusing a tool because its architecture\n * differs is exactly the hard ceremony the application-creation directive\n * rejects, and the dogfood lane's `UNRESTRICTED` profile — which asks for\n * no gate and gets none — runs unchanged through this branch.\n *\n * What is refused is a CONTRADICTION: a profile that authored a ceiling\n * narrower than UNRESTRICTED, i.e. that asked for some autonomy to be\n * withheld, against an agent from which nothing can be withheld. Running\n * it anyway would not be permissive, it would be false — the ceiling would\n * be a label, the mutation scope would never be consulted, and the only\n * account of what the run touched would be a change set taken afterwards\n * while the configuration said a gate was in place.\n *\n * The same shape as this transport's two existing refusals, and for the\n * same reason: `resolveAgentClientProtocolSessionMeta` refuses an isolation\n * posture the provider cannot express, and `modelDelivery` refuses a model\n * that could not reach the agent. A declared safety field that cannot be\n * honoured must refuse rather than be silently ignored; that is what makes\n * it mean something. The door is one word wide and always open —\n * `permissionCeiling: UNRESTRICTED` states plainly that this run has no\n * in-flight gate, which is the truth either way.\n */\n // assurance-control: WILDO.SOFTWARE.AI_PRODUCED_CHANGE_CONTROL — a ceiling narrower than unrestricted is refused for an agent its guards cannot hold (one that never asks, or OpenCode without its configuration pointer), so a ceiling is never a label.\n const guardAvailability = this.resolveAgentClientProtocolInFlightGuardAvailability(permissionEscalation, env);\n if (!guardAvailability.canFire && effectivePermissionCeiling !== AgentClientProtocol_PermissionCeiling.UNRESTRICTED) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n permissionCeiling: effectivePermissionCeiling,\n permissionEscalation: guardAvailability.behaviour,\n ...(guardAvailability.missingConfigurationEnvironmentVariable\n ? { missingConfigurationEnvironmentVariable: guardAvailability.missingConfigurationEnvironmentVariable }\n : {}),\n message:\n 'This agent does not raise a permission request before mutating, so the authored permission '\n + 'ceiling and the task mutation scope cannot be enforced in flight and the session is refused '\n + 'rather than run under a ceiling that would be a label. '\n + (guardAvailability.missingConfigurationEnvironmentVariable\n ? `Supply ${guardAvailability.missingConfigurationEnvironmentVariable} in the child environment `\n + '(name it in the execution profile\\'s `inheritedEnvironmentVariables`, pointing at a permission '\n + 'configuration OUTSIDE the application workspace), or author `permissionCeiling: UNRESTRICTED`.'\n : 'Author `permissionCeiling: UNRESTRICTED` to state that this run has no in-flight gate, or '\n + 'select an agent whose provider declares that it escalates before mutating.'),\n },\n });\n }\n // Stated at session open, beside the ceiling, so an operator watching a run\n // start learns whether anything stands between the agent and the workspace\n // — rather than learning it afterwards from a warning about a change set.\n this.logDebug('Opening ACP coding session', {\n agentRef: agent.ref,\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n permissionCeiling: effectivePermissionCeiling,\n permissionEscalation: guardAvailability.behaviour ?? null,\n inFlightPermissionGuardsCanFire: guardAvailability.canFire,\n });\n // DELIVER the model, through the channel THIS agent's provider declares.\n //\n // Until 2026-09-03 `requestedModel` was checked against the transport's\n // declared set and written into the transport metadata — and never reached\n // the spawned agent, so under HOST_MANAGED auth every session ran at the\n // OPERATOR's personal default model (measured: Opus, during a 529-overload\n // storm the agent definitions' declared model would have avoided).\n //\n // The first fix wrote `ANTHROPIC_MODEL` unconditionally from this\n // agent-NEUTRAL service, which is correct for exactly one adapter and a\n // silent no-op for every other: the same false result, one agent later.\n // So the channel is declared by the provider that knows its agent, and a\n // provider that declares none cannot have a model selected at all —\n // refused here rather than started with the choice quietly dropped.\n const modelDelivery = acpProfile.modelDelivery;\n // The model is VALIDATED as a semantic id and DELIVERED in the agent's own\n // spelling. Both halves matter: validation against `supportedModels` is\n // what refuses a mis-pinned model before an agent is spawned, and the\n // translation is what lets a multi-vendor agent — whose ids carry the\n // provider, `anthropic/claude-sonnet-5` — be addressed at all. Absent\n // means the two vocabularies coincide, which is the common case.\n const deliveredModel = acpProfile.modelTransportIds?.[requestedModel] ?? requestedModel;\n let modelSelection: { configId: string; model: string } | undefined;\n if (modelDelivery?.channel === 'environment-variable') {\n env[modelDelivery.environmentVariableName] = deliveredModel;\n } else if (modelDelivery?.channel === 'session-config-option') {\n // Set over ACP after the session opens; the runner fails the session if\n // the agent rejects it, before any prompt reaches the workspace.\n modelSelection = { configId: modelDelivery.configId, model: deliveredModel };\n } else {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n requestedModel,\n message:\n 'ACP provider declares no model-delivery channel, so the selected model cannot reach the '\n + 'agent and the session is refused rather than run at the agent\\'s own default.',\n },\n });\n }\n // A run that ANSWERS a parked session resumes it by id via `session/load`\n // instead of starting a fresh task; the input's prompt is then the answer.\n const continuationOfSessionId = (request.input as { continuationOfSessionId?: string } | undefined)\n ?.continuationOfSessionId;\n\n // (3b) The operator must be signed in to the agent (#1637). A signed-out agent completes the ACP\n // handshake and fails only on its first prompt, which used to be charged to the task as its\n // own failure. The provider declares how to read the login from local state (no tokens), and\n // it is read in the CHILD's environment — where the agent itself looks for its credentials.\n // Only a definite SIGNED_OUT refuses. An unreadable state proceeds, since a guard that guesses\n // \"signed out\" would block a working host — and so does a missing status command: the Claude and\n // Codex agents run through `npx` adapters that do not need `claude` / `codex` on PATH, so a host\n // whose CLI is absent (or only a shell alias) can still dispatch, and did before this check. An\n // application that starts its own agent command is running something the provider did not\n // describe, so its declaration does not apply.\n if (acpProfile.hostLogin && !acpExecutionProfile.command) {\n const login = await probeCodingAgentHostLoginAsync(acpProfile.hostLogin, { environment: env });\n if (login.state === CodingAgentHostLoginState.SIGNED_OUT) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n providerRef: execution.providerRef,\n loginState: login.state,\n message: `${CODING_AGENT_NOT_SIGNED_IN_MESSAGE_PREFIX} (${execution.providerRef}): ${login.detail} ${login.remedy ?? ''}`.trim(),\n },\n });\n }\n }\n\n // (4) Open the live session, then drive it turn-by-turn.\n const agentSession = await startACPAgentSession({\n // The application may override how the agent is started, but normally\n // inherits it: the provider owns the package and its pinned version.\n command: acpExecutionProfile.command ?? acpProfile.agentCommand,\n args: acpExecutionProfile.command ? acpExecutionProfile.args : acpProfile.agentArgs,\n cwd: workingDirectory,\n env,\n supportedProtocolVersions: acpProfile.supportedProtocolVersions,\n // The invocation may request LESS autonomy than the profile allows; it\n // can never request more. Intersecting tool-kind policies prevents an\n // override from granting operations absent from the profile.\n //\n // Resolved ONCE, above, and reused here: the guard-availability refusal\n // just above decides on this exact value, and re-deriving it per use\n // would let the value that was CHECKED and the value the session RUNS\n // under drift apart — the whole class of defect this lane keeps meeting.\n permissionCeiling: effectivePermissionCeiling,\n // Agent-vocabulary mode ids from the provider contract. Absent is fine —\n // the ceiling is enforced by answering permission requests, never by the\n // agent's mode — but a map hardcoded in the runner silently matched\n // nothing for any agent but the one it was written for.\n ...(acpProfile.sessionModeIdsByPermissionCeiling?.[effectivePermissionCeiling]\n ? {\n preferredSessionModeIds:\n acpProfile.sessionModeIdsByPermissionCeiling[effectivePermissionCeiling],\n }\n : {}),\n ...(modelSelection ? { modelSelection } : {}),\n ...(hostContext?.isPermittedCodingLocation\n ? { isPermittedLocation: hostContext.isPermittedCodingLocation }\n : {}),\n ...(hostContext?.isPermittedCodingReadLocation\n ? { isPermittedReadLocation: hostContext.isPermittedCodingReadLocation }\n : {}),\n ...(sessionMetaExtensions ? { sessionMetaExtensions } : {}),\n ...(acpExecutionProfile.maximumRecordedEventBytes !== undefined\n ? { maxRecordedEventBytes: acpExecutionProfile.maximumRecordedEventBytes }\n : {}),\n ...(hostContext?.onCodingSessionEvent ? { onEvent: hostContext.onCodingSessionEvent } : {}),\n ...(continuationOfSessionId ? { resumeSessionId: continuationOfSessionId } : {}),\n // The agent may ASK only a host that can hold the parked session (#3710).\n ...(hostContext?.parksCodingAgentQuestions === true ? { acceptsExplicitQuestions: true } : {}),\n });\n\n try {\n const ladder = await this.driveCodingTurnLadder({\n session: agentSession,\n firstPrompt: prompt,\n maxAutoContinuations: acpExecutionProfile.maxAutoContinuations,\n awaitingInputTtlMs: acpExecutionProfile.awaitingInputTtlMs,\n ...(acpExecutionProfile.turnTimeoutMs !== undefined ? { turnTimeoutMs: acpExecutionProfile.turnTimeoutMs } : {}),\n ...(hostContext?.codingSessionAbortSignal ? { abortSignal: hostContext.codingSessionAbortSignal } : {}),\n ...(hostContext?.classifyCodingTurnEnd ? { classify: hostContext.classifyCodingTurnEnd } : {}),\n ...(hostContext?.onCodingSessionStateChange ? { onStateChange: hostContext.onCodingSessionStateChange } : {}),\n });\n\n // (5) Result normalisation into the published contract.\n const output: CodingAgent_RunTaskOutput = {\n finalMessage: ladder.finalMessage,\n stopReason: ladder.stopReason,\n ...(ladder.rawStopReason ? { rawStopReason: ladder.rawStopReason } : {}),\n // Always emitted, including zero: absence would be indistinguishable\n // from \"no denials\", and under the strictest ceiling that is exactly the\n // distinction an operator needs.\n deniedPermissionCount: ladder.deniedPermissionCount,\n permissionDecisions: ladder.permissionDecisions,\n ...(ladder.reportedFileLocations.length > 0\n ? { reportedFileLocations: ladder.reportedFileLocations }\n : {}),\n // Absent means one turn — the single-turn shape every pre-ladder\n // consumer already assumes.\n ...(ladder.turnCount > 1 ? { turnCount: ladder.turnCount } : {}),\n ...(ladder.continuations.length > 0 ? { continuations: ladder.continuations } : {}),\n // Present ONLY when the run parked on a question — the field that stops\n // a suspended turn being read as a completed result.\n ...(ladder.suspension ? { suspension: ladder.suspension } : {}),\n };\n\n return {\n output,\n transport: {\n protocolKind: ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL as const,\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n model: requestedModel,\n negotiatedProtocolVersion: agentSession.negotiatedProtocolVersion,\n ...(agentSession.agentName ? { agentName: agentSession.agentName } : {}),\n ...(agentSession.agentVersion ? { agentVersion: agentSession.agentVersion } : {}),\n ...(agentSession.sessionModeId ? { sessionModeId: agentSession.sessionModeId } : {}),\n // Recorded on the run because the ceiling alone does not describe it.\n // A change set produced under a ceiling that could be enforced and one\n // produced under a ceiling that was inert look identical afterwards,\n // and this pair is the only thing that tells a later reader whether\n // anything stood between the agent and these files.\n ...(guardAvailability.behaviour ? { permissionEscalation: guardAvailability.behaviour } : {}),\n inFlightPermissionGuardsCanFire: guardAvailability.canFire,\n sessionId: agentSession.sessionId,\n },\n ...(ladder.usage ? { usage: ladder.usage } : {}),\n } satisfies AgentExecutionResult;\n } finally {\n // Closes on completion AND on park: a parked session is answered by a\n // fresh invocation that resumes it via `session/load`, never by holding\n // this child alive across the HTTP call that returned the question.\n agentSession.close();\n }\n });\n }\n\n /**\n * Install the host's language-model route (#3472), or remove it with `undefined`.\n *\n * Validated HERE, at installation, against the provider's ACP binding: a route naming an agent that cannot be\n * opened for a language-model session, or a model its binding does not offer, fails the host's startup instead of\n * failing the first of hundreds of calls.\n */\n public routeLanguageModelCallsOverAgentClientProtocol(route: LanguageModelAgentClientProtocolRoute | undefined): void {\n if (route === undefined) {\n this.languageModelRoute = undefined;\n return;\n }\n const execution = this.resolveLanguageModelRouteExecution(route);\n if (!execution.acpProfile.supportedModels.includes(route.model)) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { providerRef: route.acpProviderRef, model: route.model, supportedModels: execution.acpProfile.supportedModels, message: 'The language-model route names a model its ACP binding does not offer.' },\n });\n }\n if (this.readLanguageModelSessionDeclaration(route.acpProviderRef) === undefined) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { providerRef: route.acpProviderRef, message: 'The provider declares no `languageModelSession` on its ACP binding, so its agent cannot be opened for a language-model call.' },\n });\n }\n this.languageModelRoute = { route, limiter: new Bottleneck({ maxConcurrent: Math.max(1, route.maximumConcurrentSessions) }) };\n this.logger.info('Language-model calls are routed over the Agent Client Protocol', {\n acpProviderRef: route.acpProviderRef,\n model: route.model,\n routedProviderRefs: [...route.routedProviderRefs],\n maximumConcurrentSessions: route.maximumConcurrentSessions,\n });\n }\n\n /** The installed route, for a host that reports what its calls run on. */\n public readLanguageModelRoute(): LanguageModelAgentClientProtocolRoute | undefined {\n return this.languageModelRoute?.route;\n }\n\n private resolveLanguageModelRouteExecution(route: LanguageModelAgentClientProtocolRoute): Extract<ResolvedAgentExecution, { transport: 'acp' }> {\n const acpProfile = this.externalProvidersRegistry.getAgentClientProtocolProfile(route.acpProviderRef);\n const acpExecutionProfile = this.externalProvidersRegistry.getAgentClientProtocolExecutionProfile(route.acpProviderRef, route.executionProfileRef);\n if (!this.externalProvidersRegistry.isProviderEnabled(route.acpProviderRef, ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL) || !acpProfile || !acpExecutionProfile) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { providerRef: route.acpProviderRef, executionProfileRef: route.executionProfileRef, message: 'The language-model route names an ACP provider or execution profile that is not enabled.' },\n });\n }\n return {\n transport: 'acp',\n providerRef: route.acpProviderRef,\n operationKey: LLMProvider_OperationKey.GENERATE_STRUCTURED,\n executionProfileRef: route.executionProfileRef,\n acpProfile,\n acpExecutionProfile,\n } as unknown as Extract<ResolvedAgentExecution, { transport: 'acp' }>;\n }\n\n private readLanguageModelSessionDeclaration(providerRef: string) {\n const binding = this.backendProviderRegistryService.getProtocolBinding(providerRef, ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL);\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.AGENT_CLIENT_PROTOCOL) return undefined;\n return binding.runtimeContract.languageModelSession;\n }\n\n /**\n * Whether the installed route serves this call. A call it does not serve stays on the API, and the reason is logged\n * whenever a route IS installed for the agent's provider — an API call made despite the route has to say why.\n */\n private languageModelRouteServes(\n agent: FlowsActors_Agent,\n operationKey: LLMProvider_OperationKey,\n input: unknown,\n outputModeration: OutputModerationGuard | undefined,\n ): boolean {\n const installed = this.languageModelRoute;\n if (installed === undefined || !installed.route.routedProviderRefs.includes(agent.config.providerRef)) return false;\n const keptOnApi = (reason: string): false => {\n this.logger.info('A language-model call stays on the API despite the ACP route', { agentRef: agent.ref, operationKey, reason });\n return false;\n };\n if (!ROUTABLE_LANGUAGE_MODEL_OPERATIONS.has(operationKey)) return keptOnApi('the operation is not one a route serves');\n if (outputModeration !== undefined) return keptOnApi('the agent runs under an output-moderation guard, an API middleware');\n if (this.extractStructuredInputImages(input).length > 0) return keptOnApi('the input carries images');\n return true;\n }\n\n /**\n * One language-model call served by a locked-down ACP session (#3472).\n *\n * The session has no tool of the agent's own, its system prompt is the call's, and its only way to answer is the\n * host's `submit_result` tool, validated with the call's own schema. A turn that ends without an accepted submission\n * is reminded up to {@link ROUTED_CALL_REMINDER_TURNS} times; a call that still has none returns the API path's\n * failure contract (`structuredGenerationFailure`), so the caller's correction loop runs as it does on the API.\n */\n private async executeLanguageModelOperationViaACP(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n operationKey: LLMProvider_OperationKey,\n prompts: CompiledExecutionPrompts,\n ): Promise<AgentExecutionResult> {\n const installed = this.languageModelRoute!;\n const { route } = installed;\n const execution = this.resolveLanguageModelRouteExecution(route);\n const declaration = this.readLanguageModelSessionDeclaration(route.acpProviderRef)!;\n this.validateAgentClientProtocolPolicy(execution);\n\n const structured = operationKey === LLMProvider_OperationKey.GENERATE_STRUCTURED;\n const input = request.input as { schema?: unknown; includeRejectedAnswer?: unknown } | undefined;\n if (structured && !(input?.schema instanceof z.ZodType)) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_STRUCTURED_SCHEMA_REQUIRED,\n context: { operation: 'GENERATE_STRUCTURED', transport: 'acp' },\n });\n }\n const schema: z.ZodTypeAny = structured ? (input!.schema as z.ZodTypeAny) : z.object({ text: z.string().min(1) });\n const answerInstruction = structured\n ? `Return your result by calling the ${ACP_RESULT_TOOL_NAME} tool with the WHOLE result as its input. Do not answer in text: only an accepted ${ACP_RESULT_TOOL_NAME} call counts.`\n : `Return your answer by calling the ${ACP_RESULT_TOOL_NAME} tool with {\"text\": \"<your whole answer>\"}. Do not answer in text: only an accepted ${ACP_RESULT_TOOL_NAME} call counts.`;\n const prompt = `${prompts.instructions}\\n\\n${answerInstruction}`;\n const jobId = `${agent.ref}-acp-language-model-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n\n // Through the one bound seam like every other model call (#2935): a routed call queued behind another caller's\n // runs in its OWN caller's frames, so its spend, cost attribution and logs never borrow that caller's.\n return this.scheduleOnLimiter(installed.limiter, { id: jobId }, async () => {\n mkdirSync(route.scratchDirectory, { recursive: true });\n const toolServer = await startAcpResultToolServer({\n schema,\n description: structured\n ? 'Submit the result the task asks for. Its input schema IS the result schema. A refusal names every issue; correct them and submit the whole result again.'\n : 'Submit your answer as {\"text\": \"...\"}.',\n maximumSubmissions: route.maximumSubmissions,\n });\n const env = this.buildAgentClientProtocolEnvironment(execution);\n const modelDelivery = execution.acpProfile.modelDelivery;\n const deliveredModel = execution.acpProfile.modelTransportIds?.[route.model] ?? route.model;\n if (modelDelivery?.channel === 'environment-variable') env[modelDelivery.environmentVariableName] = deliveredModel;\n const toolName = declaration.mcpToolNameTemplate.replace('{server}', ACP_RESULT_TOOL_SERVER_NAME).replace('{tool}', ACP_RESULT_TOOL_NAME);\n const sessionMeta = structuredClone(declaration.sessionMetaExtensions) as Record<string, unknown>;\n sessionMeta[declaration.systemPromptMetaKey] = prompts.systemPrompt;\n let cursor: Record<string, unknown> = sessionMeta;\n declaration.preApprovedToolsMetaPath.forEach((segment, index) => {\n if (index === declaration.preApprovedToolsMetaPath.length - 1) {\n cursor[segment] = [toolName];\n } else {\n const next = cursor[segment];\n cursor[segment] = next !== null && typeof next === 'object' && !Array.isArray(next) ? next : {};\n cursor = cursor[segment] as Record<string, unknown>;\n }\n });\n\n const startedAt = Date.now();\n let agentSession: ACPAgentSession | undefined;\n let usage: CodingAgent_Usage | undefined;\n try {\n agentSession = await startACPAgentSession({\n // The same resolution as a coding session: the execution profile's command when it authors one.\n command: execution.acpExecutionProfile.command ?? execution.acpProfile.agentCommand,\n args: execution.acpExecutionProfile.command ? execution.acpExecutionProfile.args : execution.acpProfile.agentArgs,\n cwd: route.scratchDirectory,\n env,\n supportedProtocolVersions: execution.acpProfile.supportedProtocolVersions,\n // Nothing of the agent's own is admitted: the host's tool is admitted by name, every other request refused.\n permissionCeiling: AgentClientProtocol_PermissionCeiling.PROMPT_ALWAYS,\n admitsHostToolCall: ({ toolCallTitle }) => toolCallTitle !== undefined && (toolCallTitle === toolName || toolCallTitle.includes(ACP_RESULT_TOOL_NAME)),\n ...(modelDelivery?.channel === 'session-config-option' ? { modelSelection: { configId: modelDelivery.configId, model: deliveredModel } } : {}),\n sessionMetaExtensions: sessionMeta,\n mcpServers: [{ type: 'http', name: ACP_RESULT_TOOL_SERVER_NAME, url: toolServer.url, headers: [] }],\n });\n let nextPrompt = prompt;\n for (let turn = 0; turn <= ROUTED_CALL_REMINDER_TURNS; turn += 1) {\n const remainingMs = route.callTimeoutMs - (Date.now() - startedAt);\n if (remainingMs <= 0) break;\n const turnResult = await agentSession.promptTurn(nextPrompt, { turnTimeoutMs: remainingMs });\n usage = this.mergeCodingUsage(usage, turnResult.usage);\n if (toolServer.acceptedResult() !== undefined || toolServer.submissionCount() >= route.maximumSubmissions) break;\n nextPrompt = `Your turn ended without an accepted ${ACP_RESULT_TOOL_NAME} call. ${answerInstruction}`;\n }\n } finally {\n agentSession?.close();\n await toolServer.close();\n }\n\n const transport = {\n protocolKind: ExternalProvider_ExchangeProtocol_Kind.AGENT_CLIENT_PROTOCOL as const,\n providerRef: execution.providerRef,\n executionProfileRef: execution.executionProfileRef,\n model: route.model,\n negotiatedProtocolVersion: agentSession!.negotiatedProtocolVersion,\n ...(agentSession!.agentName ? { agentName: agentSession!.agentName } : {}),\n ...(agentSession!.agentVersion ? { agentVersion: agentSession!.agentVersion } : {}),\n sessionId: agentSession!.sessionId,\n };\n const accepted = toolServer.acceptedResult();\n this.logDebug('Language-model call served over ACP', {\n agentRef: agent.ref,\n operationKey,\n model: route.model,\n accepted: accepted !== undefined,\n submissions: toolServer.submissionCount(),\n toolListed: toolServer.toolWasListed(),\n durationMs: Date.now() - startedAt,\n });\n\n if (accepted !== undefined) {\n const value = accepted.value;\n const output = operationKey === LLMProvider_OperationKey.GENERATE_STRUCTURED\n ? { object: value }\n : operationKey === LLMProvider_OperationKey.CHAT_COMPLETION\n ? { message: { role: LLMProvider_MessageRole.ASSISTANT, content: (value as { text: string }).text } }\n : { text: (value as { text: string }).text };\n return { output, transport, ...(usage ? { usage } : {}) } satisfies AgentExecutionResult;\n }\n\n if (!structured) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: {\n agentRef: agent.ref,\n operationKey,\n submissions: toolServer.submissionCount(),\n toolListed: toolServer.toolWasListed(),\n message: 'The ACP session ended without an accepted answer.',\n },\n });\n }\n // The API path's failure contract, so the caller's correction loop treats this exactly as a rejected API answer.\n const refusal = toolServer.lastRefusal();\n const structuredGenerationFailure = this.buildStructuredGenerationFailure(\n refusal !== undefined ? LLMProvider_StructuredGenerationFailureKind.INVALID_OBJECT_AFTER_COMPLETED_CALL : LLMProvider_StructuredGenerationFailureKind.NO_OBJECT_GENERATED,\n new Error(refusal !== undefined ? 'AcpResultRefused' : 'AcpNoResultSubmitted'),\n {\n ...(refusal !== undefined ? { cause: new z.ZodError([...refusal.issues]) } : {}),\n ...(refusal !== undefined ? { text: JSON.stringify(refusal.submitted) } : {}),\n },\n );\n return {\n output: {\n object: undefined,\n ...(input?.includeRejectedAnswer === true && refusal !== undefined ? { rejectedAnswer: JSON.stringify(refusal.submitted) } : {}),\n },\n structuredGenerationFailure,\n transport,\n ...(usage ? { usage } : {}),\n } satisfies AgentExecutionResult;\n });\n }\n\n private extractCLITextOutput(output: unknown): string {\n if (typeof output === 'string') {\n return output;\n }\n\n if (this.isRecord(output)) {\n if (typeof output.result === 'string') {\n return output.result;\n }\n if (typeof output.text === 'string') {\n return output.text;\n }\n if (typeof output.output === 'string') {\n return output.output;\n }\n if (typeof output.content === 'string') {\n return output.content;\n }\n }\n\n return JSON.stringify(output ?? '');\n }\n\n\n /**\n * Build system prompt from agent configuration\n *\n * If agent has promptSpec, uses the PromptCompiler for structured prompt building.\n * Otherwise, falls back to legacy skill-based prompt building.\n */\n private buildSystemPrompt(agent: FlowsActors_Agent, request: FlowsActors_Agent_Invocation<any, any, any>): string {\n const parts: string[] = [];\n\n if (agent.promptSpec.role) {\n parts.push(`Role: ${agent.promptSpec.role}`);\n }\n\n if (agent.promptSpec.persona) {\n parts.push(`Persona: ${agent.promptSpec.persona}`);\n }\n\n if (request.executionContext) {\n parts.push(`Context: ${JSON.stringify(request.executionContext)}`);\n }\n\n return parts.join('\\n\\n');\n }\n\n /**\n * Build prompts using the PromptCompiler when agent has promptSpec\n * Returns compiled system and user prompts\n */\n private async buildCompiledPrompts(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n instructions: string\n ): Promise<{ systemPrompt: string; userPrompt: string }> {\n if (!agent.promptSpec) {\n // Fall back to legacy mode\n return {\n systemPrompt: this.buildSystemPrompt(agent, request),\n userPrompt: instructions,\n };\n }\n\n this.logDebug('Building compiled prompts using PromptCompiler', {\n agentRef: agent.ref,\n hasInstructions: agent.promptSpec.instructions.length > 0,\n hasHints: !!agent.promptSpec.hints?.length,\n hasCuration: !!agent.promptSpec.curation,\n });\n\n // Build context items from execution context\n // Note: User input is NOT added here - it goes in the user prompt section, not context\n const contextItems: PromptIR_ContextItem[] = [];\n\n if (request.executionContext) {\n contextItems.push({\n id: 'exec_context',\n content: JSON.stringify(request.executionContext, null, 2),\n trust: PromptIR_TrustLevel.HIGH,\n sourceKind: PromptIR_ContextSourceKind.RELATIONSHIP,\n timestamp: new Date().toISOString(),\n });\n }\n\n // Compile using the prompt compiler - works directly with agent + invocation\n const compiled = await this.promptCompiler.compile(\n agent,\n request,\n contextItems,\n instructions\n );\n\n this.logDebug('Prompts compiled', {\n agentRef: agent.ref,\n format: compiled.format,\n systemPromptLength: compiled.systemPrompt.length,\n userPromptLength: compiled.userPrompt.length,\n tokenEstimates: compiled.tokenEstimates,\n });\n\n return {\n systemPrompt: compiled.systemPrompt,\n userPrompt: compiled.userPrompt,\n };\n }\n\n /**\n * Execute operation based on operation key\n * Dispatches to specific operation handlers\n */\n private async executeOperation({ providerClient, providerRef, config, operationKey, systemPrompt, instructions, input, llmProviderConfig, outputModeration, operationObservation, modelFailovers }: executeOperationParams): Promise<AgentOperationExecutionResult> {\n // A structured generation is STREAMED beneath every other wrap, so the account-refusal, observation and\n // moderation middlewares keep seeing a buffered call exactly as before (`withStreamedGenerationDeadlines`).\n const transportOf = (providerModel: any): any => operationKey === LLMProvider_OperationKey.GENERATE_STRUCTURED ? this.withStreamedGenerationDeadlines(providerModel) : providerModel;\n // #2301: the agent's declared alternatives sit beneath every engine middleware, each with its own transport wraps, so\n // a hand-over is invisible to the account-refusal, observation and moderation layers above.\n const transportModel = this.withDeclaredModelFailover({\n primary: transportOf(this.getModelFromProvider(providerClient, config.model)),\n providerRef,\n config,\n transportOf,\n ...(modelFailovers === undefined ? {} : { sink: modelFailovers }),\n });\n const model = this.moderatedModel(this.observedModel(this.accountRefusalIsFinal(transportModel), operationObservation), outputModeration, MODERATED_OUTPUT_KIND_OF_OPERATION[operationKey] ?? FlowsActors_ModeratedOutputKind.REPLY);\n // executeOperation is only reached on the LLM/text path (image agents\n // branch to executeImageAgent in executeAgent), so the config is the LLM arm.\n const baseOptions = this.buildBaseOptions(config as FlowsActors_Agent_LLMConfiguration);\n\n try {\n switch (operationKey) {\n case LLMProvider_OperationKey.GENERATE_TEXT:\n return await this.executeGenerateText({ model, systemPrompt, instructions, input, baseOptions });\n\n case LLMProvider_OperationKey.CHAT_COMPLETION:\n return await this.executeChatCompletion({ model, systemPrompt, instructions, input, baseOptions });\n\n case LLMProvider_OperationKey.CHAT_MULTIMODAL:\n return await this.executeChatMultimodal({ model, systemPrompt, instructions, input, baseOptions });\n\n case LLMProvider_OperationKey.GENERATE_STRUCTURED:\n return await this.executeGenerateStructured({\n model,\n systemPrompt,\n instructions,\n input,\n baseOptions,\n llmProviderConfig,\n providerRef,\n structuredGenerationExecutionMode: (config as FlowsActors_Agent_LLMConfiguration).structuredGenerationExecutionMode,\n maximumStructuredOutputLeafFields: (config as FlowsActors_Agent_LLMConfiguration).maximumStructuredOutputLeafFields,\n });\n\n case LLMProvider_OperationKey.STREAM_TEXT:\n return await this.executeStreamText({ model, systemPrompt, instructions, input, baseOptions });\n\n case LLMProvider_OperationKey.STREAM_STRUCTURED:\n return await this.executeStreamStructured({ model, systemPrompt, instructions, baseOptions });\n\n default:\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.AGENT_OPERATION_NOT_SUPPORTED,\n context: {\n // diagnostic (log-only)\n operationKey,\n supportedOperations: Object.values(LLMProvider_OperationKey),\n },\n }\n );\n }\n } catch (error) {\n // #2292: a withheld output is the application's policy, not a provider fault: it reaches the caller as itself.\n if (error instanceof AgentOutputWithheldError) throw error;\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n // Extract detailed provider error information\n const errorDetails = this.extractProviderErrorDetails(error);\n\n // Log detailed error information\n this.logger.error('Operation execution failed - provider error details', {\n operationKey,\n model: config.model,\n providerRef: (providerClient as any)?.providerRef || 'unknown',\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operationKey,\n model: config.model,\n message: `Failed to execute operation ${operationKey}: ${errorDetails.errorMessage}`,\n }, providerRef);\n }\n }\n\n /**\n * #3204: the model wrapped INNERMOST so a provider account's refusal (no credits, a spend limit) is final inside the\n * SDK's retry loop instead of being asked again with back-off (`MODEL_PROVIDER_ACCOUNT_REFUSAL_IS_FINAL`). A value\n * that is not a language model object is returned as it came, so the SDK's own resolution reports it.\n */\n private accountRefusalIsFinal(model: any): any {\n if (model === null || typeof model !== 'object' || typeof model.doGenerate !== 'function') return model;\n return wrapLanguageModel({ model, middleware: MODEL_PROVIDER_ACCOUNT_REFUSAL_IS_FINAL });\n }\n\n /**\n * The agent's model with the alternatives it declares behind it (#2301, `modelFailover`): `withModelCallFailover` over\n * the primary and each alternative, every alternative built like the agent's own model (its provider client through\n * `resolveApiProviderClient`, so its credential and its declared processing region apply, then `transportOf`, the same\n * transport wraps). Built lazily, at the first failure. One that cannot be reached or built is skipped with an ERROR\n * log; startup refuses it (`assertDeclaredFailoverProvidersCanServe`), so this is the mid-life case. Returns the primary\n * itself when the agent declares none.\n */\n private withDeclaredModelFailover(input: {\n readonly primary: any;\n readonly providerRef: string;\n readonly config: FlowsActors_Agent['config'];\n readonly transportOf: (providerModel: any) => any;\n readonly sink?: ModelCallFailover[];\n }): any {\n const alternatives: readonly FlowsActors_Agent_ModelAlternative[] = isLLMAgentConfiguration(input.config) ? input.config.modelFailover ?? [] : [];\n return withModelCallFailover({\n // The registry resolves an applicability to a concrete id before an agent runs, so `config.model` names the model\n // for every registered agent. A configuration handed in unregistered names it through the built model's own\n // `modelId`, which the AI SDK's language-model contract requires, so a hand-over record never names nothing (#3583).\n primary: { providerRef: input.providerRef, model: input.config.model ?? input.primary.modelId, languageModel: input.primary },\n declaresAlternatives: alternatives.length > 0,\n alternatives: async () => {\n const candidates: ModelCallCandidate[] = [];\n for (const alternative of alternatives) {\n try {\n const reachDefect = this.modelAlternativeReachDefect(alternative.providerRef);\n if (reachDefect !== undefined) throw new Error(reachDefect);\n const client = await this.resolveApiProviderClient(alternative.providerRef);\n candidates.push({\n providerRef: alternative.providerRef,\n model: alternative.model,\n languageModel: input.transportOf(this.getModelFromProvider(client, alternative.model)),\n });\n } catch (error) {\n this.logger.error('A declared model alternative cannot serve and was skipped', {\n providerRef: alternative.providerRef,\n model: alternative.model,\n error: describeCaughtError(error),\n });\n }\n }\n return candidates;\n },\n onFailover: (failover) => {\n input.sink?.push(failover);\n this.logger.warn('An agent model call failed over to a declared alternative model', { ...failover });\n },\n });\n }\n\n /**\n * Why a provider cannot serve as a declared model alternative on this runtime (#2301), or `undefined`. It must be\n * eligible for `AI_LLM` exactly as a selected provider is — registered, declared in this runtime's scope with the\n * capability, and loaded, which the application's data residency decides (a provider outside it is never loaded) —\n * enabled, credentialed, and carry an `LLM_PROVIDER` contract. Its processing region is bound at load, like any other.\n */\n private modelAlternativeReachDefect(providerRef: string): string | undefined {\n const protocolKind = ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER;\n if (!this.externalProvidersRegistry.getProvidersForEngineCapability(EngineCapability.AI_LLM).includes(providerRef)) {\n return `provider \"${providerRef}\" is not available for AI_LLM on this runtime (not loaded — a data residency refusal unloads a provider — or not declared with AI_LLM in this scope)`;\n }\n if (!this.externalProvidersRegistry.isProviderEnabled(providerRef, protocolKind)) return `provider \"${providerRef}\" is disabled`;\n if (!this.externalProvidersRegistry.getProviderApiKey(providerRef, protocolKind)) {\n return this.externalProvidersRegistry.describeMissingProviderApiKey(providerRef, protocolKind);\n }\n const binding = this.backendProviderRegistryService.getProtocolBinding(providerRef, protocolKind);\n if (!binding || binding.runtimeContract.kind !== ProviderProtocolRuntimeKind.LLM) return `provider \"${providerRef}\" declares no LLM_PROVIDER contract`;\n return undefined;\n }\n\n /**\n * Why one declared model alternative cannot take this agent's calls (#2301), or `undefined`: what the provider must be\n * ({@link modelAlternativeReachDefect}), and what the model must serve. The model is judged on the facts the agent's own\n * model is judged on at registration: the catalog row, or a registry provider's declared model, for its reasoning\n * effort; and, where the catalog states the model's capabilities, the ones the agent's calls need (structured output,\n * tools, images). Facts nobody stated fail open, as they do for the agent's own model.\n */\n private describeModelAlternativeDefect(agent: FlowsActors_Agent, config: FlowsActors_Agent_LLMConfiguration, alternative: FlowsActors_Agent_ModelAlternative): string | undefined {\n if (config.executionProfileRef !== undefined) {\n return `declares modelFailover but runs on the execution profile \"${config.executionProfileRef}\"; a model alternative serves the API transport only`;\n }\n if (alternative.providerRef === config.providerRef && alternative.model === config.model) return `names its own model \"${alternative.model}\" as an alternative`;\n const reach = this.modelAlternativeReachDefect(alternative.providerRef);\n if (reach !== undefined) return reach;\n const catalogEntry = Object.hasOwn(LLM_MODEL_CATALOG, alternative.model) ? LLM_MODEL_CATALOG[alternative.model as LLM_Model] : undefined;\n if (catalogEntry !== undefined && catalogEntry.providerRef !== alternative.providerRef) {\n return `model \"${alternative.model}\" is served by \"${catalogEntry.providerRef}\", not by \"${alternative.providerRef}\"`;\n }\n let declaredFacts: Parameters<typeof validateReasoningEffortForModel>[2];\n if (!isLLMCatalogProvider(alternative.providerRef)) {\n const contract = this.externalProvidersRegistry.getProviderRuntimeContract(alternative.providerRef, ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER);\n declaredFacts = (contract?.kind === ProviderProtocolRuntimeKind.LLM ? contract.models?.find((declared) => declared.model === alternative.model) : undefined) ?? {};\n }\n const reasoning = validateReasoningEffortForModel(alternative.model, config.reasoningEffort, declaredFacts);\n if (reasoning !== null) return reasoning;\n const stated = catalogEntry?.ioCapabilities;\n if (stated !== undefined) {\n const needs: { readonly what: string; readonly anyOf: readonly LLM_Model_IO_Capability[] }[] = [];\n if (config.operationKey === LLMProvider_OperationKey.GENERATE_STRUCTURED || config.operationKey === LLMProvider_OperationKey.STREAM_STRUCTURED) {\n needs.push({ what: 'structured output', anyOf: [LLM_Model_IO_Capability.STRUCTURED_OUTPUTS, LLM_Model_IO_Capability.JSON_MODE] });\n }\n if (config.operationKey === LLMProvider_OperationKey.CHAT_MULTIMODAL) {\n needs.push({ what: 'images', anyOf: [LLM_Model_IO_Capability.MULTIMODAL_VISION] });\n }\n if ((agent.capabilities?.tools?.functionRefs?.length ?? 0) + (agent.capabilities?.tools?.mcpRefs?.length ?? 0) > 0) {\n needs.push({ what: 'tools', anyOf: [LLM_Model_IO_Capability.TOOL_USE, LLM_Model_IO_Capability.FUNCTION_CALLING] });\n }\n const missing = needs.filter((need) => !need.anyOf.some((capability) => stated.includes(capability))).map((need) => need.what);\n if (missing.length > 0) return `model \"${alternative.model}\" does not serve ${missing.join(', ')}, which this agent's calls need`;\n }\n return undefined;\n }\n\n /**\n * Refuses startup when an agent declares a model alternative that could not take its calls (#2301): see\n * {@link describeModelAlternativeDefect}. Without this the defect would surface only during the outage the declaration\n * exists for, as an alternative skipped with an ERROR log. The remedy is a configuration or environment edit. Agents\n * that declare no `modelFailover` are unaffected.\n */\n public assertDeclaredFailoverProvidersCanServe(): void {\n const defects: string[] = [];\n for (const agent of Object.values(this.flowsActorsRegistry.getRegistry().agents) as FlowsActors_Agent[]) {\n if (!isLLMAgentConfiguration(agent.config)) continue;\n for (const alternative of agent.config.modelFailover ?? []) {\n const defect = this.describeModelAlternativeDefect(agent, agent.config, alternative);\n if (defect !== undefined) defects.push(`agent \"${agent.ref}\", alternative ${alternative.providerRef}/${alternative.model}: ${defect}`);\n }\n }\n if (defects.length === 0) return;\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `A declared model alternative cannot take an agent's calls: ${defects.join('; ')}. `\n + 'Fix its provider configuration or credential, or remove it from the agent\\'s `modelFailover`.',\n defects,\n },\n });\n }\n\n /**\n * Get model instance from provider client\n */\n private getModelFromProvider(providerClient: any, modelName: string): any {\n if (providerClient && typeof providerClient.languageModel === 'function') {\n try {\n return providerClient.languageModel(modelName);\n } catch (error) {\n this.logger.error('Failed to get model via languageModel()', {\n modelName,\n ...projectCaughtErrorLogFields(error),\n });\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n modelName,\n message: `Failed to initialize model ${modelName} via languageModel() method`,\n originalError: describeCaughtError(error),\n stack: error instanceof Error ? error.stack : undefined,\n },\n }\n );\n }\n }\n\n if (typeof providerClient === 'function') {\n try {\n return providerClient(modelName);\n } catch (error) {\n this.logger.error('Failed to get model via function call', {\n modelName,\n ...projectCaughtErrorLogFields(error),\n });\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n modelName,\n message: `Failed to initialize model ${modelName} via provider function`,\n originalError: describeCaughtError(error),\n stack: error instanceof Error ? error.stack : undefined,\n },\n }\n );\n }\n }\n\n if (providerClient && typeof providerClient.model === 'function') {\n try {\n return providerClient.model(modelName);\n } catch (error) {\n this.logger.error('Failed to get model via model()', {\n modelName,\n ...projectCaughtErrorLogFields(error),\n });\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.VALIDATION,\n context: {\n modelName,\n message: `Failed to initialize model ${modelName} via model() method`,\n originalError: describeCaughtError(error),\n stack: error instanceof Error ? error.stack : undefined,\n },\n }\n );\n }\n }\n\n this.logger.error('Failed to get model from provider client', {\n providerType: typeof providerClient,\n providerKeys: providerClient ? Object.keys(providerClient).slice(0, 10) : [],\n hasLanguageModel: typeof providerClient?.languageModel === 'function',\n hasModel: typeof providerClient?.model === 'function',\n isFunction: typeof providerClient === 'function',\n });\n\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.AGENT_MODEL_INITIALIZATION_FAILED,\n context: {\n // diagnostic (log-only)\n modelName,\n providerType: typeof providerClient,\n hasLanguageModel: typeof providerClient?.languageModel === 'function',\n hasModel: typeof providerClient?.model === 'function',\n isFunction: typeof providerClient === 'function',\n },\n }\n );\n }\n\n /**\n * The provider model a structured-generation call runs on, answered by STREAMING under progress-based deadlines\n * (`streamedGenerationDeadlineMiddleware`). Applied INNERMOST, directly on the provider model: the account-refusal,\n * observation and output-moderation middlewares above it then still take their BUFFERED branch, so a withheld\n * answer is thrown with its usage exactly as before (their stream branches behave differently by design).\n *\n * A deadline is required: without one the call is unbounded. Measured 2026-08-20, a `top_down.market-analysis`\n * generation was dispatched and had still not returned TWELVE HOURS later; the Driver never received a result, the\n * Task-terminalization queue behind it never drained, and the next boot's startup drain inherited the stall.\n *\n * It used to be a 15-minute WALL CLOCK on a non-streaming request, which cannot tell a call still producing\n * tokens from one that hung. That held while OpenAI served the creation lane, and failed the day it moved to\n * Anthropic: a ~100 KB compliance-document candidate was still generating on Sonnet 5 when the clock expired, and\n * every retry spent another 15 minutes (reference run 42365624598, 2026-11-07). Streaming lets the bound be\n * \"nothing received for 5 minutes\", with a one-hour backstop, and the abort is the same `TimeoutError` the retry\n * policy already classifies as TIMEOUT. Both deadlines apply per SDK ATTEMPT (the middleware runs inside the SDK's\n * retry loop), where the old `abortSignal` spanned every retry of the call.\n */\n private withStreamedGenerationDeadlines(model: any): any {\n return wrapLanguageModel({\n model,\n middleware: streamedGenerationDeadlineMiddleware({\n idleMs: STREAMED_GENERATION_IDLE_DEADLINE_MS,\n totalMs: STREAMED_GENERATION_TOTAL_DEADLINE_MS,\n }),\n });\n }\n\n /**\n * The one prompt sent to auto-continue a coding agent past a self-imposed\n * pause. Named here rather than improvised at the call site so a run's\n * continuations are all identical and auditable, and so the wording — which\n * tells the agent to keep working AND to stop only when genuinely done or\n * genuinely blocked — lives in exactly one place.\n */\n private static readonly CODING_AUTO_CONTINUE_PROMPT =\n 'Continue with the task. Do not stop to ask whether to proceed — keep going until the task is '\n + 'genuinely complete. A question written in your reply reaches nobody: if you need a decision or '\n + 'input that only the operator can provide, ask it with your tool for asking the user a question. '\n + 'Otherwise decide, say what you decided in your final report, and finish.';\n\n /** Characters of an end-of-turn message kept on a continuation record for audit. */\n private static readonly CONTINUATION_MESSAGE_TAIL_CHARS = 500;\n\n /**\n * Drive a coding session turn-by-turn: continue a self-imposed pause, park a\n * question the agent ASKED, settle on completion — bounded by the profile's\n * continuation budget.\n *\n * The MECHANISM lives here; the JUDGMENT (`classify`) is the host's. The whole\n * loop fails toward settlement: any terminal stop reason, an exhausted budget,\n * or a classifier that is absent or throws all end the run with what the agent\n * has produced rather than hanging.\n *\n * ## A run parks only on a question the PROTOCOL carried (#3710)\n *\n * The only path that returns a `suspension` is a turn whose agent asked through\n * `elicitation/create` (`ACPTurnResult.explicitQuestion`), and the caller\n * must not read that as a completed result. The classifier's `NEEDS_INPUT`\n * verdict no longer parks: it is a reading of prose, and prose is where an agent\n * narrates. Reference run 42886943490 parked `build-task-seeds-quotes` for a\n * person on \"Writing the demo-quotes seed now; first checking the money value\n * shape…\", in an unattended drive nobody could answer, because the model read\n * a progress note as a question. A `NEEDS_INPUT` turn is now CONTINUED like a\n * self-pause (the continuation prompt tells the agent its prose reaches nobody\n * and how to ask), and settles with what it has once the budget is spent.\n */\n private async driveCodingTurnLadder(params: {\n session: ACPAgentSession;\n firstPrompt: string;\n maxAutoContinuations: number;\n awaitingInputTtlMs: number;\n turnTimeoutMs?: number;\n abortSignal?: AbortSignal;\n classify?: AgentInvocationHostContext['classifyCodingTurnEnd'];\n onStateChange?: AgentInvocationHostContext['onCodingSessionStateChange'];\n }): Promise<{\n finalMessage: string;\n stopReason: CodingAgent_StopReason;\n rawStopReason?: string;\n usage?: CodingAgent_Usage;\n reportedFileLocations: string[];\n deniedPermissionCount: number;\n permissionDecisions: NonNullable<CodingAgent_RunTaskOutput['permissionDecisions']>;\n turnCount: number;\n continuations: CodingAgent_ContinuationRecord[];\n suspension?: CodingAgent_SessionSuspension;\n }> {\n const { session } = params;\n const reportedFileLocations: string[] = [];\n // Copied into the OUTPUT's mutable element shape here: the runner hands out\n // readonly records, and the published contract's field is mutable.\n const permissionDecisions: NonNullable<CodingAgent_RunTaskOutput['permissionDecisions']> = [];\n const continuations: CodingAgent_ContinuationRecord[] = [];\n let usage: CodingAgent_Usage | undefined;\n let deniedPermissionCount = 0;\n let turnIndex = 0;\n let autoContinuesUsed = 0;\n let prompt = params.firstPrompt;\n\n const emitState = (state: CodingSessionLadderState): void => {\n try {\n params.onStateChange?.(state);\n } catch {\n // A live-relay sink must never fail the run it observes.\n }\n };\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n turnIndex += 1;\n emitState({ phase: CodingSessionLadderPhase.RUNNING, turnIndex });\n\n const turn = await session.promptTurn(prompt, {\n ...(params.turnTimeoutMs !== undefined ? { turnTimeoutMs: params.turnTimeoutMs } : {}),\n ...(params.abortSignal ? { abortSignal: params.abortSignal } : {}),\n });\n\n // Aggregate every turn's evidence, whatever the ladder decides next.\n for (const path of turn.reportedFileLocations) {\n if (!reportedFileLocations.includes(path)) reportedFileLocations.push(path);\n }\n for (const decision of turn.permissionDecisions) {\n permissionDecisions.push({\n ...decision,\n locations: [...decision.locations],\n offeredOptionKinds: [...decision.offeredOptionKinds],\n });\n }\n deniedPermissionCount += turn.deniedPermissionCount;\n usage = this.mergeCodingUsage(usage, turn.usage);\n\n const settle = (suspension?: CodingAgent_SessionSuspension) => ({\n finalMessage: turn.finalMessage,\n stopReason: turn.stopReason,\n ...(turn.rawStopReason ? { rawStopReason: turn.rawStopReason } : {}),\n usage,\n reportedFileLocations,\n deniedPermissionCount,\n permissionDecisions,\n turnCount: turnIndex,\n continuations,\n ...(suspension ? { suspension } : {}),\n });\n\n /*\n * The agent ASKED (#3710): the runner cancelled the turn to put the question, so this precedes the stop-reason\n * check, which would read that cancel as terminal. Not when the operator's own abort ended the turn: a run the\n * operator stopped is stopped, whatever it was asking.\n */\n if (turn.explicitQuestion !== undefined && params.abortSignal?.aborted !== true) {\n const suspension: CodingAgent_SessionSuspension = {\n sessionId: session.sessionId,\n question: turn.explicitQuestion,\n turnIndex,\n // Answerable across the child's death only if the agent persists sessions.\n resumable: session.capabilities.loadSession,\n parkedUntil: new Date(Date.now() + params.awaitingInputTtlMs).toISOString(),\n };\n emitState({ phase: CodingSessionLadderPhase.AWAITING_INPUT, turnIndex, question: turn.explicitQuestion });\n return settle(suspension);\n }\n\n // A non-voluntary stop (cancelled, max_tokens, refusal, or a reason this\n // version does not recognise) is terminal: there is nothing to continue.\n if (turn.stopReason !== CodingAgent_StopReason.END_TURN) {\n return settle();\n }\n\n // END_TURN: decide what it meant. No classifier → treat as complete AND\n // record nothing (the pre-ladder behaviour, preserved for every caller\n // that supplies none — a plain single turn carries no continuations).\n if (!params.classify) {\n return settle();\n }\n const classification = await this.classifyCodingTurnEndSafely(params.classify, turn.finalMessage, turnIndex);\n\n // A boundary is recorded only when the classifier was actually consulted,\n // so `continuations` is the audit trail of judgments, never a per-run\n // artefact that pollutes the single-turn shape.\n continuations.push({\n turnIndex,\n classification,\n agentMessageTail: turn.finalMessage.slice(-AgentsBackendService.CONTINUATION_MESSAGE_TAIL_CHARS),\n });\n\n // A prose \"question\" is continued like a self-pause, never parked (#3710, see the method comment): a question\n // the agent means to put to the operator is asked through the protocol, which parked above.\n const continues = classification === CodingAgent_EndOfTurnClassification.SELF_PAUSE\n || classification === CodingAgent_EndOfTurnClassification.NEEDS_INPUT;\n if (!continues || autoContinuesUsed >= params.maxAutoContinuations) {\n // TASK_COMPLETE, CLASSIFIER_UNAVAILABLE, or a pause past the budget:\n // settle with what the agent last produced.\n return settle();\n }\n\n autoContinuesUsed += 1;\n prompt = AgentsBackendService.CODING_AUTO_CONTINUE_PROMPT;\n }\n }\n\n /**\n * Run the host's end-of-turn classifier, mapping every failure to\n * `CLASSIFIER_UNAVAILABLE` so the ladder can settle rather than hang.\n *\n * The whole point of a separate method: the fail-open contract is one place,\n * and an unexpected classifier value (a host returning a string outside the\n * enum) degrades the same way a throw does.\n */\n private async classifyCodingTurnEndSafely(\n classify: NonNullable<AgentInvocationHostContext['classifyCodingTurnEnd']>,\n finalMessage: string,\n turnIndex: number,\n ): Promise<CodingAgent_EndOfTurnClassification> {\n try {\n const result = await classify({ finalMessage, turnIndex });\n if (Object.values(CodingAgent_EndOfTurnClassification).includes(result)) {\n return result;\n }\n this.logger.warn('Coding turn-end classifier returned an unrecognised value; treating the turn as complete', {\n turnIndex,\n received: String(result),\n });\n return CodingAgent_EndOfTurnClassification.CLASSIFIER_UNAVAILABLE;\n } catch (error) {\n // Fail OPEN. An auxiliary judgment must never make the autonomous lane hang\n // or discard a mutated workspace; the failure is recorded, not laundered.\n // The classifier is a model call, so its failure can be a vendor refusal quoting the turn it was asked about:\n // described like every model-call failure (#2368), never its message or JSON by value. A WildoBackendError (which\n // does not pass `instanceof Error`) reads by its `message`, so a missing config bound is still named (2026-09-04).\n this.logger.warn('Coding turn-end classifier failed; treating the turn as complete', {\n turnIndex,\n ...describeModelCallError(error),\n });\n return CodingAgent_EndOfTurnClassification.CLASSIFIER_UNAVAILABLE;\n }\n }\n\n /**\n * Combine per-turn usage into a session total: token counts SUM across turns;\n * the context-window pair and the COST are levels, so the latest turn's value\n * wins. Absence stays absence — a field nobody reported must not read as zero,\n * per the usage contract.\n *\n * Cost is a level because ACP reports it as the session's cumulative total, and\n * every turn of a coding run is a turn of ONE session (`promptTurn` on the same\n * runner). Summing it, as this did until #2232, counted a two-turn run's first\n * turn twice: four of app-creation-test-004's coding runs were two-turn. A turn\n * that reports no cost keeps the earlier turn's figure, which is the session's\n * total so far rather than nothing.\n *\n * spec-cite: ACP schema (`@agentclientprotocol/sdk` 1.5.0) — `UsageUpdate.cost` \"Cumulative session cost (optional)\";\n * the Claude Agent SDK's `total_cost_usd`, which the pinned adapter forwards, is likewise cumulative across turns\n * of a streaming-input session (`sdk.d.ts`, `SDKResultMessage.total_cost_usd`).\n */\n private mergeCodingUsage(\n accumulated: CodingAgent_Usage | undefined,\n turn: CodingAgent_Usage | undefined,\n ): CodingAgent_Usage | undefined {\n if (!turn) return accumulated;\n if (!accumulated) return turn;\n const merged: CodingAgent_Usage = { ...accumulated };\n for (const key of ['inputTokens', 'outputTokens', 'cachedReadTokens', 'cachedWriteTokens', 'totalTokens'] as const) {\n const a = accumulated[key];\n const b = turn[key];\n if (a !== undefined || b !== undefined) merged[key] = (a ?? 0) + (b ?? 0);\n }\n // The context window is a level, not a flow: the newest reading is current.\n if (turn.contextUsed !== undefined) merged.contextUsed = turn.contextUsed;\n if (turn.contextWindowSize !== undefined) merged.contextWindowSize = turn.contextWindowSize;\n // The session's cumulative cost: the latest turn that reported one is the total so far — unless it reported\n // a zero after a positive figure, which is a crashed result's zeroed value and not a cost (`latestCumulativeCost`).\n const cost = latestCumulativeCost(accumulated.cost, turn.cost);\n if (cost !== undefined) merged.cost = { amount: cost.amount, currency: cost.currency };\n return merged;\n }\n\n private buildBaseOptions(config: FlowsActors_Agent_LLMConfiguration): any {\n const baseOptions: any = {\n temperature: config.temperature,\n topP: config.topP,\n };\n\n // Only set maxOutputTokens if explicitly configured\n if (config.maxTokens !== undefined) {\n baseOptions.maxOutputTokens = config.maxTokens;\n }\n\n if (config.seed !== undefined) {\n baseOptions.seed = config.seed;\n }\n\n // Reasoning-effort control (Phase 3): the config enum values mirror the AI\n // SDK 7 top-level `reasoning` option exactly, so this is a direct pass-through.\n // The SDK maps it to each provider's native reasoning setting; non-reasoning\n // models ignore it. Omitted → provider default (pre-Phase-3 behavior).\n if (config.reasoningEffort !== undefined) {\n baseOptions.reasoning = config.reasoningEffort;\n }\n\n // The agent's system prompt is passed via the top-level `instructions:` option of EVERY\n // generateText/streamText call (see `executeGenerateText` and the chat builders below) — AI-SDK v7\n // (`ai@7`) rejects a `role:'system'` entry inside `messages`/`prompt`, and `buildChatMessages`\n // keeps the messages array system-free. Do NOT re-introduce a \"system in messages\" opt-in flag here:\n // a prior `baseOptions.allowSystemInMessages = true` was a SILENT NO-OP (that is not the real option\n // name — the v7 flag is the terse `l` param), which is exactly why every chat turn kept failing with\n // `AI_InvalidPromptError` until the system prompt was hoisted to `instructions:`.\n\n return baseOptions;\n }\n\n /**\n * Execute GENERATE_TEXT operation\n */\n private async executeGenerateText({ model, systemPrompt, instructions, input, baseOptions }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n /** The invocation input: a conversation in it is sent as `messages` (`textGenerationPromptOf`). */\n input?: unknown;\n baseOptions: any;\n }): Promise<AgentOperationExecutionResult> {\n try {\n const result = await generateText({\n model,\n ...this.textGenerationPromptOf(instructions, input),\n instructions: systemPrompt,\n ...baseOptions,\n });\n\n return {\n output: {\n text: result.text,\n },\n usage: this.extractUsage(result.usage),\n };\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Generate text operation failed - provider response', {\n operation: 'GENERATE_TEXT',\n hasSystemPrompt: !!systemPrompt,\n instructionsLength: instructions.length,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'GENERATE_TEXT',\n message: `Failed to generate text: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Execute CHAT_COMPLETION operation\n */\n private async executeChatCompletion({ model, systemPrompt, instructions, input, baseOptions }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n input: any;\n baseOptions: any;\n }): Promise<AgentOperationExecutionResult> {\n try {\n const messages = this.buildChatMessages(instructions, input);\n\n const result = await generateText({\n model,\n messages,\n // System prompt via the top-level option (AI-SDK v7 forbids it inside `messages`).\n instructions: systemPrompt,\n ...baseOptions,\n });\n\n return {\n output: {\n message: {\n role: LLMProvider_MessageRole.ASSISTANT,\n content: result.text,\n },\n },\n usage: this.extractUsage(result.usage),\n };\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Chat completion operation failed - provider response', {\n operation: 'CHAT_COMPLETION',\n hasSystemPrompt: !!systemPrompt,\n hasInputMessages: input && typeof input === 'object' && 'messages' in input,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'CHAT_COMPLETION',\n message: `Failed to complete chat: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Execute CHAT_MULTIMODAL operation\n */\n private async executeChatMultimodal({ model, systemPrompt, instructions, input, baseOptions }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n input: any;\n baseOptions: any;\n }): Promise<AgentOperationExecutionResult> {\n let messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string | Array<any> }> = [];\n\n try {\n if (input && typeof input === 'object' && 'messages' in input && Array.isArray(input.messages)) {\n // System prompt travels via the top-level `instructions:` option; drop any\n // `role:'system'` entries (AI-SDK v7 rejects them inside `messages`).\n messages = input.messages.filter((m: any) => m.role !== 'system');\n } else {\n messages.push({ role: 'user', content: instructions });\n }\n\n if (messages.length === 0) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.AGENT_MESSAGES_REQUIRED,\n context: {\n // diagnostic (log-only)\n operation: 'CHAT_MULTIMODAL',\n },\n }\n );\n }\n\n const result = await generateText({\n model,\n messages: this.normalizeSdkMessages(messages),\n // System prompt via the top-level option (AI-SDK v7 forbids it inside `messages`).\n instructions: systemPrompt,\n ...baseOptions,\n });\n\n return {\n output: {\n message: {\n role: LLMProvider_MessageRole.ASSISTANT,\n content: result.text,\n },\n },\n usage: this.extractUsage(result.usage),\n };\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Chat multimodal operation failed - provider response', {\n operation: 'CHAT_MULTIMODAL',\n hasSystemPrompt: !!systemPrompt,\n hasInputMessages: input && typeof input === 'object' && 'messages' in input,\n messagesCount: messages.length,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'CHAT_MULTIMODAL',\n message: `Failed to complete multimodal chat: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Read the OPTIONAL vision image parts off a GENERATE_STRUCTURED invocation\n * input (see `LLMProvider_GenerateStructuredInputSchema.images`). Returns `[]`\n * when none are present so the caller stays on the plain text-prompt path.\n * Defensive at the boundary: only well-formed `{ type: 'image', image }` parts\n * (non-empty string locator) survive; anything else is dropped rather than\n * handed to the SDK as a broken content part.\n */\n private extractStructuredInputImages(input: unknown): LLMProvider_ImageContent[] {\n if (!this.isRecord(input) || !Array.isArray(input.images)) {\n return [];\n }\n return (input.images as unknown[]).filter(\n (part): part is LLMProvider_ImageContent =>\n this.isRecord(part)\n && part.type === 'image'\n && typeof part.image === 'string'\n && part.image.length > 0,\n );\n }\n\n /**\n * Build the AI-SDK content argument for a structured-generation call.\n *\n * With no images this is a plain `{ prompt }` (text-only structured\n * generation — the historical behaviour, byte-identical). With images it\n * becomes a single multimodal user `{ messages: [...] }` whose content is the\n * instruction text followed by each image part, so the AI SDK feeds the pixels\n * to a vision-capable model (e.g. `gpt-4o`) and constrains the answer to the\n * requested schema. `system` is passed separately by the caller and is not\n * duplicated here.\n */\n private buildStructuredContentArgs(\n instructions: string,\n images: LLMProvider_ImageContent[],\n ): { prompt: string } | { messages: Array<{ role: 'user'; content: Array<Record<string, unknown>> }> } {\n if (images.length === 0) {\n return { prompt: instructions };\n }\n return {\n messages: [\n {\n role: 'user',\n content: [\n { type: 'text', text: instructions },\n ...images.map((part) => this.toSdkFilePart(part.image)),\n ],\n },\n ],\n };\n }\n\n /**\n * Translate our internal image locator (`LLMProvider_ImageContent.image` — a\n * data URI or URL) into an AI SDK v7 **file content part**.\n *\n * WHY: the SDK's `{ type: 'image', image }` content part was deprecated in v7\n * (it warns on every call and becomes a hard error in a future major). The v7\n * shape is `{ type: 'file', data, mediaType }`. This is the ONE translation\n * seam — our own `{ type: 'image', image }` domain vocabulary\n * ({@link LLMProvider_ImageContentSchema}) is intentionally kept; only the\n * SDK-facing emission changes.\n *\n * `mediaType` is required by the file part. We derive the concrete type from a\n * data URI when present (the case both internal producers actually emit —\n * they build `data:image/<fmt>;base64,…`); for a bare URL we sniff the\n * extension and fall back to the generic `image/*` the SDK itself suggests.\n */\n private toSdkFilePart(image: string): { type: 'file'; data: string; mediaType: string } {\n return { type: 'file', data: image, mediaType: this.deriveImageMediaType(image) };\n }\n\n /** Best-effort image media-type from a data URI or URL; generic `image/*` if unknown. */\n private deriveImageMediaType(image: string): string {\n const dataUri = /^data:(image\\/[^;]+)[;,]/i.exec(image);\n if (dataUri) return dataUri[1].toLowerCase();\n const ext = /\\.(png|jpe?g|gif|webp|bmp|svg|avif|tiff?)(?:[?#]|$)/i.exec(image);\n if (ext) {\n const e = ext[1].toLowerCase();\n if (e === 'jpg' || e === 'jpeg') return 'image/jpeg';\n if (e === 'svg') return 'image/svg+xml';\n if (e === 'tif' || e === 'tiff') return 'image/tiff';\n return `image/${e}`;\n }\n return 'image/*';\n }\n\n /**\n * Rewrite any legacy `{ type: 'image', image }` parts inside caller-supplied\n * CHAT_MULTIMODAL messages into v7 file parts, leaving every other part\n * untouched. Defensive: the internal producers route images through the\n * structured path above, but CHAT_MULTIMODAL forwards opaque caller `messages`\n * verbatim, so a caller passing the deprecated shape would otherwise leak it\n * to the SDK. Fail-open on unexpected shapes — never drop a caller's content.\n */\n private normalizeSdkMessages(\n messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string | Array<any> }>,\n ): Array<{ role: 'system' | 'user' | 'assistant'; content: string | Array<any> }> {\n return messages.map((message) => {\n if (!Array.isArray(message.content)) return message;\n const content = message.content.map((part) =>\n this.isRecord(part) && part.type === 'image' && typeof part.image === 'string'\n ? this.toSdkFilePart(part.image)\n : part,\n );\n return { ...message, content };\n });\n }\n\n /**\n * Execute GENERATE_STRUCTURED operation\n */\n private async executeGenerateStructured({\n model,\n systemPrompt,\n instructions,\n input,\n baseOptions,\n llmProviderConfig,\n providerRef,\n structuredGenerationExecutionMode,\n maximumStructuredOutputLeafFields,\n }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n input: any;\n baseOptions: any;\n llmProviderConfig?: LLMProvider_Configuration;\n providerRef: string;\n structuredGenerationExecutionMode?: StructuredGenerationExecutionMode;\n maximumStructuredOutputLeafFields?: number;\n }): Promise<AgentOperationExecutionResult> {\n try {\n if (!input || typeof input !== 'object' || !('schema' in input) || !input.schema) {\n throw this.errorBuilder.buildError(\n ErrorType.VALIDATION,\n undefined,\n {\n customMessageReference: ErrorCustomMessageReference.AGENT_STRUCTURED_SCHEMA_REQUIRED,\n context: {\n // diagnostic (log-only)\n operation: 'GENERATE_STRUCTURED',\n hasInput: !!input,\n inputType: typeof input,\n hasSchema: input && typeof input === 'object' && 'schema' in input,\n },\n }\n );\n }\n\n const schema = input.schema;\n const images = this.extractStructuredInputImages(input);\n if (\n structuredGenerationExecutionMode === StructuredGenerationExecutionMode.SINGLE_CALL_REQUIRED\n && (!Number.isSafeInteger(maximumStructuredOutputLeafFields) || (maximumStructuredOutputLeafFields ?? 0) <= 0)\n ) {\n throw this.errorBuilder.buildError(ErrorType.CONFIGURATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: {\n operation: 'GENERATE_STRUCTURED',\n message: 'A single-call structured agent requires one positive immutable maximumStructuredOutputLeafFields value.',\n },\n });\n }\n const maxFields = maximumStructuredOutputLeafFields\n ?? llmProviderConfig?.maxStructuredDataFieldAllowed\n ?? DEFAULT_MAX_STRUCTURED_DATA_FIELD_ALLOWED;\n const isOpenAI = this.llmProviderRequestsStrictJsonSchema(providerRef);\n const strictSchemaProfile = isOpenAI === true ? this.llmProviderStrictSchemaProfile(providerRef) : undefined;\n const nativeConstrainedDecoding = isOpenAI === true ? undefined : this.llmProviderNativeConstrainedDecoding(providerRef);\n\n const shapePlan = planStructuredGenerationShape(schema, maxFields);\n\n this.logDebug('Checking if schema needs chunking', {\n leafFieldCount: shapePlan.leafFieldCount,\n maxFields,\n needsChunking: shapePlan.planKind === StructuredGenerationPlanKind.CHUNKED,\n unchunkableOverLimit: shapePlan.planKind === StructuredGenerationPlanKind.UNCHUNKABLE_OVER_LIMIT,\n isOpenAI,\n imageCount: images.length,\n });\n\n if (\n structuredGenerationExecutionMode === StructuredGenerationExecutionMode.SINGLE_CALL_REQUIRED\n && shapePlan.planKind !== StructuredGenerationPlanKind.SINGLE_CALL\n ) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: {\n operation: 'GENERATE_STRUCTURED',\n message: 'The registered agent requires one physical provider call, but the output schema requires chunking.',\n leafFieldCount: shapePlan.leafFieldCount,\n maxFields,\n },\n });\n }\n\n if (shapePlan.planKind === StructuredGenerationPlanKind.UNCHUNKABLE_OVER_LIMIT) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: {\n operation: 'GENERATE_STRUCTURED',\n message: 'The output schema exceeds the provider field limit and its root semantics cannot be preserved across chunks.',\n leafFieldCount: shapePlan.leafFieldCount,\n maxFields,\n },\n });\n }\n\n if (shapePlan.planKind === StructuredGenerationPlanKind.CHUNKED) {\n return await this.executeGenerateStructuredChunked({\n model,\n systemPrompt,\n instructions,\n images,\n schema,\n baseOptions,\n maxFields,\n leafFieldCount: shapePlan.leafFieldCount,\n schemaChunks: shapePlan.schemaChunks,\n isOpenAI,\n strictSchemaProfile,\n nativeConstrainedDecoding,\n });\n } else {\n return await this.executeGenerateStructuredSingle({\n model,\n systemPrompt,\n instructions,\n images,\n schema,\n baseOptions,\n isOpenAI,\n strictSchemaProfile,\n nativeConstrainedDecoding,\n includeRejectedAnswer: (input as { includeRejectedAnswer?: unknown }).includeRejectedAnswer === true,\n });\n }\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Generate structured operation failed - provider response', {\n operation: 'GENERATE_STRUCTURED',\n hasSchema: input && typeof input === 'object' && 'schema' in input,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'GENERATE_STRUCTURED',\n message: `Failed to generate structured data: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Execute structured generation with chunking - runs chunks in parallel\n */\n private async executeGenerateStructuredChunked({ model, systemPrompt, instructions, images, schema, baseOptions, maxFields, leafFieldCount, schemaChunks, isOpenAI, strictSchemaProfile, nativeConstrainedDecoding }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n images: LLMProvider_ImageContent[];\n schema: z.ZodSchema<any>;\n baseOptions: any;\n maxFields: number;\n leafFieldCount: number;\n schemaChunks: readonly z.ZodSchema[];\n isOpenAI: boolean | null;\n /** The provider's strict-mode limits, present when it requests strict decoding (#2344). */\n strictSchemaProfile?: StrictStructuredOutputProfile;\n /** The provider's native constrained-decoding limits and unconstrained path, when it declares them (#3146). */\n nativeConstrainedDecoding?: NativeConstrainedDecodingContract;\n }): Promise<AgentOperationExecutionResult> {\n try {\n this.logDebug('Chunking structured generation - parallel execution', {\n totalLeafFields: leafFieldCount,\n maxFields,\n chunks: schemaChunks.length,\n isOpenAI,\n });\n\n // Execute all chunks in parallel using Promise.all\n const chunkPromises = schemaChunks.map(async (chunkSchema, index) => {\n try {\n this.logDebug(`Starting structured chunk ${index + 1}/${schemaChunks.length}`);\n\n const prepared = this.prepareStructuredOutputSchema(chunkSchema, isOpenAI, strictSchemaProfile, nativeConstrainedDecoding, languageModelId(model));\n const chunkResult = await this.generateObjectHonouringStrictRefusal(prepared, (call) => generateObject({\n model,\n mode: \"json\",\n instructions: systemPrompt,\n schema: call.schema,\n ...this.buildStructuredContentArgs(instructions, images),\n ...this.structuredCallBaseOptions(baseOptions, call),\n ...call.providerOptions,\n }));\n\n this.logDebug(`Completed structured chunk ${index + 1}/${schemaChunks.length}`);\n\n return {\n index,\n object: chunkResult.object as Record<string, unknown>,\n usage: this.extractUsage(chunkResult.usage),\n failure: null as unknown,\n };\n } catch (error) {\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error(`Failed to generate structured chunk ${index + 1}/${schemaChunks.length} - provider response`, {\n operation: 'GENERATE_STRUCTURED',\n chunkIndex: index,\n totalChunks: schemaChunks.length,\n ...errorDetails,\n });\n\n // Same rule the single-call path states: a structured-generation failure carrying provider\n // usage IS a completed physical call, so throwing here discards billable truth. This site\n // used to throw, and it cost a live application its budget allocation PERMANENTLY -- the\n // discarded usage made the settlement ACCOUNTING_UNVERIFIABLE, which fail-closes every later\n // admission on that allocation, and a Work Cycle's allocation is bootstrapped once for the\n // application's life. The provider had reported exact usage on the very error we then called\n // unverifiable (6,680 input / 3,521 output tokens, with the cache-write split).\n //\n // Returning rather than throwing also keeps the SIBLING chunks' metering, which `Promise.all`\n // would otherwise drop on the floor along with this one.\n return {\n index,\n object: null,\n usage: this.extractUsage(\n typeof error === 'object' && error !== null && 'usage' in error\n ? (error as { usage: unknown }).usage\n : undefined,\n ),\n failure: error as unknown,\n };\n }\n });\n\n // Wait for all chunks to complete in parallel\n const chunkResultsWithMeta = await Promise.all(chunkPromises);\n\n // Sort by index to ensure consistent merge order, then extract objects\n const chunkResults = chunkResultsWithMeta\n .sort((a, b) => a.index - b.index)\n .flatMap(r => (r.object === null ? [] : [r.object]));\n\n // Aggregate usage from all chunks. A cache or reasoning split is summed only when EVERY chunk reported\n // it (#1598): a total over the chunks that happened to report would understate the split and read as exact.\n const { inputTokenDetails: exactInputTokenDetails, outputTokenDetails: exactOutputTokenDetails, ...totalUsage } =\n this.aggregateExtractedUsage(chunkResultsWithMeta.map((result) => result.usage));\n\n // Aggregate metering FIRST (above), then decide the outcome: a partially-failed chunked call is\n // still a set of completed, billable physical calls, and the Driver must be able to account for\n // every one of them before it classifies the missing object.\n // #2292 Phase 3: a chunk withheld by output moderation fails the whole answer as a withholding, metered over EVERY\n // chunk (siblings included) — the reason the chunks return their failure rather than throw.\n const withheldChunk = chunkResultsWithMeta.find((result) => result.failure instanceof AgentOutputWithheldError);\n if (withheldChunk !== undefined) {\n throw (withheldChunk.failure as AgentOutputWithheldError).withUsage({\n ...totalUsage,\n ...(exactInputTokenDetails === undefined ? {} : { inputTokenDetails: exactInputTokenDetails }),\n ...(exactOutputTokenDetails === undefined ? {} : { outputTokenDetails: exactOutputTokenDetails }),\n });\n }\n // #3204: a chunk the provider's ACCOUNT refused (no credits, a spend limit) is no answer the model failed to give.\n // Returned as a missing object it would read as the model's failure and be asked again; it fails the call as the\n // environment's refusal instead, whose remedy is a person's.\n const accountRefusedChunk = chunkResultsWithMeta.find((result) => result.failure !== null && readModelProviderAccountRefusal(result.failure) !== undefined);\n if (accountRefusedChunk !== undefined) {\n const errorDetails = this.extractProviderErrorDetails(accountRefusedChunk.failure);\n throw this.buildModelCallFailure(accountRefusedChunk.failure, errorDetails, {\n operation: 'GENERATE_STRUCTURED',\n message: `Failed to generate structured data with chunking: ${errorDetails.errorMessage}`,\n });\n }\n const failedChunk = chunkResultsWithMeta.find((result) => result.object === null);\n // `includeRejectedAnswer` is deliberately NOT honoured here: a failed chunk's text is one fragment of\n // the answer, and handing it to a retry as \"your previous answer\" would tell the model it wrote less\n // than it did. A chunked caller keeps the findings-only retry.\n if (failedChunk !== undefined) {\n const failureError = failedChunk.failure as { cause?: unknown; finishReason?: unknown; text?: unknown };\n return {\n output: { object: undefined },\n usage: {\n ...totalUsage,\n ...(exactInputTokenDetails === undefined ? {} : { inputTokenDetails: exactInputTokenDetails }),\n ...(exactOutputTokenDetails === undefined ? {} : { outputTokenDetails: exactOutputTokenDetails }),\n },\n structuredGenerationFailure: this.buildStructuredGenerationFailure(\n typeof failedChunk.failure === 'object' && failedChunk.failure !== null && 'usage' in failedChunk.failure\n ? LLMProvider_StructuredGenerationFailureKind.INVALID_OBJECT_AFTER_COMPLETED_CALL\n : LLMProvider_StructuredGenerationFailureKind.NO_OBJECT_GENERATED,\n failedChunk.failure,\n failureError,\n ),\n };\n }\n\n const mergedResult = this.mergeChunkedObjects(chunkResults);\n\n this.logDebug('All structured chunks completed and merged', {\n chunks: schemaChunks.length,\n totalUsage,\n });\n\n return {\n output: {\n object: mergedResult,\n },\n usage: {\n ...totalUsage,\n ...(exactInputTokenDetails === undefined ? {} : { inputTokenDetails: exactInputTokenDetails }),\n ...(exactOutputTokenDetails === undefined ? {} : { outputTokenDetails: exactOutputTokenDetails }),\n },\n };\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'GENERATE_STRUCTURED',\n message: `Failed to generate structured data with chunking: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Assemble the caller-facing reason a structured generation produced no object.\n *\n * Carries NO generated text — only `generatedTextLength`, which separates a truncated\n * completion from an empty one without disclosing content. `validationIssues` likewise\n * carries only an issue's code, path, what the SCHEMA expected, and — for a `custom` issue\n * alone — the sentence a refinement in this repository's own source wrote. Never Zod's\n * message for any other code, which is composed around the rejected value\n * (see {@link projectStructuredValidationIssues}).\n *\n * The chunked path calls this too. It used to throw a typed backend error instead, on the\n * reasoning that the reason \"already reaches the caller intact\" -- true of the REASON and false\n * of the USAGE, which is what the budget settles against. See the failure branch in\n * {@link executeGenerateStructuredChunked} for what that cost.\n */\n private buildStructuredGenerationFailure(\n kind: LLMProvider_StructuredGenerationFailureKind,\n error: unknown,\n providerError: { cause?: unknown; finishReason?: unknown; text?: unknown },\n ): LLMProvider_StructuredGenerationFailure {\n const errorName = error instanceof Error\n ? error.name\n : (typeof error === 'object' && error !== null && 'name' in error && typeof error.name === 'string'\n ? error.name\n : typeof error);\n const cause = providerError.cause;\n const validationCauseName = cause instanceof Error\n ? cause.name\n : (typeof cause === 'object' && cause !== null && 'name' in cause && typeof cause.name === 'string'\n ? cause.name\n : typeof cause);\n const validationIssues = projectStructuredValidationIssues(cause);\n // ROOT KEY NAMES, and only when the failure is `unrecognized_keys`.\n //\n // Zod 4 builds that issue at two sites and only one carries `keys` (v4/core/schemas.js:748 vs :1352);\n // the path taken here is the one that omits them, so the issue reports \"some unknown key exists at the\n // root\" and nothing more. That is undiagnosable: a single stray key discards a 40,000-character result\n // and there is no way to learn which key it was.\n //\n // The boundary this function holds is about VALUES: the rejected content must never reach a log. Root\n // KEY NAMES of a schema-driven generation are schema shape, are compared against a schema the reader\n // already has, and are emitted only on this one failure code -- never for `invalid_type`,\n // `invalid_format` or any issue whose path could name user content.\n const rootKeys = validationIssues.some((issue) => issue.code === 'unrecognized_keys')\n ? projectStructuredRootKeyNames(providerError.text)\n : undefined;\n return {\n kind,\n /*\n * NOT `describeCaughtError(error)`, which resolves to `error.message` — and an AI SDK\n * structured-generation error's message IS a JSON serialization of the whole error, carrying\n * `text` (the model's rejected output), `response.body` and the validation `value`.\n *\n * The rule was already written down one field over: `LLMProvider_StructuredValidationIssueSchema`\n * drops each issue's own `message` because \"a provider validation error retains the rejected\n * value in its message, so carrying it would copy private model output into any log, trace or\n * persisted failure record that receives this reason\". That is exactly this field — and the\n * envelope's own schema promises \"Contains NO generated text\", a promise this line broke for\n * every consumer, including `describeStructuredGenerationFailure`, whose docstring repeats it.\n *\n * Built from the two payload-free facts already resolved above. Nothing diagnostic is lost:\n * `errorName`, `validationCauseName`, `validationIssues`, `finishReason` and\n * `generatedTextLength` carry the whole picture, and the rejected text still reaches a caller\n * that explicitly opted in — on the OUTPUT, where this boundary does not apply.\n */\n message: `${errorName} (${kind})`,\n errorName,\n validationCauseName,\n ...(validationIssues.length > 0\n ? {\n validationIssues: validationIssues.map((issue) => ({\n code: issue.code,\n path: [...issue.path],\n ...(issue.keys ? { keys: [...issue.keys] } : {}),\n ...(issue.expected ? { expected: issue.expected } : {}),\n ...(issue.format ? { format: issue.format } : {}),\n ...(issue.pattern ? { pattern: issue.pattern } : {}),\n ...(issue.values ? { values: [...issue.values] } : {}),\n ...(issue.refinementMessage ? { refinementMessage: issue.refinementMessage } : {}),\n })),\n }\n : {}),\n ...(rootKeys && rootKeys.length > 0 ? { rootKeys: [...rootKeys] } : {}),\n ...(typeof providerError.finishReason === 'string' ? { finishReason: providerError.finishReason } : {}),\n generatedTextLength: typeof providerError.text === 'string' ? providerError.text.length : null,\n };\n }\n\n /**\n * The schema a structured call sends, and whether it is decoded STRICTLY (#2344).\n *\n * A provider whose contract requests strict JSON Schema (`structuredOutputs.strictJsonSchema: true`) is\n * sent the strict form derived from the Zod schema (`deriveStrictStructuredOutputSchema`): every\n * property required, every object closed, optional members as a `null` union. The Zod schema stays the\n * VALIDATOR, through `jsonSchema(…, { validate })`, after the answer is restored to its own shape, so\n * defaults, refinements and the paths of any rejection are exactly what they were. A schema with no\n * strict form is sent as it is with strict mode OFF, and the reason is logged.\n *\n * `restoreAnswerText` maps a REJECTED answer's text back to the original shape too: a retry patches\n * that text as \"your previous answer\", and the `null`s strict decoding wrote for absent members would\n * otherwise read as values the original schema refuses.\n *\n * A provider that instead declares NATIVE constrained decoding with complexity limits (Anthropic, #3146) is\n * prepared by `prepareForNativeConstrainedDecoding`: the schema is sent as it is, constrained or not depending on\n * whether it fits those limits, and nothing is derived or restored.\n */\n private prepareStructuredOutputSchema(\n schema: z.ZodSchema<any>,\n requestsStrictJsonSchema: boolean | null,\n strictSchemaProfile: StrictStructuredOutputProfile | undefined,\n nativeConstrainedDecoding?: NativeConstrainedDecodingContract,\n modelId?: string,\n ): PreparedStructuredOutputSchema {\n // The model answers in JSON (#3478): the schema it is decoded with, and described to it, is the JSON form of the one\n // declared, so a `z.date()` reads an RFC 3339 string and has a JSON Schema shape at all (a plain date has none).\n schema = jsonParsingSchemaOf(schema);\n const asSent = (strictJsonSchema: boolean | null) => (strictJsonSchema === null ? {} : { providerOptions: { openai: { strictJsonSchema } } });\n const lax = { schema, providerOptions: asSent(requestsStrictJsonSchema === null ? null : false) };\n if (requestsStrictJsonSchema !== true && nativeConstrainedDecoding !== undefined) {\n return this.prepareForNativeConstrainedDecoding(schema, nativeConstrainedDecoding, modelId);\n }\n if (requestsStrictJsonSchema !== true) {\n return { strict: undefined, lax: { schema, providerOptions: asSent(requestsStrictJsonSchema) }, decodedStrictly: false, restoreAnswerText: (text) => text };\n }\n if (strictSchemaProfile === undefined) {\n // The contract type makes the profile required beside `strictJsonSchema: true`; this is the door for\n // a caller that reached here without one, and it decodes as before rather than guessing limits.\n this.logger.warn('Strict structured output requested with no strict-mode profile; decoding without strict mode', { operation: 'GENERATE_STRUCTURED' });\n return { strict: undefined, lax, decodedStrictly: false, restoreAnswerText: (text) => text };\n }\n const derived = deriveStrictStructuredOutputSchema(schema, strictSchemaProfile);\n if (derived.kind === StrictStructuredOutputSchemaKind.UNREPRESENTABLE) {\n this.logger.warn('Structured output has no strict schema form; decoding without strict mode', {\n operation: 'GENERATE_STRUCTURED',\n reasons: derived.reasons.slice(0, 10),\n reasonCount: derived.reasons.length,\n });\n return { strict: undefined, lax, decodedStrictly: false, restoreAnswerText: (text) => text };\n }\n if (derived.narrowings.length > 0) {\n // At info, not debug: a narrowing is a place the model CANNOT write, and the module that finds it\n // promises it is reported, never hidden (#2344 review).\n this.logger.info('Strict structured output leaves members out of decoding', { operation: 'GENERATE_STRUCTURED', narrowings: derived.narrowings });\n }\n const prepared: PreparedStructuredOutputSchema = {\n strict: {\n schema: jsonSchema(derived.jsonSchema as Parameters<typeof jsonSchema>[0], {\n validate: (value) => {\n const parsed = schema.safeParse(derived.restore(value));\n return parsed.success ? { success: true, value: parsed.data } : { success: false, error: parsed.error };\n },\n }),\n providerOptions: asSent(true),\n },\n lax,\n decodedStrictly: true,\n restoreAnswerText: (text) => {\n if (!prepared.decodedStrictly) return text;\n try {\n return JSON.stringify(derived.restore(JSON.parse(text)));\n } catch {\n return text;\n }\n },\n };\n return prepared;\n }\n\n /**\n * How a structured call is sent to a provider whose NATIVE constrained decoding has complexity limits (#3146).\n *\n * Anthropic compiles the schema of a structured call into a decoding grammar and refuses one with more than 24\n * optional or 16 union-typed parameters. `HumanInputFormSchema` carries 32 optionals, so every form an\n * Anthropic-backed agent composed was refused. The composer now sends only the field types its questions admit\n * (`humanInputFormSchemaForFields`), in a vocabulary without validation constraints, which fits every combination\n * of question kinds (21 optional parameters at most, #3176): the unconstrained path is the fallback, not the plan,\n * since without the grammar the model may answer the wrong shape (measured: 5 of 20 free-text forms invalid).\n * A schema within the declared limits is sent constrained, with the\n * unconstrained path as its retry; one over them, or one that cannot be measured, goes straight to the unconstrained\n * path. A model that refuses the unconstrained path is sent the constrained call only: if the schema is over the\n * limits the provider's refusal is the answer, and the warning says why. The Zod schema is the validator in every\n * case, so no answer is accepted that it refuses; past the limits only decoding-time enforcement is given up.\n */\n private prepareForNativeConstrainedDecoding(\n schema: z.ZodSchema<any>,\n native: NativeConstrainedDecodingContract,\n modelId: string | undefined,\n ): PreparedStructuredOutputSchema {\n const constrained: PreparedStructuredOutputCall = { schema, providerOptions: { providerOptions: native.constrainedProviderOptions } };\n const complexity = measureConstrainedDecodingComplexity(schema);\n const overLimits = exceedsConstrainedDecodingLimits(complexity, native.limits);\n const measured = {\n operation: 'GENERATE_STRUCTURED',\n model: modelId ?? null,\n optionalParameters: complexity?.optionalParameters ?? null,\n unionTypedParameters: complexity?.unionTypedParameters ?? null,\n limits: native.limits,\n };\n /*\n * The same conversion the SDK applies to the Zod schema (`asSchema`), minus the keywords that only validate, and\n * validated by that same schema: the answer is held to every pattern and bound, after decoding instead of during it.\n */\n const sent = asSchema(schema);\n const relaxed: PreparedStructuredOutputCall = {\n schema: jsonSchema(async (): Promise<JSONSchema7> => withoutDecodingValidationConstraints(await sent.jsonSchema) as JSONSchema7, {\n validate: async (value) => {\n const parsed = await schema.safeParseAsync(value);\n return parsed.success ? { success: true, value: parsed.data } : { success: false, error: parsed.error };\n },\n }),\n providerOptions: { providerOptions: native.constrainedProviderOptions },\n };\n const path = native.unconstrainedPath;\n if (modelId !== undefined && path.refusedByModels.includes(modelId)) {\n if (overLimits) this.logger.warn('Structured output exceeds the provider\\'s constrained-decoding limits, and this model admits no unconstrained path; the provider is expected to refuse it', measured);\n // Its one fallback is the relaxed CONSTRAINED call (#3204): the model refuses the unconstrained path outright.\n return { strict: constrained, lax: relaxed, laxIsRelaxedConstrained: true, decodedStrictly: false, restoreAnswerText: (text) => text };\n }\n const unconstrained: PreparedStructuredOutputCall = { schema, providerOptions: { providerOptions: path.providerOptions }, withoutReasoning: path.forcesToolUse };\n if (overLimits) {\n // Relaxing removes no optional or union-typed parameter, so it cannot bring a schema over the COUNTED limits back under them.\n this.logger.info('Structured output exceeds the provider\\'s constrained-decoding limits; sending it unconstrained', measured);\n return { strict: undefined, lax: unconstrained, decodedStrictly: false, restoreAnswerText: (text) => text };\n }\n return { strict: constrained, relaxed, lax: unconstrained, decodedStrictly: false, restoreAnswerText: (text) => text };\n }\n\n /** The call's base options, without the agent's reasoning setting when the prepared call is sent without it (#3146). */\n private structuredCallBaseOptions(baseOptions: any, call: PreparedStructuredOutputCall): any {\n if (!call.withoutReasoning || baseOptions?.reasoning === undefined) return baseOptions;\n const { reasoning: _omitted, ...rest } = baseOptions;\n return rest;\n }\n\n /**\n * Run a structured call strictly when it was prepared that way, and once more WITHOUT strict mode when\n * the provider refuses the request because of the schema it was sent (`isStrictSchemaRequestRefusal`, or a\n * native constrained decoder's complexity refusal, `isConstrainedDecodingComplexityRefusal`, #3146).\n *\n * A native decoder's refusal over the grammar's SIZE is first answered with the RELAXED constrained call when one was\n * prepared (#3204): the same grammar without its validation-only keywords. Only a second complexity refusal reaches\n * `lax`. A refusal over a COUNTED limit goes straight to `lax`, since relaxing removes no counted parameter.\n *\n * The door beside the refusal (`design-philosophy.md`, \"Immutability needs a paired mutation path\"): a\n * strict schema the derivation judged representable that the provider still refuses must never stop\n * generation. It costs one request that produced nothing, and it is logged, so a schema the derivation\n * misjudges is visible rather than silent.\n */\n private async generateObjectHonouringStrictRefusal<T>(\n prepared: PreparedStructuredOutputSchema,\n call: (sent: PreparedStructuredOutputCall) => Promise<T>,\n ): Promise<T> {\n if (prepared.strict === undefined) return call(prepared.lax);\n try {\n return await call(prepared.strict);\n } catch (error) {\n if (!isStrictSchemaRequestRefusal(error) && !isConstrainedDecodingComplexityRefusal(error)) throw error;\n const describe = (refusal: unknown) => (refusal instanceof Error ? refusal.message.slice(0, 500) : String(refusal).slice(0, 500));\n prepared.decodedStrictly = false;\n if (prepared.relaxed !== undefined && isCompiledGrammarSizeRefusal(error)) {\n this.logger.warn('The provider refused the structured-output schema as too complex to compile; retrying it constrained without its validation-only keywords', {\n operation: 'GENERATE_STRUCTURED',\n errorMessage: describe(error),\n });\n try {\n return await call(prepared.relaxed);\n } catch (relaxedError) {\n if (!isConstrainedDecodingComplexityRefusal(relaxedError)) throw relaxedError;\n error = relaxedError;\n }\n }\n this.logger.warn(prepared.laxIsRelaxedConstrained === true\n ? 'The provider refused the structured-output schema it was sent; retrying it constrained without its validation-only keywords'\n : 'The provider refused the structured-output schema it was sent; retrying without constrained decoding', {\n operation: 'GENERATE_STRUCTURED',\n errorMessage: describe(error),\n });\n return call(prepared.lax);\n }\n }\n\n /**\n * Execute structured generation without chunking\n */\n private async executeGenerateStructuredSingle({ model, systemPrompt, instructions, images, schema, baseOptions, isOpenAI, strictSchemaProfile, nativeConstrainedDecoding, includeRejectedAnswer = false }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n images: LLMProvider_ImageContent[];\n schema: z.ZodSchema<any>;\n baseOptions: any;\n isOpenAI: boolean | null;\n /** The provider's strict-mode limits, present when it requests strict decoding (#2344). */\n strictSchemaProfile?: StrictStructuredOutputProfile;\n /** The provider's native constrained-decoding limits and unconstrained path, when it declares them (#3146). */\n nativeConstrainedDecoding?: NativeConstrainedDecodingContract;\n /** See `LLMProvider_GenerateStructuredInputSchema.includeRejectedAnswer`. */\n includeRejectedAnswer?: boolean;\n }): Promise<AgentOperationExecutionResult> {\n // Outside the `try`: the catch arms below read whether the call that threw decoded strictly, to map a\n // rejected answer's text back to the original schema's shape (#2344).\n const prepared = this.prepareStructuredOutputSchema(schema, isOpenAI, strictSchemaProfile, nativeConstrainedDecoding, languageModelId(model));\n try {\n this.logDebug('Generating structured normally', {\n hasSchema: !!schema,\n instructionsLength: instructions.length,\n hasSystemPrompt: !!systemPrompt,\n isOpenAI,\n imageCount: images.length,\n });\n\n const result = await this.generateObjectHonouringStrictRefusal(prepared, (call) => generateObject({\n model,\n mode: \"json\",\n instructions: systemPrompt,\n schema: call.schema,\n ...this.buildStructuredContentArgs(instructions, images),\n ...this.structuredCallBaseOptions(baseOptions, call),\n ...call.providerOptions,\n }));\n\n return {\n output: {\n object: result.object,\n },\n usage: this.extractUsage(result.usage),\n // The THIRD path that can hand a caller `{ object: undefined }`, and the one the\n // two catch arms below hide: `generateObject` RESOLVING with no object at all.\n // That is off-contract for the AI SDK — `object` is declared non-optional and\n // absence is signalled by throwing — but nothing here validates that, so leaving\n // it unattached would put a hole in the vocabulary's own invariant (every path\n // that returns no object says why), precisely where a caller has the least other\n // evidence: no error was raised, so `finishReason` and a validation cause do not\n // exist either. Attaching it costs one comparison on the success path and keeps\n // \"no `structuredGenerationFailure`\" meaning \"there IS an object\".\n ...(result.object === undefined\n ? {\n structuredGenerationFailure: {\n kind: LLMProvider_StructuredGenerationFailureKind.RESOLVED_WITHOUT_OBJECT,\n message: 'The structured-generation call resolved without raising, but carried no object.',\n generatedTextLength: null,\n } satisfies LLMProvider_StructuredGenerationFailure,\n }\n : {}),\n };\n } catch (error) {\n // #2292 Phase 3: a withheld answer is not an invalid object — it reaches the caller as itself, with its usage.\n if (error instanceof AgentOutputWithheldError) throw error;\n // Any structured-generation failure that carries provider usage represents a\n // completed physical call. Preserve its metering and let the Driver classify\n // the missing/invalid object; throwing here would discard billable truth.\n if (typeof error === 'object' && error !== null && 'usage' in error) {\n const providerError = error as { cause?: unknown; finishReason?: unknown; text?: unknown; usage: unknown };\n // Do not log the generated text: it can contain application-private\n // context. The error/cause and non-sensitive shape metadata are enough\n // to distinguish truncation, schema validation and provider refusal.\n // Previously this branch retained billing but erased the only reason a\n // real model result became `{ object: undefined }`, making live judge\n // failures impossible to diagnose.\n // The SAME facts go to the log line and to the caller. Logging them only was the\n // second half of the defect this branch already documents: the reason existed, but\n // exclusively inside the process's own log file, so a caller could report nothing\n // more specific than \"no object\" and an operator had to grep the companion log for\n // the line above to learn which schema paths the model had omitted.\n const structuredGenerationFailure = this.buildStructuredGenerationFailure(\n LLMProvider_StructuredGenerationFailureKind.INVALID_OBJECT_AFTER_COMPLETED_CALL,\n error,\n providerError,\n );\n this.logger.error('Structured generation completed without a valid object', {\n operation: 'GENERATE_STRUCTURED',\n errorName: structuredGenerationFailure.errorName,\n errorMessage: structuredGenerationFailure.message,\n validationCauseName: structuredGenerationFailure.validationCauseName,\n validationIssues: structuredGenerationFailure.validationIssues,\n finishReason: structuredGenerationFailure.finishReason,\n generatedTextLength: structuredGenerationFailure.generatedTextLength,\n });\n return {\n // The rejected TEXT rides on the output only for a caller that opted in, and never on the log line\n // above or on `structuredGenerationFailure`, which is telemetry every trace sink emits.\n output: {\n object: undefined,\n ...(includeRejectedAnswer && typeof providerError.text === 'string' ? { rejectedAnswer: prepared.restoreAnswerText(providerError.text) } : {}),\n },\n usage: this.extractUsage(error.usage),\n structuredGenerationFailure,\n };\n }\n // semantic-literal-boundary: AI SDK cross-realm error identity fallback\n const noObjectError = (\n typeof error === 'object'\n && error !== null\n && (\n // The SDK error's stable payload shape is retained even when bundlers or\n // mocked module realms erase its prototype/name marker.\n ('response' in error && 'finishReason' in error && 'text' in error)\n ||\n ('name' in error && error.name === 'AI_NoObjectGeneratedError')\n || (error as Record<PropertyKey, unknown>)[Symbol.for('vercel.ai.error.AI_NoObjectGeneratedError')] === true\n )\n )\n || error instanceof NoObjectGeneratedError\n || NoObjectGeneratedError.isInstance(error);\n if (noObjectError) {\n // No usage-bearing payload was recognised on the branch above, so no shape metadata\n // was recovered. The reason is still attached — a caller must be able to tell this\n // apart from the validated-and-rejected case, and specifically must NOT read the\n // absent `validationIssues` here as evidence that the schema was satisfied.\n return {\n output: {\n object: undefined,\n ...(includeRejectedAnswer && typeof (error as { text?: unknown }).text === 'string'\n ? { rejectedAnswer: prepared.restoreAnswerText((error as { text: string }).text) }\n : {}),\n },\n usage: this.extractUsage((error as NoObjectGeneratedError).usage),\n structuredGenerationFailure: this.buildStructuredGenerationFailure(\n LLMProvider_StructuredGenerationFailureKind.NO_OBJECT_GENERATED,\n error,\n error as { cause?: unknown; finishReason?: unknown; text?: unknown },\n ),\n };\n }\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Failed to generate structured data - provider response', {\n operation: 'GENERATE_STRUCTURED',\n hasSchema: !!schema,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'GENERATE_STRUCTURED',\n message: `Failed to generate structured data: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Execute STREAM_TEXT operation\n */\n private async executeStreamText({ model, systemPrompt, instructions, input, baseOptions }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n /** The invocation input: a conversation in it is sent as `messages` (`textGenerationPromptOf`). */\n input?: unknown;\n baseOptions: any;\n }): Promise<AgentOperationExecutionResult> {\n try {\n const result = await streamText({\n model,\n ...this.textGenerationPromptOf(instructions, input),\n instructions: systemPrompt,\n ...baseOptions,\n onError: SUPPRESS_SDK_STREAM_ERROR_PRINT,\n });\n\n let fullText = '';\n try {\n fullText = await this.drainBufferedStreamText(result);\n } catch (streamError) {\n // #2292 Phase 3: a withheld output reaches the caller as itself, with its usage, like a provider failure.\n if (streamError instanceof AgentModelCallFailedError || streamError instanceof AgentOutputWithheldError) throw streamError;\n // Described, never quoted by value (#2368): a stream failure comes from the model call and can carry the vendor's\n // answer. `describeModelCallError` keeps the name, a redacted message, the status and the frames.\n const streamFailure = describeModelCallError(streamError);\n this.logger.error('Failed to read text stream', {\n ...streamFailure,\n textLength: fullText.length,\n });\n throw this.buildModelCallFailure(streamError, streamFailure, {\n operation: 'STREAM_TEXT',\n message: `Failed to read text stream: ${String(streamFailure.errorMessage ?? streamFailure.errorName)}`,\n });\n }\n\n const usage = await result.usage;\n\n return {\n output: {\n textDelta: fullText,\n },\n usage: this.extractUsage(usage),\n };\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n this.rethrowModelCallFailure(error, 'STREAM_TEXT');\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Stream text operation failed - provider response', {\n operation: 'STREAM_TEXT',\n hasSystemPrompt: !!systemPrompt,\n instructionsLength: instructions.length,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'STREAM_TEXT',\n message: `Failed to stream text: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n /**\n * Execute STREAM_STRUCTURED operation\n */\n private async executeStreamStructured({ model, systemPrompt, instructions, baseOptions }: {\n model: any;\n systemPrompt: string;\n instructions: string;\n baseOptions: any;\n }): Promise<AgentOperationExecutionResult> {\n try {\n const result = await streamText({\n model,\n prompt: instructions,\n instructions: systemPrompt,\n ...baseOptions,\n onError: SUPPRESS_SDK_STREAM_ERROR_PRINT,\n });\n\n let fullText = '';\n try {\n fullText = await this.drainBufferedStreamText(result);\n } catch (streamError) {\n // #2292 Phase 3: a withheld output reaches the caller as itself, with its usage, like a provider failure.\n if (streamError instanceof AgentModelCallFailedError || streamError instanceof AgentOutputWithheldError) throw streamError;\n const errorDetails = this.extractProviderErrorDetails(streamError);\n\n this.logger.error('Failed to read structured stream - provider response', {\n operation: 'STREAM_STRUCTURED',\n textLength: fullText.length,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(streamError, errorDetails, {\n operation: 'STREAM_STRUCTURED',\n message: `Failed to read structured stream: ${errorDetails.errorMessage}`,\n });\n }\n\n const usage = await result.usage;\n\n let parsedOutput: unknown = fullText;\n try {\n parsedOutput = JSON.parse(fullText);\n } catch (parseError) {\n // Described (#2368): V8's JSON parse error quotes the text it refused, which is the model's output.\n this.logDebug('Failed to parse structured stream as JSON, returning as text', {\n ...describeModelCallError(parseError),\n textLength: fullText.length,\n });\n }\n\n return {\n output: {\n object: parsedOutput,\n },\n usage: this.extractUsage(usage),\n };\n } catch (error) {\n // #2292 Phase 3: a withheld output reaches the caller as itself (`executeOperation` passes it through).\n if (error instanceof AgentOutputWithheldError) throw error;\n this.rethrowModelCallFailure(error, 'STREAM_STRUCTURED');\n // Re-throw if it's already a built error\n if (isWildoBackendError(error)) {\n throw error;\n }\n\n const errorDetails = this.extractProviderErrorDetails(error);\n\n this.logger.error('Stream structured operation failed - provider response', {\n operation: 'STREAM_STRUCTURED',\n hasSystemPrompt: !!systemPrompt,\n instructionsLength: instructions.length,\n ...errorDetails,\n });\n\n throw this.buildModelCallFailure(error, errorDetails, {\n operation: 'STREAM_STRUCTURED',\n message: `Failed to stream structured data: ${errorDetails.errorMessage}`,\n });\n }\n }\n\n // ==========================================================================\n // Honest token streaming (invokeAgentStreaming path)\n // --------------------------------------------------------------------------\n // NOTE: the `executeStreamText` / `executeStreamStructured` methods ABOVE are\n // the BUFFERED fallback for the `STREAM_*` operation keys when invoked through\n // the callback-less `invokeAgent` (there is no delta channel on that path, so\n // they assemble the full result). Real per-token delivery is the block below,\n // reached only via `invokeAgentStreaming`, which forwards each delta as it\n // arrives and never buffer-collapses.\n // ==========================================================================\n\n /**\n * Execute a streaming agent turn: resolve transport + prompts, then stream over\n * the API. Fails closed (typed {@link AgentStreamingUnsupportedError}) for the\n * CLI transport and for image agents — neither produces a token stream in v1.\n */\n private async executeAgentStreaming(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n handlers: AgentStreamHandlers,\n /** The organizations the turn works for, as `invokeAgentStreaming` derived them for its admission. */\n organizationScope: ModelCallOrganizationScope,\n toolContext?: FunctionToolExecutionContext,\n ): Promise<AgentExecutionResult> {\n if (isImageAgentConfiguration(agent.config)) {\n throw new AgentStreamingUnsupportedError('operation', 'Image agents do not produce a token stream.');\n }\n const execution = this.resolveAgentExecution(agent);\n // An ACP execution is refused just below, before the prompts are used; a stream is otherwise an API operation.\n const prompts = await this.buildExecutionPrompts(agent, request, execution.transport === 'acp' ? ConversationDelivery.SINGLE_PROMPT : CONVERSATION_DELIVERY_OF_OPERATION[execution.operationKey]);\n if (execution.transport === 'acp') {\n // A coding session DOES stream, but not tokens: it streams tool calls,\n // diffs and usage. Routing it through a token-delta handler would report\n // an agent's narration as if it were the model's output and drop\n // everything that matters. Coding progress is delivered through\n // `AgentInvocationHostContext.onCodingSessionEvent` instead.\n throw new AgentStreamingUnsupportedError('transport', 'Token streaming is not supported for the ACP coding transport; use invokeAgent and observe progress through onCodingSessionEvent.');\n }\n // #2292 R8: from here on the agent is seen with the guardrails the organizations this turn acts for tightened: its\n // own organization's, and each representing organization's its principal stands there through. The same scope its\n // suspensions were asked for (`invokeAgentStreaming`).\n agent = await this.agentUnderTurnPolicies(agent, organizationScope);\n // #3295: a resumed turn runs under at least the treatment it paused under, whatever organizations this call names.\n if (toolContext?.heldPersonalDataTreatment) {\n agent = { ...agent, contentGuardrails: effectiveAgentContentGuardrails(agent.contentGuardrails, [{ personalDataTreatment: toolContext.heldPersonalDataTreatment }]) };\n }\n // Refuses before any tool or MCP session is opened when the agent declares moderation nothing can serve.\n const operationObservation = this.operationObservationOf(request);\n const moderationOrigin = { toolContext, initiator: request.initiator, observation: operationObservation };\n // #3364 step 3: a turn that can read records gets a guard even when its agent declares no moderation, so an owner whose\n // rows reach the model can make the reply judged; until one does, it judges nothing and holds nothing.\n const outputModeration = this.outputModerationGuardOf(agent, moderationOrigin)\n ?? (toolContext ? this.ownerTightenableOutputModerationGuardOf(agent, moderationOrigin) : undefined);\n // A resumed turn is judged under at least what it paused under: the records its owners tightened it for are in the\n // paused messages it replays.\n if (toolContext?.heldOutputModeration) outputModeration?.tighten(toolContext.heldOutputModeration);\n const approvalGatedToolRoutes = new Map<string, HumanDecision_RouteKind>();\n const personalDataGuard = this.personalDataGuardOf(agent, toolContext);\n if (personalDataGuard) this.personalDataGuards.set(request, personalDataGuard);\n const toolResultScreen = this.toolResultScreenOf(agent, toolContext, operationObservation);\n // #2841: the tool events reach the operation observation on their way to the caller's handler.\n handlers = operationObservation.observeHandlers(handlers);\n // #2877: a record a tool returns is treated under the policy of the organization that owns it too.\n const recordOwnerPolicy = this.recordOwnerPolicyOf(request, agent, organizationScope, toolContext, operationObservation, outputModeration);\n const functionTools = this.resolveAgentTools(agent, toolContext, approvalGatedToolRoutes, personalDataGuard, toolResultScreen, recordOwnerPolicy);\n /*\n * MCP tools are DISCOVERED, which means a network call per declared server, bounded by that\n * server's discovery budget. A server that does not answer contributes nothing and the turn\n * proceeds — so this cannot fail the invocation, only shorten the tool list.\n */\n const { tools: mcpTools, sessions: mcpSessions } = await this.resolveAgentMcpTools(agent, toolContext, toolResultScreen, personalDataGuard);\n const tools = functionTools || Object.keys(mcpTools).length > 0\n ? { ...(functionTools ?? {}), ...mcpTools }\n : undefined;\n const toolApproval = this.buildToolApprovalConfiguration(approvalGatedToolRoutes, toolContext?.auth?.executionType, toolContext?.initiationKind);\n const toolApprovalSecret = toolApproval ? this.resolveToolApprovalSecretOrThrow(agent, new Set(approvalGatedToolRoutes.keys())) : undefined;\n try {\n const streamed = await this.executeAgentViaApiStreaming(agent, request, execution, prompts, handlers, tools, toolApproval, toolApprovalSecret, outputModeration);\n // #3364 step 3: a pause records the moderation its replies were judged under, owners' tightenings included.\n if (streamed.approvalSuspension && outputModeration?.judgesAnything) streamed.approvalSuspension.outputModerationAtPause = outputModeration.currentPolicy();\n return streamed;\n } finally {\n /*\n * Released in a `finally` so a thrown turn does not leak a session on somebody else's server.\n * `closeSession` swallows its own failures by contract — a server MAY refuse to let a client\n * end a session — so this can never turn a successful turn into a failed one, nor mask the\n * error of a failing one.\n */\n await Promise.all(mcpSessions.map((session) => this.mcpClient?.closeSession(session, null)));\n }\n }\n\n /**\n * Record one outbound MCP attempt on the audit trail.\n *\n * Fire-and-forget and feature-detected: an absent or failing audit sink must never fail the act it\n * was going to observe. A turn that produced its answer must not be turned into a failure because\n * the trail could not be written — the observation is evidence, not a gate.\n *\n * Emitted for the CALL path always, and for DISCOVERY only when the outbound guard refused the\n * target. That asymmetry is deliberate: a refused target is an attempted egress a reviewer wants\n * beside the calls that succeeded, whereas a server being unreachable or slow is availability, and\n * putting every timeout on the security trail would bury the rows that mean something. Those still\n * reach the log, at WARN, with the same server ref and host.\n */\n private recordMcpAttempt(input: {\n agentRef: string;\n mcpServerRef: string;\n destinationHost: string;\n outcome: McpOutcomeKind;\n toolName?: string;\n connectionOwnerScope?: string;\n credentialId?: string;\n credentialSetByUserId?: string;\n actingIdentity: { userId?: string; organizationId?: string };\n /**\n * The turn's verified auth, as the row's principal (#1595): a delegated turn's MCP call is the\n * delegating client's, and `initiatorUserId` alone would record it as the person acting first-party.\n */\n principal?: AuditPrincipalFacts;\n }): void {\n if (!this.auditLogs) return;\n void this.auditLogs.logMcpToolCall({\n mcpServerRef: input.mcpServerRef,\n destinationHost: input.destinationHost,\n toolName: input.toolName,\n outcome: input.outcome,\n connectionOwnerScope: input.connectionOwnerScope,\n credentialId: input.credentialId,\n ...(input.credentialSetByUserId === undefined ? {} : { credentialSetByUserId: input.credentialSetByUserId }),\n initiatorUserId: input.actingIdentity.userId,\n organizationId: input.actingIdentity.organizationId,\n agentRef: input.agentRef,\n }, undefined, input.principal).catch((error) => {\n this.logger.warn('Could not record an MCP tool attempt on the audit trail; the turn is unaffected', {\n agentRef: input.agentRef,\n mcpServerRef: input.mcpServerRef,\n ...projectCaughtErrorLogFields(error),\n });\n });\n }\n\n /**\n * Resolve an agent's `capabilities.tools.mcpRefs` into callable tools by DISCOVERING what each\n * declared server offers (#491).\n *\n * ## A server that cannot be reached contributes NOTHING, and the turn continues\n *\n * Fail-closed on the CLAIM, fail-open on the turn. Discovery happens here, at turn start, so a\n * server that is unreachable, whose credential is unavailable, or whose target is refused simply\n * adds no tools — and the model is never offered a capability it cannot use. That is the whole\n * correction #491 exists for, one level down: the agent card advertised MCP servers that resolved\n * to nothing, and the fix is not to advertise more carefully but to make what is offered be what\n * can actually be called.\n *\n * Every one of those is logged at WARN with the server ref and destination HOST. A server quietly\n * unreachable for a week must be visible as that, rather than as an agent that became less capable\n * for no stated reason.\n *\n * ## The tools are NOT the same kind of thing as a functionRef, and are named so\n *\n * A `functionRef` dispatches a LOCAL resource operation and owes that operation's declared roles\n * ACL and rate limit (#556). An MCP tool dispatches nothing locally — it leaves the trust boundary\n * — so those gates have no operation to apply to. What it owes instead is enforced where a caller\n * cannot skip it: the outbound target guard and the timeouts live inside the client, the credential\n * comes from a resolver service, and the endpoint was refused at registration if it was plaintext.\n *\n * The `mcp_<serverRef>_<toolName>` prefix keeps the two planes distinguishable in a trace and\n * prevents a third-party tool name from colliding with a declared `functionRef`.\n *\n * Returns the open sessions so the caller can release them; see `executeAgentStreaming`.\n */\n private async resolveAgentMcpTools(\n agent: FlowsActors_Agent,\n toolContext?: FunctionToolExecutionContext,\n /** #2292: screens each MCP result for prompt injection before the model reads it; absent when the agent declares none. */\n toolResultScreen?: ToolResultScreen,\n /**\n * #2292 R8: the turn's personal-data treatment, declared or set by an organization's policy. An MCP result has no\n * schema the engine can read, so under a treatment its model is sent it withheld whole, like a function tool that\n * does not declare its result; an error result keeps its kind only.\n */\n personalDataGuard?: PersonalDataGuard,\n ): Promise<{ tools: Record<string, any>; sessions: McpSession[] }> {\n const mcpRefs = agent.capabilities?.tools?.mcpRefs;\n const empty = { tools: {} as Record<string, any>, sessions: [] as McpSession[] };\n if (!mcpRefs?.length || !toolContext) return empty;\n if (toolContext.autonomousTrigger === AutonomousTurnTrigger.INBOUND_DELIVERY) {\n // #1611: an MCP tool's effect is declared nowhere the engine can read (the list is discovered from\n // the server at turn start), so none can be shown to be a read, and a turn running on inbound content\n // is offered no tool that might write unreviewed. Withheld whole, and said so.\n this.logger.info('MCP tools are withheld from a turn started by an inbound delivery: their effects cannot be classified', {\n agentRef: agent.ref, mcpRefs,\n });\n return empty;\n }\n if (!this.mcpClient || !this.mcpCredentialResolver) {\n // Declared, and this deployment bound no MCP services. Reported rather than silently empty:\n // the agent is about to be less capable than its declaration says, and nothing else would say so.\n this.logger.warn('Agent declares MCP servers but this deployment binds no MCP client; the agent will run without those tools', {\n agentRef: agent.ref,\n mcpRefs,\n });\n return empty;\n }\n\n const actingIdentity = {\n userId: toolContext.auth?.initiatorIds?.userId,\n organizationId: toolContext.organizationId,\n };\n\n const tools: Record<string, any> = {};\n const sessions: McpSession[] = [];\n\n for (const ref of mcpRefs) {\n const server = this.flowsActorsRegistry.getMcpServer(ref);\n if (!server) {\n // The registry refuses this at initialization, so reaching it means the agent was registered\n // afterwards through the public `registerAgent`. Skipped rather than thrown: a turn is the\n // wrong place to fail an application's configuration.\n this.logger.warn('Agent declares an MCP server the application never declared; skipping', { agentRef: agent.ref, mcpRef: ref });\n continue;\n }\n\n const credential = await this.mcpCredentialResolver.resolve(server, actingIdentity);\n if (credential.kind !== McpCredentialOutcomeKind.RESOLVED) {\n this.logger.warn('No credential for a declared MCP server; the agent will run without its tools', {\n agentRef: agent.ref,\n mcpServerRef: ref,\n outcome: credential.kind,\n // Slot NAMES only: a connection exists under a slot the provider no longer declares, so the\n // remedy is to reconnect rather than to connect (#624).\n ...(credential.kind === McpCredentialOutcomeKind.STORED_UNDER_RETIRED_SLOT ? { retiredSecretSlugs: credential.retiredSecretSlugs } : {}),\n });\n continue;\n }\n\n // The session spends the credential's connection on every request, so the connection's vendor budget (#1938) is\n // the one a provider operation on that connection also spends.\n // #2973: metered for this turn, so a turn a re-read trigger's delivery started spends that lane's share.\n // Only the delivery the turn came through decides the lane, so a turn with none spends as an ordinary call.\n const arrivedThrough = toolContext?.auth?.arrivedThrough;\n const connection = credential.connection && arrivedThrough ? { ...credential.connection, meteredFor: { arrivedThrough } } : credential.connection;\n const discovery = await this.mcpClient.openSession(server, credential.token, connection);\n if (discovery.kind !== McpOutcomeKind.OK) {\n this.logger.warn('An MCP server contributed no tools to this turn', {\n agentRef: agent.ref,\n mcpServerRef: discovery.mcpServerRef,\n destinationHost: discovery.destinationHost,\n outcome: discovery.kind,\n detail: discovery.detail,\n });\n // A refused TARGET is an attempted egress a guard blocked — a security event, and the row a\n // reviewer wants beside the calls that succeeded. Everything else here is availability.\n if (discovery.kind === McpOutcomeKind.REFUSED_TARGET) {\n // Discovery runs at turn start, outside any tool call, so the agent frame is opened here for this\n // one row: the refused egress was the AGENT's, and the row must say so (#1595).\n runWithAgentActorFrame(agentActorForToolCall(agent, toolContext), () => this.recordMcpAttempt({\n agentRef: agent.ref,\n mcpServerRef: discovery.mcpServerRef,\n destinationHost: discovery.destinationHost,\n outcome: discovery.kind,\n connectionOwnerScope: credential.source,\n credentialId: credential.credentialId,\n credentialSetByUserId: credential.credentialSetByUserId,\n actingIdentity,\n principal: toolContext.auth,\n }));\n }\n continue;\n }\n\n sessions.push(discovery.session);\n for (const descriptor of discovery.session.tools) {\n // A third-party server's names are whatever it chose, and one name the model's provider refuses fails\n // the WHOLE request, so the name is mapped into the set every model API accepts (#1080).\n const toolName = toPortableModelToolName(`mcp_${ref}_${descriptor.name}`);\n if (toolName in tools) {\n // Two names that differ only in characters the mapping replaces (`a.b` / `a_b`) arrive under one\n // key. Letting the second overwrite the first would bind the model's call to a tool it was not\n // described, so the first is kept and the second is reported.\n this.logger.warn('Two MCP tools map to the same model-facing name; the second is not offered to the model', {\n agentRef: agent.ref,\n mcpServerRef: ref,\n toolName,\n skippedToolName: descriptor.name,\n });\n continue;\n }\n tools[toolName] = tool({\n description: descriptor.description ?? descriptor.title ?? `${server.displayName}: ${descriptor.name}`,\n // The server's own JSON Schema, passed to the model unchanged. Re-deriving it as Zod would\n // be a second description of somebody else's contract, and the two would drift.\n inputSchema: jsonSchema(descriptor.inputSchema as never),\n // #2292: an MCP server's answer is content somebody else wrote, the clearest case for screening. Its error\n // results below are returned AS results, so they are screened too. Under a personal-data treatment the answer\n // cannot be classified field by field (no schema), so the model is sent it withheld whole, and an error result\n // its kind only; neither is screened, since neither carries anything the server wrote. The person and the\n // conversation's tool trace keep what the server returned.\n ...(personalDataGuard ? {\n toModelOutput: async ({ output }: { output: unknown }) => ({\n type: 'json' as const,\n value: (isMcpErrorResult(output) ? { error: output.error } : personalDataGuard.withholdWhole()) as never,\n }),\n } : toolResultScreen ? {\n toModelOutput: async ({ toolCallId, output }: { toolCallId: string; output: unknown }) =>\n await toolResultScreen.forModel(toolCallId, toolName, output) as never,\n } : {}),\n // Runs inside the agent frame, like a function tool: anything this call records — the MCP\n // attempt row below, any write a future MCP plane makes locally — names the agent (#1595).\n execute: async (args: any) => runWithAgentActorFrame(agentActorForToolCall(agent, toolContext, toolName), async () => {\n let outcome: Awaited<ReturnType<McpClientBackendService['callTool']>>;\n try {\n outcome = await this.mcpClient!.callTool(discovery.session, descriptor.name, args ?? {}, credential.token);\n } catch (error) {\n // The client answers rather than throws; a throw is a defect, and its text could carry the server's words.\n // A screened or treated agent's model is told the kind only, as for a function tool.\n if (toolResultScreen || personalDataGuard) throw guardedToolError(error);\n throw error;\n }\n /*\n * Every ATTEMPT is recorded, not only what worked. Recording successes alone would hide\n * exactly what a reviewer looks for first — the refusals, the timeouts, and the tools\n * that answered with their own error.\n */\n this.recordMcpAttempt({\n agentRef: agent.ref,\n mcpServerRef: server.ref,\n destinationHost: mcpServerDestinationHost(server.url),\n outcome: outcome.kind,\n toolName: descriptor.name,\n connectionOwnerScope: credential.source,\n credentialId: credential.credentialId,\n credentialSetByUserId: credential.credentialSetByUserId,\n actingIdentity,\n principal: toolContext.auth,\n });\n if (outcome.kind === McpOutcomeKind.OK) return outcome.content;\n /*\n * Returned to the MODEL as a result rather than thrown, and the difference is deliberate.\n * A thrown tool error becomes an SDK tool-error result the model narrates as prose, which\n * is how an ACL denial once got narrated as \"I don't have permission to write to that\n * list\" and sent an investigator at the list. A typed value the model can read lets it\n * retry or route around — which is the whole reason these five kinds are kept apart.\n */\n this.logger.warn('An MCP tool call did not succeed; the model is told and may route around it', {\n agentRef: agent.ref,\n mcpServerRef: outcome.mcpServerRef,\n destinationHost: outcome.destinationHost,\n toolName: descriptor.name,\n outcome: outcome.kind,\n detail: outcome.detail,\n });\n return { error: outcome.kind, detail: outcome.detail };\n }),\n });\n }\n }\n\n return { tools, sessions };\n }\n\n /**\n * #2292 R8: `agent` as one call sees it, its declared guardrails tightened by the agent policy of every\n * organization the call acts for. The runtime that opened the turn has usually resolved those policies already (a frame\n * covering at least these organizations, its unreadable reading included); otherwise they are read here. Either way they are MERGED with the declaration,\n * so nothing carried can loosen it. A policy that cannot be read refuses the call: an organization that asked for its\n * agents to be stricter is never read as having asked for nothing. A call acting for no organization applies none to the\n * agent; the records it reads are treated under their owners' policies at the model boundary (#2877, `recordOwnerPolicyOf`).\n */\n private async agentUnderTurnPolicies(agent: FlowsActors_Agent, scope: ModelCallOrganizationScope): Promise<FlowsActors_Agent> {\n if (!isLLMAgentConfiguration(agent.config)) return agent;\n if (scope.unreadable !== undefined) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: `Agent '${agent.ref}' cannot run: ${scope.unreadable}. It is not run untightened.` },\n });\n }\n const organizationIds = organizationIdsOfCallScope(scope);\n if (organizationIds.length === 0) return agent;\n const lookup = agentPoliciesInFrame(organizationIds) ?? await readAgentPolicies(this.repositoriesRegistry, organizationIds);\n if (lookup.unreadable !== undefined) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: `Agent '${agent.ref}' cannot run: ${lookup.unreadable}. It is not run untightened.` },\n });\n }\n if (lookup.policies.length === 0) return agent;\n return { ...agent, contentGuardrails: effectiveAgentContentGuardrails(agent.contentGuardrails, lookup.policies) };\n }\n\n /**\n * #2292: the screen this agent's tool results go through before its model reads them, or `undefined` when it declares no\n * prompt-injection screening. Refuses the invocation when it declares screening and no classifier can serve it:\n * running unscreened is the outcome the declaration exists to prevent. The one exception is declared by the\n * environment, never by the agent: `agentContentGuardrails: RUN_UNGUARDED` where no classifier offers screening at all\n * (`runsUnguarded`), where `undefined` is returned and the boot report names the agent as running unguarded.\n */\n private toolResultScreenOf(\n agent: FlowsActors_Agent,\n toolContext?: FunctionToolExecutionContext,\n /** #2841: the invocation's operation observation, told each verdict the screen reaches. */\n observation?: AgentOperationObservationRecorder,\n ): ToolResultScreen | undefined {\n if (!agent.contentGuardrails?.promptInjection) return undefined;\n // assurance-control: WILDO.SECURITY.FAIL_CLOSED, WILDO.AI.UNTRUSTED_CONTENT_SCREENING — an agent that declares\n // prompt-injection screening does not run where nothing can screen, and a result that could not be screened reaches\n // its model only as a withheld notice; except in an environment that DECLARES it runs agents unguarded where no\n // classifier offers screening, which runs it unscreened and names it at boot and in launch-blockers\n const contentSafety = this.contentSafety;\n // The one predicate the boot report also runs (`reportUnservableAgentContentGuardrails`), so the two cannot disagree.\n const gap = contentGuardrailClassifierGapOf(contentSafety, { kind: ClassifierBackedContentGuardrail.PROMPT_INJECTION });\n // The environment declared its agents run unguarded where no classifier serves them, and none does: named at boot.\n if (gap?.runsUnguarded) return undefined;\n const unavailable = gap?.reason;\n if (unavailable !== undefined || !contentSafety) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: `Agent '${agent.ref}' screens its tool results for prompt injection (contentGuardrails.promptInjection, declared or set by an organization's policy), and they cannot be screened: ${unavailable}. It is not run.` },\n });\n }\n observation?.screensToolResults();\n return new ToolResultScreen(\n (text) => contentSafety.screenForPromptInjection(text),\n (record) => this.recordToolResultWithholding(agent, toolContext, record),\n observation?.observeScreening,\n );\n }\n\n /**\n * #2292 Phase 3: the model this call runs on — wrapped with the output-moderation middleware when the agent declares\n * moderation, as it is. Below the SDK, so a withheld tool call is never executed and never put before an approver.\n */\n private moderatedModel(model: any, outputModeration: OutputModerationGuard | undefined, generateOutputKind: FlowsActors_ModeratedOutputKind): any {\n if (!outputModeration) return model;\n return wrapLanguageModel({ model, middleware: outputModeration.middleware(generateOutputKind) });\n }\n\n /**\n * #2292 Phase 3: this agent's output moderation for one invocation, or `undefined` when it declares none. Refuses the\n * invocation, before any model call, when it declares moderation and nothing can serve it: no content-safety service,\n * no provider-call recorder (a judgement nobody can show happened), or no provider that moderates output in every\n * category the policy names. The one exception is declared by the environment: `agentContentGuardrails: RUN_UNGUARDED`\n * where no classifier offers moderation at all (`runsUnguarded`), where `undefined` is returned and the boot report\n * names the agent as running unguarded.\n */\n private outputModerationGuardOf(\n agent: FlowsActors_Agent,\n origin: {\n toolContext?: FunctionToolExecutionContext;\n initiator?: ExecutionContext_InitiatorIds;\n /** #2841: the invocation's operation observation, told each judgement and the withholding the guard applies. */\n observation?: AgentOperationObservationRecorder;\n },\n ): OutputModerationGuard | undefined {\n const policy = agent.contentGuardrails?.outputModeration?.blockAtOrAbove;\n if (!policy) return undefined;\n // assurance-control: WILDO.SECURITY.FAIL_CLOSED, WILDO.AI.OUTPUT_MODERATION — an agent that declares output moderation\n // does not run where nothing can judge its output, and an output that could not be judged is withheld; except in an\n // environment that DECLARES it runs agents unguarded where no classifier offers moderation, named at boot\n const categories = outputModerationCategories(policy);\n const contentSafety = this.contentSafety;\n // The one predicate the boot report also runs (`reportUnservableAgentContentGuardrails`), so the two cannot disagree.\n const gap = contentGuardrailClassifierGapOf(contentSafety, { kind: ClassifierBackedContentGuardrail.OUTPUT_MODERATION, categories });\n // The environment declared its agents run unguarded where no classifier serves them, and none does: named at boot.\n if (gap?.runsUnguarded) return undefined;\n const unavailable = gap?.reason;\n if (unavailable !== undefined || !contentSafety) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: `Agent '${agent.ref}' moderates its output (contentGuardrails.outputModeration, declared or set by an organization's policy), and its output cannot be judged: ${unavailable}. It is not run.` },\n });\n }\n origin.observation?.moderatesOutput();\n return new OutputModerationGuard(\n policy,\n this.moderateOutputWhereServable(),\n (withholding) => {\n origin.observation?.observeOutputWithholding(withholding);\n this.recordOutputWithholding(agent, origin, withholding);\n },\n agent.disclosure?.reasoning === true,\n origin.observation?.observeModerationJudgement,\n );\n }\n\n /**\n * #3364 step 3: the output moderation of a turn whose agent declares none, which an organization whose rows reach the\n * model tightens (`OutputModerationGuard.tighten`). It judges nothing, and holds nothing, until one does. It does not\n * refuse the turn where nothing can judge: whether anything will be asked is unknown until the rows are read, and what\n * is asked then and cannot be judged is withheld (`OUTPUT_NOT_MODERATED`) by `moderateOutputWhereServable`.\n *\n * `undefined` where the environment declares its agents run unguarded and no classifier offers moderation here: an\n * owner's policy then has nothing to tighten, exactly as the agent's own declaration has nothing to enforce.\n */\n private ownerTightenableOutputModerationGuardOf(\n agent: FlowsActors_Agent,\n origin: { toolContext?: FunctionToolExecutionContext; initiator?: ExecutionContext_InitiatorIds; observation?: AgentOperationObservationRecorder },\n ): OutputModerationGuard | undefined {\n if (contentGuardrailClassifierGapOf(this.contentSafety, { kind: ClassifierBackedContentGuardrail.OUTPUT_MODERATION, categories: [] })?.runsUnguarded) {\n return undefined;\n }\n return new OutputModerationGuard(\n {},\n this.moderateOutputWhereServable(),\n (withholding) => {\n origin.observation?.observeOutputWithholding(withholding);\n this.recordOutputWithholding(agent, origin, withholding);\n },\n agent.disclosure?.reasoning === true,\n origin.observation?.observeModerationJudgement,\n );\n }\n\n /**\n * #3364 step 3: judge a text in these categories, or answer NOT_MODERATED (with the reason) when no classifier can serve\n * them here. Asked at every judgement because an owner's policy can add categories mid-turn that the declared ones did\n * not need, through the predicate the boot report and the guard builder share (`contentGuardrailClassifierGapOf`).\n */\n private moderateOutputWhereServable(): (text: string, categories: readonly ContentSafety_HarmCategory[]) => Promise<ContentSafetyModerationResult> {\n return async (text, categories) => {\n const contentSafety = this.contentSafety;\n const unavailable = contentGuardrailClassifierGapOf(contentSafety, { kind: ClassifierBackedContentGuardrail.OUTPUT_MODERATION, categories })?.reason;\n if (unavailable !== undefined || !contentSafety) {\n return { outcome: ContentSafetyModerationOutcome.NOT_MODERATED, reason: `the output cannot be judged in ${categories.join(', ')}: ${unavailable ?? 'no content-safety service'}` };\n }\n return contentSafety.moderateOutput(text, categories);\n };\n }\n\n /**\n * #2292 Phase 3: one audit row per withheld output — OUTPUT_WITHHELD when it reached the policy, OUTPUT_MODERATION_FAILED\n * when it could not be judged. A conversational turn is routed to its organization and attributed to its principal (the\n * tool context); a buffered call (a flow step, a deliberation, the question-form composer) carries no principal and is\n * routed to the organization its initiator names, when it names one. Fire-and-forget: the output is already withheld.\n */\n private recordOutputWithholding(\n agent: FlowsActors_Agent,\n origin: { toolContext?: FunctionToolExecutionContext; initiator?: ExecutionContext_InitiatorIds },\n withholding: OutputWithholding,\n ): void {\n const auditLogs = this.auditLogs;\n const toolContext = origin.toolContext;\n const organizationId = toolContext ? toolContext.organizationId : origin.initiator?.organizationId;\n const initiatorUserId = toolContext ? toolContext.auth?.initiatorIds?.userId : origin.initiator?.userId;\n const fields = {\n agentRef: agent.ref,\n outputKind: withholding.outputKind,\n ...(withholding.toolName ? { toolName: withholding.toolName } : {}),\n ...(withholding.toolCallId ? { toolCallId: withholding.toolCallId } : {}),\n ...(withholding.providerRef ? { providerRef: withholding.providerRef } : {}),\n ...(toolContext?.executionId ? { executionId: toolContext.executionId } : {}),\n ...(initiatorUserId ? { initiatorUserId } : {}),\n ...(organizationId ? { organizationId } : {}),\n };\n this.logger.warn('An agent\\'s output was withheld by its output moderation', { ...fields, code: withholding.code });\n if (!auditLogs) return;\n const written = withholding.code === FlowsActors_ExecutionErrorCode.OUTPUT_WITHHELD\n ? auditLogs.logAgentOutputWithheld({ ...fields, flaggedCategories: [...(withholding.flaggedCategories ?? [])] }, toolContext?.auth)\n : auditLogs.logAgentOutputModerationFailed({ ...fields, ...(withholding.failureReason ? { failureReason: withholding.failureReason } : {}) }, toolContext?.auth);\n written.catch((error) => {\n this.logger.warn('Could not record a withheld output on the audit trail; the call is unaffected', { ...fields, error: describeCaughtError(error) });\n });\n }\n\n /**\n * #2292: one audit row per withheld tool result — CONTENT_QUARANTINED for an attack, CONTENT_SCREENING_FAILED when it\n * could not be screened. Ids and names only, routed to the turn's organization, attributed to the turn's principal.\n * Fire-and-forget like the MCP attempt row: the withholding already happened, and a missing audit sink must not undo\n * it or fail the turn.\n */\n private recordToolResultWithholding(agent: FlowsActors_Agent, toolContext: FunctionToolExecutionContext | undefined, record: ToolResultScreeningRecord): void {\n const auditLogs = this.auditLogs;\n const fields = {\n agentRef: agent.ref,\n contentSource: FlowsActors_ScreenedContentSource.TOOL_RESULT,\n toolName: record.toolName,\n toolCallId: record.toolCallId,\n ...(record.result.providerRef ? { providerRef: record.result.providerRef } : {}),\n ...(toolContext?.executionId ? { executionId: toolContext.executionId } : {}),\n ...(toolContext?.auth?.initiatorIds?.userId ? { initiatorUserId: toolContext.auth.initiatorIds.userId } : {}),\n ...(toolContext?.organizationId ? { organizationId: toolContext.organizationId } : {}),\n };\n this.logger.warn('An agent tool result was withheld from its model by its content guardrail', { ...fields, outcome: record.result.outcome });\n if (!auditLogs) return;\n const written = record.result.outcome === ContentSafetyScreeningOutcome.NOT_SCREENED\n ? auditLogs.logAgentContentScreeningFailed({ ...fields, failureReason: record.result.reason }, toolContext?.auth)\n : auditLogs.logAgentContentQuarantined(fields, toolContext?.auth);\n written.catch((error) => {\n this.logger.warn('Could not record a withheld tool result on the audit trail; the turn is unaffected', { ...fields, error: describeCaughtError(error) });\n });\n }\n\n /**\n * #2292: the guard that applies this agent's declared personal-data treatment to what its tools send the model, over the\n * conversation's placeholder table when the turn carries one (a conversation loads it from its row and stores it again),\n * else a table for this invocation. `undefined` when the agent declares no treatment.\n */\n private personalDataGuardOf(agent: FlowsActors_Agent, toolContext?: FunctionToolExecutionContext): PersonalDataGuard | undefined {\n const declared = agent.contentGuardrails?.personalData;\n if (!declared) return undefined;\n // assurance-control: WILDO.PRIVACY.DATA_MINIMIZATION, WILDO.PRIVACY.THIRD_PARTY_PROCESSING — a guarded agent's model\n // provider is sent personal fields only as the declared treatment, and each call records what was withheld\n // R7: the treatment is recorded per call (what was not sent in clear). A process that cannot record it does not run a\n // guarded agent: an unrecorded treatment is one nobody can show was applied.\n if (!this.providerCallRecorder) {\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: { message: `Agent '${agent.ref}' treats personal data (contentGuardrails.personalData, declared or set by an organization's policy), and this process records no provider calls, so the treatment could not be recorded. It is not run.` },\n });\n }\n const table = toolContext?.personalDataPlaceholders ?? new PersonalDataPlaceholderTable();\n if (toolContext && !toolContext.personalDataPlaceholders) toolContext.personalDataPlaceholders = table;\n const registry = toolContext?.services.resourcesRegistry;\n return new PersonalDataGuard(declared.treatment, table, (resourceType) => registry?.tryGetResourceConfiguration(resourceType as never) as never);\n }\n\n /**\n * #2877, #3364: what a tool result's rows need to be treated under the policy of the organization that OWNS each one\n * (`treatRecordsResultByOwner`): its personal-data treatment and machine-reader placeholders per row, its screening\n * through an owner screen when the call screens nothing, and its output moderation by tightening `outputModeration`. The call's own organizations (its scope) are already applied to the agent; the others\n * are read here, once per call, from the turn's frame when it covers them. A row needing a treatment on a call that has\n * no guard is treated by a `REMOVE` guard created on first use over the call's table, and recorded on the call's trace\n * like a declared one. `undefined` when the call has no tool context, so offers no tool.\n *\n * Unlike a declared guard (`personalDataGuardOf`), the owner guard does not refuse a process without a provider-call\n * recorder: it appears mid-turn, after the model was called, and it only ever withholds. A turn is never run\n * untreated for want of the recorder; it can only send less, and the call's trace still names what was withheld.\n */\n private recordOwnerPolicyOf(\n request: object,\n agent: FlowsActors_Agent,\n scope: ModelCallOrganizationScope,\n toolContext?: FunctionToolExecutionContext,\n /** #2841: the invocation's operation observation, told each verdict the owner screen reaches. */\n observation?: AgentOperationObservationRecorder,\n /** #3364 step 3: the call's output moderation, tightened by each owner whose rows reach the model. */\n outputModeration?: OutputModerationGuard,\n ): (RecordOwnerPolicyContext & { readonly createdOwnerGuard: () => PersonalDataGuard | undefined }) | undefined {\n if (!toolContext) return undefined;\n const registry = toolContext.services.resourcesRegistry;\n const configurationOf = (resourceType: string) => registry?.tryGetResourceConfiguration(resourceType as never) as { resourcePrimaryScope?: ResourcePrimaryScope } | undefined;\n const lookups = new Map<string, Promise<AgentPolicyLookup>>();\n let ownerGuard: PersonalDataGuard | undefined;\n let ownerScreen: ToolResultScreen | undefined;\n const coveredOrganizationIds = organizationIdsOfCallScope(scope);\n // What the tools act in, which confines what they read; the call's scope can name more (a case's tenant).\n const acting = toolContext.auth?.initiatorIds?.organizationId;\n const actingOrganizationId = typeof acting === 'string' && acting.length > 0 ? acting : undefined;\n return {\n coveredOrganizationIds,\n ...(actingOrganizationId ? { actingOrganizationId } : {}),\n // The set retrieval narrows to: the acting tenant, else the caller's organization-wide memberships.\n possibleOwnerOrganizationIds: () => (actingOrganizationId ? [actingOrganizationId] : resolveCallerOrganizationIds((toolContext.auth ?? {}) as never)),\n // The organization row is its own scope root: its owner is its id. Every other organization-owned row names it.\n ownerOf: organizationNamedByRecord,\n // #3369: counted on the call's operation record, so the population is measured rather than assumed.\n rowsOwnerNotDerived: (call, rows) => {\n observation?.observeRowsOwnerNotDerived(call.toolCallId, rows);\n this.logger.info('A tool returned rows naming no organization that nothing could attribute; they reached the model under the strictest agent policy', {\n agentRef: agent.ref, toolName: call.toolName, rows,\n });\n },\n readPolicies: (organizationIds) => {\n const key = organizationIds.join('\\u0000');\n let lookup = lookups.get(key);\n if (!lookup) {\n const framed = agentPoliciesInFrame(organizationIds);\n lookup = framed ? Promise.resolve(framed) : readAgentPolicies(this.repositoriesRegistry, organizationIds);\n lookups.set(key, lookup);\n }\n return lookup;\n },\n // An unregistered resource is treated as organization-owned (fail closed); a registered one by its declared scope.\n isOrganizationOwned: (resourceType) => (configurationOf(resourceType)?.resourcePrimaryScope ?? ResourcePrimaryScope.ORGANIZATIONS) === ResourcePrimaryScope.ORGANIZATIONS,\n ownerGuard: () => {\n if (!ownerGuard) {\n const table = toolContext.personalDataPlaceholders ?? new PersonalDataPlaceholderTable();\n ownerGuard = new PersonalDataGuard(RedactionType.REMOVE, table, (resourceType) => configurationOf(resourceType) as never);\n if (!this.personalDataGuards.get(request)) this.personalDataGuards.set(request, ownerGuard);\n }\n return ownerGuard;\n },\n createdOwnerGuard: () => ownerGuard,\n // assurance-control: WILDO.AI.OUTPUT_MODERATION — a reply drawn from an organization's records is judged under that organization's output policy too\n rowsReachedModelFrom: (tightenings) => {\n // One entry at a time, so the lower severity wins whatever the order: entries of several owners, or a policy that\n // names a category twice, would let the LAST win through a single `Object.fromEntries` (#3364 review N1).\n for (const tightening of tightenings) {\n for (const entry of tightening.outputModeration ?? []) outputModeration?.tighten({ [entry.category]: entry.blockAtOrAbove });\n }\n },\n // #3364: a row whose owner screens is screened even when the call does not. Withholdings are recorded as the call's\n // own screen records them. Where nothing can screen, the screen answers NOT_SCREENED and the rows are withheld,\n // unless the environment declares its agents run unguarded where no classifier serves them: then no screen.\n // assurance-control: WILDO.AI.UNTRUSTED_CONTENT_SCREENING, WILDO.SECURITY.FAIL_CLOSED — a row whose owner asked for screening reaches the model only screened clean, except in an environment that declares it runs agents unguarded where no classifier offers screening\n ownerScreen: () => {\n if (!ownerScreen) {\n const contentSafety = this.contentSafety;\n const gap = contentGuardrailClassifierGapOf(contentSafety, { kind: ClassifierBackedContentGuardrail.PROMPT_INJECTION });\n if (gap?.runsUnguarded) return undefined;\n const unavailable = gap?.reason;\n observation?.screensToolResults();\n ownerScreen = new ToolResultScreen(\n unavailable !== undefined || !contentSafety\n ? async () => ({ outcome: ContentSafetyScreeningOutcome.NOT_SCREENED, reason: `the organization that owns these records screens them, and they cannot be screened: ${unavailable ?? 'no content-safety service'}` })\n : (text) => contentSafety.screenForPromptInjection(text),\n (record) => this.recordToolResultWithholding(agent, toolContext, record),\n observation?.observeScreening,\n );\n }\n return ownerScreen;\n },\n };\n }\n\n /**\n * Resolve an agent's declarative `capabilities.tools.functionRefs` into AI-SDK\n * `tool(...)` definitions, closing each over the caller's `toolContext` so the\n * tool executes as the user. Returns `undefined` when the agent declares no\n * tools or no context was supplied (grounding disabled). Unknown refs are\n * skipped with a debug log rather than failing the whole invocation.\n *\n * assurance-control: WILDO.AI.AGENT_AUTHORITY_CONFINEMENT — every tool is closed over its caller's context, so it acts with the caller's authority and no more.\n */\n private resolveAgentTools(\n agent: FlowsActors_Agent,\n toolContext?: FunctionToolExecutionContext,\n /** Populated with the identifier-safe name of every tool that requires a human decision, and its gate's route. */\n approvalGatedToolRoutes: Map<string, HumanDecision_RouteKind> = new Map(),\n /** #2292: the agent's personal-data treatment, applied at the MODEL boundary of every tool it is offered. */\n personalDataGuard?: PersonalDataGuard,\n /** #2292: screens each result for prompt injection before the model reads it; absent when the agent declares none. */\n toolResultScreen?: ToolResultScreen,\n /** #2877: treats each returned row under its owning organization's policy too (`recordOwnerPolicyOf`). */\n recordOwnerPolicy?: RecordOwnerPolicyContext & { readonly createdOwnerGuard: () => PersonalDataGuard | undefined },\n ): Record<string, any> | undefined {\n const functionRefs = agent.capabilities?.tools?.functionRefs;\n if (!functionRefs?.length || !toolContext) return undefined;\n\n const tools: Record<string, any> = {};\n /** #3369: what each tool call's dispatches reached, by `toolCallId`, read when its result is sent to the model. */\n const observedOwners = new Map<string, ToolCallRecordOwners>();\n for (const ref of functionRefs) {\n const functionTool: FunctionTool | undefined = this.flowsActorsRegistry.getFunctionTool(ref);\n if (!functionTool) {\n this.logDebug('Agent declares an unknown function tool; skipping', { agentRef: agent.ref, functionRef: ref });\n continue;\n }\n // #1611: a turn whose input came from outside (an autonomous turn started by an inbound delivery) is\n // offered only tools that read, or that a reviewer must approve. Withheld, not denied: the model is\n // never shown a write it could be talked into asking for.\n if (!isFunctionToolOfferedToTurn(functionTool, toolContext.autonomousTrigger, toolContext.initiationKind)) {\n this.logger.info(functionTool.presentsRecords\n ? 'A tool that shows records is withheld from a turn no conversation draws for a person (A2A, autonomous)'\n : 'A write tool is withheld from a turn started by an inbound delivery; declare it READ or gate it on a reviewer to offer it', {\n agentRef: agent.ref, functionRef: ref,\n });\n continue;\n }\n // Provider tool names must be identifier-safe; functionRefs use dots. Shared with the\n // approval-modification path, which must reverse it — see `modelToolNameForFunctionRef`.\n const toolName = modelToolNameForFunctionRef(ref);\n if (toolName in tools) {\n // The mapping is not injective. The approval path resolves a name back to the FIRST declared ref\n // that maps to it, so keeping the first here is what keeps the two directions agreeing.\n this.logger.warn('Two declared function refs map to the same model-facing name; the second is not offered to the model', {\n agentRef: agent.ref,\n functionRef: ref,\n toolName,\n });\n continue;\n }\n // #2292: a tool that does not say what its result carries could return anything. An agent that DECLARES a treatment\n // is never offered one (startup refuses it). An agent an organization's policy put under a treatment still is (#2292\n // R8): the tool runs and the person sees its result, but its MODEL is sent the result withheld whole\n // (`treatToolOutputForModel`), never in clear — rather than the tool silently disappearing from the agent.\n const personalDataOutput = functionTool.personalDataOutput;\n if (personalDataGuard && !personalDataOutput) {\n this.logger.info('A tool that does not declare what its result carries reaches this guarded agent\\'s model only withheld whole', {\n agentRef: agent.ref, functionRef: ref,\n });\n }\n // #2848: the ARGUMENTS of every tool that can change something are checked, whatever its result declares. Keyed on\n // the resource the arguments describe (`argumentsResource`), else the records the tool returns; a guarded write\n // naming neither accepts no placeholder at all, and a withheld marker is refused everywhere. See `argumentsAToolRunsWith`.\n tools[toolName] = tool({\n description: functionTool.description,\n // Under TOKENIZE a personal field also accepts a placeholder, which its own type (an email, a date) would refuse\n // before the value could be put back; the arguments are re-identified and validated against the tool's own schema\n // in `execute`.\n inputSchema: sdkInputSchemaOfFunctionTool(functionTool, personalDataGuard),\n // #2292: what the MODEL is sent of the result: treated for personal data, then screened for prompt injection, in\n // that order so the classifier reads placeholders. Applied only where model messages are built, so the person, the\n // conversation's tool trace and the cards keep what the tool returned.\n // A tool returning the person's own answer is not third-party content and is not screened.\n // #2877: a tool returning records is always given a model-side view, so a row an organization outside the call's\n // scope owns is treated under that organization's policy even on a call that declares no treatment.\n ...(personalDataGuard || (recordOwnerPolicy && (personalDataOutput?.kind === FunctionToolPersonalDataOutputKind.RECORDS_OF_RESOURCE\n || personalDataOutput?.kind === FunctionToolPersonalDataOutputKind.TREATED_BY_TOOL))\n || (toolResultScreen && !functionTool.returnsThePersonsOwnWords) ? {\n toModelOutput: async ({ toolCallId, output }: { toolCallId: string; output: unknown }) => {\n // #2761: the engine wrote this result and it quotes nothing a record or a third party holds, so it reaches the\n // model as it is: withholding or screening it would hide the very sentence it exists to deliver.\n if (isFunctionToolRefusalResult(output)) return { type: 'json' as const, value: output as never };\n const observed = observedOwners.get(toolCallId);\n const ownerToolCall = {\n toolCallId,\n toolName,\n callScreensResult: toolResultScreen !== undefined && !functionTool.returnsThePersonsOwnWords,\n unattributedRows: unattributedRowOwnershipOf(functionTool),\n ...(observed ? { observedOwners: observed } : {}),\n };\n const modelSide = recordOwnerPolicy && personalDataOutput?.kind === FunctionToolPersonalDataOutputKind.RECORDS_OF_RESOURCE\n ? await treatRecordsResultByOwner(output, personalDataOutput.resourceType, personalDataGuard, recordOwnerPolicy, ownerToolCall)\n : recordOwnerPolicy && personalDataOutput?.kind === FunctionToolPersonalDataOutputKind.TREATED_BY_TOOL\n ? await treatToolTreatedResultByPossibleOwners(output, personalDataOutput.treat, personalDataGuard, recordOwnerPolicy, ownerToolCall)\n : personalDataGuard ? treatToolOutputForModel(output, personalDataOutput, personalDataGuard) : output;\n if (!toolResultScreen || functionTool.returnsThePersonsOwnWords) return { type: 'json' as const, value: modelSide as never };\n return await toolResultScreen.forModel(toolCallId, toolName, modelSide) as never;\n },\n } : {}),\n /**\n * OBSERVE the failure, then re-throw it unchanged.\n *\n * The AI SDK catches whatever a tool throws and turns it into a tool-error RESULT that is fed\n * back to the model, which then narrates it to the user in prose. That is the right runtime\n * behaviour — the model can apologise, retry or ask a question — but it means a failing tool\n * produces NO server-side record of any kind: not an error, not a warning, not a debug line.\n * The only trace is whatever the model chose to say, and the model is guessing: an\n * `authorizations_access_denied` on the CREATE was narrated as \"I don't have permission to\n * write to that list\", which points an investigator at the list rather than at the ACL.\n *\n * That cost a full debugging session against a live stack — the failure could not be\n * attributed from the logs at all, because there were none. An app author hitting the same\n * thing has strictly less to work with, since the engine internals are not theirs to read.\n *\n * Re-throwing is what keeps this observation-only: the SDK still receives the same error, so\n * the model still sees the same tool result and the conversation is unchanged.\n */\n //\n // The call runs inside the AGENT FRAME (#1595). Every `ExecutionContext` the tool builds — through\n // a framework factory, by hand from `toolContext.auth`, or through an `*AsSystem` helper — adopts\n // it, so every audit row the tool causes names this agent and this execution without the tool\n // doing anything. Opened HERE, once per call, rather than threaded through the tool context,\n // because a hand-written tool that forgot to copy it would record the agent's write as the\n // user's own.\n // assurance-control: WILDO.AUDIT.CONTEXT_ATTRIBUTION — an agent's tool calls are attributed to the agent on every audit row\n execute: async (args: any, callOptions: { toolCallId: string }) => runWithAgentActorFrame(agentActorForToolCall(agent, toolContext, ref), async () => {\n try {\n // #2877: once a row was withheld from this call's model, its writes are checked as a guarded call's are, so a\n // withheld marker is never stored.\n const effectiveArgs = await argumentsAToolExecutesWith(functionTool, personalDataGuard ?? recordOwnerPolicy?.createdOwnerGuard(), args);\n toolContext.onFunctionToolExecuting?.(callOptions.toolCallId);\n if (!recordOwnerPolicy) return await functionTool.execute(effectiveArgs, toolContext);\n // #3369: the owners of the rows this call's dispatches return, so a row the tool returns without its\n // organization is still attributed (`treatRecordsResultByOwner`).\n const { result, owners } = await observingRecordOwners(() => functionTool.execute(effectiveArgs, toolContext));\n observedOwners.set(callOptions.toolCallId, owners);\n return result;\n } catch (error) {\n this.logger.warn('Agent function tool execution failed; the model will be told, so nothing else records this', {\n agentRef: agent.ref,\n functionRef: ref,\n toolName,\n ...projectCaughtErrorLogFields(error),\n });\n // #2761: a refusal only the PERSON can resolve, in the application, is returned as a typed result carrying the\n // engine's own sentence, not re-thrown for the model to narrate in its own words. Checked before the guarded\n // re-throw: the result names no record value, only what the person must do.\n const refusal = functionToolRefusalOf(error);\n if (refusal) return refusal;\n // #2292: an error's text can quote a record's value (a duplicate email, a conflicting name), and the SDK sends it\n // to the model as it is. A guarded agent's model is told only what kind of failure it was; a placeholder\n // refusal, which names no value, is passed on so the model can correct the call.\n // A screened agent's model is told the kind too: an error's text can carry what a third party wrote, and an error\n // result is not screened.\n if ((personalDataGuard || recordOwnerPolicy?.createdOwnerGuard() || toolResultScreen) && !(error instanceof PersonalDataPlaceholderRefusal)) throw guardedToolError(error);\n throw error;\n }\n }),\n });\n // ⚠️ The SDK's tool-level `needsApproval` is DELIBERATELY not set — it is deprecated\n // (\"tool approval is handled on a generateText / streamText level now\"), so the gate is\n // declared here and applied at the CALL site via `toolApproval`. Keeping the translation in\n // one place also means an app author never writes the SDK's vocabulary.\n // `resolveFunctionToolApprovalGate` is the one reader of `requiresHumanApproval` and `humanApproval`\n // (#1594), so the gate the model is held to and the route a pause is given cannot disagree about\n // whether a tool is gated.\n const approvalGate = resolveFunctionToolApprovalGate(functionTool);\n if (approvalGate) approvalGatedToolRoutes.set(toolName, approvalGate.route);\n }\n return Object.keys(tools).length > 0 ? tools : undefined;\n }\n\n /**\n * The approval-signing key, or `undefined` when this runtime holds no tool-approval key (#2893).\n *\n * PUBLIC because there are two moments that need this exact key and only one of them is a turn:\n * the tool loop SIGNS an approval request when it suspends, and — since approve-with-modifications\n * (#566) — a resume RE-SIGNS it after an approver authored different arguments. A second\n * derivation in the resume path would be a second key the day either expression moved, and the\n * failure would present as a forged approval rather than as the configuration skew it is.\n *\n * Returns rather than throws, because the two callers owe different answers: a TURN that cannot\n * sign must be refused outright (see below), while a MODIFICATION that cannot be re-signed must\n * leave the pause standing so the approver can still approve the call as proposed.\n */\n public resolveToolApprovalSigningKey(): string | undefined {\n const purposeKey = applicationSymmetricKeyOf(this.appConfig, CryptoKey_Purpose.TOOL_APPROVAL_SIGNING);\n return purposeKey ? deriveToolApprovalSigningKey(purposeKey) : undefined;\n }\n\n /**\n * The HMAC secret that signs approval requests — REQUIRED once any tool is approval-gated.\n *\n * Fails CLOSED, and the asymmetry is the reason. Without a secret the SDK still suspends and still\n * resumes, so everything looks like it works; what silently disappears is the binding between an\n * approval and the tool call it approved, which is what stops a client forging one. The tools an\n * author bothered to gate are precisely those where a forged approval is worst, so degrading to\n * unsigned approvals would remove the protection exactly where it was asked for.\n *\n * Refusing the TURN (rather than the tool) is deliberate: silently dropping the gated tool from an\n * agent's toolset would leave the agent quietly less capable with no signal, which is harder to\n * diagnose than a startup-shaped failure naming the missing configuration.\n *\n * ## Where the key comes from\n *\n * Its own key purpose, `CryptoKey_Purpose.TOOL_APPROVAL_SIGNING` (#2893), minted by the platform and delivered to the\n * backend and the minions, which both run agents: a resume must verify what a suspension signed, wherever each ran.\n *\n * It used to be derived from the application's primary secret. That made the key whatever the bearer credential was,\n * so anyone holding the credential could forge approvals, and a minion (which holds its own credential under the same\n * name) signed with a key the backend could not verify. Before that, a bespoke `WILDO_TOOL_APPROVAL_SECRET` was read\n * that no deployment ever set, so the gate refused every turn. A delivered purpose key has neither defect.\n *\n * The approval secret is still the purpose key's HMAC over a versioned label ({@link deriveToolApprovalSigningKey}), so\n * the key is never handed to the SDK verbatim. Deliberately NOT offered as an override-if-set: a second source would\n * mean two backends that disagree about whether an approval is valid, and the failure would look like a forged\n * approval rather than a configuration skew.\n */\n private resolveToolApprovalSecretOrThrow(agent: FlowsActors_Agent, approvalGatedToolNames: Set<string>): string {\n const signingKey = this.resolveToolApprovalSigningKey();\n if (signingKey) return signingKey;\n\n throw this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.CONFIGURATION,\n context: {\n message: `Agent \"${agent.ref}\" declares human-approval tools (${[...approvalGatedToolNames].join(', ')}) but this runtime holds no tool-approval key (security.symmetricKeys.tool_approval_signing), so approvals cannot be signed. Approval decisions would be unsigned and therefore forgeable by a client, so the turn is refused rather than run with the gate weakened.`,\n agentRef: agent.ref,\n },\n });\n }\n\n /**\n * The SDK call-level approval configuration for a resolved tool set, or `undefined` when no\n * declared tool is approval-gated.\n *\n * `'user-approval'` is the status that SUSPENDS the tool loop and emits a\n * `tool-approval-request`; the other statuses (`approved` / `denied` / `not-applicable`) decide\n * without a human and are not what a `requiresHumanApproval` declaration means. The SDK still reports\n * an `approved` / `denied` decision as a `tool-approval-request`, marked `isAutomatic`, which the stream\n * reader must not take for a pause (#3254, `streamTextToDeltas`).\n */\n private buildToolApprovalConfiguration(\n approvalGatedToolRoutes: Map<string, HumanDecision_RouteKind>,\n /** The turn's principal. `undefined` is treated as unable to answer — fail closed. */\n executionType?: ExecutionContext_ExecutionType,\n /** The door that opened the turn, from the row (#1594). Only an AUTONOMOUS machine turn may pause, on a reviewer route. */\n initiationKind?: FlowsActors_InitiationKind | null,\n ): Record<string, ToolApprovalDecision> | undefined {\n if (approvalGatedToolRoutes.size === 0) return undefined;\n\n // A call that nobody could answer must be DENIED, never suspended (D-HITL-3, now the predicate\n // `admitsDecisionSuspension`, decided PER TOOL because the route is the tool's). Suspending such a\n // turn is not a safe default: it parks the execution waiting for a decision nobody is routed.\n //\n // Denial is also the better OUTCOME, not merely the safe one: the SDK reports the refusal to\n // the model, which answers explaining that the action needs human approval. The caller gets a\n // usable reply instead of a turn that never returns.\n const denied: ToolApprovalDecision = { type: 'denied', reason: 'This action requires approval from a person, and this caller is not one. Ask a user to perform it, or run it through an interactive session.' };\n return Object.fromEntries([...approvalGatedToolRoutes].map(([name, routeKind]) => [\n name,\n admitsDecisionSuspension({ executionType, initiationKind, routeKind }) ? 'user-approval' : denied,\n ]));\n }\n\n /** API-transport streaming — mirrors executeAgentViaApi but forwards deltas + tool events. */\n private async executeAgentViaApiStreaming(\n agent: FlowsActors_Agent,\n request: FlowsActors_Agent_Invocation<any, any, any>,\n execution: Extract<ResolvedAgentExecution, { transport: 'api' }>,\n prompts: CompiledExecutionPrompts,\n handlers: AgentStreamHandlers,\n tools?: Record<string, any>,\n toolApproval?: Record<string, ToolApprovalDecision>,\n toolApprovalSecret?: string,\n outputModeration?: OutputModerationGuard,\n ): Promise<AgentExecutionResult> {\n const aiProvider = await this.resolveApiProviderClient(execution.providerRef);\n const limiter = this.getBottleneckForProvider(\n execution.providerRef,\n ExternalProvider_ExchangeProtocol_Kind.LLM_PROVIDER,\n );\n const jobId = `${agent.ref}-api-stream-${Date.now()}-${Math.random().toString(36).substring(7)}`;\n\n this.logDebug('Scheduling streaming API call through rate limiter', {\n agentRef: agent.ref,\n providerRef: execution.providerRef,\n operationKey: execution.operationKey,\n model: agent.config.model,\n toolCount: tools ? Object.keys(tools).length : 0,\n jobId,\n });\n\n const modelFailovers: ModelCallFailover[] = [];\n const result = await this.scheduleOnLimiter(\n limiter,\n { id: jobId },\n () => this.streamOperation({\n providerClient: aiProvider,\n providerRef: execution.providerRef,\n modelFailovers,\n config: agent.config,\n operationKey: execution.operationKey,\n systemPrompt: prompts.systemPrompt,\n instructions: prompts.instructions,\n input: request.input,\n handlers,\n tools,\n toolApproval,\n toolApprovalSecret,\n outputModeration,\n operationObservation: this.operationObservationOf(request),\n personalDataGuard: this.personalDataGuards.get(request),\n }),\n );\n\n return {\n ...result,\n ...this.apiTransportOf(execution.providerRef, agent.config.model, modelFailovers),\n };\n }\n\n /**\n * Dispatch a streaming operation by key. Only text-producing operations\n * (GENERATE_TEXT / CHAT_COMPLETION and their THINKING variants) stream; other\n * keys throw {@link AgentStreamingUnsupportedError}. The output shape matches\n * the buffered executors so `normalizeOperationOutput` is identical.\n */\n private async streamOperation({ providerClient, providerRef, modelFailovers, config, operationKey, systemPrompt, instructions, input, handlers, tools, toolApproval, toolApprovalSecret, outputModeration, operationObservation, personalDataGuard }: streamOperationParams): Promise<{ output: unknown; usage?: any; approvalSuspension?: AgentApprovalSuspension }> {\n // A conversational stream's text is the reply; tool inputs and shown reasoning are named by the middleware itself.\n // #2301: a declared alternative takes a step whose stream the provider failed to OPEN (`withModelCallFailover`).\n const providerModel = this.withDeclaredModelFailover({\n primary: this.getModelFromProvider(providerClient, config.model),\n providerRef,\n config,\n transportOf: (alternativeModel) => alternativeModel,\n ...(modelFailovers === undefined ? {} : { sink: modelFailovers }),\n });\n const model = this.moderatedModel(this.observedModel(this.accountRefusalIsFinal(providerModel), operationObservation), outputModeration, FlowsActors_ModeratedOutputKind.REPLY);\n const baseOptions = this.buildBaseOptions(config as FlowsActors_Agent_LLMConfiguration);\n\n try {\n switch (operationKey) {\n case LLMProvider_OperationKey.GENERATE_TEXT: {\n const { text, usage, approvalSuspension } = await this.streamTextToDeltas({ model, ...this.textGenerationPromptOf(instructions, input), instructions: systemPrompt, baseOptions, tools, toolApproval, toolApprovalSecret, personalDataGuard }, handlers);\n return { output: { text }, usage, approvalSuspension };\n }\n\n case LLMProvider_OperationKey.CHAT_COMPLETION: {\n const messages = this.buildChatMessages(instructions, input);\n // System prompt goes via the top-level `instructions:` option (AI-SDK v7\n // forbids it inside `messages`), exactly like the GENERATE_TEXT branch above.\n const { text, usage, approvalSuspension } = await this.streamTextToDeltas({ model, messages, instructions: systemPrompt, baseOptions, tools, toolApproval, toolApprovalSecret, personalDataGuard }, handlers);\n return { output: { message: { role: LLMProvider_MessageRole.ASSISTANT, content: text } }, usage, approvalSuspension };\n }\n\n default:\n throw new AgentStreamingUnsupportedError('operation', `Operation ${operationKey} does not produce a token stream; use invokeAgent (buffered) instead.`);\n }\n } catch (error) {\n if (error instanceof AgentStreamingUnsupportedError) throw error;\n if (error instanceof AgentOutputWithheldError) throw error;\n this.rethrowModelCallFailure(error, operationKey);\n if (isWildoBackendError(error)) throw error;\n const errorDetails = this.extractProviderErrorDetails(error);\n this.logger.error('Streaming operation failed - provider response', { operationKey, ...errorDetails });\n throw this.buildModelCallFailure(error, errorDetails, { operationKey, message: `Failed to stream operation ${operationKey}: ${errorDetails.errorMessage}` });\n }\n }\n\n /**\n * Run AI-SDK `streamText` and iterate its `fullStream`, forwarding text deltas\n * through `handlers.onDelta` and tool-call/result lifecycle events through\n * `handlers.onToolEvent` as they arrive (honest streaming — no buffering). When\n * `tools` are supplied a bounded multi-step loop is enabled\n * (`stopWhen: stepCountIs(MAX_TOOL_STEPS)`) so the model can call a tool and\n * continue. A throwing handler is swallowed (debug-logged) so a consumer error\n * never breaks the stream. Returns the assembled text + normalized usage, or throws\n * {@link AgentModelCallFailedError} when the provider failed the call (an `error` part, #2191).\n */\n private async streamTextToDeltas(\n args: {\n model: any; prompt?: string; instructions?: string; messages?: any[]; baseOptions: any;\n tools?: Record<string, any>; toolApproval?: Record<string, ToolApprovalDecision>; toolApprovalSecret?: string;\n /** #2855: see `streamOperationParams.personalDataGuard`. */\n personalDataGuard?: PersonalDataGuard;\n },\n handlers: AgentStreamHandlers,\n ): Promise<{ text: string; usage?: any; approvalSuspension?: AgentApprovalSuspension }> {\n const { baseOptions, tools, toolApproval, toolApprovalSecret, personalDataGuard, ...streamArgs } = args;\n /*\n * #2855: what each MODEL STEP is sent of a tool call a PERSON authored (an approver's edit): its\n * personal arguments treated by this invocation's guard, its mark removed. The SDK executes the approved call from the\n * messages BEFORE the first step and never from a step's prompt, so the person's values run and the model reads only\n * the treatment. Through `prepareStep`, whose messages carry forward to later steps (treated once, counted once); with\n * no tools nothing executes from the messages, and they are treated before the call. `promptMessages` below stays the\n * untreated array, so a second pause stores the call as it runs, mark included, and its resume is treated again.\n */\n const modelMessagesOf = (messages: any[]): any[] => modelCopyOfPersonAuthoredToolCalls(messages, personalDataGuard);\n const callArgs = !tools && Array.isArray(streamArgs.messages) ? { ...streamArgs, messages: modelMessagesOf(streamArgs.messages) } : streamArgs;\n\n // ── Usage must be accumulated AS STEPS FINISH, not read only at the end ────────────────────\n //\n // On an ABORTED stream AI-SDK ends `fullStream` normally (an `abort` part) but **rejects**\n // `result.usage`. Reading only that terminal promise therefore threw here, which skipped\n // the runtime's usage report upstream (then `reportUsage` into A2A's `turnTotalTokens`, then `reportTurnUsage`\n // into the one usage port, #1855; the charge is now this service's own, #2935), and meant `recordTurnTokens` was\n // NEVER called — so a cancelled turn moved the tenant's token budget by zero while the\n // provider had really generated (and charged for) output. That made cancellation an\n // unmetered-spend path a caller could drive on demand: start a turn, hang up, repeat.\n //\n // Per-step usage is known the moment each step completes, so it survives an abort. Only the\n // IN-FLIGHT step's partial output is unrecoverable — a small, bounded, honest gap rather than\n // losing the whole turn's consumption.\n //\n // Each step's FULL extracted usage is kept (#1598), so the per-step total keeps the cache and reasoning\n // splits too; `aggregateExtractedUsage` sums a split only when every step reported it.\n const stepUsages: ReturnType<AgentsBackendService['extractUsage']>[] = [];\n\n const result = await streamText({\n ...callArgs,\n ...baseOptions,\n onStepFinish: (step: any) => {\n stepUsages.push(this.extractUsage(step?.usage));\n },\n // The SDK's default `onError` prints the raw failure to stderr and nothing else. The `error`\n // PART below is what makes the call fail, and `streamOperation` logs it with the provider's\n // details, so the default would only add an unstructured duplicate (#2191).\n onError: SUPPRESS_SDK_STREAM_ERROR_PRINT,\n // AFTER `baseOptions` on purpose: the signal is per-INVOCATION, whereas\n // `baseOptions` is derived from the agent's static config, so it must not be\n // overridable by configuration.\n ...(handlers.abortSignal ? { abortSignal: handlers.abortSignal } : {}),\n // Human-in-the-loop. `toolApproval` suspends the loop on a gated call; the secret HMAC-signs\n // the request so a replayed approval cannot be forged by a client. The caller guarantees they\n // travel together — see the fail-closed check where the configuration is built.\n ...(toolApproval ? { toolApproval, experimental_toolApprovalSecret: toolApprovalSecret } : {}),\n ...(tools\n ? {\n tools,\n stopWhen: stepCountIs(MAX_TOOL_STEPS),\n // Sanitize the CONTINUATION prompt of the multi-step tool loop: extended-thinking models\n // emit an empty-text assistant `reasoning` part that the provider's prompt validation\n // rejects when it is fed back for the next step, killing every step after the first.\n // `prepareStep`'s `messages` override is the SDK-supported seam for this and carries\n // forward to later steps. See `stripEmptyReasoningParts`.\n // #3192: the same seam tells the model a reviewer changed a call. Read from these raw messages, because the\n // override below removes the mark: the instructions carry forward, so the step that reads the mark states it.\n prepareStep: ({ messages, instructions }: { messages: any[]; instructions?: any }) => {\n const stated = withReviewerEditStatements(instructions, reviewerEditStatementsOf(messages));\n return { messages: stripEmptyReasoningParts(modelMessagesOf(messages)), ...(stated === undefined ? {} : { instructions: stated }) };\n },\n }\n : {}),\n });\n\n let full = '';\n let approvalSuspension: AgentApprovalSuspension | undefined;\n /** The FIRST `error` part — the provider's failure. Later parts are its consequences. */\n let providerFailure: { error: unknown } | undefined;\n for await (const part of result.fullStream) {\n // A provider failure arrives as a PART, never as a throw (#2191). Recorded outside the handler\n // `try` below on purpose: that `try` swallows consumer errors, and this is not one. The stream is\n // drained to its end rather than abandoned, so every finished step still reports its usage.\n if (part.type === 'error') {\n providerFailure ??= { error: (part as { error?: unknown }).error };\n continue;\n }\n try {\n if (part.type === 'text-delta') {\n full += part.text;\n handlers.onDelta(part.text);\n } else if (part.type === 'tool-call') {\n handlers.onToolEvent?.({ phase: FlowsActors_ToolCallPhase.CALL, toolCallId: part.toolCallId, toolName: part.toolName, input: part.input });\n } else if (part.type === 'tool-result') {\n // A PRELIMINARY result is a streaming tool's partial output; the final one follows with the same id.\n if (!(part as { preliminary?: boolean }).preliminary) {\n handlers.onToolEvent?.({ phase: FlowsActors_ToolCallPhase.RESULT, toolCallId: part.toolCallId, toolName: part.toolName, input: part.input, output: part.output });\n }\n } else if (part.type === 'tool-error') {\n handlers.onToolEvent?.({ phase: FlowsActors_ToolCallPhase.ERROR, toolCallId: part.toolCallId, toolName: part.toolName, input: part.input, error: part.error });\n } else if (part.type === 'tool-output-denied') {\n // The call was refused and never ran: by the person it was waiting on, or by the approval configuration when no\n // person could be asked (#3254, an automatic denial). Without this the call stayed at CALL (#2524).\n handlers.onToolEvent?.({ phase: FlowsActors_ToolCallPhase.DENIED, toolCallId: part.toolCallId, toolName: part.toolName });\n } else if (part.type === 'reasoning-delta') {\n handlers.onReasoningDelta?.(part.text);\n } else if (part.type === 'source') {\n handlers.onSource?.(toFlowsActorsSource(part));\n } else if (part.type === 'tool-approval-request' && (part as { isAutomatic?: boolean }).isAutomatic !== true) {\n // The tool loop has STOPPED and is waiting for a human. This is a terminal outcome of the\n // turn, not an error: the model produced no further text and will not until the decision\n // is replayed. Captured here rather than inferred from `finishReason`, because the part\n // carries the `approvalId` the resume must echo — and the SDK binds that id to the tool\n // call with an HMAC signature, so it cannot be reconstructed after the fact.\n //\n // Only a request a PERSON must answer (#3254). The SDK also reports a decision the configuration already made\n // (`buildToolApprovalConfiguration`'s `{ type: 'denied' }` for a principal no person waits on) as a request,\n // marked `isAutomatic`, followed by its own response and a `tool-output-denied`, and the loop carries on: the\n // model reads the refusal and answers. Taking that for a pause parked an A2A organization client's turn on a\n // call already refused, and raised a decision no answer could apply.\n // spec-cite: ai 7.0.142 `dist/index.d.ts`, the approval request's `isAutomatic` (\"Flag indicating whether the tool was automatically approved or denied.\"), and `docs/03-agents/06-tool-approvals.mdx`, \"Handle Manual Approvals\", which collects only `part.type === 'tool-approval-request' && !part.isAutomatic`.\n approvalSuspension = {\n approvalId: (part as any).approvalId,\n toolCallId: (part as any).toolCall?.toolCallId ?? (part as any).toolCallId,\n toolName: (part as any).toolCall?.toolName ?? (part as any).toolName,\n toolArgs: (part as any).toolCall?.input ?? (part as any).input,\n sdkModelMessages: [],\n };\n }\n } catch (cbError) {\n this.logDebug('Streaming handler threw (non-fatal)', {\n ...projectCaughtErrorLogFields(cbError),\n });\n }\n }\n\n // ── A provider failure FAILS the call ──────────────────────────────────────────────────────\n //\n // Returning here, as this method did until #2191, handed back `{ text: '' }` for a call the\n // provider refused, and the caller recorded a COMPLETED turn with no message. Throwing reaches the\n // failure arm every caller already has. A CANCELLED call is left to the caller's own signal check:\n // the SDK replaces the remainder of an aborted stream with an `abort` part, and a cancellation is\n // not a provider failure even if a failing chunk raced it.\n //\n // Usage is the per-step total, never `result.usage`: after a later step's call fails the SDK\n // resolves the terminal total as an EMPTY usage (no `finish` part was seen), which would meter a\n // tool loop's finished steps as zero. No finished step → no usage at all (see the error's JSDoc).\n // #2292 Phase 3: the output-moderation middleware ends a withheld step with its own error part, after the step's\n // `finish` usage. Checked FIRST: it is the application's policy, not a provider failure, and carries the step's usage.\n if (providerFailure?.error instanceof AgentOutputWithheldError) {\n throw providerFailure.error.withUsage(stepUsages.length > 0 ? this.aggregateExtractedUsage(stepUsages) : undefined);\n }\n if (providerFailure && !handlers.abortSignal?.aborted) {\n throw new AgentModelCallFailedError(providerFailure.error, stepUsages.length > 0 ? this.aggregateExtractedUsage(stepUsages) : undefined);\n }\n\n // Guarded: `result.usage` rejects on a stream aborted before ANY step finished. An unguarded\n // read here is what turned cancellation into an unmetered path.\n let terminalUsage: unknown;\n try {\n terminalUsage = await result.usage;\n } catch (usageError) {\n this.logDebug('Stream usage unavailable (aborted, or the provider omitted it) — metering the per-step total instead', {\n ...projectCaughtErrorLogFields(usageError),\n });\n }\n const usage = this.selectStreamTurnUsage(terminalUsage, stepUsages);\n\n // The resume payload is the WHOLE conversation the model was in when it stopped: the prompt this call was given,\n // then every step's response messages. The runtime resumes with `[...payload, approval response]`, which is the\n // SDK's own manual-approval recipe (ai 7, `docs/03-agents/06-tool-approvals.mdx`, \"Handle Manual Approvals\":\n // `messages.push(...result.responseMessages)` onto the messages the call was given).\n //\n // #3145: this stored `(await result.response).messages` alone, which is wrong twice. `response` is the LAST step's\n // metadata, so a turn that read something before the gated call lost that step; and response messages never carry\n // the prompt, so the resumed call opened on an assistant tool call with no user message before it. An answered\n // question then ended \"your message didn't come through\", and an approved call ran with the request that asked\n // for it gone. Read AFTER the stream drains, so the assistant turn carrying the approval request is included.\n if (approvalSuspension) {\n try {\n const promptMessages = streamArgs.messages ?? (streamArgs.prompt !== undefined ? [{ role: 'user', content: streamArgs.prompt }] : []);\n approvalSuspension.sdkModelMessages = [...promptMessages, ...((await result.responseMessages) ?? [])];\n } catch (messagesError) {\n this.logDebug('Could not capture resume messages for a suspended turn', {\n ...projectCaughtErrorLogFields(messagesError),\n });\n }\n }\n\n return {\n text: full,\n usage,\n approvalSuspension,\n };\n }\n\n /**\n * Choose what a streamed turn meters: the SDK's terminal total, or the sum of the steps that finished.\n *\n * The terminal total is authoritative when it carries numbers, because it is the provider's own account of the\n * whole turn. It carries none on a turn that was cut short, and ai@7 signals that in TWO ways, not one (#2252):\n *\n * - no step finished → `result.usage` REJECTS (`terminalUsage` arrives here `undefined`);\n * - a step finished, then the stream was aborted → `result.usage` RESOLVES to the empty usage, every field\n * `undefined`, because the total is only ever set by a `finish` part and an aborted stream emits none.\n * (ai@7.0.142 `dist/index.js`, the `eventProcessor` flush: it rejects only when no step was recorded or a\n * no-output error was seen, and otherwise resolves `recordedTotalUsage ?? createNullLanguageModelUsage()`.)\n *\n * Keying the choice on rejection alone, as this method did until #2252, preferred the empty total in the second\n * case and metered a cancelled tool loop as zero tokens while the provider charged for its finished steps — the\n * caller-driveable unmetered-spend path the per-step accumulation exists to close. So the test is whether the\n * total REPORTS usage (`tokenUsageComplete`, i.e. both token counts are numbers), not whether it settled.\n *\n * Rejected: keying on `abortSignal.aborted`. A turn can finish and THEN be cancelled, and its terminal total is\n * then complete and right; the content of the total is what decides, not the cancellation that raced it.\n *\n * A complete terminal total is still not trusted as COMPLETE when a finished step reported no usage: the SDK\n * sums step usage treating a missing count as 0, so its total would claim completeness for a turn one of whose\n * steps was never metered. The per-step sum carries the same counts and says it is incomplete.\n *\n * With no finished step and no terminal total the result is all-zero and marked incomplete, exactly what\n * `extractUsage(undefined)` reports.\n */\n private selectStreamTurnUsage(\n terminalUsage: unknown,\n stepUsages: readonly ReturnType<AgentsBackendService['extractUsage']>[],\n ): ReturnType<AgentsBackendService['extractUsage']> {\n const terminal = terminalUsage === undefined ? undefined : this.extractUsage(terminalUsage);\n if (terminal?.tokenUsageComplete && stepUsages.every((step) => step.tokenUsageComplete)) return terminal;\n if (stepUsages.length > 0) return this.aggregateExtractedUsage(stepUsages);\n return terminal ?? this.aggregateExtractedUsage(stepUsages);\n }\n\n /**\n * What a text-generation call (GENERATE_TEXT, STREAM_TEXT) sends as its prompt: a conversation input as `messages`, so the\n * bounded replay keeps each turn's role and reaches the model once, and any other input as the single `prompt`. The\n * instructions of a conversation are only its current turn (`invocationInstructionsOf`), which is the last message.\n */\n private textGenerationPromptOf(instructions: string, input: unknown): { prompt: string } | { messages: ReturnType<AgentsBackendService['buildChatMessages']> } {\n return invocationConversationOf(input) ? { messages: this.buildChatMessages(instructions, input) } : { prompt: instructions };\n }\n\n /**\n * Build the AI-SDK `messages` array for a chat turn: a caller-supplied\n * `input.messages` conversation, or a single user turn from `instructions`.\n *\n * The array is deliberately SYSTEM-FREE. AI-SDK v7 (`ai@7.x`) rejects a\n * `role:'system'` entry inside `messages` (\"System messages are not allowed in\n * the prompt or messages fields. Use the instructions option instead.\"). The\n * agent's system prompt must be passed by the CALLER via the top-level\n * `instructions:` option of `generateText` / `streamText` (as `executeGenerateText`\n * does), NEVER pushed in here. Any `role:'system'` entry a caller left in\n * `input.messages` is filtered out so the array stays v7-valid (and a new array is\n * returned — the caller's `input.messages` is never mutated). Shared by the\n * buffered chat executor and the streaming path. Throws VALIDATION when no\n * messages result.\n */\n private buildChatMessages(\n instructions: string,\n input: any,\n ): Array<{ role: 'system' | 'user' | 'assistant'; content: string | Array<any> }> {\n let messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string | Array<any> }> = [];\n\n if (input && typeof input === 'object' && 'messages' in input && Array.isArray(input.messages)) {\n // System prompt travels via the top-level `instructions:` option, so drop any\n // `role:'system'` entries here (they would be rejected by AI-SDK v7).\n messages = input.messages.filter((m: any) => m.role !== 'system');\n } else {\n messages.push({ role: 'user', content: instructions });\n }\n\n if (messages.length === 0) {\n throw this.errorBuilder.buildError(ErrorType.VALIDATION, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_MESSAGES_REQUIRED,\n context: { operation: 'CHAT_COMPLETION' }, // diagnostic (log-only)\n });\n }\n return messages;\n }\n\n /**\n * Sum several physical results' extracted usage into one (the chunks of a chunked structured call, the steps\n * of an aborted stream). Prompt, completion and total are summed; completeness holds only if every part was\n * complete. Each cache or reasoning dimension is summed only when EVERY part reported it (#1598 I6): a\n * split known for some parts only would be an understatement presented as exact, so it is left absent and\n * the cost calculator prices the whole as uncached input / plain output instead. With no parts the result is\n * all-zero and marked incomplete, which is what `extractUsage(undefined)` reports too.\n */\n private aggregateExtractedUsage(parts: readonly ReturnType<AgentsBackendService['extractUsage']>[]): ReturnType<AgentsBackendService['extractUsage']> {\n const sum = (read: (part: ReturnType<AgentsBackendService['extractUsage']>) => number | undefined): number | undefined =>\n parts.length > 0 && parts.every((part) => read(part) !== undefined)\n ? parts.reduce((total, part) => total + read(part)!, 0)\n : undefined;\n const noCacheTokens = sum((part) => part.inputTokenDetails?.noCacheTokens);\n const cacheReadTokens = sum((part) => part.inputTokenDetails?.cacheReadTokens);\n const cacheWriteTokens = sum((part) => part.inputTokenDetails?.cacheWriteTokens);\n const textTokens = sum((part) => part.outputTokenDetails?.textTokens);\n const reasoningTokens = sum((part) => part.outputTokenDetails?.reasoningTokens);\n return {\n promptTokens: parts.reduce((total, part) => total + part.promptTokens, 0),\n completionTokens: parts.reduce((total, part) => total + part.completionTokens, 0),\n totalTokens: parts.reduce((total, part) => total + part.totalTokens, 0),\n // No parts is no report at all, never a complete one.\n tokenUsageComplete: parts.length > 0 && parts.every((part) => part.tokenUsageComplete),\n // The three input categories travel together, as the calculator reads them: all or none.\n ...(noCacheTokens !== undefined && cacheReadTokens !== undefined && cacheWriteTokens !== undefined\n ? { inputTokenDetails: { noCacheTokens, cacheReadTokens, cacheWriteTokens } }\n : {}),\n ...(textTokens !== undefined || reasoningTokens !== undefined\n ? { outputTokenDetails: { ...(textTokens === undefined ? {} : { textTokens }), ...(reasoningTokens === undefined ? {} : { reasoningTokens }) } }\n : {}),\n };\n }\n\n /**\n * Extract usage information from AI SDK usage object\n * Handles different usage object structures across providers\n */\n private extractUsage(usage: any): AgentModelCallUsage {\n // AI SDK usage object structure varies by provider\n // Common properties: promptTokens, completionTokens, totalTokens\n const observedPromptTokens = usage?.promptTokens ?? usage?.inputTokens;\n const observedCompletionTokens = usage?.completionTokens ?? usage?.outputTokens;\n const tokenUsageComplete = typeof observedPromptTokens === 'number' && typeof observedCompletionTokens === 'number';\n const promptTokens = observedPromptTokens ?? 0;\n const completionTokens = observedCompletionTokens ?? 0;\n const totalTokens = usage?.totalTokens ?? (promptTokens + completionTokens);\n\n const details = usage?.inputTokenDetails;\n // AI SDK 7 `LanguageModelUsage.outputTokenDetails` (#1598): OpenAI, Google, xAI and Perplexity report the\n // reasoning split; Anthropic and Mistral do not. Only a NUMBER is kept, so an unreported split stays absent.\n const outputDetails = usage?.outputTokenDetails;\n const textTokens = typeof outputDetails?.textTokens === 'number' ? outputDetails.textTokens : undefined;\n const reasoningTokens = typeof outputDetails?.reasoningTokens === 'number' ? outputDetails.reasoningTokens : undefined;\n return {\n promptTokens,\n completionTokens,\n totalTokens,\n tokenUsageComplete,\n ...(details && typeof details === 'object'\n ? {\n inputTokenDetails: {\n ...(details.noCacheTokens === undefined ? {} : { noCacheTokens: details.noCacheTokens }),\n ...(details.cacheReadTokens === undefined ? {} : { cacheReadTokens: details.cacheReadTokens }),\n ...(details.cacheWriteTokens === undefined ? {} : { cacheWriteTokens: details.cacheWriteTokens }),\n },\n }\n : {}),\n ...(textTokens !== undefined || reasoningTokens !== undefined\n ? {\n outputTokenDetails: {\n ...(textTokens === undefined ? {} : { textTokens }),\n ...(reasoningTokens === undefined ? {} : { reasoningTokens }),\n },\n }\n : {}),\n };\n }\n\n /**\n * Re-throw a {@link AgentModelCallFailedError} unchanged, logging the provider's own failure first.\n *\n * Every operation's `catch` calls this before its generic wrapping. Wrapping would rebuild the error\n * as an INTERNAL backend error and drop the usage it carries, which the failure paths meter, and the\n * typed class, which is how the conversational runtime tells a provider failure apart in its log.\n */\n private rethrowModelCallFailure(error: unknown, operation: string): void {\n if (!(error instanceof AgentModelCallFailedError)) return;\n this.logger.error('The model call failed on the stream; the invocation fails with its reason', {\n operation,\n ...this.extractProviderErrorDetails(error.providerError),\n });\n throw error;\n }\n\n /**\n * Drain a BUFFERED stream's text, failing on a provider failure instead of returning what arrived.\n *\n * `textStream` is the obvious reader and the wrong one: it keeps text deltas and DROPS the `error`\n * part, so a mid-stream provider failure (an `overloaded_error` event after the response began)\n * came back as a successful, truncated or empty text (#2191). Reading `fullStream` keeps the part.\n *\n * A refusal before any output also rejects `result.usage`; on that path the error carries no usage,\n * because the provider ran nothing. A failure after output began still resolves it, with what was used.\n */\n private async drainBufferedStreamText(result: { fullStream: AsyncIterable<any>; usage: PromiseLike<unknown> }): Promise<string> {\n let text = '';\n let providerFailure: { error: unknown } | undefined;\n for await (const part of result.fullStream) {\n if (part?.type === 'text-delta') text += part.text;\n else if (part?.type === 'error') providerFailure ??= { error: part.error };\n }\n if (providerFailure) {\n let usage: AgentModelCallUsage | undefined;\n try {\n usage = this.extractUsage(await result.usage);\n } catch {\n usage = undefined;\n }\n // #2292 Phase 3: a withheld output is not a provider failure (see `streamTextToDeltas`).\n if (providerFailure.error instanceof AgentOutputWithheldError) throw providerFailure.error.withUsage(usage);\n throw new AgentModelCallFailedError(providerFailure.error, usage);\n }\n return text;\n }\n\n /**\n * The error a failed model call throws: every provider-call failure site in this service builds it here (#3204).\n *\n * A provider ACCOUNT's refusal (no credits left, a spend or usage limit, billing — `readModelProviderAccountRefusal`)\n * is the environment's condition, never an internal fault: it answers `EXTERNAL_SERVICE` (502) with the stable\n * reference `MODEL_PROVIDER_ACCOUNT_REFUSED`. Its context names the reason, the provider and the provider's own message\n * for the log; the wire carries the reason only (least disclosure: the requester may be an application's end user),\n * and the operator reads the rest in the log and on the companion's creation loop. Every other failure stays\n * `INTERNAL`, exactly as before. Measured on run 42073501412: an OpenAI\n * account out of credits answered 429 on every structured generation and the companion reported each as a critical\n * INTERNAL 500, so the drive stopped `loop-refused` and the run read `stalled`.\n */\n private buildModelCallFailure(\n error: unknown,\n errorDetails: Record<string, unknown>,\n context: Record<string, unknown>,\n providerRef?: string,\n ): WildoError_Backend {\n const refusal = readModelProviderAccountRefusal(error, providerRef);\n if (refusal !== undefined) {\n return this.errorBuilder.buildError(ErrorType.EXTERNAL_SERVICE, undefined, {\n customMessageReference: ErrorCustomMessageReference.MODEL_PROVIDER_ACCOUNT_REFUSED,\n context: { ...context, ...errorDetails, ...refusal, message: describeModelProviderAccountRefusal(refusal) },\n });\n }\n return this.errorBuilder.buildError(ErrorType.INTERNAL, undefined, {\n customMessageReference: ErrorCustomMessageReference.INTERNAL,\n context: { ...context, ...errorDetails },\n });\n }\n\n /**\n * What a failed model call records of the vendor's answer (#2368): see `describeModelCallError`. The vendor's body,\n * response headers and `data` are never recorded by value: a refusal can quote the prompt content it refused, and these\n * details are logged and spread into the thrown error's context, where erasure does not reach. What is kept is named\n * field by field there: the status, the vendor's type and code, its redacted message, token counts, operational headers.\n */\n private extractProviderErrorDetails(error: unknown): Record<string, unknown> {\n return describeModelCallError(error);\n }\n\n // ================================\n // Agent Validation\n // ================================\n\n /**\n * The organizations a BUFFERED call works for (`invokeAgent`, a structured call on another agent's model): the scope its\n * agent's suspensions (#2843) and its content guardrails (#2292 R8) are both read for. Built once, at the entry point,\n * and handed to the execution, so an organization that suspended an agent, or tightened it, is asked about the same\n * calls.\n *\n * Four sources, each engine-set, never a caller's or a model's:\n *\n * 1. the organization the call names (an `invokeAgent` initiator's, a structured call's explicit attribution);\n * 2. the work frame's tenant, merged field by field with the call's explicit attribution as its cost record is\n * (`resolveModelCallAttribution`);\n * 3. the tenant of the case that attribution names, read from the case row by the provider-call recorder\n * (`caseTenantOf`), as the tenant a call's cost is recorded against is. An actor run carries no tenant of its own:\n * its frame names its run and its case (`actorRunWorkAttribution`), so this is how an application's own actor run on\n * a case is asked;\n * 4. the organization of the run's requester, from the spend frame. A flow run's frame names no tenant, and its\n * `agent.call` step names none, so without this a flow step was asked only for the application's suspensions and\n * ran with the agent's declared guardrails, whatever its organization had decided (#2843 review H1). The flow\n * service opens that frame only for a requester acting in the run's organization (`inFlowRunSpendFrame`), and a\n * conversational turn opens it for its authenticated principal, so it names the organization the work is done in.\n *\n * The call is made for the first one present, in the order the cost record decides its tenant (the case's row, then the\n * named organization, then the frame's), then the requester's. Every other one present is applied as well rather than\n * outranked: a suspension only refuses and a policy only tightens, so one more organization's can never let through\n * what one of them stops. Where they disagree (a case row of another tenant than its frame says) the call is refused or\n * tightened by both, which is the fail-closed reading. Rejected: picking one winner, which would let the loser's\n * suspension silently not apply.\n *\n * A case row whose read FAILED is not \"no tenant\": that organization may have suspended the agent, so the scope carries\n * `unreadable` and the call is refused, as an unreadable suspension or policy refuses it. A row that was not found (a\n * create still in its transaction, a deleted row), or has no tenant (an application-scoped work unit), gives none.\n *\n * A call none of the four names (a deliberation the dev companion runs, an application's own call outside any request,\n * turn, flow or case) works for no organization: only the application's suspensions refuse it, and no organization's\n * policy tightens it.\n *\n * A buffered call carries no role entries, so the representing organization is the one its attribution names (a\n * machine acting for a firm), when it represents one of the organizations above.\n */\n private async buildCallOrganizationScope(\n namedOrganizationId: string | undefined,\n explicitAttribution?: ModelCallAttributionInput,\n ): Promise<ModelCallOrganizationScope> {\n const attribution = resolveModelCallAttribution(explicitAttribution, getCurrentWorkAttributionFrame()).attribution;\n const requesterOrganizationId = getCurrentModelSpendFrame()?.auth?.initiatorIds?.organizationId;\n const caseTenant = attribution.caseRef && this.providerCallRecorder ? await this.providerCallRecorder.caseTenantOf(attribution.caseRef) : undefined;\n const caseOrganizationId = caseTenant?.kind === CaseTenantReadingKind.TENANT ? caseTenant.organizationId : undefined;\n const present = [caseOrganizationId, namedOrganizationId, attribution.organizationId, requesterOrganizationId]\n .filter((id): id is string => typeof id === 'string' && id.length > 0);\n const organizationIds = [...new Set(present)];\n const organizationId = organizationIds[0];\n const via = attribution.viaOrganization;\n return {\n ...(organizationId ? { organizationId } : {}),\n alsoWorkedForOrganizationIds: organizationIds.slice(1),\n representingOrganizationIds: via && organizationIds.includes(via.organizationId) ? [via.representingOrganizationId] : [],\n ...(caseTenant?.kind === CaseTenantReadingKind.UNREADABLE\n ? { unreadable: `the organization of case '${attribution.caseRef!.resourceType}/${attribution.caseRef!.resourceId}' could not be read: ${caseTenant.detail}` }\n : {}),\n };\n }\n\n /**\n * The organizations a STREAMING call works for (a conversational turn): the turn's organization (its tool context's, else\n * its initiator's), derived further exactly as a buffered call's is (`buildCallOrganizationScope`: the case's tenant, the\n * work frame's, the turn principal's), plus each organization the principal represents in the turn's organization through\n * its role entries (#2618). One scope for the turn's suspensions and its guardrails, so the two cannot disagree about\n * which organizations a turn acts for.\n */\n private async buildStreamingCallOrganizationScope(\n toolContext: FunctionToolExecutionContext | undefined,\n initiatorOrganizationId: string | undefined,\n explicitAttribution?: ModelCallAttributionInput,\n ): Promise<ModelCallOrganizationScope> {\n const turnOrganizationId = toolContext?.organizationId ?? initiatorOrganizationId;\n const derived = await this.buildCallOrganizationScope(turnOrganizationId, explicitAttribution);\n const throughRoles = resolveRepresentingOrganizationIdsInOrganization(toolContext?.auth?.initiatorRoles, turnOrganizationId);\n return { ...derived, representingOrganizationIds: [...new Set([...(derived.representingOrganizationIds ?? []), ...throughRoles])] };\n }\n\n /**\n * The admission every model call passes, at each of this service's three entry points (`invokeAgent`,\n * `invokeAgentStreaming`, `generateStructuredOnAgentModel`), before anything is sent to a model. Every door reaches one\n * of them: an A2A turn, an autonomous turn, a Slack/Teams message, an in-app turn, a flow's `agent.call` step, the form\n * composer, and an application's own call.\n *\n * 1. The agent's declared `status` must be ACTIVE (`AGENT_NOT_ACTIVE`): the deploy-time switch.\n * 2. #2843: the agent must not be suspended, for the whole application or for an organization the call acts for (its\n * own, and each representing organization). A suspended agent is refused with `AGENT_SUSPENDED` (CONFLICT: the\n * caller may call it, the agent's current state forbids it); a suspension that cannot be read refuses the call too,\n * as `INFRASTRUCTURE` (retryable). Each refusal is recorded (`SUSPENDED_AGENT_CALL_REFUSED`), naming the door of the\n * conversation or flow run the call was made in.\n *\n * Two decisions, taken by the practice a kill switch follows (a flag or a disabled credential takes effect on the next\n * request; nothing reaches into a request already being served):\n *\n * - **A call already running is not stopped.** A model call in another process cannot be reached from here, and one in\n * this process ends after its bounded tool steps (`MAX_TOOL_STEPS`). What a suspension guarantees is that the NEXT call\n * is refused, including a turn's resume after an approval, which is a new call. Stopping a running turn stays its\n * owner's (`cancelTurn`).\n * - **Queued autonomous occurrences are not skipped ahead of time.** Each one that comes due opens its turn, and that\n * turn's first model call is refused here: the turn ends FAILED with `AGENT_SUSPENDED`, nothing reaches a model, and\n * the refusal is recorded with the door `autonomous`. No queue or schedule state is changed, so resuming the agent\n * needs nothing else: the next occurrence runs.\n *\n * assurance-control: WILDO.AI.HUMAN_OVERSIGHT, WILDO.SECURITY.FAIL_CLOSED — an agent an administrator suspended is refused before its model is called, at every door, and an unreadable suspension refuses the call.\n */\n private async validateAgentStatus(agent: FlowsActors_Agent, scope: ModelCallOrganizationScope): Promise<void> {\n if (agent.status !== FlowsActors_Agent_Status.ACTIVE) {\n throw this.errorBuilder.buildError( ErrorType.VALIDATION, undefined,\n { customMessageReference: ErrorCustomMessageReference.AGENT_NOT_ACTIVE,\n context: { agentRef: agent.ref, status: agent.status }}); // diagnostic (log-only)\n }\n // Only in a process that boots an application (`enforceAgentSuspensions`): the dev companion and the platform's\n // services answer to no application's suspensions.\n if (!this.resolveSuspendingApplicationId) return;\n const lookup: AgentSuspensionLookup = scope.unreadable !== undefined\n ? { kind: AgentSuspensionLookupKind.UNREADABLE, detail: scope.unreadable }\n : await this.readSuspensionOf(agent.ref, organizationIdsOfCallScope(scope));\n if (lookup.kind === AgentSuspensionLookupKind.ADMITTED) return;\n const door = getCurrentModelSpendFrame()?.door;\n this.recordSuspendedAgentCallRefusal(agent.ref, lookup, scope.organizationId);\n if (lookup.kind === AgentSuspensionLookupKind.UNREADABLE) {\n this.logger.error('An agent\\'s suspensions could not be read; the call is refused rather than run', { agentRef: agent.ref, door, detail: lookup.detail });\n throw this.errorBuilder.buildError(ErrorType.INFRASTRUCTURE, undefined, {\n customMessageReference: ErrorCustomMessageReference.INFRASTRUCTURE,\n context: {\n agentRef: agent.ref,\n ...(door ? { door } : {}),\n // Read back by `agentSuspensionRefusalOf`.\n agentSuspensionRefusalReason: AgentSuspensionRefusalReason.SUSPENSION_UNREADABLE,\n message: `Whether agent '${agent.ref}' is suspended could not be read, so its model was not called.`,\n },\n });\n }\n this.logger.warn('A suspended agent was called; the call is refused before its model runs', {\n agentRef: agent.ref, door, suspensionScope: lookup.scope, ...(lookup.organizationId ? { suspendedForOrganizationId: lookup.organizationId } : {}),\n });\n throw this.errorBuilder.buildError(ErrorType.CONFLICT, undefined, {\n customMessageReference: ErrorCustomMessageReference.AGENT_SUSPENDED,\n context: {\n agentRef: agent.ref,\n code: ErrorCustomMessageReference.AGENT_SUSPENDED,\n suspensionScope: lookup.scope,\n ...(door ? { door } : {}),\n agentSuspensionRefusalReason: AgentSuspensionRefusalReason.SUSPENDED,\n message: lookup.scope === AgentSuspensionScope.APPLICATION\n ? `Agent '${agent.ref}' is suspended for the whole application, so its model was not called.`\n : `Agent '${agent.ref}' is suspended for this organization, so its model was not called.`,\n },\n });\n }\n\n /**\n * #3313: what {@link validateAgentStatus} would answer for a call of `agentRef` for `organizationIds`, asked of a call\n * that has not been made, so a person's approval can be refused while its decision still stands. It only reads: no call\n * was refused, so it writes no `SUSPENDED_AGENT_CALL_REFUSED` row and logs nothing. The call itself is still checked when\n * it is made, and may be for more organizations (a case's tenant): this is the same reading, not a replacement for it.\n */\n public async readCallAdmission(agentRef: string, organizationIds: readonly string[]): Promise<AgentCallAdmission> {\n if (this.flowsActorsRegistry.getAgent(agentRef)?.status !== FlowsActors_Agent_Status.ACTIVE) return AgentCallAdmission.AGENT_NOT_ACTIVE;\n if (!this.resolveSuspendingApplicationId) return AgentCallAdmission.ADMITTED;\n const lookup = await this.readSuspensionOf(agentRef, organizationIds);\n if (lookup.kind === AgentSuspensionLookupKind.SUSPENDED) return AgentCallAdmission.SUSPENDED;\n return lookup.kind === AgentSuspensionLookupKind.UNREADABLE ? AgentCallAdmission.UNREADABLE : AgentCallAdmission.ADMITTED;\n }\n\n /**\n * #2843: how this process names the application whose suspensions it answers to, set by `enforceAgentSuspensions` at\n * the application's boot. Unset in a process that boots no application (the dev companion, a platform service): there\n * the admission reads no suspension.\n */\n private resolveSuspendingApplicationId: (() => Promise<string>) | undefined;\n\n /**\n * #2843: start refusing suspended agents. Called once by the application's startup (`StartApplicationBackendService`),\n * before it serves anything, never by a process that boots no application. The application's id is resolved per call\n * (the identity service memoizes it), so a call checked before the identity is primed is still checked.\n */\n public enforceAgentSuspensions(resolveApplicationId: () => Promise<string>): void {\n this.resolveSuspendingApplicationId = resolveApplicationId;\n }\n\n /** #2843: the call's suspensions; an application id that cannot be resolved refuses it like an unreadable record. */\n private async readSuspensionOf(agentRef: string, organizationIds: readonly string[]): Promise<AgentSuspensionLookup> {\n let applicationId: string;\n try {\n applicationId = await this.resolveSuspendingApplicationId!();\n } catch (error) {\n return { kind: AgentSuspensionLookupKind.UNREADABLE, detail: `the application whose suspensions apply could not be resolved: ${describeCaughtError(error)}` };\n }\n return readAgentSuspension(this.repositoriesRegistry, agentRef, { applicationId, organizationIds });\n }\n\n /**\n * #2843: one `SUSPENDED_AGENT_CALL_REFUSED` row per refused call, as the principal of the conversation or flow run it was\n * made in (its spend frame), else for the organization it was made for. Fire-and-forget: the refusal stands whether or\n * not it could be recorded, and a failed write is logged.\n */\n private recordSuspendedAgentCallRefusal(agentRef: string, lookup: Exclude<AgentSuspensionLookup, { kind: AgentSuspensionLookupKind.ADMITTED }>, callOrganizationId: string | undefined): void {\n if (typeof this.auditLogs?.logSuspendedAgentCallRefused !== 'function') return;\n const frame = getCurrentModelSpendFrame();\n const suspended = lookup.kind === AgentSuspensionLookupKind.SUSPENDED ? lookup : undefined;\n void this.auditLogs.logSuspendedAgentCallRefused({\n agentRef,\n reason: suspended ? AgentSuspensionRefusalReason.SUSPENDED : AgentSuspensionRefusalReason.SUSPENSION_UNREADABLE,\n ...(suspended ? { suspensionScope: suspended.scope } : {}),\n ...(suspended?.organizationId ? { suspendedForOrganizationId: suspended.organizationId } : {}),\n ...(frame ? { door: frame.door } : {}),\n }, frame?.auth, callOrganizationId).catch((error: unknown) => {\n this.logger.warn('A refused call to a suspended agent could not be recorded (non-fatal)', { agentRef, ...projectCaughtErrorLogFields(error) });\n });\n }\n\n /**\n * Validate that everything an agent DECLARES resolves — function tools in the registry and MCP\n * servers in the application's declaration — and that any explicitly-required function refs are\n * declared by the agent. Returns false on any gap rather than throwing, so callers can decide how\n * to degrade.\n *\n * ## Why `mcpRefs` are checked here as well (#491)\n *\n * `FlowsActorsRegistryService.initialize` already REFUSES an agent whose `mcpRefs` name no\n * declared server, so on the ordinary path this is redundant — and it is kept anyway, because\n * `registerAgent` is PUBLIC and the refusal is not on it. An agent registered after initialization\n * bypasses that gate entirely today, so this is the only site that would notice.\n *\n * The refusal is deliberately NOT moved onto `registerAgent`: addon load order is not guaranteed,\n * and a per-registration check would refuse a coherent application for the order its addons\n * happened to load in. Two sites answering the same question at two different moments is the\n * correct shape here — one fails the boot, one degrades an invocation.\n */\n public validateAgentCapabilities(agentRef: string, requiredCapabilities: string[]): boolean {\n const agent = this.flowsActorsRegistry.getAgentOrThrow(agentRef);\n const declaredFunctionRefs = agent.capabilities?.tools?.functionRefs ?? [];\n const declaredMcpRefs = agent.capabilities?.tools?.mcpRefs ?? [];\n\n // Every tool the agent declares must resolve in the registry.\n const unresolved = declaredFunctionRefs.filter((ref) => !this.flowsActorsRegistry.hasFunctionTool(ref));\n // And every MCP server it names must be one the application declared.\n const unresolvedMcpRefs = declaredMcpRefs.filter((ref) => !this.flowsActorsRegistry.hasMcpServer(ref));\n // Every explicitly-required capability must be declared by the agent.\n const missingRequired = requiredCapabilities.filter((ref) => !declaredFunctionRefs.includes(ref));\n\n const isValid = unresolved.length === 0 && unresolvedMcpRefs.length === 0 && missingRequired.length === 0;\n this.logDebug('Agent capabilities validated', { agentRef, requiredCapabilities, unresolved, unresolvedMcpRefs, missingRequired, isValid });\n return isValid;\n }\n\n // ================================\n // Agent Discovery\n // ================================\n\n public getAvailableAgents(): FlowsActors_Agent[] {\n const registry = this.flowsActorsRegistry.getRegistry();\n return Object.values(registry.agents).filter((agent: FlowsActors_Agent) => agent.status === FlowsActors_Agent_Status.ACTIVE);\n }\n\n public getAgentsBySkillType(skillType: string): FlowsActors_Agent[] {\n return this.getAvailableAgents().filter(agent => agent.promptSpec.skillType === skillType);\n }\n\n /**\n * Whether the operator is signed in to a provider's coding agent, read from the agent's own status\n * command (no model call) — the same check that refuses a dispatch to a signed-out agent (#1637).\n * `null` when the provider declares no coding agent or no way to read its login.\n *\n * Read in the AGENT's environment — the base set plus the provider's declared variables — never this\n * process's: `claude auth status` reports `loggedIn: true` from an `ANTHROPIC_API_KEY` the dispatched\n * agent never receives, so reading with the full environment showed \"signed in\" for an agent every\n * dispatch refused. An application's execution profile may widen the set further; the provider's\n * declaration is the part every dispatch shares. Public so a host (the companion) can show the state\n * before anything is dispatched; asynchronous so a slow status command never stalls it.\n */\n public async readCodingAgentHostLogin(providerRef: string): Promise<{ providerRef: string; state: CodingAgentHostLoginState; detail: string; remedy: string | null } | null> {\n const profile = this.externalProvidersRegistry.getAgentClientProtocolProfile(providerRef);\n if (!profile?.hostLogin) return null;\n const environment = buildAgentSubprocessEnvironment(profile.inheritedEnvironmentVariables ?? []);\n return { providerRef, ...(await probeCodingAgentHostLoginAsync(profile.hostLogin, { environment })) };\n }\n\n /**\n * What a coding agent of this provider and execution profile is STARTED with, for a host that must reason about the\n * agent's own network route (#3262): its environment (the dispatch's own composition, without the injected secret,\n * which says nothing about the route) and its resolved ACP session metadata (where, for Claude Code, the\n * host-configuration posture becomes the `settingSources` whose settings files add to that environment).\n *\n * `null` when the provider declares no ACP profile or the profile is unknown. Throws what the dispatch would throw on\n * the same configuration (a declared secret in the inherited list, conflicting isolation metadata).\n */\n public readCodingAgentLaunchConfiguration(providerRef: string, executionProfileRef: string): { environment: NodeJS.ProcessEnv; sessionMeta: Record<string, unknown> | undefined } | null {\n const acpProfile = this.externalProvidersRegistry.getAgentClientProtocolProfile(providerRef);\n const acpExecutionProfile = this.externalProvidersRegistry.getAgentClientProtocolExecutionProfile(providerRef, executionProfileRef);\n if (!acpProfile || !acpExecutionProfile) return null;\n const execution: Extract<ResolvedAgentExecution, { transport: 'acp' }> = {\n transport: 'acp',\n providerRef,\n operationKey: CodingAgent_OperationKey.RUN_CODING_TASK,\n executionProfileRef,\n acpProfile,\n acpExecutionProfile,\n };\n return { environment: this.composeAgentClientProtocolInheritedEnvironment(execution), sessionMeta: this.resolveAgentClientProtocolSessionMeta(execution) };\n }\n\n public getAgent(agentRef: string): FlowsActors_Agent | undefined {\n return this.flowsActorsRegistry.getAgent(agentRef);\n }\n\n public getAgentOrThrow(agentRef: string): FlowsActors_Agent {\n return this.flowsActorsRegistry.getAgentOrThrow(agentRef);\n }\n\n // ================================\n // Debug Methods\n // ================================\n\n public getDebugInfo(): { totalAgents: number; activeAgents: number; agentsByProvider: Record<string, number>; agentsBySkillType: Record<string, number> } {\n const allAgents = Object.values(this.flowsActorsRegistry.getRegistry().agents) as FlowsActors_Agent[];\n\n const activeAgents = allAgents.filter(a => a.status === FlowsActors_Agent_Status.ACTIVE);\n\n const agentsByProvider: Record<string, number> = {};\n const agentsBySkillType: Record<string, number> = {};\n\n allAgents.forEach(agent => {\n const provider = agent.config.providerRef;\n agentsByProvider[provider] = (agentsByProvider[provider] || 0) + 1;\n\n const skillType = agent.promptSpec.skillType;\n agentsBySkillType[skillType] = (agentsBySkillType[skillType] || 0) + 1;\n });\n\n return { totalAgents: allAgents.length, activeAgents: activeAgents.length, agentsByProvider, agentsBySkillType, };\n }\n}\n\n/**\n * #2292: a tool's result as a guarded agent's model may read it, by what the tool declares its result carries. A result\n * the tool does not classify is withheld whole: it could carry anything.\n */\nfunction treatToolOutputForModel(output: unknown, declaration: FunctionTool['personalDataOutput'], guard: PersonalDataGuard): unknown {\n switch (declaration?.kind) {\n case FunctionToolPersonalDataOutputKind.RECORDS_OF_RESOURCE:\n return treatRecordsResult(output, guard, declaration.resourceType);\n case FunctionToolPersonalDataOutputKind.TREATED_BY_TOOL:\n return declaration.treat(output, guard);\n case FunctionToolPersonalDataOutputKind.NOT_FROM_RECORDS:\n return output;\n default:\n return guard.withholdWhole();\n }\n}\n\n/**\n * #2292 R8: whether an MCP tool's result is the error result `resolveAgentMcpTools` returns (`{ error, detail }`, the\n * error an outcome kind). A server answer that happens to have that shape is read as one too, and the model is then sent\n * only an outcome kind: never anything the server wrote.\n */\nfunction isMcpErrorResult(output: unknown): output is { error: McpOutcomeKind; detail?: unknown } {\n if (typeof output !== 'object' || output === null || Array.isArray(output)) return false;\n const keys = Object.keys(output);\n return keys.every((key) => key === 'error' || key === 'detail')\n && (Object.values(McpOutcomeKind) as unknown[]).includes((output as { error?: unknown }).error);\n}\n\n/**\n * #2761: the refusals a function tool's call can meet that only the PERSON can resolve, and only in the application. Each\n * is returned to the model as a typed result (`{ error, detail }`) carrying the engine's sentence, never re-thrown: a thrown\n * tool error reaches the model as an SDK tool-error result it narrates in its own words, so the person would be told\n * whatever the model made of an `AUTHORIZATION / STEP_UP_REQUIRED` string. The refusal itself stands; the model cannot\n * satisfy it and is told so.\n *\n * The case that motivated it: a chat turn (Slack, Teams) acts with an authority rebuilt from the member's chat link, which\n * carries no `lastAuthenticatedAt`, so under a user type's `authPolicy.stepUpAuth` every write its tools attempt is\n * refused. The same holds for an in-application turn whose authentication has aged past the policy: the tool runs on the\n * server, so no client is there to answer the step-up challenge.\n */\nexport enum AgentFunctionToolRefusalKind {\n /** The operation needs a recent authentication (the step-up gate, `ErrorCustomMessageReference.STEP_UP_REQUIRED`). */\n STEP_UP_REQUIRED = 'STEP_UP_REQUIRED',\n /**\n * An organization this request reaches through a relationship requires a second factor of its own\n * (`ErrorCustomMessageReference.STEP_UP_REQUIRED_BY_GRANTING_ORGANIZATION`).\n */\n GRANTING_ORGANIZATION_SECOND_FACTOR_REQUIRED = 'GRANTING_ORGANIZATION_SECOND_FACTOR_REQUIRED',\n}\n\n/**\n * The sentence the model is given for each refusal, for the model to relay. Written for the person, and true on every\n * surface a turn runs from: a chat member must open the application, and an in-application user must confirm there too.\n */\nconst AGENT_FUNCTION_TOOL_REFUSAL_DETAIL: Record<AgentFunctionToolRefusalKind, string> = {\n [AgentFunctionToolRefusalKind.STEP_UP_REQUIRED]:\n 'This action needs the person to confirm it is them first, and that cannot be done from here. Tell them to open the application, confirm their identity there, then ask again. Do not retry the call.',\n [AgentFunctionToolRefusalKind.GRANTING_ORGANIZATION_SECOND_FACTOR_REQUIRED]:\n 'An organization this action reaches requires the person to sign in with a second factor, and that cannot be done from here. Tell them to open the application, complete the second factor there, then ask again. Do not retry the call.',\n};\n\n/** #2761: what a function tool returns to the model for a refusal only the person can resolve. */\nexport interface AgentFunctionToolRefusalResult {\n readonly error: AgentFunctionToolRefusalKind;\n readonly detail: string;\n}\n\n/** #2761: the typed result for an error that is such a refusal, or `undefined` for any other error (which is re-thrown). */\nexport function functionToolRefusalOf(error: unknown): AgentFunctionToolRefusalResult | undefined {\n if (!isWildoBackendError(error) || error.type !== ErrorType.AUTHORIZATION) return undefined;\n const kind = error.customMessageReference === ErrorCustomMessageReference.STEP_UP_REQUIRED\n ? AgentFunctionToolRefusalKind.STEP_UP_REQUIRED\n : error.customMessageReference === ErrorCustomMessageReference.STEP_UP_REQUIRED_BY_GRANTING_ORGANIZATION\n ? AgentFunctionToolRefusalKind.GRANTING_ORGANIZATION_SECOND_FACTOR_REQUIRED\n : undefined;\n return kind === undefined ? undefined : { error: kind, detail: AGENT_FUNCTION_TOOL_REFUSAL_DETAIL[kind] };\n}\n\n/** #2761: whether a function tool's output is a refusal result the engine wrote (exactly `{ error, detail }`, both known). */\nfunction isFunctionToolRefusalResult(output: unknown): output is AgentFunctionToolRefusalResult {\n if (typeof output !== 'object' || output === null || Array.isArray(output)) return false;\n const keys = Object.keys(output);\n if (keys.length !== 2 || !keys.includes('error') || !keys.includes('detail')) return false;\n const { error, detail } = output as { error?: unknown; detail?: unknown };\n return (Object.values(AgentFunctionToolRefusalKind) as unknown[]).includes(error)\n && detail === AGENT_FUNCTION_TOOL_REFUSAL_DETAIL[error as AgentFunctionToolRefusalKind];\n}\n\n/** #2292: what a guarded agent's model is told about a failed tool call — its kind, never its text. */\nfunction guardedToolError(error: unknown): Error {\n const kind = isWildoBackendError(error) ? [error.type, error.customMessageReference].filter(Boolean).join(' / ') : 'error';\n return new Error(`The tool call failed (${kind}). Its details are not shown to you, because they can quote record values this agent may not see.`);\n}\n\n/**\n * The usage a failed model call carries, whichever failure it is: a provider failure ({@link AgentModelCallFailedError})\n * or an output its moderation withheld ({@link AgentOutputWithheldError}, #2292). One reader for every failure path that\n * meters — the failure trace, the conversational runtime's usage report — so a failure class cannot silently stop being\n * metered.\n */\nexport function modelCallUsageOfFailure(error: unknown): AgentModelCallUsage | undefined {\n if (error instanceof AgentModelCallFailedError || error instanceof AgentOutputWithheldError) return error.usage;\n return undefined;\n}\n\n/** #3313: what the admission of a model call would answer, read without making the call (`readCallAdmission`). */\nexport enum AgentCallAdmission {\n /** The call would be admitted. */\n ADMITTED = 'admitted',\n /** The agent's declared status is not active. */\n AGENT_NOT_ACTIVE = 'agent_not_active',\n /** An administrator suspended the agent for the application or an organization the call acts for. */\n SUSPENDED = 'suspended',\n /** A suspension record could not be read, and the call would be refused for it. */\n UNREADABLE = 'unreadable',\n}\n\n/**\n * #2843: why a call was refused for its agent's suspension, read back from the error `validateAgentStatus` threw, or\n * `undefined` for any other error. A caller (a conversational turn) tells the person \"this assistant is suspended\"\n * instead of \"it failed\".\n */\nexport function agentSuspensionRefusalOf(error: unknown): { reason: AgentSuspensionRefusalReason; scope?: AgentSuspensionScope } | undefined {\n if (!isWildoBackendError(error)) return undefined;\n const context = error.context as Record<string, unknown> | undefined;\n const reason = context?.agentSuspensionRefusalReason;\n if (!Object.values(AgentSuspensionRefusalReason).includes(reason as AgentSuspensionRefusalReason)) return undefined;\n const scope = context?.suspensionScope;\n return {\n reason: reason as AgentSuspensionRefusalReason,\n ...(Object.values(AgentSuspensionScope).includes(scope as AgentSuspensionScope) ? { scope: scope as AgentSuspensionScope } : {}),\n };\n}\n\n/**\n * #2935: the reason a model call was refused by its organization's model allowance before it ran\n * (`AgentsBackendService` refuses a flow's call this way), or `undefined` for any other error, a provider's failure\n * included. What lets a caller report a spent allowance as such rather than as a broken step.\n */\nexport function modelSpendRefusalOf(error: unknown): { reason: A2ATokenBudgetDenialReason } | undefined {\n if (!isWildoBackendError(error)) return undefined;\n const reason = (error.context as Record<string, unknown> | undefined)?.modelSpendRefusalReason;\n return Object.values(A2ATokenBudgetDenialReason).includes(reason as A2ATokenBudgetDenialReason)\n ? { reason: reason as A2ATokenBudgetDenialReason }\n : undefined;\n}\n"]}
|