From 4d2105f442d641875cf0f5eae0d67af63a6d7f53 Mon Sep 17 00:00:00 2001 From: Hunter Sadler Date: Fri, 25 Sep 2026 17:18:15 -0600 Subject: [PATCH] Intake SDK snapshot for Copilot CLI 1.0.89-4 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../workflows/sdk-consistency-review.lock.yml | 1850 ------- .github/workflows/sdk-consistency-review.md | 147 - .github/workflows/sdk-runtime-artifact.yml | 2 + .github/workflows/sdk.yml | 4 + docs/developer-docs/secrets.md | 6 +- dotnet/src/Generated/Rpc.cs | 2954 ++++------- dotnet/src/Generated/SessionEvents.cs | 431 +- .../test/E2E/RpcExtensionsLoadedE2ETests.cs | 6 +- dotnet/test/E2E/RpcSurfaceCoverageE2ETests.cs | 84 +- dotnet/test/E2E/RpcSurfaceTestCli.cs | 24 +- ...cenarioTestingJsExtensionBridgeE2ETests.cs | 6 +- .../ScenarioTestingServerControlE2ETests.cs | 28 +- dotnet/test/E2E/ScenarioTestingTestCli.cs | 22 +- dotnet/test/Harness/TestHelper.cs | 43 +- .../rpc_generated_surface_gaps_e2e_test.go | 68 +- ...cenario_testing_server_control_e2e_test.go | 76 +- go/rpc/permission_request_managed_approval.go | 2 +- go/rpc/zrpc.go | 2206 +++----- go/rpc/zrpc_encoding.go | 1164 ++-- go/rpc/zsession_encoding.go | 292 +- go/rpc/zsession_events.go | 687 +-- go/zsession_events.go | 75 +- .../copilot/generated/ModelChangeSource.java | 4 +- .../PermissionAssentDetectedEvent.java | 2 +- .../PermissionCarriedForwardEvent.java | 2 +- ...ermissionContextualAuthorizationEvent.java | 2 +- ...sionMessageAuthorizationDegradedEvent.java | 2 +- .../PermissionMessageAuthorizationEvent.java | 2 +- ...ermissionMessageAuthorizationPolarity.java | 2 +- ...rmissionMessageAuthorizationReadEvent.java | 2 +- .../SessionCompactionCompleteEvent.java | 4 +- .../copilot/generated/SessionEvent.java | 12 +- .../generated/SubagentStartedEvent.java | 6 +- ...vent.java => WorkflowRunSettledEvent.java} | 22 +- ...tus.java => WorkflowRunSettledStatus.java} | 12 +- ...vent.java => WorkflowRunStartedEvent.java} | 22 +- ...vent.java => WorkflowRunUpdatedEvent.java} | 18 +- .../copilot/generated/rpc/AccountKind.java | 45 + ...ryAgentOptions.java => AccountStatus.java} | 28 +- .../generated/rpc/AuthEnumerateValue.java | 39 + ...t.java => AuthEnumerateValueAccounts.java} | 30 +- ....java => AuthEnumerateValueProviders.java} | 30 +- ...unOptions.java => AuthLoginResultDto.java} | 14 +- ...Status.java => AuthLoginResultStatus.java} | 22 +- .../copilot/generated/rpc/AuthLoginStep.java | 43 + ...tPhase.java => AuthLoginStepAwaiting.java} | 19 +- .../generated/rpc/AuthLoginStepCompleted.java | 41 + .../generated/rpc/AuthLoginStepError.java | 41 + .../rpc/AuthLoginStepInputRequired.java | 41 + ...ava => AuthLoginStepNeedsInteraction.java} | 21 +- .../generated/rpc/AuthLoginStepOpenUrl.java | 41 + .../copilot/generated/rpc/AuthReadValue.java | 40 + .../rpc/AuthReadValueActiveAccount.java | 41 + ...mits.java => AuthReadValueLastErrors.java} | 31 +- .../generated/rpc/AuthReadValueStatus.java | 41 + .../copilot/generated/rpc/AuthStatusDto.java | 39 + .../generated/rpc/FactoryAgentSummary.java | 57 - .../generated/rpc/FactoryExecuteParams.java | 38 - .../generated/rpc/FactoryLogLineKind.java | 35 - .../rpc/FactoryPhaseObservation.java | 55 - .../generated/rpc/FactoryProgressLine.java | 41 - .../generated/rpc/FactoryProgressPage.java | 42 - .../generated/rpc/FactoryRunLimits.java | 37 - .../generated/rpc/FactoryRunResult.java | 43 - .../generated/rpc/FactoryRunStatus.java | 45 - .../generated/rpc/FactoryRunSummary.java | 69 - .../generated/rpc/FactoryRunTerminal.java | 39 - ...ointAction.java => LoginProviderKind.java} | 26 +- .../generated/rpc/ModelChangeSource.java | 4 +- ...nConsumed.java => ProviderDescriptor.java} | 16 +- .../copilot/generated/rpc/RunOptions.java | 37 - .../generated/rpc/SessionAccountsApi.java | 85 + ...va => SessionAccountsEnumerateParams.java} | 8 +- ...ams.java => SessionAccountsGetParams.java} | 8 +- ...=> SessionAccountsLoginAdvanceParams.java} | 12 +- ...lApi.java => SessionAccountsLoginApi.java} | 34 +- .../rpc/SessionAccountsLoginBeginParams.java | 32 + ...a => SessionAccountsLoginBeginResult.java} | 10 +- ... => SessionAccountsLoginCancelParams.java} | 8 +- ...ams.java => SessionAccountsSetParams.java} | 8 +- ...ult.java => SessionAccountsSetResult.java} | 10 +- .../rpc/SessionFactoryAgentParams.java | 38 - .../generated/rpc/SessionFactoryApi.java | 245 - .../rpc/SessionFactoryCancelResult.java | 46 - .../rpc/SessionFactoryGetRunDetailResult.java | 75 - .../SessionFactoryGetRunProgressParams.java | 40 - .../SessionFactoryGetRunProgressResult.java | 41 - .../rpc/SessionFactoryGetRunResult.java | 46 - .../rpc/SessionFactoryJournalGetParams.java | 36 - .../rpc/SessionFactoryJournalGetResult.java | 32 - .../rpc/SessionFactoryJournalPutParams.java | 38 - .../rpc/SessionFactoryListRunsParams.java | 36 - .../rpc/SessionFactoryListRunsResult.java | 39 - .../rpc/SessionFactoryLogParams.java | 37 - ...SessionFactoryPauseAtCheckpointParams.java | 36 - ...SessionFactoryPauseAtCheckpointResult.java | 30 - .../rpc/SessionFactoryPauseResult.java | 46 - .../SessionFactoryResumeFromToolParams.java | 36 - .../rpc/SessionFactoryResumeParams.java | 38 - .../rpc/SessionFactoryRunFromToolParams.java | 38 - .../rpc/SessionFactoryRunFromToolResult.java | 46 - .../rpc/SessionFactoryRunParams.java | 36 - .../rpc/SessionFactoryRunResult.java | 46 - ...SessionModelApplyStartupOverlayParams.java | 6 +- .../copilot/generated/rpc/SessionRpc.java | 6 +- .../SlashCommandInvocationResultSetModel.java | 7 + .../copilot/RpcSurfaceParityE2ETest.java | 92 +- nodejs/docs/extensions.md | 1 - nodejs/docs/factories.md | 296 -- nodejs/docs/factory-patterns.md | 194 - nodejs/docs/workflows.md | 6 +- nodejs/package.json | 2 +- nodejs/src/cliVersion.ts | 2 +- nodejs/src/client.ts | 28 +- nodejs/src/extension.ts | 69 +- nodejs/src/factory.ts | 539 -- nodejs/src/generated/rpc.ts | 2359 +++------ nodejs/src/generated/session-events.ts | 256 +- nodejs/src/index.ts | 30 +- nodejs/src/session.ts | 676 +-- nodejs/src/types.ts | 64 +- nodejs/src/workflow.ts | 11 +- .../test/e2e/fixtures/factory-extension.mjs | 234 - .../test/e2e/fixtures/workflow-extension.mjs | 210 +- nodejs/test/e2e/harness/sdkTestContext.ts | 2 +- .../test/e2e/rpc_surface_coverage.e2e.test.ts | 2 +- ...ctory.e2e.test.ts => workflow.e2e.test.ts} | 278 +- nodejs/test/extension.test.ts | 23 +- nodejs/test/factory.test.ts | 2772 ---------- nodejs/test/session-event-types.test.ts | 52 +- nodejs/test/workflow.test.ts | 57 +- python/copilot/generated/rpc.py | 4718 ++++++----------- python/copilot/generated/session_events.py | 999 ++-- python/e2e/test_rpc_generated_surface_e2e.py | 80 +- rust/src/generated/api_types.rs | 2473 +++------ rust/src/generated/rpc.rs | 721 +-- rust/src/generated/session_events.rs | 202 +- rust/tests/e2e/rpc_surface_coverage.rs | 112 +- rust/tests/session_test.rs | 6 +- 139 files changed, 9115 insertions(+), 21308 deletions(-) delete mode 100644 .github/workflows/sdk-consistency-review.lock.yml delete mode 100644 .github/workflows/sdk-consistency-review.md rename java/sdk/src/generated/java/com/github/copilot/generated/{FactoryRunSettledEvent.java => WorkflowRunSettledEvent.java} (68%) rename java/sdk/src/generated/java/com/github/copilot/generated/{FactoryRunSettledStatus.java => WorkflowRunSettledStatus.java} (68%) rename java/sdk/src/generated/java/com/github/copilot/generated/{FactoryRunStartedEvent.java => WorkflowRunStartedEvent.java} (59%) rename java/sdk/src/generated/java/com/github/copilot/generated/{FactoryRunUpdatedEvent.java => WorkflowRunUpdatedEvent.java} (65%) create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/AccountKind.java rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{FactoryAgentOptions.java => AccountStatus.java} (53%) create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthEnumerateValue.java rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{SessionFactoryResumeFromToolResult.java => AuthEnumerateValueAccounts.java} (57%) rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{SessionFactoryResumeResult.java => AuthEnumerateValueProviders.java} (57%) rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{FactoryToolRunOptions.java => AuthLoginResultDto.java} (71%) rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{FactoryPhaseStatus.java => AuthLoginResultStatus.java} (63%) create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStep.java rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{FactoryCurrentPhase.java => AuthLoginStepAwaiting.java} (77%) create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepCompleted.java create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepError.java create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepInputRequired.java rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{FactoryLogLine.java => AuthLoginStepNeedsInteraction.java} (74%) create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepOpenUrl.java create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValue.java create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValueActiveAccount.java rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{FactoryDeclaredLimits.java => AuthReadValueLastErrors.java} (61%) create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValueStatus.java create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthStatusDto.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryAgentSummary.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryExecuteParams.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryLogLineKind.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseObservation.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressLine.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressPage.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunLimits.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunResult.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunStatus.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunSummary.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunTerminal.java rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{FactoryPauseCheckpointAction.java => LoginProviderKind.java} (52%) rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{FactoryRunConsumed.java => ProviderDescriptor.java} (67%) delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/RunOptions.java create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsApi.java rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{SessionFactoryPauseParams.java => SessionAccountsEnumerateParams.java} (83%) rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{SessionFactoryGetRunParams.java => SessionAccountsGetParams.java} (85%) rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{FactoryAbortParams.java => SessionAccountsLoginAdvanceParams.java} (73%) rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{SessionFactoryJournalApi.java => SessionAccountsLoginApi.java} (56%) create mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginBeginParams.java rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{FactoryExecuteResult.java => SessionAccountsLoginBeginResult.java} (76%) rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{SessionFactoryCancelParams.java => SessionAccountsLoginCancelParams.java} (85%) rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{SessionFactoryGetRunDetailParams.java => SessionAccountsSetParams.java} (83%) rename java/sdk/src/generated/java/com/github/copilot/generated/rpc/{SessionFactoryAgentResult.java => SessionAccountsSetResult.java} (76%) delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryAgentParams.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryApi.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryCancelResult.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailResult.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressParams.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressResult.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunResult.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalGetParams.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalGetResult.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalPutParams.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsParams.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsResult.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryLogParams.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseAtCheckpointParams.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseAtCheckpointResult.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseResult.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeFromToolParams.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeParams.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunFromToolParams.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunFromToolResult.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunParams.java delete mode 100644 java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunResult.java delete mode 100644 nodejs/docs/factories.md delete mode 100644 nodejs/docs/factory-patterns.md delete mode 100644 nodejs/src/factory.ts delete mode 100644 nodejs/test/e2e/fixtures/factory-extension.mjs rename nodejs/test/e2e/{factory.e2e.test.ts => workflow.e2e.test.ts} (52%) delete mode 100644 nodejs/test/factory.test.ts diff --git a/.github/workflows/sdk-consistency-review.lock.yml b/.github/workflows/sdk-consistency-review.lock.yml deleted file mode 100644 index 867cca9145..0000000000 --- a/.github/workflows/sdk-consistency-review.lock.yml +++ /dev/null @@ -1,1850 +0,0 @@ -# gh-aw-metadata: {"schema_version":"v4","frontmatter_hash":"460e0bbc747eb7d0e062a8982fde1107719822da18b787fb1ffa16d1aac12798","body_hash":"e3a2e1a79536caf26d05fbeca8ef0c9dcf43a1279504e508823b071f5750962c","compiler_version":"v0.88.2","strict":true,"agent_id":"copilot","agent_model":"${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-5' }}","detection_agent_id":"copilot","detection_agent_model":"${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-5' }}","engine_versions":{"copilot":"1.0.80"}} -# gh-aw-manifest: {"version":1,"secrets":["GH_AW_DEFAULT_OTLP_HEADERS","GH_AW_GITHUB_MCP_SERVER_TOKEN","GH_AW_GITHUB_TOKEN","GITHUB_TOKEN"],"actions":[{"repo":"actions/cache/restore","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/cache/save","sha":"55cc8345863c7cc4c66a329aec7e433d2d1c52a9","version":"v6.1.0"},{"repo":"actions/checkout","sha":"3d3c42e5aac5ba805825da76410c181273ba90b1","version":"v7.0.1"},{"repo":"actions/download-artifact","sha":"3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c","version":"v8.0.1"},{"repo":"actions/github-script","sha":"373c709c69115d41ff229c7e5df9f8788daa9553","version":"v9"},{"repo":"actions/github-script","sha":"3a2844b7e9c422d3c10d287c895573f7108da1b3","version":"v9.0.0"},{"repo":"actions/upload-artifact","sha":"043fb46d1a93c77aae656e7c1c64a875d1fc6a0a","version":"v7.0.1"},{"repo":"github/gh-aw-actions/setup","sha":"9271a1804551c0dc4fb0085a97979950aa2f8489","version":"v0.88.2"}],"containers":[{"image":"ghcr.io/github/gh-aw-firewall/agent:0.28.12","digest":"sha256:390051be4ed1847f774fd8980b61d3a3523574c0175d00c3fc7cdf2002a88202","pinned_image":"ghcr.io/github/gh-aw-firewall/agent:0.28.12@sha256:390051be4ed1847f774fd8980b61d3a3523574c0175d00c3fc7cdf2002a88202"},{"image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.12","digest":"sha256:d7d533d87c80d87ff91ac0e21e9299055c3beedff1536262b97ed700fb065a32","pinned_image":"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.12@sha256:d7d533d87c80d87ff91ac0e21e9299055c3beedff1536262b97ed700fb065a32"},{"image":"ghcr.io/github/gh-aw-firewall/squid:0.28.12","digest":"sha256:52c34aca98d2a6833c329f1505912a6949c4fda16618c010c979bd59ea99254f","pinned_image":"ghcr.io/github/gh-aw-firewall/squid:0.28.12@sha256:52c34aca98d2a6833c329f1505912a6949c4fda16618c010c979bd59ea99254f"},{"image":"ghcr.io/github/gh-aw-mcpg:v0.4.15","digest":"sha256:60cd97533e93d8e7be36b979c0f08a70846189bda6190f28bbd6d427bc0d9b6e","pinned_image":"ghcr.io/github/gh-aw-mcpg:v0.4.15@sha256:60cd97533e93d8e7be36b979c0f08a70846189bda6190f28bbd6d427bc0d9b6e"},{"image":"ghcr.io/github/gh-aw-node","digest":"sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e","pinned_image":"ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e"},{"image":"ghcr.io/github/github-mcp-server:v1.11.0","digest":"sha256:fbec75de11c255213fa08d80fb166abe73d851fff631c51c0079872967720699","pinned_image":"ghcr.io/github/github-mcp-server:v1.11.0@sha256:fbec75de11c255213fa08d80fb166abe73d851fff631c51c0079872967720699"}],"has_pull_request":true,"mcp_servers":[{"name":"github","tools":["get_commit","get_file_contents","get_latest_release","get_me","get_pull_request","get_pull_request_comments","get_pull_request_diff","get_pull_request_files","get_pull_request_review_comments","get_pull_request_reviews","get_pull_request_status","get_release_by_tag","get_tag","issue_read","list_branches","list_commits","list_issue_types","list_issues","list_pull_requests","list_releases","list_starred_repositories","list_tags","pull_request_read","search_code","search_issues","search_pull_requests","search_repositories"]},{"name":"safeoutputs","tools":["add_comment","create_pull_request_review_comment","missing_data","missing_tool","noop"]}]} -# This file was automatically generated by gh-aw (v0.88.2). DO NOT EDIT. To debug this workflow, load the skill at https://github.com/github/gh-aw/blob/main/debug.md -# -# ___ _ _ -# / _ \ | | (_) -# | |_| | __ _ ___ _ __ | |_ _ ___ -# | _ |/ _` |/ _ \ '_ \| __| |/ __| -# | | | | (_| | __/ | | | |_| | (__ -# \_| |_/\__, |\___|_| |_|\__|_|\___| -# __/ | -# _ _ |___/ -# | | | | / _| | -# | | | | ___ _ __ _ __| |_| | _____ ____ -# | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___| -# \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \ -# \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/ -# -# -# To update this file, edit the corresponding .md file and run: -# gh aw compile -# Not all edits will cause changes to this file. -# -# For more information: https://github.github.com/gh-aw/introduction/overview/ -# -# Reviews PRs to ensure features are implemented consistently across all SDK language implementations -# -# Secrets used: -# - GH_AW_DEFAULT_OTLP_HEADERS -# - GH_AW_GITHUB_MCP_SERVER_TOKEN -# - GH_AW_GITHUB_TOKEN -# - GITHUB_TOKEN -# -# Custom actions used: -# - actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 -# - actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 -# - actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 -# - actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 -# - actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 -# - actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 -# - actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 -# - github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2 -# -# Container images used: -# - ghcr.io/github/gh-aw-firewall/agent:0.28.12@sha256:390051be4ed1847f774fd8980b61d3a3523574c0175d00c3fc7cdf2002a88202 -# - ghcr.io/github/gh-aw-firewall/api-proxy:0.28.12@sha256:d7d533d87c80d87ff91ac0e21e9299055c3beedff1536262b97ed700fb065a32 -# - ghcr.io/github/gh-aw-firewall/squid:0.28.12@sha256:52c34aca98d2a6833c329f1505912a6949c4fda16618c010c979bd59ea99254f -# - ghcr.io/github/gh-aw-mcpg:v0.4.15@sha256:60cd97533e93d8e7be36b979c0f08a70846189bda6190f28bbd6d427bc0d9b6e -# - ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e -# - ghcr.io/github/github-mcp-server:v1.11.0@sha256:fbec75de11c255213fa08d80fb166abe73d851fff631c51c0079872967720699 - -name: "SDK Consistency Review Agent" -on: - pull_request: - paths: - - nodejs/** - - python/** - - go/** - - dotnet/** - - java/** - - rust/** - - "!java/docs/**" - - "!java/*.txt" - - "!java/*.md" - types: - - opened - - synchronize - - reopened - - ready_for_review - # roles: all # Roles processed as role check in pre-activation job - workflow_dispatch: - inputs: - aw_context: - default: "" - description: "Agent caller context (used internally by Agentic Workflows)." - required: false - type: string - pr_number: - description: PR number to review - required: true - type: string - -permissions: {} - -concurrency: - group: "gh-aw-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref || github.run_id }}" - cancel-in-progress: true - -run-name: "SDK Consistency Review Agent" - -env: - OTEL_EXPORTER_OTLP_ENDPOINT: ${{ vars.GH_AW_DEFAULT_OTLP_ENDPOINT }} - OTEL_SERVICE_NAME: gh-aw.sdk-consistency-review - OTEL_RESOURCE_ATTRIBUTES: 'gh-aw.workflow.name=SDK%20Consistency%20Review%20Agent,gh-aw.repository=${{ github.repository }},gh-aw.run.id=${{ github.run_id }},github.run_id=${{ github.run_id }},gh-aw.engine.id=copilot' - OTEL_EXPORTER_OTLP_HEADERS: ${{ secrets.GH_AW_DEFAULT_OTLP_HEADERS }} - GH_AW_OTLP_ENDPOINTS: '[{"url":"${{ vars.GH_AW_DEFAULT_OTLP_ENDPOINT }}","headers":"${{ secrets.GH_AW_DEFAULT_OTLP_HEADERS }}"}]' - GH_AW_OTLP_IF_MISSING: ignore - -jobs: - activation: - if: > - (github.event_name != 'pull_request' || github.event.pull_request.head.repo.id == github.repository_id) && - ((github.event_name != 'pull_request' && github.event_name != 'pull_request_review') || github.event.pull_request.stack == null || - github.event.pull_request.stack.position == github.event.pull_request.stack.size) - runs-on: ubuntu-slim - permissions: - actions: read - contents: read - env: - GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} - GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} - outputs: - body: ${{ steps.sanitized.outputs.body }} - comment_id: "" - comment_repo: "" - daily_ai_credits_exceeded: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_exceeded == 'true' }} - daily_ai_credits_guardrail_status: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_guardrail_status || '' }} - daily_ai_credits_threshold: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_threshold || '' }} - daily_ai_credits_total_effective_tokens: ${{ steps.daily-effective-workflow-guardrail.outputs.daily_ai_credits_total_effective_tokens || '' }} - engine_id: ${{ steps.generate_aw_info.outputs.engine_id }} - lockdown_check_failed: ${{ steps.generate_aw_info.outputs.lockdown_check_failed == 'true' }} - model: ${{ steps.generate_aw_info.outputs.model }} - oauth_token_check_failed: ${{ steps.check-oauth-tokens.outputs.oauth_token_check_failed == 'true' }} - setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} - setup-span-id: ${{ steps.setup.outputs.span-id }} - setup-trace-id: ${{ steps.setup.outputs.trace-id }} - stale_lock_file_failed: ${{ steps.check-lock-file.outputs.stale_lock_file_failed == 'true' }} - text: ${{ steps.sanitized.outputs.text }} - title: ${{ steps.sanitized.outputs.title }} - steps: - - name: Setup Scripts - id: setup - uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2 - with: - destination: ${{ runner.temp }}/gh-aw/actions - job-name: ${{ github.job }} - safe-output-artifact-client: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} - env: - GH_AW_SETUP_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/sdk-consistency-review.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.80" - GH_AW_INFO_AWF_VERSION: "v0.28.12" - GH_AW_INFO_ENGINE_ID: "copilot" - - name: Mask OTLP telemetry headers - run: bash "${RUNNER_TEMP}/gh-aw/actions/mask_otlp_headers.sh" - - name: Generate agentic run info - id: generate_aw_info - env: - GH_AW_INFO_ENGINE_ID: "copilot" - GH_AW_INFO_ENGINE_NAME: "GitHub Copilot CLI" - GH_AW_INFO_MODEL: "${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-5' }}" - GH_AW_INFO_VERSION: "1.0.80" - GH_AW_INFO_AGENT_VERSION: "1.0.80" - GH_AW_INFO_CLI_VERSION: "v0.88.2" - GH_AW_INFO_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_INFO_EXPERIMENTAL: "false" - GH_AW_INFO_SUPPORTS_TOOLS_ALLOWLIST: "true" - GH_AW_INFO_STAGED: "false" - GH_AW_INFO_ALLOWED_DOMAINS: '["defaults"]' - GH_AW_INFO_FIREWALL_ENABLED: "true" - GH_AW_INFO_AWF_VERSION: "v0.28.12" - GH_AW_INFO_AWMG_VERSION: "" - GH_AW_INFO_FIREWALL_TYPE: "squid" - GH_AW_INFO_AGENT_RUNTIME: "" - GH_AW_COMPILED_STRICT: "true" - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'generate_aw_info.cjs')); - await main(core, context); - - name: Restore daily AIC usage cache - id: restore-daily-aic-cache - if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} - continue-on-error: true - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - key: agentic-workflow-usage-sdkconsistencyreview-${{ github.run_id }} - restore-keys: agentic-workflow-usage-sdkconsistencyreview- - path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl - - name: Restore daily AIC usage cache (artifact fallback) - id: restore-daily-aic-cache-fallback - if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} - continue-on-error: true - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_RESTORE_DAILY_AIC_CACHE_HIT: ${{ steps.restore-daily-aic-cache.outputs.cache-hit }} - GH_AW_RESTORE_DAILY_AIC_CACHE_MATCHED_KEY: ${{ steps.restore-daily-aic-cache.outputs.cache-matched-key }} - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'restore_aic_usage_cache_fallback.cjs')); - await main(); - - name: Check daily workflow token guardrail - id: daily-effective-workflow-guardrail - if: ${{ env.GH_AW_MAX_DAILY_AI_CREDITS != '' }} - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_WORKFLOW_ID: "sdk-consistency-review" - GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - GH_AW_WORKFLOW_DISPATCH_AW_CONTEXT: ${{ github.event.inputs.aw_context || '' }} - GH_AW_HAS_SLASH_COMMAND: "false" - GH_AW_HAS_LABEL_COMMAND: "false" - GH_AW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GH_AW_MAX_DAILY_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_DAILY_AI_CREDITS || '5000' }} - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'check_daily_aic_workflow_guardrail.cjs')); - await main(); - - name: Check for OAuth tokens - id: check-oauth-tokens - run: bash "${RUNNER_TEMP}/gh-aw/actions/check_oauth_tokens.sh" - env: - GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} - GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - - name: Checkout .github and .agents folders - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - sparse-checkout: | - .github - .agents - .claude - .codex - .gemini - .pi - sparse-checkout-cone-mode: true - fetch-depth: 1 - - name: Save agent config folders for base branch restoration - env: - GH_AW_AGENT_FOLDERS: ".agents .github" - GH_AW_AGENT_FILES: "AGENTS.md" - run: | - bash "${RUNNER_TEMP}/gh-aw/actions/save_base_github_folders.sh" - - name: Check workflow lock file - id: check-lock-file - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_WORKFLOW_FILE: "sdk-consistency-review.lock.yml" - GH_AW_CONTEXT_WORKFLOW_REF: "${{ github.workflow_ref }}" - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'check_workflow_timestamp_api.cjs')); - await main(); - - name: Check compile-agentic version - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_COMPILED_VERSION: "v0.88.2" - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'check_version_updates.cjs')); - await main(); - - name: Compute current body text - id: sanitized - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_ALLOWED_DOMAINS: "api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,ppa.launchpad.net,s.symcb.com,s.symcd.com,security.ubuntu.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'compute_text.cjs')); - await main(); - - name: Log runtime features - if: ${{ contains(toJSON(vars), '"GH_AW_RUNTIME_FEATURES":') }} - run: bash "${RUNNER_TEMP}/gh-aw/actions/log_runtime_features_summary.sh" - - name: Create prompt with built-in context - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_ACTIONS_DIR: ${{ runner.temp }}/gh-aw/actions - GH_AW_PROMPT: ${{ runner.temp }}/gh-aw/aw-prompts/prompt.txt - GH_AW_SAFE_OUTPUTS: ${{ runner.temp }}/gh-aw/safeoutputs/outputs.jsonl - GH_AW_PROMPT_CONFIG: "{\"items\":[{\"content_env\":\"GH_AW_PROMPT_CONTENT_0000\"},{\"file\":\"xpia.md\"},{\"file\":\"temp_folder_prompt.md\"},{\"file\":\"markdown.md\"},{\"file\":\"safe_outputs_prompt.md\"},{\"content_env\":\"GH_AW_PROMPT_CONTENT_0001\"},{\"content_env\":\"GH_AW_PROMPT_CONTENT_0002\"},{\"file\":\"mcp_cli_tools_with_safeoutputs_prompt.md\"},{\"content_env\":\"GH_AW_PROMPT_CONTENT_0003\"},{\"file\":\"github_mcp_tools_with_safeoutputs_prompt.md\"},{\"content_env\":\"GH_AW_PROMPT_CONTENT_0004\"},{\"content_env\":\"GH_AW_PROMPT_CONTENT_0005\"}]}" - GH_AW_EXPR_1A3A194A: ${{ github.event.discussion.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'discussion' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} - GH_AW_EXPR_463A214A: ${{ github.event.pull_request.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'pull_request' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} - GH_AW_EXPR_802A9F6A: ${{ github.event.issue.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'issue' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} - GH_AW_EXPR_A0E5D436: ${{ github.event.pull_request.number || inputs.pr_number }} - GH_AW_EXPR_FF1D34CE: ${{ github.event.comment.id || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').comment_id }} - GH_AW_GITHUB_ACTOR: ${{ github.actor }} - GH_AW_GITHUB_REPOSITORY: ${{ github.repository }} - GH_AW_GITHUB_RUN_ID: ${{ github.run_id }} - GH_AW_GITHUB_WORKSPACE: ${{ github.workspace }} - GH_AW_INPUTS_PR_NUMBER: ${{ inputs.pr_number }} - GH_AW_PROMPT_CONTENT_0000: "\n" - GH_AW_PROMPT_CONTENT_0001: "\nTools: add_comment, create_pull_request_review_comment(max:10), missing_tool, missing_data, noop\n" - GH_AW_PROMPT_CONTENT_0002: "\n" - GH_AW_PROMPT_CONTENT_0003: "\nThe following GitHub context information is available for this workflow:\n{{#if github.actor}}\n- **actor**: __GH_AW_GITHUB_ACTOR__\n{{/if}}\n{{#if github.repository}}\n- **repository**: __GH_AW_GITHUB_REPOSITORY__\n{{/if}}\n{{#if github.workspace}}\n- **workspace**: __GH_AW_GITHUB_WORKSPACE__\n{{/if}}\n{{#if github.event.issue.number || (github.aw.context.item_type == 'issue' && github.aw.context.item_number)}}\n- **issue-number**: #__GH_AW_EXPR_802A9F6A__\n{{/if}}\n{{#if github.event.discussion.number || (github.aw.context.item_type == 'discussion' && github.aw.context.item_number)}}\n- **discussion-number**: #__GH_AW_EXPR_1A3A194A__\n{{/if}}\n{{#if github.event.pull_request.number || (github.aw.context.item_type == 'pull_request' && github.aw.context.item_number)}}\n- **pull-request-number**: #__GH_AW_EXPR_463A214A__\n{{/if}}\n{{#if github.event.comment.id || github.aw.context.comment_id}}\n- **comment-id**: __GH_AW_EXPR_FF1D34CE__\n{{/if}}\n{{#if github.run_id}}\n- **workflow-run-id**: __GH_AW_GITHUB_RUN_ID__\n{{/if}}\n\n\n" - GH_AW_PROMPT_CONTENT_0004: "\n" - GH_AW_PROMPT_CONTENT_0005: "{{#runtime-import .github/workflows/sdk-consistency-review.md}}\n" - with: - script: | - const { setupGlobals } = require(process.env.GH_AW_ACTIONS_DIR + '/setup_globals.cjs'); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(process.env.GH_AW_ACTIONS_DIR + '/create_prompt.cjs'); - await main(core); - - name: Interpolate variables and render templates - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_PROMPT: ${{ runner.temp }}/gh-aw/aw-prompts/prompt.txt - GH_AW_ENGINE_ID: "copilot" - GH_AW_EXPR_A0E5D436: ${{ github.event.pull_request.number || inputs.pr_number }} - GH_AW_GITHUB_REPOSITORY: ${{ github.repository }} - GH_AW_INPUTS_PR_NUMBER: ${{ inputs.pr_number }} - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'interpolate_prompt.cjs')); - await main(); - - name: Substitute placeholders - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_PROMPT: ${{ runner.temp }}/gh-aw/aw-prompts/prompt.txt - GH_AW_EXPR_1A3A194A: ${{ github.event.discussion.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'discussion' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} - GH_AW_EXPR_463A214A: ${{ github.event.pull_request.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'pull_request' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} - GH_AW_EXPR_802A9F6A: ${{ github.event.issue.number || (fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_type == 'issue' && fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').item_number) }} - GH_AW_EXPR_A0E5D436: ${{ github.event.pull_request.number || inputs.pr_number }} - GH_AW_EXPR_FF1D34CE: ${{ github.event.comment.id || fromJSON(github.event.inputs.aw_context || github.event.client_payload.aw_context || '{}').comment_id }} - GH_AW_GITHUB_ACTOR: ${{ github.actor }} - GH_AW_GITHUB_REPOSITORY: ${{ github.repository }} - GH_AW_GITHUB_RUN_ID: ${{ github.run_id }} - GH_AW_GITHUB_WORKSPACE: ${{ github.workspace }} - GH_AW_INPUTS_PR_NUMBER: ${{ inputs.pr_number }} - GH_AW_MCP_CLI_SERVERS_LIST: "- `github` — run `github --help` to see available tools\n- `safeoutputs` — run `safeoutputs --help` to see available tools" - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - - const substitutePlaceholders = require(path.join(actionsDir, 'substitute_placeholders.cjs')); - - // Call the substitution function - return await substitutePlaceholders({ - file: process.env.GH_AW_PROMPT, - substitutions: { - GH_AW_EXPR_1A3A194A: process.env.GH_AW_EXPR_1A3A194A, - GH_AW_EXPR_463A214A: process.env.GH_AW_EXPR_463A214A, - GH_AW_EXPR_802A9F6A: process.env.GH_AW_EXPR_802A9F6A, - GH_AW_EXPR_A0E5D436: process.env.GH_AW_EXPR_A0E5D436, - GH_AW_EXPR_FF1D34CE: process.env.GH_AW_EXPR_FF1D34CE, - GH_AW_GITHUB_ACTOR: process.env.GH_AW_GITHUB_ACTOR, - GH_AW_GITHUB_REPOSITORY: process.env.GH_AW_GITHUB_REPOSITORY, - GH_AW_GITHUB_RUN_ID: process.env.GH_AW_GITHUB_RUN_ID, - GH_AW_GITHUB_WORKSPACE: process.env.GH_AW_GITHUB_WORKSPACE, - GH_AW_INPUTS_PR_NUMBER: process.env.GH_AW_INPUTS_PR_NUMBER, - GH_AW_MCP_CLI_SERVERS_LIST: process.env.GH_AW_MCP_CLI_SERVERS_LIST - } - }); - - name: Validate prompt placeholders - env: - GH_AW_PROMPT: ${{ runner.temp }}/gh-aw/aw-prompts/prompt.txt - run: | - bash "${RUNNER_TEMP}/gh-aw/actions/validate_prompt_placeholders.sh" - - name: Print prompt - env: - GH_AW_PROMPT: ${{ runner.temp }}/gh-aw/aw-prompts/prompt.txt - run: | - bash "${RUNNER_TEMP}/gh-aw/actions/print_prompt_summary.sh" - - name: Stage prompt files for artifact upload - run: | - mkdir -p /tmp/gh-aw/aw-prompts - cp -a "${RUNNER_TEMP}/gh-aw/aw-prompts/." /tmp/gh-aw/aw-prompts/ - - name: Upload activation artifact - if: success() || failure() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: activation - include-hidden-files: true - path: | - /tmp/gh-aw/aw_info.json - /tmp/gh-aw/models.json - /tmp/gh-aw/aw-prompts/prompt.txt - /tmp/gh-aw/aw-prompts/prompt-template.txt - /tmp/gh-aw/aw-prompts/prompt-import-tree.json - /tmp/gh-aw/github_rate_limits.jsonl - /tmp/gh-aw/base - /tmp/gh-aw/.github/agents - /tmp/gh-aw/.github/skills - if-no-files-found: ignore - retention-days: 1 - - agent: - needs: activation - if: needs.activation.outputs.daily_ai_credits_exceeded != 'true' - runs-on: ubuntu-latest - permissions: - contents: read - copilot-requests: write - issues: read - pull-requests: read - timeout-minutes: 60 - env: - DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} - GH_AW_ASSETS_ALLOWED_EXTS: "" - GH_AW_ASSETS_BRANCH: "" - GH_AW_ASSETS_MAX_SIZE_KB: 0 - GH_AW_MCP_LOG_DIR: /tmp/gh-aw/mcp-logs/safeoutputs - GH_AW_PR_HEAD_BASE_BRANCH: "" - GH_AW_PR_HEAD_BASE_PR_NUMBER: "" - GH_AW_PR_HEAD_BASE_REF: "" - GH_AW_PR_HEAD_BASE_REPO: "" - GH_AW_PR_HEAD_BASE_SHA: "" - GH_AW_PR_HEAD_REPO: "" - GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} - GH_AW_WORKFLOW_ID_SANITIZED: sdkconsistencyreview - outputs: - agentic_engine_timeout: ${{ steps.detect-agent-errors.outputs.agentic_engine_timeout || 'false' }} - ai_credits_rate_limit_error: ${{ steps.parse-mcp-gateway.outputs.ai_credits_rate_limit_error || 'false' }} - aic: ${{ steps.parse-mcp-gateway.outputs.aic }} - ambient_context: ${{ steps.parse-mcp-gateway.outputs.ambient_context }} - checkout_pr_success: ${{ steps.checkout-pr.outputs.checkout_pr_success || 'true' }} - effective_tokens: ${{ steps.parse-mcp-gateway.outputs.effective_tokens }} - has_patch: ${{ steps.collect_output.outputs.has_patch }} - http_400_response_error: ${{ steps.detect-agent-errors.outputs.http_400_response_error || 'false' }} - inference_access_error: ${{ steps.detect-agent-errors.outputs.inference_access_error || 'false' }} - invocation_cap_exceeded: ${{ steps.detect-agent-errors.outputs.invocation_cap_exceeded || 'false' }} - max_cache_misses_exceeded: ${{ steps.detect-agent-errors.outputs.max_cache_misses_exceeded || 'false' }} - mcp_policy_error: ${{ steps.detect-agent-errors.outputs.mcp_policy_error || 'false' }} - missing_model_pricing_error: ${{ steps.detect-agent-errors.outputs.missing_model_pricing_error || 'false' }} - missing_model_pricing_model_name: ${{ steps.detect-agent-errors.outputs.missing_model_pricing_model_name || '' }} - model: ${{ needs.activation.outputs.model }} - model_not_supported_error: ${{ steps.detect-agent-errors.outputs.model_not_supported_error || 'false' }} - output: ${{ steps.collect_output.outputs.output }} - output_types: ${{ steps.collect_output.outputs.output_types }} - setup-parent-span-id: ${{ steps.setup.outputs.parent-span-id || steps.setup.outputs.span-id }} - setup-span-id: ${{ steps.setup.outputs.span-id }} - setup-trace-id: ${{ steps.setup.outputs.trace-id }} - shell_expansion_guard_rejected: ${{ steps.detect-agent-errors.outputs.shell_expansion_guard_rejected || 'false' }} - unknown_model_ai_credits: ${{ steps.parse-mcp-gateway.outputs.unknown_model_ai_credits || 'false' }} - steps: - - name: Setup Scripts - id: setup - uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2 - with: - destination: ${{ runner.temp }}/gh-aw/actions - job-name: ${{ github.job }} - trace-id: ${{ needs.activation.outputs.setup-trace-id }} - parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} - env: - GH_AW_SETUP_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/sdk-consistency-review.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.80" - GH_AW_INFO_AWF_VERSION: "v0.28.12" - GH_AW_INFO_ENGINE_ID: "copilot" - - name: Set runtime paths - id: set-runtime-paths - env: - GH_AW_RUNNER_TOOL_CACHE: ${{ runner.tool_cache }} - run: | - if [ -z "${RUNNER_TOOL_CACHE:-}" ]; then - echo "RUNNER_TOOL_CACHE=${GH_AW_RUNNER_TOOL_CACHE}" >> "$GITHUB_ENV" - fi - { - echo "GH_AW_SAFE_OUTPUTS=${RUNNER_TEMP}/gh-aw/safeoutputs/outputs.jsonl" - echo "GH_AW_SAFE_OUTPUTS_CONFIG_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/config.json" - echo "GH_AW_SAFE_OUTPUTS_TOOLS_PATH=${RUNNER_TEMP}/gh-aw/safeoutputs/tools.json" - } >> "$GITHUB_OUTPUT" - - name: Mask OTLP telemetry headers - run: bash "${RUNNER_TEMP}/gh-aw/actions/mask_otlp_headers.sh" - - name: Check OTLP telemetry configuration - run: bash "${RUNNER_TEMP}/gh-aw/actions/check_otlp_default_credentials.sh" - - name: Checkout repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Create gh-aw temp directory - run: bash "${RUNNER_TEMP}/gh-aw/actions/create_gh_aw_tmp_dir.sh" - - name: Configure gh CLI for GitHub Enterprise - run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_gh_for_ghe.sh" - env: - GH_TOKEN: ${{ github.token }} - - name: Download activation artifact - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: activation - path: /tmp/gh-aw - - name: Configure Git credentials - env: - GITHUB_REPOSITORY: ${{ github.repository }} - GITHUB_SERVER_URL: ${{ github.server_url }} - GITHUB_TOKEN: ${{ github.token }} - run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - - name: Checkout PR branch - id: checkout-pr - if: | - github.event.pull_request || github.event.issue.pull_request || github.event_name == 'workflow_dispatch' && fromJSON(github.event.inputs.aw_context || '{}').item_type == 'pull_request' - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - with: - github-token: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'checkout_pr_branch.cjs')); - await main(); - - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" - env: - GH_HOST: github.com - GH_AW_COMPILED_VERSION: v0.88.2 - - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.28.12 --rootless - - name: Determine automatic lockdown mode for GitHub MCP Server - id: determine-automatic-lockdown - uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 - env: - GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} - GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const determineAutomaticLockdown = require(path.join(actionsDir, 'determine_automatic_lockdown.cjs')); - await determineAutomaticLockdown(github, context, core); - - name: Restore agent config folders from base branch - if: steps.checkout-pr.outcome == 'success' - env: - GH_AW_AGENT_FOLDERS: ".agents .github" - GH_AW_AGENT_FILES: "AGENTS.md" - run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_base_github_folders.sh" - - name: Restore inline sub-agents from activation artifact - env: - GH_AW_SUB_AGENT_DIR: ".github/agents" - GH_AW_SUB_AGENT_EXT: ".agent.md" - run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_sub_agents.sh" - - name: Restore inline skills from activation artifact - env: - GH_AW_SKILL_DIR: ".github/skills" - run: bash "${RUNNER_TEMP}/gh-aw/actions/restore_inline_skills.sh" - - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.28.12@sha256:390051be4ed1847f774fd8980b61d3a3523574c0175d00c3fc7cdf2002a88202 ghcr.io/github/gh-aw-firewall/api-proxy:0.28.12@sha256:d7d533d87c80d87ff91ac0e21e9299055c3beedff1536262b97ed700fb065a32 ghcr.io/github/gh-aw-firewall/squid:0.28.12@sha256:52c34aca98d2a6833c329f1505912a6949c4fda16618c010c979bd59ea99254f ghcr.io/github/gh-aw-mcpg:v0.4.15@sha256:60cd97533e93d8e7be36b979c0f08a70846189bda6190f28bbd6d427bc0d9b6e ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e ghcr.io/github/github-mcp-server:v1.11.0@sha256:fbec75de11c255213fa08d80fb166abe73d851fff631c51c0079872967720699 - - name: Prepare Safe Outputs Directories - run: | - mkdir -p "${RUNNER_TEMP}/gh-aw/safeoutputs" - mkdir -p /tmp/gh-aw/safeoutputs - mkdir -p /tmp/gh-aw/mcp-logs/safeoutputs - - name: Generate Safe Outputs Config - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_FILE_ROOT: "${{ runner.temp }}/gh-aw" - GH_AW_FILE_CONFIG: "{\"files\":[{\"path\":\"safeoutputs/config.json\",\"content_env\":\"GH_AW_SAFE_OUTPUTS_CONFIG\"}]}" - GH_AW_SAFE_OUTPUTS_CONFIG: "{\"add_comment\":{\"hide_older_comments\":true,\"max\":1},\"create_pull_request_review_comment\":{\"max\":10,\"side\":\"RIGHT\"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"false\"},\"report_incomplete\":{}}" - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'create_files.cjs')); - await main(); - - name: Generate Safe Outputs Tools - env: - GH_AW_TOOLS_META_JSON: | - { - "description_suffixes": { - "add_comment": " CONSTRAINTS: Maximum 1 comment(s) can be added. Supports reply_to_id for discussion threading.", - "create_pull_request_review_comment": " CONSTRAINTS: Maximum 10 review comment(s) can be created. Comments will be on the RIGHT side of the diff." - }, - "repo_params": {}, - "dynamic_tools": [] - } - GH_AW_VALIDATION_JSON: | - { - "add_comment": { - "defaultMax": 1, - "fields": { - "body": { - "required": true, - "type": "string", - "sanitize": true, - "maxLength": 65000 - }, - "comment_id": { - "optionalPositiveInteger": true - }, - "item_number": { - "issueOrPRNumber": true - }, - "pr": { - "issueOrPRNumber": true - }, - "pr_number": { - "issueOrPRNumber": true - }, - "reply_to_id": { - "type": "string", - "maxLength": 256 - }, - "repo": { - "type": "string", - "maxLength": 256 - }, - "target": { - "type": "string", - "enum": [ - "status" - ] - }, - "temporary_id": { - "type": "string", - "pattern": "^#?aw_[A-Za-z0-9_]{3,12}$" - } - } - }, - "create_pull_request_review_comment": { - "defaultMax": 1, - "fields": { - "body": { - "required": true, - "type": "string", - "sanitize": true, - "maxLength": 65000 - }, - "line": { - "required": true, - "positiveInteger": true - }, - "path": { - "required": true, - "type": "string" - }, - "pull_request_number": { - "optionalPositiveInteger": true - }, - "repo": { - "type": "string", - "maxLength": 256 - }, - "side": { - "type": "string", - "enum": [ - "LEFT", - "RIGHT" - ] - }, - "start_line": { - "optionalPositiveInteger": true - } - }, - "customValidation": "startLineLessOrEqualLine" - }, - "missing_data": { - "defaultMax": 20, - "fields": { - "alternatives": { - "type": "string", - "sanitize": true, - "maxLength": 256 - }, - "context": { - "type": "string", - "sanitize": true, - "maxLength": 256 - }, - "data_type": { - "type": "string", - "sanitize": true, - "maxLength": 128 - }, - "reason": { - "type": "string", - "sanitize": true, - "maxLength": 256 - } - } - }, - "missing_tool": { - "defaultMax": 20, - "fields": { - "alternatives": { - "type": "string", - "sanitize": true, - "maxLength": 512 - }, - "reason": { - "required": true, - "type": "string", - "sanitize": true, - "maxLength": 256 - }, - "tool": { - "type": "string", - "sanitize": true, - "maxLength": 128 - } - } - }, - "noop": { - "defaultMax": 1, - "fields": { - "message": { - "required": true, - "type": "string", - "sanitize": true, - "maxLength": 65000 - } - } - }, - "report_incomplete": { - "defaultMax": 5, - "fields": { - "details": { - "type": "string", - "sanitize": true, - "maxLength": 65000 - }, - "reason": { - "required": true, - "type": "string", - "sanitize": true, - "maxLength": 1024 - } - } - } - } - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'generate_safe_outputs_tools.cjs')); - await main(); - - name: Start MCP Gateway - id: start-mcp-gateway - env: - GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST: ${{ vars.GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST || 'true' }} - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_SAFE_OUTPUTS_CONFIG_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_CONFIG_PATH }} - GH_AW_SAFE_OUTPUTS_TOOLS_PATH: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS_TOOLS_PATH }} - GH_AW_SINK_VISIBILITY: ${{ steps.determine-automatic-lockdown.outputs.visibility }} - GITHUB_MCP_GUARD_MIN_INTEGRITY: ${{ steps.determine-automatic-lockdown.outputs.min_integrity }} - GITHUB_MCP_GUARD_REPOS: ${{ steps.determine-automatic-lockdown.outputs.repos }} - GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - set -eo pipefail - mkdir -p "${RUNNER_TEMP}/gh-aw/mcp-config" - if [ -n "${GITHUB_EVENT_PATH:-}" ] && [ -r "${GITHUB_EVENT_PATH}" ]; then - GH_AW_SAFEOUTPUTS_EVENT_PATH="${RUNNER_TEMP}/gh-aw/safeoutputs/github_event.json" - cp "${GITHUB_EVENT_PATH}" "${GH_AW_SAFEOUTPUTS_EVENT_PATH}" - export GITHUB_EVENT_PATH="${GH_AW_SAFEOUTPUTS_EVENT_PATH}" - fi - - # Export gateway environment variables for MCP config and gateway script - export MCP_GATEWAY_PORT="8080" - export MCP_GATEWAY_DOMAIN="awmg-mcpg" - export MCP_GATEWAY_HOST_DOMAIN="localhost" - MCP_GATEWAY_AGENT_ID=$(openssl rand -base64 45 | tr -d '/+=') - echo "::add-mask::${MCP_GATEWAY_AGENT_ID}" - export MCP_GATEWAY_AGENT_ID - export MCP_GATEWAY_PAYLOAD_DIR="/tmp/gh-aw/mcp-payloads" - mkdir -p "${MCP_GATEWAY_PAYLOAD_DIR}" - export MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD="524288" - export MCP_GATEWAY_ALLOWED_MOUNT_ROOTS="${GITHUB_WORKSPACE}:rw,${RUNNER_TEMP}/gh-aw:ro,${RUNNER_TEMP}/gh-aw/safeoutputs:rw,/opt:ro,/tmp:rw,/usr/bin/gh:ro" - export GH_AW_PR_HEAD_BASE_BRANCH="${GH_AW_PR_HEAD_BASE_BRANCH:-}" - export GH_AW_PR_HEAD_BASE_SHA="${GH_AW_PR_HEAD_BASE_SHA:-}" - export GH_AW_PR_HEAD_BASE_REPO="${GH_AW_PR_HEAD_BASE_REPO:-}" - export GH_AW_PR_HEAD_BASE_PR_NUMBER="${GH_AW_PR_HEAD_BASE_PR_NUMBER:-}" - export GH_AW_PR_HEAD_BASE_REF="${GH_AW_PR_HEAD_BASE_REF:-}" - export GH_AW_PR_HEAD_REPO="${GH_AW_PR_HEAD_REPO:-}" - export DEBUG="*" - - export GH_AW_ENGINE="copilot" - MCP_GATEWAY_UID=$(id -u 2>/dev/null || echo '0') - MCP_GATEWAY_GID=$(id -g 2>/dev/null || echo '0') - source "${RUNNER_TEMP}/gh-aw/actions/resolve_docker_socket_gid.sh" - export MCP_GATEWAY_DOCKER_COMMAND='docker run -i --rm --network bridge -p 127.0.0.1:'"${MCP_GATEWAY_PORT}"':'"${MCP_GATEWAY_PORT}"' --name awmg-mcpg --add-host host.docker.internal:host-gateway --user '"${MCP_GATEWAY_UID}"':'"${MCP_GATEWAY_GID}"' --group-add '"${DOCKER_SOCK_GID}"' -v '"${DOCKER_SOCK_PATH}"':/var/run/docker.sock -e MCP_GATEWAY_PORT -e MCP_GATEWAY_DOMAIN -e MCP_GATEWAY_AGENT_ID -e MCP_GATEWAY_PAYLOAD_DIR -e MCP_GATEWAY_PAYLOAD_SIZE_THRESHOLD -e DOCKER_HOST=unix:///var/run/docker.sock -e DEBUG -e MCP_GATEWAY_LOG_DIR -e GH_AW_MCP_LOG_DIR -e GH_AW_SAFE_OUTPUTS -e GH_AW_SAFE_OUTPUTS_CONFIG_PATH -e GH_AW_SAFE_OUTPUTS_TOOLS_PATH -e GH_AW_PR_HEAD_BASE_BRANCH -e GH_AW_PR_HEAD_BASE_SHA -e GH_AW_PR_HEAD_BASE_REPO -e GH_AW_PR_HEAD_BASE_PR_NUMBER -e GH_AW_PR_HEAD_BASE_REF -e GH_AW_PR_HEAD_REPO -e GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST -e GH_AW_ASSETS_BRANCH -e GH_AW_ASSETS_MAX_SIZE_KB -e GH_AW_ASSETS_ALLOWED_EXTS -e DEFAULT_BRANCH -e GITHUB_MCP_SERVER_TOKEN -e GITHUB_MCP_GUARD_MIN_INTEGRITY -e GITHUB_MCP_GUARD_REPOS -e GH_AW_SINK_VISIBILITY -e GITHUB_REPOSITORY -e GITHUB_SERVER_URL -e GITHUB_SHA -e GITHUB_WORKSPACE -e GITHUB_TOKEN -e GITHUB_RUN_ID -e GITHUB_RUN_NUMBER -e GITHUB_RUN_ATTEMPT -e GITHUB_JOB -e GITHUB_ACTION -e GITHUB_EVENT_NAME -e GITHUB_EVENT_PATH -e GITHUB_ACTOR -e GITHUB_ACTOR_ID -e GITHUB_TRIGGERING_ACTOR -e GITHUB_WORKFLOW -e GITHUB_WORKFLOW_REF -e GITHUB_WORKFLOW_SHA -e GITHUB_REF -e GITHUB_REF_NAME -e GITHUB_REF_TYPE -e GITHUB_HEAD_REF -e GITHUB_BASE_REF -e RUNNER_TEMP -e RUNNER_TOOL_CACHE -e MCP_GATEWAY_ALLOWED_MOUNT_ROOTS -e GITHUB_AW_OTEL_TRACE_ID -e GITHUB_AW_OTEL_PARENT_SPAN_ID -e OTEL_EXPORTER_OTLP_HEADERS -v /tmp/gh-aw/mcp-payloads:/tmp/gh-aw/mcp-payloads:rw -v /opt:/opt:ro -v /tmp:/tmp:rw -v '"${GITHUB_WORKSPACE}"':'"${GITHUB_WORKSPACE}"':rw -v '"${RUNNER_TEMP}"'/gh-aw/safeoutputs:'"${RUNNER_TEMP}"'/gh-aw/safeoutputs:rw ghcr.io/github/gh-aw-mcpg:v0.4.15' - - mkdir -p "$HOME/.copilot" - GH_AW_NODE=$(which node 2>/dev/null || command -v node 2>/dev/null || echo node) - cat << GH_AW_MCP_CONFIG_46604863f3d8e286_EOF | "$GH_AW_NODE" "${RUNNER_TEMP}/gh-aw/actions/start_mcp_gateway.cjs" - { - "mcpServers": { - "github": { - "type": "stdio", - "container": "ghcr.io/github/github-mcp-server:v1.11.0", - "env": { - "GITHUB_FEATURES": "fields_param", - "GITHUB_HOST": "${GITHUB_SERVER_URL}", - "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_MCP_SERVER_TOKEN}", - "GITHUB_READ_ONLY": "1", - "GITHUB_TOOLSETS": "context,repos,issues,pull_requests" - }, - "guard-policies": { - "allow-only": { - "min-integrity": "$GITHUB_MCP_GUARD_MIN_INTEGRITY", - "repos": "$GITHUB_MCP_GUARD_REPOS" - } - } - }, - "safeoutputs": { - "type": "stdio", - "container": "ghcr.io/github/gh-aw-node", - "mounts": ["\${GITHUB_WORKSPACE}:\${GITHUB_WORKSPACE}:rw", "${RUNNER_TEMP}/gh-aw/safeoutputs:${RUNNER_TEMP}/gh-aw/safeoutputs:rw", "/tmp/gh-aw:/tmp/gh-aw:rw"], - "args": ["-w", "\${GITHUB_WORKSPACE}"], - "entrypoint": "sh", - "entrypointArgs": ["-c", "sh ${RUNNER_TEMP}/gh-aw/safeoutputs/start_safe_outputs_mcp.sh"], - "env": { - "DEBUG": "*", - "DEFAULT_BRANCH": "\${DEFAULT_BRANCH}", - "GH_AW_ASSETS_ALLOWED_EXTS": "\${GH_AW_ASSETS_ALLOWED_EXTS}", - "GH_AW_ASSETS_BRANCH": "\${GH_AW_ASSETS_BRANCH}", - "GH_AW_ASSETS_MAX_SIZE_KB": "\${GH_AW_ASSETS_MAX_SIZE_KB}", - "GH_AW_MCP_LOG_DIR": "\${GH_AW_MCP_LOG_DIR}", - "GH_AW_SAFE_OUTPUTS": "\${GH_AW_SAFE_OUTPUTS}", - "GH_AW_SAFE_OUTPUTS_CONFIG_PATH": "\${GH_AW_SAFE_OUTPUTS_CONFIG_PATH}", - "GH_AW_SAFE_OUTPUTS_TOOLS_PATH": "\${GH_AW_SAFE_OUTPUTS_TOOLS_PATH}", - "GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST": "\${GH_AW_POLICY_ALLOW_CREATE_PULL_REQUEST}", - "GH_AW_PR_HEAD_BASE_BRANCH": "\${GH_AW_PR_HEAD_BASE_BRANCH}", - "GH_AW_PR_HEAD_BASE_SHA": "\${GH_AW_PR_HEAD_BASE_SHA}", - "GH_AW_PR_HEAD_BASE_REPO": "\${GH_AW_PR_HEAD_BASE_REPO}", - "GH_AW_PR_HEAD_BASE_PR_NUMBER": "\${GH_AW_PR_HEAD_BASE_PR_NUMBER}", - "GH_AW_PR_HEAD_BASE_REF": "\${GH_AW_PR_HEAD_BASE_REF}", - "GH_AW_PR_HEAD_REPO": "\${GH_AW_PR_HEAD_REPO}", - "GITHUB_EVENT_NAME": "\${GITHUB_EVENT_NAME}", - "GITHUB_EVENT_PATH": "\${GITHUB_EVENT_PATH}", - "GITHUB_REPOSITORY": "\${GITHUB_REPOSITORY}", - "GITHUB_SHA": "\${GITHUB_SHA}", - "GITHUB_TOKEN": "\${GITHUB_TOKEN}", - "GITHUB_WORKSPACE": "\${GITHUB_WORKSPACE}", - "RUNNER_TEMP": "\${RUNNER_TEMP}" - }, - "guard-policies": { - "write-sink": { - "accept": [ - "*" - ], - "sink-visibility": "${GH_AW_SINK_VISIBILITY}" - } - } - } - }, - "gateway": { - "port": $MCP_GATEWAY_PORT, - "domain": "${MCP_GATEWAY_DOMAIN}", - "agentId": "${MCP_GATEWAY_AGENT_ID}", - "payloadDir": "${MCP_GATEWAY_PAYLOAD_DIR}", - "startupTimeout": 120, - "opentelemetry": { - "endpoint": "${OTEL_EXPORTER_OTLP_ENDPOINT}", - "traceId": "${GITHUB_AW_OTEL_TRACE_ID}", - "spanId": "${GITHUB_AW_OTEL_PARENT_SPAN_ID}" - } - } - } - GH_AW_MCP_CONFIG_46604863f3d8e286_EOF - - name: Mount MCP servers as CLIs - id: mount-mcp-clis - continue-on-error: true - env: - MCP_GATEWAY_AGENT_ID: ${{ steps.start-mcp-gateway.outputs.gateway-agent-id }} - MCP_GATEWAY_DOMAIN: ${{ steps.start-mcp-gateway.outputs.gateway-domain }} - MCP_GATEWAY_PORT: ${{ steps.start-mcp-gateway.outputs.gateway-port }} - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io); - const { main } = require(path.join(actionsDir, 'mount_mcp_as_cli.cjs')); - await main(); - - name: Clean credentials - continue-on-error: true - run: bash "${RUNNER_TEMP}/gh-aw/actions/clean_git_credentials.sh" - - name: Audit pre-agent workspace - id: pre_agent_audit - continue-on-error: true - run: bash "${RUNNER_TEMP}/gh-aw/actions/audit_pre_agent_workspace.sh" - - name: Execute GitHub Copilot CLI - id: agentic_execution - # Copilot CLI tool arguments (sorted): - timeout-minutes: 15 - run: | - set -o pipefail - printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt - trap 'gh_aw_exit_code=$?; mkdir -p /tmp/gh-aw >/dev/null 2>&1 || true; printf "%s" "$gh_aw_exit_code" > /tmp/gh-aw/agent_execution_exit_code.txt || true; rm -f "$HOME/.copilot/settings.json"; if [ "$gh_aw_exit_code" -ne 0 ]; then echo "::error::Agent execution exited with code $gh_aw_exit_code"; fi' EXIT - mkdir -p "$HOME/.copilot" - printf '%s' '{"builtInAgents":{"rubberDuck":false}}' > "$HOME/.copilot/settings.json" - export XDG_CONFIG_HOME="$HOME" - export GH_AW_MCP_CONFIG="$HOME/.copilot/mcp-config.json" - GH_AW_COPILOT_SRC="$(command -v copilot 2>/dev/null || true)" - if [ -z "$GH_AW_COPILOT_SRC" ] || [ ! -x "$GH_AW_COPILOT_SRC" ]; then - echo "GitHub Copilot CLI executable not found on PATH after installation" >&2 - exit 127 - fi - GH_AW_COPILOT_BIN="${RUNNER_TEMP}/gh-aw/bin/copilot" - mkdir -p "${RUNNER_TEMP}/gh-aw/bin" - if [ "$GH_AW_COPILOT_SRC" != "$GH_AW_COPILOT_BIN" ]; then - cp "$GH_AW_COPILOT_SRC" "$GH_AW_COPILOT_BIN" - fi - chmod 755 "$GH_AW_COPILOT_BIN" - - touch /tmp/gh-aw/agent-step-summary.md - GH_AW_NODE_BIN=$(command -v node 2>/dev/null || true) - export GH_AW_NODE_BIN - export COPILOT_API_KEY="$COPILOT_DUMMY_BYOK" - (umask 177 && touch /tmp/gh-aw/agent-stdio.log) - GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-1000}" - if [[ ! "$GH_AW_MAX_AI_CREDITS" =~ ^[0-9]+$ ]]; then - GH_AW_MAX_AI_CREDITS="1000" - fi - printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.28.12/awf-config.schema.json\",\"network\":{\"allowDomains\":[\"api.snapcraft.io\",\"archive.ubuntu.com\",\"azure.archive.ubuntu.com\",\"crl.geotrust.com\",\"crl.globalsign.com\",\"crl.identrust.com\",\"crl.sectigo.com\",\"crl.thawte.com\",\"crl.usertrust.com\",\"crl.verisign.com\",\"crl3.digicert.com\",\"crl4.digicert.com\",\"crls.ssl.com\",\"json-schema.org\",\"json.schemastore.org\",\"keyserver.ubuntu.com\",\"ocsp.digicert.com\",\"ocsp.geotrust.com\",\"ocsp.globalsign.com\",\"ocsp.identrust.com\",\"ocsp.sectigo.com\",\"ocsp.ssl.com\",\"ocsp.thawte.com\",\"ocsp.usertrust.com\",\"ocsp.verisign.com\",\"packagecloud.io\",\"packages.cloud.google.com\",\"packages.microsoft.com\",\"ppa.launchpad.net\",\"s.symcb.com\",\"s.symcd.com\",\"security.ubuntu.com\",\"ts-crl.ws.symantec.com\",\"ts-ocsp.ws.symantec.com\",\"www.googleapis.com\"],\"isolation\":true,\"topologyAttach\":[\"awmg-mcpg\"]},\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.5\",\"gpt-5.6\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"auto\":[\"copilot/auto\",\"large\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"detection\":[\"small\"],\"evals\":[\"small\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-3.6-flash\":[\"copilot/gemini-3.6*flash*\",\"google/gemini-3.6*flash*\",\"gemini/gemini-3.6*flash*\"],\"gemini-3.7-flash\":[\"copilot/gemini-3.7*flash*\",\"google/gemini-3.7*flash*\",\"gemini/gemini-3.7*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"grok\":[\"copilot/*grok*\",\"openai/*grok*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mai-code-1-flash-picker\":[\"copilot/MAI-Code-1-Flash-picker*\",\"copilot/mai-code-1-flash-picker*\",\"openai/MAI-Code-1-Flash-picker*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"raptor-mini\":[\"copilot/raptor*\",\"openai/raptor*\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-5*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\",\"anthropic/*sonnet-5*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.28.12,squid=sha256:52c34aca98d2a6833c329f1505912a6949c4fda16618c010c979bd59ea99254f,agent=sha256:390051be4ed1847f774fd8980b61d3a3523574c0175d00c3fc7cdf2002a88202,api-proxy=sha256:d7d533d87c80d87ff91ac0e21e9299055c3beedff1536262b97ed700fb065a32,cli-proxy=sha256:5250629d48eaedfedf2e948785228e8da29eec2a83cbab58ea0751c14a7b021d\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" - cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" - GH_AW_DOCKER_HOST="" - if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST="${DOCKER_HOST}" - fi - if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_CHROOT_BINARIES_SOURCE_PATH="${RUNNER_TEMP}/gh-aw" GH_AW_CHROOT_IDENTITY_HOME="${RUNNER_TEMP}/gh-aw/home" node "${RUNNER_TEMP}/gh-aw/actions/patch_awf_chroot_config.cjs" - fi - GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" - if [ -d "$GH_AW_TOOL_CACHE" ]; then - if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then - GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" - fi - fi - # shellcheck disable=SC1003,SC2016,SC2086 - GH_AW_AWF_ENGINE_NAME=copilot \ - GH_AW_AWF_HARNESS_MARKER='[copilot-harness]' \ - GH_AW_AWF_LOG_FILE=/tmp/gh-aw/agent-stdio.log \ - GH_AW_AWF_ATTEMPT_LOG_NAME=copilot \ - bash "${RUNNER_TEMP}/gh-aw/actions/run_awf_with_startup_retries.sh" -- \ - awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env ACTIONS_ID_TOKEN_REQUEST_TOKEN --exclude-env ACTIONS_ID_TOKEN_REQUEST_URL --exclude-env COPILOT_GITHUB_TOKEN --exclude-env GITHUB_MCP_SERVER_TOKEN --exclude-env MCP_GATEWAY_AGENT_ID --mount /tmp/gh-aw:/tmp/gh-aw:rw --log-level info --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/mcp-cli/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && GH_AW_NODE_EXEC="${GH_AW_NODE_BIN:-}"; if [ -z "$GH_AW_NODE_EXEC" ] || [ ! -x "$GH_AW_NODE_EXEC" ]; then GH_AW_NODE_EXEC="$(command -v node 2>/dev/null || true)"; fi; if [ -z "$GH_AW_NODE_EXEC" ]; then echo "node runtime missing on this runner — check runtimes.node in workflow YAML" >&2; exit 127; fi; GH_AW_NPM_GLOBAL_ROOT="$(npm root -g 2>/dev/null || true)"; if [ -n "$GH_AW_NPM_GLOBAL_ROOT" ]; then export NODE_PATH="${GH_AW_NPM_GLOBAL_ROOT}${NODE_PATH:+:${NODE_PATH}}"; fi; "$GH_AW_NODE_EXEC" "${RUNNER_TEMP}/gh-aw/actions/copilot_harness.cjs" "${RUNNER_TEMP}/gh-aw/bin/copilot" --add-dir /tmp/gh-aw/ --log-level all --log-dir /tmp/gh-aw/sandbox/agent/logs/ --disable-builtin-mcps --no-ask-user --allow-all-tools --allow-all-paths --add-dir "${GITHUB_WORKSPACE}" --prompt-file /tmp/gh-aw/aw-prompts/prompt.txt' - env: - AWF_REFLECT_ENABLED: 1 - COPILOT_AGENT_RUNNER_TYPE: STANDALONE - COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ github.token }} - COPILOT_MODEL: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-5' }} - GH_AW_LLM_PROVIDER: github - GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} - GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} - GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }} - GH_AW_PHASE: agent - GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_TIMEOUT_MINUTES: 15 - GH_AW_VERSION: v0.88.2 - GITHUB_API_URL: ${{ github.api_url }} - GITHUB_AW: true - GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows - GITHUB_HEAD_REF: ${{ github.head_ref }} - GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN || secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - GITHUB_REF_NAME: ${{ github.ref_name }} - GITHUB_SERVER_URL: ${{ github.server_url }} - GITHUB_STEP_SUMMARY: /tmp/gh-aw/agent-step-summary.md - GITHUB_WORKSPACE: ${{ github.workspace }} - GIT_AUTHOR_EMAIL: github-actions[bot]@users.noreply.github.com - GIT_AUTHOR_NAME: github-actions[bot] - GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com - GIT_COMMITTER_NAME: github-actions[bot] - RUNNER_TEMP: ${{ runner.temp }} - S2STOKENS: true - TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - - name: Detect agent errors - if: always() - id: detect-agent-errors - continue-on-error: true - env: - GH_AW_AGENTIC_EXECUTION_OUTCOME: ${{ steps.agentic_execution.outcome }} - GH_AW_ENGINE_STEP_TIMEOUT_MINUTES: 15 - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'detect_agent_errors.cjs')); - await main(); - - name: Configure Git credentials - env: - GITHUB_REPOSITORY: ${{ github.repository }} - GITHUB_SERVER_URL: ${{ github.server_url }} - GITHUB_TOKEN: ${{ github.token }} - run: bash "${RUNNER_TEMP}/gh-aw/actions/configure_git_credentials.sh" - - name: Copy Copilot session state files to logs - if: always() - continue-on-error: true - run: bash "${RUNNER_TEMP}/gh-aw/actions/copy_copilot_session_state.sh" - - name: Stop MCP Gateway - if: always() - continue-on-error: true - env: - MCP_GATEWAY_PORT: ${{ steps.start-mcp-gateway.outputs.gateway-port }} - MCP_GATEWAY_AGENT_ID: ${{ steps.start-mcp-gateway.outputs.gateway-agent-id }} - GATEWAY_PID: ${{ steps.start-mcp-gateway.outputs.gateway-pid }} - run: | - bash "${RUNNER_TEMP}/gh-aw/actions/stop_mcp_gateway.sh" "$GATEWAY_PID" - - name: Redact secrets in logs - if: always() - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'redact_secrets.cjs')); - await main(); - env: - GH_AW_SECRET_NAMES: 'GH_AW_GITHUB_MCP_SERVER_TOKEN,GH_AW_GITHUB_TOKEN,GITHUB_TOKEN' - SECRET_GH_AW_GITHUB_MCP_SERVER_TOKEN: ${{ secrets.GH_AW_GITHUB_MCP_SERVER_TOKEN }} - SECRET_GH_AW_GITHUB_TOKEN: ${{ secrets.GH_AW_GITHUB_TOKEN }} - SECRET_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - name: Append agent step summary - if: always() - run: bash "${RUNNER_TEMP}/gh-aw/actions/append_agent_step_summary.sh" - - name: Copy Safe Outputs - if: always() - env: - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - run: | - mkdir -p /tmp/gh-aw - cp "$GH_AW_SAFE_OUTPUTS" /tmp/gh-aw/safeoutputs.jsonl 2>/dev/null || true - - name: Ingest agent output - id: collect_output - if: always() - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - GH_AW_ALLOWED_DOMAINS: "api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,ppa.launchpad.net,s.symcb.com,s.symcd.com,security.ubuntu.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" - GITHUB_SERVER_URL: ${{ github.server_url }} - GITHUB_API_URL: ${{ github.api_url }} - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'collect_ndjson_output.cjs')); - await main(); - - name: Parse agent logs for step summary - if: always() - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_AGENT_OUTPUT: /tmp/gh-aw/sandbox/agent/logs/ - GH_AW_SAFE_OUTPUTS: ${{ steps.set-runtime-paths.outputs.GH_AW_SAFE_OUTPUTS }} - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'parse_copilot_log.cjs')); - await main(); - - name: Parse MCP Gateway logs for step summary - if: always() - id: parse-mcp-gateway - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'parse_mcp_gateway_log.cjs')); - await main(); - - name: Print firewall logs - if: always() - continue-on-error: true - env: - AWF_LOGS_DIR: /tmp/gh-aw/sandbox/firewall/logs - run: bash "${RUNNER_TEMP}/gh-aw/actions/print_firewall_logs.sh" --rootless - - name: Parse token usage for step summary - if: always() - continue-on-error: true - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'parse_token_usage.cjs')); - await main(); - - name: Print AWF reflect summary - if: always() - continue-on-error: true - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'awf_reflect_summary.cjs')); - await main(); - - name: Generate observability summary - if: always() - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'generate_observability_summary.cjs')); - await main(core); - - name: Write agent output placeholder if missing - if: always() - run: | - if [ ! -f /tmp/gh-aw/agent_output.json ]; then - echo '{"items":[]}' > /tmp/gh-aw/agent_output.json - fi - # Small dedicated copy of the agent output so safe-output processing - # survives a failed or timed-out upload of the larger agent artifact - - name: Upload agent output fallback artifact - if: always() - continue-on-error: true - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: agent-output-fallback - path: | - /tmp/gh-aw/agent_output.json - /tmp/gh-aw/safeoutputs.jsonl - if-no-files-found: ignore - - name: Upload agent artifacts - if: always() - continue-on-error: true - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: agent - path: | - /tmp/gh-aw/aw-prompts/prompt.txt - /tmp/gh-aw/sandbox/agent/logs/ - /tmp/gh-aw/redacted-urls.log - /tmp/gh-aw/mcp-logs/ - /tmp/gh-aw/agent_usage.json - /tmp/gh-aw/agent-stdio.log - /tmp/gh-aw/pre-agent-audit.txt - /tmp/gh-aw/agent/ - /tmp/gh-aw/github_rate_limits.jsonl - /tmp/gh-aw/otel.jsonl - /tmp/gh-aw/otlp-export-errors.jsonl - /tmp/gh-aw/safeoutputs.jsonl - /tmp/gh-aw/agent_output.json - /tmp/gh-aw/aw-*.patch - /tmp/gh-aw/aw-*.bundle - /tmp/gh-aw/awf-config.json - /tmp/gh-aw/sandbox/firewall/logs/ - /tmp/gh-aw/sandbox/firewall/audit/ - /tmp/gh-aw/sandbox/firewall/awf-reflect.json - if-no-files-found: ignore - - conclusion: - needs: - - activation - - agent - - detection - - safe_outputs - if: > - always() && (needs.agent.result != 'skipped' || needs.activation.outputs.lockdown_check_failed == 'true' || - needs.activation.outputs.oauth_token_check_failed == 'true' || needs.activation.outputs.stale_lock_file_failed == 'true' || - needs.activation.outputs.daily_ai_credits_exceeded == 'true') - runs-on: ubuntu-slim - permissions: - actions: read - issues: write - pull-requests: write - concurrency: - group: "gh-aw-conclusion-sdk-consistency-review" - cancel-in-progress: false - queue: max - env: - GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} - outputs: - incomplete_count: ${{ steps.report_incomplete.outputs.incomplete_count }} - noop_message: ${{ steps.noop.outputs.noop_message }} - tools_reported: ${{ steps.missing_tool.outputs.tools_reported }} - total_count: ${{ steps.missing_tool.outputs.total_count }} - steps: - - name: Setup Scripts - id: setup - uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2 - with: - destination: ${{ runner.temp }}/gh-aw/actions - job-name: ${{ github.job }} - trace-id: ${{ needs.activation.outputs.setup-trace-id }} - parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} - env: - GH_AW_SETUP_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/sdk-consistency-review.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.80" - GH_AW_INFO_AWF_VERSION: "v0.28.12" - GH_AW_INFO_ENGINE_ID: "copilot" - - name: Download agent output artifact - id: download-agent-output - continue-on-error: true - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - pattern: "{agent,agent-output-fallback}" - merge-multiple: true - path: /tmp/gh-aw/ - - name: Setup agent output environment variable - id: setup-agent-output-env - if: steps.download-agent-output.outcome == 'success' - run: | - mkdir -p /tmp/gh-aw/ - find "/tmp/gh-aw/" -type f -print - if [ -f "/tmp/gh-aw/agent_output.json" ]; then - echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - fi - - name: Download detection artifact - id: download-detection-artifact - continue-on-error: true - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: detection - path: /tmp/gh-aw/threat-detection/ - - name: Download Safe Outputs Items Manifest - id: download-safe-outputs-manifest - if: always() - continue-on-error: true - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - pattern: safe-outputs-items - merge-multiple: true - path: /tmp/gh-aw/ - - name: Collect usage artifact files - if: always() - continue-on-error: true - run: bash "${RUNNER_TEMP}/gh-aw/actions/collect_usage_artifact_files.sh" - - name: Upload usage artifact - if: always() - continue-on-error: true - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: usage - path: | - /tmp/gh-aw/usage/aw_info.json - /tmp/gh-aw/usage/aw-info.jsonl - /tmp/gh-aw/usage/agent_usage.json - /tmp/gh-aw/usage/agent_usage.jsonl - /tmp/gh-aw/usage/detection_usage.jsonl - /tmp/gh-aw/usage/evals.jsonl - /tmp/gh-aw/usage/graders/grader_manifest.json - /tmp/gh-aw/usage/graders/grader_results.json - /tmp/gh-aw/usage/github_rate_limits.jsonl - /tmp/gh-aw/usage/agent/token_usage.jsonl - /tmp/gh-aw/usage/detection/token_usage.jsonl - /tmp/gh-aw/usage/activity/summary.json - if-no-files-found: ignore - - name: Restore daily AIC usage cache - id: restore-daily-aic-cache-conclusion - if: always() - continue-on-error: true - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - key: agentic-workflow-usage-sdkconsistencyreview-${{ github.run_id }} - restore-keys: agentic-workflow-usage-sdkconsistencyreview- - path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl - - name: Write daily AIC usage cache entry - id: write-daily-aic-cache - if: always() - continue-on-error: true - uses: actions/github-script@373c709c69115d41ff229c7e5df9f8788daa9553 # v9 - with: - github-token: ${{ github.token }} - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context); - const { main } = require(path.join(actionsDir, 'write_daily_aic_usage_cache.cjs')); - await main(); - - name: Save daily AIC usage cache - id: save-daily-aic-cache - if: always() - continue-on-error: true - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - key: agentic-workflow-usage-sdkconsistencyreview-${{ github.run_id }} - path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl - - name: Upload daily AIC usage cache artifact - id: upload-daily-aic-cache - if: always() - continue-on-error: true - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: aic-usage-cache - path: /tmp/gh-aw/agentic-workflow-usage-cache.jsonl - if-no-files-found: ignore - retention-days: 7 - - name: Process no-op messages - id: noop - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} - GH_AW_NOOP_MAX: "1" - GH_AW_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/sdk-consistency-review.md" - GH_AW_TRACKER_ID: "sdk-consistency-review" - GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} - GH_AW_NOOP_REPORT_AS_ISSUE: "false" - GH_AW_AIC: ${{ needs.agent.outputs.aic }} - GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} - GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} - GH_AW_WORKFLOW_ID: "sdk-consistency-review" - with: - github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'handle_noop_message.cjs')); - await main(); - - name: Log detection run - id: detection_runs - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} - GH_AW_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/sdk-consistency-review.md" - GH_AW_TRACKER_ID: "sdk-consistency-review" - GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} - GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} - with: - github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'handle_detection_runs.cjs')); - await main(); - - name: Record missing tool - id: missing_tool - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} - GH_AW_MISSING_TOOL_CREATE_ISSUE: "true" - GH_AW_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/sdk-consistency-review.md" - GH_AW_TRACKER_ID: "sdk-consistency-review" - with: - github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'missing_tool.cjs')); - await main(); - - name: Record incomplete - id: report_incomplete - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} - GH_AW_REPORT_INCOMPLETE_CREATE_ISSUE: "true" - GH_AW_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/sdk-consistency-review.md" - GH_AW_TRACKER_ID: "sdk-consistency-review" - with: - github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'report_incomplete_handler.cjs')); - await main(); - - name: Handle agent failure - id: handle_agent_failure - if: always() - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} - GH_AW_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/sdk-consistency-review.md" - GH_AW_TRACKER_ID: "sdk-consistency-review" - GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - GH_AW_AGENT_CONCLUSION: ${{ needs.agent.result }} - GH_AW_WORKFLOW_ID: "sdk-consistency-review" - GH_AW_ACTION_FAILURE_ISSUE_EXPIRES_HOURS: "0" - GH_AW_ENGINE_ID: "copilot" - GH_AW_CHECKOUT_PR_SUCCESS: ${{ needs.agent.outputs.checkout_pr_success }} - GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens || '' }} - GH_AW_AI_CREDITS_RATE_LIMIT_ERROR: ${{ needs.agent.outputs.ai_credits_rate_limit_error || 'false' }} - GH_AW_UNKNOWN_MODEL_AI_CREDITS: ${{ needs.agent.outputs.unknown_model_ai_credits || 'false' }} - GH_AW_AIC: ${{ needs.agent.outputs.aic }} - GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} - GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_MAX_AI_CREDITS || '1000' }} - GH_AW_INFERENCE_ACCESS_ERROR: ${{ needs.agent.outputs.inference_access_error }} - GH_AW_MCP_POLICY_ERROR: ${{ needs.agent.outputs.mcp_policy_error }} - GH_AW_AGENTIC_ENGINE_TIMEOUT: ${{ needs.agent.outputs.agentic_engine_timeout }} - GH_AW_MODEL_NOT_SUPPORTED_ERROR: ${{ needs.agent.outputs.model_not_supported_error }} - GH_AW_HTTP_400_RESPONSE_ERROR: ${{ needs.agent.outputs.http_400_response_error }} - GH_AW_MAX_CACHE_MISSES_EXCEEDED: ${{ needs.agent.outputs.max_cache_misses_exceeded }} - GH_AW_MISSING_MODEL_PRICING_ERROR: ${{ needs.agent.outputs.missing_model_pricing_error }} - GH_AW_MISSING_MODEL_PRICING_MODEL_NAME: ${{ needs.agent.outputs.missing_model_pricing_model_name }} - GH_AW_SHELL_EXPANSION_GUARD_REJECTED: ${{ needs.agent.outputs.shell_expansion_guard_rejected }} - GH_AW_ENGINE_API_HOSTS: "api.enterprise.githubcopilot.com,api.githubcopilot.com,api.business.githubcopilot.com,api.individual.githubcopilot.com" - GH_AW_LOCKDOWN_CHECK_FAILED: ${{ needs.activation.outputs.lockdown_check_failed }} - GH_AW_OAUTH_TOKEN_CHECK_FAILED: ${{ needs.activation.outputs.oauth_token_check_failed }} - GH_AW_STALE_LOCK_FILE_FAILED: ${{ needs.activation.outputs.stale_lock_file_failed }} - GH_AW_DAILY_AI_CREDITS_EXCEEDED: ${{ needs.activation.outputs.daily_ai_credits_exceeded }} - GH_AW_DAILY_AI_CREDITS_TOTAL_EFFECTIVE_TOKENS: ${{ needs.activation.outputs.daily_ai_credits_total_effective_tokens }} - GH_AW_DAILY_AI_CREDITS_THRESHOLD: ${{ needs.activation.outputs.daily_ai_credits_threshold }} - GH_AW_GROUP_REPORTS: "false" - GH_AW_FAILURE_REPORT_AS_ISSUE: "true" - GH_AW_MISSING_TOOL_REPORT_AS_FAILURE: "true" - GH_AW_MISSING_DATA_REPORT_AS_FAILURE: "true" - GH_AW_TIMEOUT_MINUTES: "15" - with: - github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'handle_agent_failure.cjs')); - await main(); - - name: Report failed jobs - id: report_failed_jobs - if: always() - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} - GH_AW_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/sdk-consistency-review.md" - GH_AW_TRACKER_ID: "sdk-consistency-review" - GH_AW_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - GH_AW_REPORT_FAILED_JOBS: "true" - with: - github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'report_failed_jobs.cjs')); - await main(); - - detection: - needs: - - activation - - agent - if: always() && needs.agent.result != 'skipped' - runs-on: ubuntu-latest - permissions: - contents: read - copilot-requests: write - timeout-minutes: 10 - env: - GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} - outputs: - aic: ${{ steps.parse_detection_token_usage.outputs.aic }} - detection_conclusion: ${{ steps.detection_conclusion.outputs.conclusion }} - detection_reason: ${{ steps.detection_conclusion.outputs.reason }} - detection_success: ${{ steps.detection_conclusion.outputs.success }} - steps: - - name: Setup Scripts - id: setup - uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2 - with: - destination: ${{ runner.temp }}/gh-aw/actions - job-name: ${{ github.job }} - trace-id: ${{ needs.activation.outputs.setup-trace-id }} - parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} - env: - GH_AW_SETUP_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/sdk-consistency-review.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.80" - GH_AW_INFO_AWF_VERSION: "v0.28.12" - GH_AW_INFO_ENGINE_ID: "copilot" - - name: Download activation artifact - continue-on-error: true - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - name: activation - path: /tmp/gh-aw - - name: Download agent output artifact - id: download-agent-output - continue-on-error: true - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - pattern: "{agent,agent-output-fallback}" - merge-multiple: true - path: /tmp/gh-aw/ - - name: Setup agent output environment variable - id: setup-agent-output-env - if: steps.download-agent-output.outcome == 'success' - run: | - mkdir -p /tmp/gh-aw/ - find "/tmp/gh-aw/" -type f -print - if [ -f "/tmp/gh-aw/agent_output.json" ]; then - echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - fi - - name: Checkout repository for patch context - if: needs.agent.outputs.has_patch == 'true' - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - # --- Threat Detection --- - - name: Clean stale firewall files from agent artifact - run: | - rm -rf /tmp/gh-aw/sandbox/firewall/logs - rm -rf /tmp/gh-aw/sandbox/firewall/audit - - name: Download container images - run: bash "${RUNNER_TEMP}/gh-aw/actions/download_docker_images.sh" ghcr.io/github/gh-aw-firewall/agent:0.28.12@sha256:390051be4ed1847f774fd8980b61d3a3523574c0175d00c3fc7cdf2002a88202 ghcr.io/github/gh-aw-firewall/api-proxy:0.28.12@sha256:d7d533d87c80d87ff91ac0e21e9299055c3beedff1536262b97ed700fb065a32 ghcr.io/github/gh-aw-firewall/squid:0.28.12@sha256:52c34aca98d2a6833c329f1505912a6949c4fda16618c010c979bd59ea99254f - - name: Check if detection needed - id: detection_guard - if: always() - env: - OUTPUT_TYPES: ${{ needs.agent.outputs.output_types }} - HAS_PATCH: ${{ needs.agent.outputs.has_patch }} - run: | - if [[ -n "$OUTPUT_TYPES" || "$HAS_PATCH" == "true" ]]; then - echo "run_detection=true" >> "$GITHUB_OUTPUT" - echo "Detection will run: output_types=$OUTPUT_TYPES, has_patch=$HAS_PATCH" - else - echo "run_detection=false" >> "$GITHUB_OUTPUT" - echo "Detection skipped: no agent outputs or patches to analyze" - fi - - name: Clear MCP Config for detection - if: always() && steps.detection_guard.outputs.run_detection == 'true' - run: | - rm -f "${RUNNER_TEMP}/gh-aw/mcp-config/mcp-servers.json" - rm -f "$HOME/.copilot/mcp-config.json" - rm -f "$GITHUB_WORKSPACE/.gemini/settings.json" - - name: Prepare threat detection files - if: always() && steps.detection_guard.outputs.run_detection == 'true' - run: | - bash "${RUNNER_TEMP}/gh-aw/actions/prepare_threat_detection_files.sh" - - name: Setup threat detection - if: always() && steps.detection_guard.outputs.run_detection == 'true' - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - WORKFLOW_NAME: "SDK Consistency Review Agent" - WORKFLOW_DESCRIPTION: "Reviews PRs to ensure features are implemented consistently across all SDK language implementations" - HAS_PATCH: ${{ needs.agent.outputs.has_patch }} - GH_AW_DETECTION_CONTINUE_ON_ERROR: "true" - GH_AW_DETECTION_SKIP_PROMPT_SUMMARY: "true" - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'setup_threat_detection.cjs')); - await main(); - - name: Ensure threat-detection directory and log - if: always() && steps.detection_guard.outputs.run_detection == 'true' - run: | - mkdir -p /tmp/gh-aw/threat-detection - touch /tmp/gh-aw/threat-detection/detection.log - - name: Install AWF binary - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_awf_binary.sh" v0.28.12 --rootless - - name: Install GitHub Copilot CLI - run: bash "${RUNNER_TEMP}/gh-aw/actions/install_copilot_cli.sh" - env: - GH_HOST: github.com - GH_AW_COMPILED_VERSION: v0.88.2 - - name: Install threat-detect binary - if: always() && steps.detection_guard.outputs.run_detection == 'true' - continue-on-error: true - run: | - bash "${RUNNER_TEMP}/gh-aw/actions/install_threat_detect_binary.sh" v0.5.1 - - name: Execute threat detection with AWF - id: detection_agentic_execution - if: always() && steps.detection_guard.outputs.run_detection == 'true' - continue-on-error: true - timeout-minutes: 10 - env: - AWF_REFLECT_ENABLED: 1 - COPILOT_AGENT_RUNNER_TYPE: STANDALONE - COPILOT_DUMMY_BYOK: dummy-byok-key-for-offline-mode - COPILOT_GITHUB_TOKEN: ${{ github.token }} - COPILOT_MODEL: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-5' }} - GH_AW_HARNESS_MAX_RETRIES: 0 - GH_AW_LLM_PROVIDER: github - GH_AW_MAX_AI_CREDITS: ${{ vars.GH_AW_DEFAULT_DETECTION_MAX_AI_CREDITS || '400' }} - GH_AW_MAX_TURNS: ${{ vars.GH_AW_DEFAULT_MAX_TURNS || '' }} - GH_AW_MODEL_FALLBACK: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'auto' }} - GH_AW_PHASE: detection - GH_AW_PROMPT: /tmp/gh-aw/aw-prompts/prompt.txt - GH_AW_TIMEOUT_MINUTES: 10 - GH_AW_VERSION: v0.88.2 - GITHUB_API_URL: ${{ github.api_url }} - GITHUB_AW: true - GITHUB_COPILOT_INTEGRATION_ID: agentic-workflows - GITHUB_HEAD_REF: ${{ github.head_ref }} - GITHUB_REF_NAME: ${{ github.ref_name }} - GITHUB_SERVER_URL: ${{ github.server_url }} - GITHUB_STEP_SUMMARY: /tmp/gh-aw/agent-step-summary.md - GITHUB_WORKSPACE: ${{ github.workspace }} - GIT_AUTHOR_EMAIL: github-actions[bot]@users.noreply.github.com - GIT_AUTHOR_NAME: github-actions[bot] - GIT_COMMITTER_EMAIL: github-actions[bot]@users.noreply.github.com - GIT_COMMITTER_NAME: github-actions[bot] - RUNNER_TEMP: ${{ runner.temp }} - S2STOKENS: true - TRACEPARENT: ${{ env.GITHUB_AW_OTEL_TRACE_ID != '' && env.GITHUB_AW_OTEL_PARENT_SPAN_ID != '' && format('00-{0}-{1}-01', env.GITHUB_AW_OTEL_TRACE_ID, env.GITHUB_AW_OTEL_PARENT_SPAN_ID) || '' }} - WORKFLOW_NAME: "SDK Consistency Review Agent" - WORKFLOW_DESCRIPTION: "Reviews PRs to ensure features are implemented consistently across all SDK language implementations" - HAS_PATCH: ${{ needs.agent.outputs.has_patch }} - GH_AW_DETECTION_CONTINUE_ON_ERROR: "true" - run: | - set -o pipefail - printf '%s' "$(date +%s%3N)" > /tmp/gh-aw/agent_cli_start_ms.txt - GH_AW_COPILOT_SRC="$(command -v copilot 2>/dev/null || true)" - if [ -z "$GH_AW_COPILOT_SRC" ] || [ ! -x "$GH_AW_COPILOT_SRC" ]; then - echo "GitHub Copilot CLI executable not found on PATH after installation" >&2 - exit 127 - fi - GH_AW_COPILOT_BIN="${RUNNER_TEMP}/gh-aw/bin/copilot" - mkdir -p "${RUNNER_TEMP}/gh-aw/bin" - if [ "$GH_AW_COPILOT_SRC" != "$GH_AW_COPILOT_BIN" ]; then - cp "$GH_AW_COPILOT_SRC" "$GH_AW_COPILOT_BIN" - fi - chmod 755 "$GH_AW_COPILOT_BIN" - - (umask 177 && touch /tmp/gh-aw/threat-detection/detection.log) - GH_AW_MAX_AI_CREDITS="${GH_AW_MAX_AI_CREDITS:-400}" - if [[ ! "$GH_AW_MAX_AI_CREDITS" =~ ^[0-9]+$ ]]; then - GH_AW_MAX_AI_CREDITS="400" - fi - printf '%s\n' "{\"\$schema\":\"https://github.com/github/gh-aw-firewall/releases/download/v0.28.12/awf-config.schema.json\",\"apiProxy\":{\"enabled\":true,\"enableTokenSteering\":true,\"maxRuns\":500,\"maxAiCredits\":${GH_AW_MAX_AI_CREDITS},\"maxCacheMisses\":5,\"models\":{\"agent\":[\"sonnet-6x\",\"gpt-5.4\",\"gpt-5.5\",\"gpt-5.6\",\"gpt-5.3\",\"gemini-pro\",\"any\"],\"antigravity\":[\"copilot/antigravity*\",\"google/antigravity*\",\"gemini/antigravity*\"],\"any\":[\"copilot/*\",\"anthropic/*\",\"openai/*\",\"google/*\",\"gemini/*\"],\"auto\":[\"copilot/auto\",\"large\"],\"claude\":[\"agent\"],\"codex\":[\"agent\"],\"coding\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\",\"gpt-5-codex\",\"kimi\"],\"computer-use\":[\"copilot/*computer-use*\",\"google/*computer-use*\",\"gemini/*computer-use*\",\"openai/*computer-use*\"],\"copilot\":[\"agent\"],\"deep-research\":[\"copilot/deep-research*\",\"copilot/o3-deep-research*\",\"copilot/o4-mini-deep-research*\",\"google/deep-research*\",\"gemini/deep-research*\",\"openai/o3-deep-research*\",\"openai/o4-mini-deep-research*\"],\"detection\":[\"small\"],\"evals\":[\"small\"],\"fable\":[\"copilot/*fable*\",\"anthropic/*fable*\"],\"gemini\":[\"agent\"],\"gemini-3-flash\":[\"copilot/gemini-3*flash*\",\"google/gemini-3*flash*\",\"gemini/gemini-3*flash*\"],\"gemini-3-pro\":[\"copilot/gemini-3*pro*\",\"google/gemini-3*pro*\",\"google/nano-banana*\",\"gemini/gemini-3*pro*\"],\"gemini-3.1-flash\":[\"copilot/gemini-3.1*flash*\",\"google/gemini-3.1*flash*\",\"gemini/gemini-3.1*flash*\"],\"gemini-3.1-pro\":[\"copilot/gemini-3.1*pro*\",\"google/gemini-3.1*pro*\",\"gemini/gemini-3.1*pro*\"],\"gemini-3.5-flash\":[\"copilot/gemini-3.5*flash*\",\"google/gemini-3.5*flash*\",\"gemini/gemini-3.5*flash*\"],\"gemini-3.6-flash\":[\"copilot/gemini-3.6*flash*\",\"google/gemini-3.6*flash*\",\"gemini/gemini-3.6*flash*\"],\"gemini-3.7-flash\":[\"copilot/gemini-3.7*flash*\",\"google/gemini-3.7*flash*\",\"gemini/gemini-3.7*flash*\"],\"gemini-flash\":[\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"],\"gemini-flash-lite\":[\"copilot/gemini-*flash*lite*\",\"google/gemini-*flash*lite*\",\"gemini/gemini-*flash*lite*\"],\"gemini-omni\":[\"copilot/gemini-omni*\",\"google/gemini-omni*\",\"gemini/gemini-omni*\"],\"gemini-pro\":[\"copilot/gemini-*pro*\",\"google/gemini-*pro*\",\"gemini/gemini-*pro*\"],\"gemma\":[\"copilot/gemma*\",\"google/gemma*\",\"gemini/gemma*\"],\"gpt-5\":[\"copilot/gpt-5*\",\"openai/gpt-5*\"],\"gpt-5-codex\":[\"copilot/gpt-5*codex*\",\"openai/gpt-5*codex*\"],\"gpt-5-mini\":[\"copilot/gpt-5*mini*\",\"openai/gpt-5*mini*\"],\"gpt-5-nano\":[\"copilot/gpt-5*nano*\",\"openai/gpt-5*nano*\"],\"gpt-5-pro\":[\"copilot/gpt-5*pro*\",\"openai/gpt-5*pro*\"],\"gpt-5.1\":[\"copilot/gpt-5.1*\",\"openai/gpt-5.1*\"],\"gpt-5.2\":[\"copilot/gpt-5.2*\",\"openai/gpt-5.2*\"],\"gpt-5.3\":[\"copilot/gpt-5.3*\",\"openai/gpt-5.3*\"],\"gpt-5.4\":[\"copilot/gpt-5.4*\",\"openai/gpt-5.4*\"],\"gpt-5.5\":[\"copilot/gpt-5.5*\",\"openai/gpt-5.5*\"],\"gpt-5.6\":[\"copilot/gpt-5.6*\",\"openai/gpt-5.6*\"],\"grok\":[\"copilot/*grok*\",\"openai/*grok*\"],\"haiku\":[\"copilot/*haiku*\",\"anthropic/*haiku*\"],\"image-generation\":[\"copilot/gpt-image*\",\"openai/gpt-image*\",\"openai/chatgpt-image*\",\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"google/imagen*\"],\"kimi\":[\"copilot/kimi*\",\"openai/kimi*\"],\"kiwi\":[\"copilot/kiwi*\",\"openai/kiwi*\"],\"large\":[\"sonnet\",\"gpt-5-pro\",\"gpt-5\",\"gemini-pro\"],\"lyria\":[\"google/lyria*\",\"gemini/lyria*\",\"copilot/lyria*\"],\"mai-code\":[\"copilot/MAI-Code*\",\"copilot/mai-code*\",\"openai/MAI-Code*\"],\"mai-code-1-flash-picker\":[\"copilot/MAI-Code-1-Flash-picker*\",\"copilot/mai-code-1-flash-picker*\",\"openai/MAI-Code-1-Flash-picker*\"],\"mini\":[\"haiku\",\"gpt-5-mini\",\"gpt-5-nano\",\"gemini-flash-lite\"],\"nano-banana\":[\"copilot/nano-banana*\",\"google/nano-banana*\",\"gemini/nano-banana*\"],\"opus\":[\"copilot/*opus*\",\"anthropic/*opus*\"],\"opusplan\":[\"opus?effort=high\"],\"raptor-mini\":[\"copilot/raptor*\",\"openai/raptor*\"],\"reasoning\":[\"copilot/o1*\",\"copilot/o3*\",\"copilot/o4*\",\"openai/o1*\",\"openai/o3*\",\"openai/o4*\"],\"robotics\":[\"copilot/*robotics*\",\"google/*robotics*\",\"gemini/*robotics*\"],\"small\":[\"mini\"],\"small-agent\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash\"],\"sonnet\":[\"copilot/*sonnet*\",\"anthropic/*sonnet*\"],\"sonnet-6x\":[\"copilot/*sonnet-4.5*\",\"copilot/*sonnet-4.6*\",\"copilot/*sonnet-5*\",\"copilot/*sonnet-4-5-*\",\"anthropic/*sonnet-4-5-*\",\"copilot/*sonnet-4-6*\",\"anthropic/*sonnet-4-6*\",\"anthropic/*sonnet-5*\"],\"summarization\":[\"haiku\",\"gpt-5-mini\",\"gemini-flash-lite\",\"mini\"],\"veo\":[\"google/veo*\",\"gemini/veo*\"],\"vision\":[\"copilot/gemini-*image*\",\"google/gemini-*image*\",\"gemini/gemini-*image*\",\"copilot/gemini-*flash*\",\"google/gemini-*flash*\",\"gemini/gemini-*flash*\"]}},\"container\":{\"imageTag\":\"0.28.12,squid=sha256:52c34aca98d2a6833c329f1505912a6949c4fda16618c010c979bd59ea99254f,agent=sha256:390051be4ed1847f774fd8980b61d3a3523574c0175d00c3fc7cdf2002a88202,api-proxy=sha256:d7d533d87c80d87ff91ac0e21e9299055c3beedff1536262b97ed700fb065a32,cli-proxy=sha256:5250629d48eaedfedf2e948785228e8da29eec2a83cbab58ea0751c14a7b021d\"},\"logging\":{\"proxyLogsDir\":\"/tmp/gh-aw/sandbox/firewall/logs\",\"auditDir\":\"/tmp/gh-aw/sandbox/firewall/audit\"}}" > "${RUNNER_TEMP}/gh-aw/awf-config.json" - cp "${RUNNER_TEMP}/gh-aw/awf-config.json" /tmp/gh-aw/awf-config.json - export GH_AW_MODELS_JSON_PATH="/tmp/gh-aw/models.json" - GH_AW_DOCKER_HOST="" - if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - GH_AW_DOCKER_HOST="${DOCKER_HOST}" - fi - if [[ "${DOCKER_HOST:-}" =~ ^tcp:// ]]; then - _GH_AW_CHROOT_JSON=$(jq -c --arg src "${RUNNER_TEMP}/gh-aw" --arg user "$(id -un)" --argjson uid "$(id -u)" --argjson gid "$(id -g)" --arg home "${RUNNER_TEMP}/gh-aw/home" '.chroot={"binariesSourcePath":$src,"identity":{"user":$user,"uid":$uid,"gid":$gid,"home":$home}}' "${RUNNER_TEMP}/gh-aw/awf-config.json") || { echo "chroot config patch failed" >&2; exit 1; } - printf '%s\n' "$_GH_AW_CHROOT_JSON" > "${RUNNER_TEMP}/gh-aw/awf-config.json" - fi - GH_AW_TOOL_CACHE_MOUNT="" - GH_AW_TOOL_CACHE="${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}" - if [ -d "$GH_AW_TOOL_CACHE" ]; then - if [[ "$GH_AW_TOOL_CACHE" != /opt/* ]]; then - GH_AW_TOOL_CACHE_MOUNT="$GH_AW_TOOL_CACHE:$GH_AW_TOOL_CACHE:ro" - fi - fi - # shellcheck disable=SC1003,SC2016,SC2086 - awf --config "${RUNNER_TEMP}/gh-aw/awf-config.json" --container-workdir "${GITHUB_WORKSPACE}" --mount "${RUNNER_TEMP}/gh-aw:${RUNNER_TEMP}/gh-aw:ro" --mount "${RUNNER_TEMP}/gh-aw:/host${RUNNER_TEMP}/gh-aw:ro" ${GH_AW_TOOL_CACHE_MOUNT:+--mount "$GH_AW_TOOL_CACHE_MOUNT"} ${GH_AW_DOCKER_HOST:+--docker-host "$GH_AW_DOCKER_HOST"} --env-all --exclude-env ACTIONS_ID_TOKEN_REQUEST_TOKEN --exclude-env ACTIONS_ID_TOKEN_REQUEST_URL --exclude-env COPILOT_GITHUB_TOKEN --mount /tmp/gh-aw:/tmp/gh-aw:rw --mount /tmp/gh-aw/threat-detection:/tmp/gh-aw/threat-detection:rw --log-level info --skip-pull \ - -- /bin/bash -c 'set +o histexpand; export PATH="${RUNNER_TEMP}/gh-aw/bin:$PATH" && : "${RUNNER_TOOL_CACHE:?RUNNER_TOOL_CACHE must be set}"; GH_AW_TOOL_CACHE="$RUNNER_TOOL_CACHE"; export PATH="$(find "$GH_AW_TOOL_CACHE" -maxdepth 5 -type d -name bin 2>/dev/null | tr '\''\n'\'' '\'':'\'')$PATH"; [ -n "$GOROOT" ] && export PATH="$GOROOT/bin:$PATH" || true; [ -n "$ERLANG_HOME" ] && export PATH="$ERLANG_HOME/bin:$PATH" || true && threat-detect --engine copilot --output /tmp/gh-aw/threat-detection/detection_result.json /tmp/gh-aw/threat-detection' 2>&1 | tee -a /tmp/gh-aw/threat-detection/detection.log - - name: Render detection log - if: always() && steps.detection_guard.outputs.run_detection == 'true' - continue-on-error: true - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'render_detection_log.cjs')); - await main(); - - name: Copy detection firewall logs - if: always() && steps.detection_guard.outputs.run_detection == 'true' - continue-on-error: true - run: | - mkdir -p /tmp/gh-aw/threat-detection/sandbox/firewall - if [ -d /tmp/gh-aw/sandbox/firewall/logs ]; then mkdir -p /tmp/gh-aw/threat-detection/sandbox/firewall/logs && cp -r /tmp/gh-aw/sandbox/firewall/logs/. /tmp/gh-aw/threat-detection/sandbox/firewall/logs/; fi - if [ -d /tmp/gh-aw/sandbox/firewall/audit ]; then mkdir -p /tmp/gh-aw/threat-detection/sandbox/firewall/audit && cp -r /tmp/gh-aw/sandbox/firewall/audit/. /tmp/gh-aw/threat-detection/sandbox/firewall/audit/; fi - - name: Upload threat detection artifact - if: always() && steps.detection_guard.outputs.run_detection == 'true' - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: detection - path: | - /tmp/gh-aw/threat-detection/detection_result.json - /tmp/gh-aw/threat-detection/sandbox/firewall/logs/ - /tmp/gh-aw/threat-detection/sandbox/firewall/audit/ - if-no-files-found: ignore - - name: Parse threat detection token usage for step summary - id: parse_detection_token_usage - if: always() - continue-on-error: true - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_TOKEN_USAGE_SUMMARY_TITLE: Threat Detection Token Usage - with: - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'parse_token_usage.cjs')); - await main(); - - name: Conclude threat detection - id: detection_conclusion - if: always() - continue-on-error: true - env: - RUN_DETECTION: ${{ steps.detection_guard.outputs.run_detection }} - DETECTION_AGENTIC_EXECUTION_OUTCOME: ${{ steps.detection_agentic_execution.outcome }} - GH_AW_DETECTION_CONTINUE_ON_ERROR: "true" - run: | - bash "${RUNNER_TEMP}/gh-aw/actions/conclude_threat_detection.sh" /tmp/gh-aw/threat-detection/detection_result.json - - safe_outputs: - needs: - - activation - - agent - - detection - if: (!cancelled()) && needs.agent.result != 'skipped' && needs.detection.result == 'success' - runs-on: ubuntu-slim - permissions: - issues: write - pull-requests: write - timeout-minutes: 45 - env: - GH_AW_AGENT_AIC: ${{ needs.agent.outputs.aic }} - GH_AW_AIC: ${{ needs.agent.outputs.aic }} - GH_AW_AMBIENT_CONTEXT: ${{ needs.agent.outputs.ambient_context }} - GH_AW_CALLER_WORKFLOW_ID: "${{ github.repository }}/sdk-consistency-review" - GH_AW_DETECTION_CONCLUSION: ${{ needs.detection.outputs.detection_conclusion }} - GH_AW_DETECTION_REASON: ${{ needs.detection.outputs.detection_reason }} - GH_AW_EFFECTIVE_TOKENS: ${{ needs.agent.outputs.effective_tokens }} - GH_AW_ENGINE_ID: "copilot" - GH_AW_ENGINE_MODEL: "${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-5' }}" - GH_AW_HEAD_SHA: ${{ github.event.pull_request.head.sha }} - GH_AW_RUNTIME_FEATURES: ${{ vars.GH_AW_RUNTIME_FEATURES }} - GH_AW_THREAT_DETECTION_AIC: ${{ needs.detection.outputs.aic }} - GH_AW_TRACKER_ID: "sdk-consistency-review" - GH_AW_WORKFLOW_ID: "sdk-consistency-review" - GH_AW_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_WORKFLOW_SOURCE_URL: "${{ github.server_url }}/${{ github.repository }}/blob/${{ github.ref_name }}/.github/workflows/sdk-consistency-review.md" - outputs: - code_push_failure_count: ${{ steps.process_safe_outputs.outputs.code_push_failure_count }} - code_push_failure_errors: ${{ steps.process_safe_outputs.outputs.code_push_failure_errors }} - comment_id: ${{ steps.process_safe_outputs.outputs.comment_id }} - comment_url: ${{ steps.process_safe_outputs.outputs.comment_url }} - create_discussion_error_count: ${{ steps.process_safe_outputs.outputs.create_discussion_error_count }} - create_discussion_errors: ${{ steps.process_safe_outputs.outputs.create_discussion_errors }} - process_safe_outputs_items_applied: ${{ steps.process_safe_outputs.outputs.items_applied }} - process_safe_outputs_items_cancelled: ${{ steps.process_safe_outputs.outputs.items_cancelled }} - process_safe_outputs_items_deferred: ${{ steps.process_safe_outputs.outputs.items_deferred }} - process_safe_outputs_items_failed: ${{ steps.process_safe_outputs.outputs.items_failed }} - process_safe_outputs_items_skipped: ${{ steps.process_safe_outputs.outputs.items_skipped }} - process_safe_outputs_items_succeeded: ${{ steps.process_safe_outputs.outputs.items_succeeded }} - process_safe_outputs_items_warnings: ${{ steps.process_safe_outputs.outputs.items_warnings }} - process_safe_outputs_processed_count: ${{ steps.process_safe_outputs.outputs.processed_count }} - process_safe_outputs_status: ${{ steps.process_safe_outputs.outputs.status }} - process_safe_outputs_temporary_id_map: ${{ steps.process_safe_outputs.outputs.temporary_id_map }} - steps: - - name: Setup Scripts - id: setup - uses: github/gh-aw-actions/setup@9271a1804551c0dc4fb0085a97979950aa2f8489 # v0.88.2 - with: - destination: ${{ runner.temp }}/gh-aw/actions - job-name: ${{ github.job }} - trace-id: ${{ needs.activation.outputs.setup-trace-id }} - parent-span-id: ${{ needs.activation.outputs.setup-parent-span-id || needs.activation.outputs.setup-span-id }} - env: - GH_AW_SETUP_WORKFLOW_NAME: "SDK Consistency Review Agent" - GH_AW_CURRENT_WORKFLOW_REF: ${{ github.repository }}/.github/workflows/sdk-consistency-review.lock.yml@${{ github.ref }} - GH_AW_INFO_VERSION: "1.0.80" - GH_AW_INFO_AWF_VERSION: "v0.28.12" - GH_AW_INFO_ENGINE_ID: "copilot" - - name: Mask OTLP telemetry headers - run: bash "${RUNNER_TEMP}/gh-aw/actions/mask_otlp_headers.sh" - - name: Download agent output artifact - id: download-agent-output - continue-on-error: true - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 - with: - pattern: "{agent,agent-output-fallback}" - merge-multiple: true - path: /tmp/gh-aw/ - - name: Setup agent output environment variable - id: setup-agent-output-env - if: steps.download-agent-output.outcome == 'success' - run: | - mkdir -p /tmp/gh-aw/ - find "/tmp/gh-aw/" -type f -print - if [ -f "/tmp/gh-aw/agent_output.json" ]; then - echo "GH_AW_AGENT_OUTPUT=/tmp/gh-aw/agent_output.json" >> "$GITHUB_OUTPUT" - fi - - name: Configure GH_HOST for enterprise compatibility - id: ghes-host-config - shell: bash - run: | # zizmor: ignore[github-env] - GITHUB_SERVER_URL is set by GitHub Actions, not user input. - # Derive GH_HOST from GITHUB_SERVER_URL so the gh CLI targets the correct - # GitHub instance (GHES/GHEC). On github.com this is a harmless no-op. - GH_HOST="${GITHUB_SERVER_URL#https://}" - GH_HOST="${GH_HOST#http://}" - echo "GH_HOST=${GH_HOST}" >> "$GITHUB_ENV" - - name: Process Safe Outputs - id: process_safe_outputs - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - GH_AW_AGENT_OUTPUT: ${{ steps.setup-agent-output-env.outputs.GH_AW_AGENT_OUTPUT }} - GH_AW_COMMENT_ID: ${{ needs.activation.outputs.comment_id }} - GH_AW_ALLOWED_DOMAINS: "api.snapcraft.io,archive.ubuntu.com,azure.archive.ubuntu.com,crl.geotrust.com,crl.globalsign.com,crl.identrust.com,crl.sectigo.com,crl.thawte.com,crl.usertrust.com,crl.verisign.com,crl3.digicert.com,crl4.digicert.com,crls.ssl.com,json-schema.org,json.schemastore.org,keyserver.ubuntu.com,ocsp.digicert.com,ocsp.geotrust.com,ocsp.globalsign.com,ocsp.identrust.com,ocsp.sectigo.com,ocsp.ssl.com,ocsp.thawte.com,ocsp.usertrust.com,ocsp.verisign.com,packagecloud.io,packages.cloud.google.com,packages.microsoft.com,ppa.launchpad.net,s.symcb.com,s.symcd.com,security.ubuntu.com,ts-crl.ws.symantec.com,ts-ocsp.ws.symantec.com,www.googleapis.com" - GITHUB_SERVER_URL: ${{ github.server_url }} - GITHUB_API_URL: ${{ github.api_url }} - GH_AW_SAFE_OUTPUTS_HANDLER_CONFIG: "{\"add_comment\":{\"hide_older_comments\":true,\"max\":1},\"create_pull_request_review_comment\":{\"max\":10,\"side\":\"RIGHT\"},\"create_report_incomplete_issue\":{},\"missing_data\":{},\"missing_tool\":{},\"noop\":{\"max\":1,\"report-as-issue\":\"false\"},\"report_incomplete\":{}}" - with: - github-token: ${{ secrets.GH_AW_GITHUB_TOKEN || secrets.GITHUB_TOKEN }} - script: | - const path = require('path'); - const actionsDir = path.join(process.env.RUNNER_TEMP, 'gh-aw', 'actions'); - const { setupGlobals } = require(path.join(actionsDir, 'setup_globals.cjs')); - setupGlobals(core, github, context, exec, io, getOctokit); - const { main } = require(path.join(actionsDir, 'process_safe_outputs.cjs')); - await main(); - - name: Upload Safe Outputs Items - if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 - with: - name: safe-outputs-items - path: | - /tmp/gh-aw/safe-output-items.jsonl - /tmp/gh-aw/temporary-id-map.json - /tmp/gh-aw/safe-output-errors.json - if-no-files-found: ignore diff --git a/.github/workflows/sdk-consistency-review.md b/.github/workflows/sdk-consistency-review.md deleted file mode 100644 index 8346bcdd63..0000000000 --- a/.github/workflows/sdk-consistency-review.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -description: Reviews PRs to ensure features are implemented consistently across all SDK language implementations -tracker-id: sdk-consistency-review -model: ${{ vars.GH_AW_MODEL_AGENT_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-5' }} -on: - roles: all - pull_request: - types: [opened, synchronize, reopened, ready_for_review] - paths: - - "nodejs/**" - - "python/**" - - "go/**" - - "dotnet/**" - - "java/**" - - "rust/**" - - "!java/docs/**" - - "!java/*.txt" - - "!java/*.md" - workflow_dispatch: - inputs: - pr_number: - description: "PR number to review" - required: true - type: string -permissions: - contents: read - pull-requests: read - issues: read - copilot-requests: write -tools: - github: - toolsets: [default] -safe-outputs: - create-pull-request-review-comment: - max: 10 - add-comment: - max: 1 - hide-older-comments: true - allowed-reasons: [outdated] - threat-detection: - engine: - id: copilot - model: ${{ vars.GH_AW_MODEL_DETECTION_COPILOT || vars.GH_AW_DEFAULT_MODEL_COPILOT || 'claude-sonnet-5' }} -timeout-minutes: 15 ---- - - - -# SDK Consistency Review Agent - -You are an AI code reviewer specialized in ensuring consistency across multi-language SDK implementations. This repository contains six SDK implementations (Node.js/TypeScript, Python, Go, .NET, Java, and Rust) that should maintain feature parity and consistent API design. - -## Your Task - -When a pull request modifies any SDK client code, review it to ensure: - -1. **Cross-language consistency**: If a feature is added/modified in one SDK, check whether: - - The same feature exists in other SDK implementations - - The feature is implemented consistently across all languages - - API naming and structure are parallel (accounting for language conventions) - -2. **Feature parity**: Identify if this PR creates inconsistencies by: - - Adding a feature to only one language - - Changing behavior in one SDK that differs from others - - Introducing language-specific functionality that should be available everywhere - -3. **API design consistency**: Check that: - - Method/function names follow the same semantic pattern (e.g., `createSession` vs `create_session` vs `CreateSession`) - - Parameter names and types are equivalent - - Return types are analogous - - Error handling patterns are similar - -## Context - -- Repository: ${{ github.repository }} -- PR number: ${{ github.event.pull_request.number || inputs.pr_number }} -- Modified files: Use GitHub tools to fetch the list of changed files - -## SDK Locations - -Determine the SDK root from the repository tree: use `src/sdk` when the language implementations are nested there (the runtime repository), otherwise use the repository root (the standalone SDK repository). All paths below are relative to that SDK root. Use repository-relative paths, including `src/sdk/` when applicable, when reading files or posting review comments. - -- **Node.js/TypeScript**: `nodejs/src/` -- **Python**: `python/copilot/` -- **Go**: `go/` -- **.NET**: `dotnet/src/` -- **Java**: `java/sdk/src/main/java/` -- **Rust**: `rust/src/` - -In the runtime repository, review SDK changes under `src/sdk/`; use other runtime code only as context, not as a separate SDK implementation. - -## Review Process - -1. **Get the authoritative PR delta**: - - Call `pull_request_read` with `method: get_files` for the PR, paginating until all changed files are retrieved - - Call `pull_request_read` with `method: get_diff` for the PR - - Treat these GitHub API responses as the only authoritative source of which changes belong to the PR, including when the PR head is a merge commit - - Base every claim about what the PR adds or modifies on the API diff; use the local checkout only for surrounding context and cross-SDK comparison - - Never infer the PR base from `HEAD^`, merge-parent ordering, recent commits, or local branch refs - - If the API file list or diff cannot be retrieved, call `missing_data` and stop; do not substitute an inferred local `git diff` range -2. **Identify the changed SDK(s)**: Determine which language implementation(s) are modified in the authoritative PR delta -3. **Analyze the changes**: Understand what feature/fix is being implemented from the authoritative PR delta -4. **Cross-reference other SDKs**: Check if the equivalent functionality exists in other language implementations: - - Read the corresponding files in other SDK directories - - Compare method signatures, behavior, and documentation -5. **Report findings**: If inconsistencies are found: - - Use `create-pull-request-review-comment` to add inline comments on specific lines where changes should be made - - Use `add-comment` to provide a summary of cross-SDK consistency findings - - Be specific about which SDKs need updates and what changes would bring them into alignment - -## Guidelines - -1. **Be respectful**: This is a technical review focusing on consistency, not code quality judgments -2. **Account for language idioms**: - - TypeScript uses camelCase (e.g., `createSession`) - - Python uses snake_case (e.g., `create_session`) - - Go uses PascalCase for exported/public functions (e.g., `CreateSession`) and camelCase for unexported/private functions - - .NET uses PascalCase (e.g., `CreateSession`) - - Java uses camelCase for methods (e.g., `createSession`) and PascalCase for classes - - Rust uses snake_case for functions and methods (e.g., `create_session`) and PascalCase for types - - Focus on public API methods when comparing across languages -3. **Focus on API surface**: Prioritize public APIs over internal implementation details -4. **Distinguish between bugs and features**: - - Bug fixes in one SDK might reveal bugs in others - - New features should be considered for all SDKs -5. **Suggest, don't demand**: Frame feedback as suggestions for maintaining consistency -6. **Skip trivial changes**: Don't flag minor differences like comment styles or variable naming -7. **Only comment if there are actual consistency issues**: If the PR maintains consistency or only touches one SDK's internal implementation, acknowledge it positively in a summary comment - -## Example Scenarios - -### Good: Consistent feature addition - -If a PR adds a new `setTimeout` option to the Node.js SDK and the equivalent feature already exists or is added to Python, Go, .NET, Java, and Rust in the same PR. - -### Bad: Inconsistent feature - -If a PR adds a `withRetry` method to only the Python SDK, but this functionality doesn't exist in other SDKs and would be useful everywhere. - -### Good: Language-specific optimization - -If a PR optimizes JSON parsing in Go using native libraries specific to Go's ecosystem—this doesn't need to be mirrored exactly in other languages. - -## Output Format - -- **If consistency issues found**: Add specific review comments pointing to the gaps and suggest which other SDKs need similar changes -- **If no issues found**: Add a brief summary comment confirming the changes maintain cross-SDK consistency diff --git a/.github/workflows/sdk-runtime-artifact.yml b/.github/workflows/sdk-runtime-artifact.yml index b67646bf19..d49e3be680 100644 --- a/.github/workflows/sdk-runtime-artifact.yml +++ b/.github/workflows/sdk-runtime-artifact.yml @@ -82,6 +82,7 @@ jobs: dist-pkg-tarballs/ src/core/sharedApi/runtime-generated/index.d.ts src/native/runtime/runtime.*.node + src/native/runtime/runtime.*.node.metadata src/native/runtime/copilot-runtime.* src/native/runtime/index.d.ts src/native/cli/cli-native.*.node @@ -151,6 +152,7 @@ jobs: dist-pkg-tarballs/ src/core/sharedApi/runtime-generated/index.d.ts src/native/runtime/runtime.*.node + src/native/runtime/runtime.*.node.metadata src/native/runtime/copilot-runtime.* src/native/runtime/index.d.ts src/native/cli/cli-native.*.node diff --git a/.github/workflows/sdk.yml b/.github/workflows/sdk.yml index bb96fb22fd..94e5ae17bb 100644 --- a/.github/workflows/sdk.yml +++ b/.github/workflows/sdk.yml @@ -77,6 +77,7 @@ jobs: path: | windows-x64-addons-receipt.txt src/native/runtime/runtime.win32-x64-msvc.node + src/native/runtime/runtime.win32-x64-msvc.node.metadata src/native/runtime/copilot-runtime.win32-x64-msvc.exe src/native/runtime/index.d.ts src/native/cli/cli-native.win32-x64-msvc.node @@ -124,6 +125,7 @@ jobs: - name: Verify Windows x64 addons if: steps.cache.outputs.cache-hit != 'true' run: | + test -s src/native/runtime/runtime.win32-x64-msvc.node.metadata for artifact in \ src/native/runtime/runtime.win32-x64-msvc.node \ src/native/runtime/copilot-runtime.win32-x64-msvc.exe \ @@ -143,6 +145,7 @@ jobs: path: | windows-x64-addons-receipt.txt src/native/runtime/runtime.win32-x64-msvc.node + src/native/runtime/runtime.win32-x64-msvc.node.metadata src/native/runtime/copilot-runtime.win32-x64-msvc.exe src/native/runtime/index.d.ts src/native/cli/cli-native.win32-x64-msvc.node @@ -154,6 +157,7 @@ jobs: name: sdk-bazel-cross-addons-win32-x64-release path: | src/native/runtime/runtime.win32-x64-msvc.node + src/native/runtime/runtime.win32-x64-msvc.node.metadata src/native/runtime/copilot-runtime.win32-x64-msvc.exe src/native/runtime/index.d.ts src/native/cli/cli-native.win32-x64-msvc.node diff --git a/docs/developer-docs/secrets.md b/docs/developer-docs/secrets.md index 416a7b6bfb..ff7bd7d79c 100644 --- a/docs/developer-docs/secrets.md +++ b/docs/developer-docs/secrets.md @@ -17,13 +17,13 @@ These secrets are used by the authoritative SDK build/test workflow and the publ These secrets power the GitHub Agentic Workflows (gh-aw) used for issue triage, code generation, and release automation. * **`COPILOT_GITHUB_TOKEN`**: GitHub OAuth token consumed by the Copilot CLI for AI authentication. Required by all agentic workflows when invoking `copilot` for AI inference. - * Workflows: `issue-triage.lock.yml`, `issue-classification.lock.yml`, `handle-bug.lock.yml`, `handle-enhancement.lock.yml`, `handle-question.lock.yml`, `handle-documentation.lock.yml`, `java-codegen-check.yml`, `java-codegen-fix.lock.yml`, `java-smoke-test.yml`, `java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml`, `release-changelog.lock.yml`, `sdk-consistency-review.lock.yml`, `cross-repo-issue-analysis.lock.yml` + * Workflows: `issue-triage.lock.yml`, `issue-classification.lock.yml`, `handle-bug.lock.yml`, `handle-enhancement.lock.yml`, `handle-question.lock.yml`, `handle-documentation.lock.yml`, `java-codegen-check.yml`, `java-codegen-fix.lock.yml`, `java-smoke-test.yml`, `java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml`, `release-changelog.lock.yml`, `cross-repo-issue-analysis.lock.yml` * **`GH_AW_GITHUB_TOKEN`**: Optional GitHub token override for repository operations (reading code, creating pull requests, and making GitHub API calls). If unset, workflows use the automatic `GITHUB_TOKEN`. - * Workflows: `issue-triage.lock.yml`, `issue-classification.lock.yml`, `handle-bug.lock.yml`, `handle-enhancement.lock.yml`, `handle-question.lock.yml`, `handle-documentation.lock.yml`, `java-codegen-fix.lock.yml`, `java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml`, `release-changelog.lock.yml`, `sdk-consistency-review.lock.yml`, `cross-repo-issue-analysis.lock.yml` + * Workflows: `issue-triage.lock.yml`, `issue-classification.lock.yml`, `handle-bug.lock.yml`, `handle-enhancement.lock.yml`, `handle-question.lock.yml`, `handle-documentation.lock.yml`, `java-codegen-fix.lock.yml`, `java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml`, `release-changelog.lock.yml`, `cross-repo-issue-analysis.lock.yml` * **`GH_AW_GITHUB_MCP_SERVER_TOKEN`**: Optional token override for the GitHub MCP server container. If unset, workflows fall back to `GH_AW_GITHUB_TOKEN` and then the automatic `GITHUB_TOKEN`. - * Workflows: `issue-triage.lock.yml`, `issue-classification.lock.yml`, `handle-bug.lock.yml`, `handle-enhancement.lock.yml`, `handle-question.lock.yml`, `handle-documentation.lock.yml`, `java-codegen-fix.lock.yml`, `java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml`, `release-changelog.lock.yml`, `sdk-consistency-review.lock.yml`, `cross-repo-issue-analysis.lock.yml` + * Workflows: `issue-triage.lock.yml`, `issue-classification.lock.yml`, `handle-bug.lock.yml`, `handle-enhancement.lock.yml`, `handle-question.lock.yml`, `handle-documentation.lock.yml`, `java-codegen-fix.lock.yml`, `java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml`, `release-changelog.lock.yml`, `cross-repo-issue-analysis.lock.yml` * **`GH_AW_CI_TRIGGER_TOKEN`**: Token used to trigger CI workflows from within agentic workflow runs. * Workflows: `java-codegen-fix.lock.yml`, `java-adapt-handwritten-code-to-accept-upgrade-changes.lock.yml`, `release-changelog.lock.yml` diff --git a/dotnet/src/Generated/Rpc.cs b/dotnet/src/Generated/Rpc.cs index f4b993c288..751de8706a 100644 --- a/dotnet/src/Generated/Rpc.cs +++ b/dotnet/src/Generated/Rpc.cs @@ -6999,95 +6999,15 @@ internal sealed class SessionGitHubAuthLastAuthErrorsRequest public string SessionId { get; set; } = string.Empty; } -/// A file included in the session debug bundle. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class DebugCollectLogsCollectedEntry -{ - /// Relative path of the file in the staged bundle/archive. - [JsonPropertyName("bundlePath")] - public string BundlePath { get; set; } = string.Empty; - - /// Redacted output size in bytes. - [JsonPropertyName("sizeBytes")] - public long SizeBytes { get; set; } - - /// Source category for this entry. - [JsonPropertyName("source")] - public DebugCollectLogsSource Source { get; set; } -} - -/// An optional debug bundle entry that could not be included. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class DebugCollectLogsSkippedEntry -{ - /// Relative path requested for this bundle entry. - [JsonPropertyName("bundlePath")] - public string BundlePath { get; set; } = string.Empty; - - /// Server-local source path that could not be read. - [JsonPropertyName("path")] - public string? Path { get; set; } - - /// Reason the entry was skipped. - [JsonPropertyName("reason")] - public string Reason { get; set; } = string.Empty; -} - -/// Result of collecting a session debug bundle. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class DebugCollectLogsResult -{ - /// Files included in the bundle. - [JsonPropertyName("entries")] - public IList Entries { get => field ??= []; set; } - - /// Destination kind that was written. - [JsonPropertyName("kind")] - public DebugCollectLogsResultKind Kind { get; set; } - - /// Actual archive path or staging directory path written. This may differ from the requested path when no-overwrite suffixing or fallback-to-temp-directory was needed. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; - - /// Optional files or directories that could not be included. - [JsonPropertyName("skippedEntries")] - public IList? SkippedEntries { get; set; } -} - -/// A caller-provided server-local file or directory to include in the debug bundle. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class DebugCollectLogsEntry -{ - /// Relative path to use inside the staged bundle/archive. - [JsonPropertyName("bundlePath")] - public string BundlePath { get; set; } = string.Empty; - - /// Kind of source path to include. - [JsonPropertyName("kind")] - public DebugCollectLogsEntryKind Kind { get; set; } - - /// Server-local source path to read. - [JsonPropertyName("path")] - public string Path { get; set; } = string.Empty; - - /// How text content from this entry should be redacted. Defaults to plain-text. With none, no redaction is applied; the caller must ensure any necessary redaction is performed before this call. - [JsonPropertyName("redaction")] - public DebugCollectLogsRedaction? Redaction { get; set; } - - /// When true, collection fails if this entry cannot be read. Defaults to false, which records the entry in `skippedEntries`. - [JsonPropertyName("required")] - public bool? Required { get; set; } -} - -/// Destination for the session debug bundle. +/// The enumerated collection, keyed by the same selector as the query. /// Polymorphic base type discriminated by kind. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] [JsonPolymorphic( TypeDiscriminatorPropertyName = "kind", UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(DebugCollectLogsDestinationArchive), "archive")] -[JsonDerivedType(typeof(DebugCollectLogsDestinationDirectory), "directory")] -public partial class DebugCollectLogsDestination +[JsonDerivedType(typeof(AuthEnumerateValueAccounts), "accounts")] +[JsonDerivedType(typeof(AuthEnumerateValueProviders), "providers")] +public partial class AuthEnumerateValue { /// The type discriminator. [JsonPropertyName("kind")] @@ -7095,1418 +7015,941 @@ public partial class DebugCollectLogsDestination } -/// The archive variant of . -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public partial class DebugCollectLogsDestinationArchive : DebugCollectLogsDestination -{ - /// - [JsonIgnore] - public override string Kind => "archive"; - - /// When true, create the archive atomically without overwriting an existing file by appending ` (N)` before the extension as needed. Defaults to false. - [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("noOverwrite")] - public bool? NoOverwrite { get; set; } - - /// Absolute or server-relative path for the .tgz archive to create. - [JsonPropertyName("outputPath")] - public required string OutputPath { get; set; } -} - -/// The directory variant of . +/// One signed-in account in the roster forest. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public partial class DebugCollectLogsDestinationDirectory : DebugCollectLogsDestination +public sealed class AccountStatus { - /// - [JsonIgnore] - public override string Kind => "directory"; + /// Whether this is the active account. + [JsonPropertyName("active")] + public bool Active { get; set; } - /// Directory where files should be staged. The directory is created if needed. - [JsonPropertyName("outputDirectory")] - public required string OutputDirectory { get; set; } -} + /// Opaque id of the account this one was derived from (e.g. an EMU account's base Entra identity); absent for a root account. Matches the base identity account's selectionId, forming the derivation edge. + [JsonPropertyName("derivedFrom")] + public string? DerivedFrom { get; set; } -/// Built-in session diagnostics to include in the bundle. Omitted fields default to true. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class DebugCollectLogsInclude -{ - /// Server-local path to the current process log. When set, it is included as `process.log` and its directory is searched for prior logs from the same session. - [JsonPropertyName("currentProcessLogPath")] - public string? CurrentProcessLogPath { get; set; } - - /// Include the session event log (`events.jsonl`). Defaults to true. - [JsonPropertyName("events")] - public bool? Events { get; set; } - - /// Server-local path to the session's events.jsonl file. Internal callers normally omit this and let the runtime derive it from the session. - [JsonPropertyName("eventsPath")] - public string? EventsPath { get; set; } - - /// Maximum number of previous process logs to include. Defaults to 5. - [JsonPropertyName("previousProcessLogLimit")] - public long? PreviousProcessLogLimit { get; set; } - - /// Server-local process log directory to search when `currentProcessLogPath` is unavailable, useful for collecting logs for inactive sessions. - [JsonPropertyName("processLogDirectory")] - public string? ProcessLogDirectory { get; set; } - - /// Include process logs for the session. Defaults to true. - [JsonPropertyName("processLogs")] - public bool? ProcessLogs { get; set; } - - /// Include interactive shell logs written under the session's `shell-logs` directory. Defaults to true. - [JsonPropertyName("shellLogs")] - public bool? ShellLogs { get; set; } -} - -/// Options for collecting a session debug bundle with configurable redaction. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class DebugCollectLogsRequest -{ - /// Caller-provided server-local files or directories to include in addition to the runtime's built-in session diagnostics. This lets host applications add their own diagnostics without changing the API shape. - [JsonPropertyName("additionalEntries")] - public IList? AdditionalEntries { get; set; } - - /// Where the bundle should be written. Use `archive` to produce a .tgz, or `directory` to stage files for caller-managed upload/post-processing. - [JsonPropertyName("destination")] - public DebugCollectLogsDestination Destination { get => field ??= new(); set; } - - /// Which built-in session diagnostics to include. Omitted fields default to true. - [JsonPropertyName("include")] - public DebugCollectLogsInclude? Include { get; set; } - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} - -/// Canvas action that the agent or host can invoke. To discover the input schema for a particular action, call the list_canvas_capabilities tool. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class CanvasAction -{ - /// Description of the action. - [JsonPropertyName("description")] - public string? Description { get; set; } - - /// JSON Schema for the action input. - [JsonPropertyName("inputSchema")] - public JsonElement? InputSchema { get; set; } - - /// Action name exposed by the canvas provider. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; -} - -/// Canvas available in the current session. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class DiscoveredCanvas -{ - /// Actions the agent or host may invoke on an open instance. - [JsonPropertyName("actions")] - public IList? Actions { get; set; } - - /// Provider-local canvas identifier. - [JsonPropertyName("canvasId")] - public string CanvasId { get; set; } = string.Empty; - - /// Short, single-sentence description shown to the agent in canvas catalogs. - [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] - [MinLength(1)] - [JsonPropertyName("description")] - public string Description { get; set; } = string.Empty; - - /// Human-readable canvas name. - [JsonPropertyName("displayName")] - public string DisplayName { get; set; } = string.Empty; - - /// Owning provider identifier. - [JsonPropertyName("extensionId")] - public string ExtensionId { get; set; } = string.Empty; + /// Authentication host URL. + [Url] + [StringSyntax(StringSyntaxAttribute.Uri)] + [JsonPropertyName("host")] + public string Host { get; set; } = string.Empty; - /// Owning extension display name, when available. - [JsonPropertyName("extensionName")] - public string? ExtensionName { get; set; } + /// The provider kind of this account. + [JsonPropertyName("kind")] + public AccountKind Kind { get; set; } - /// Host-local PNG path for the canvas icon, when supplied. - [JsonPropertyName("icon")] - public string? Icon { get; set; } + /// Authenticated login/username. + [JsonPropertyName("login")] + public string Login { get; set; } = string.Empty; - /// JSON Schema for canvas open input. - [JsonPropertyName("inputSchema")] - public JsonElement? InputSchema { get; set; } + /// Opaque selection id used to switch to, or log out, this account. + [JsonPropertyName("selectionId")] + public string SelectionId { get; set; } = string.Empty; } -/// Declared canvases available in this session. +/// The accounts variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class CanvasList +public partial class AuthEnumerateValueAccounts : AuthEnumerateValue { - /// Declared canvases available in this session. - [JsonPropertyName("canvases")] - public IList Canvases { get => field ??= []; set; } -} + /// + [JsonIgnore] + public override string Kind => "accounts"; -/// Identifies the target session. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class SessionCanvasListRequest -{ - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// The signed-in account forest; empty when not logged in. + [JsonPropertyName("items")] + public required IList Items { get; set; } } -/// Open canvas instance snapshot. +/// A provider offered for interactive login. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class OpenCanvasInstance +public sealed class ProviderDescriptor { - /// Provider-local canvas identifier. - [JsonPropertyName("canvasId")] - public string CanvasId { get; set; } = string.Empty; - - /// Owning provider identifier. - [JsonPropertyName("extensionId")] - public string ExtensionId { get; set; } = string.Empty; - - /// Owning extension display name, when available. - [JsonPropertyName("extensionName")] - public string? ExtensionName { get; set; } - - /// Host-local PNG path for the canvas icon, when supplied. - [JsonPropertyName("icon")] - public string? Icon { get; set; } - - /// Input supplied when the instance was opened. - [JsonPropertyName("input")] - public JsonElement? Input { get; set; } - - /// Stable caller-supplied canvas instance identifier. - [JsonPropertyName("instanceId")] - public string InstanceId { get; set; } = string.Empty; - - /// Provider-supplied status text. - [JsonPropertyName("status")] - public string? Status { get; set; } - - /// Rendered title. - [JsonPropertyName("title")] - public string? Title { get; set; } - - /// URL for web-rendered canvases. - [JsonPropertyName("url")] - public string? Url { get; set; } -} + /// Whether this provider is currently available to sign in with. + [JsonPropertyName("available")] + public bool Available { get; set; } -/// Live open-canvas snapshot. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class CanvasListOpenResult -{ - /// Currently open canvas instances. - [JsonPropertyName("openCanvases")] - public IList OpenCanvases { get => field ??= []; set; } -} + /// The neutral provider kind. + [JsonPropertyName("kind")] + public LoginProviderKind Kind { get; set; } -/// Identifies the target session. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class SessionCanvasListOpenRequest -{ - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Human-readable menu label, owned by the runtime so every consumer renders identical text. + [JsonPropertyName("label")] + public string Label { get; set; } = string.Empty; } -/// Canvas open parameters. +/// The providers variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class CanvasOpenRequest +public partial class AuthEnumerateValueProviders : AuthEnumerateValue { - /// Provider-local canvas identifier. - [JsonPropertyName("canvasId")] - public string CanvasId { get; set; } = string.Empty; - - /// Owning provider identifier. Optional when the canvasId is unique across providers; required to disambiguate when multiple providers register the same canvasId. - [JsonPropertyName("extensionId")] - public string? ExtensionId { get; set; } - - /// Canvas open input. - [JsonPropertyName("input")] - public JsonElement? Input { get; set; } - - /// Caller-supplied stable instance identifier. - [JsonPropertyName("instanceId")] - public string InstanceId { get; set; } = string.Empty; + /// + [JsonIgnore] + public override string Kind => "providers"; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// The providers offered for interactive login. + [JsonPropertyName("items")] + public required IList Items { get; set; } } -/// Canvas close parameters. +/// Selects which accounts collection to enumerate. A no-arg selector is the empty-payload variant. +/// Polymorphic base type discriminated by kind. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class CanvasCloseRequest +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(AuthEnumerateQueryAccounts), "accounts")] +[JsonDerivedType(typeof(AuthEnumerateQueryProviders), "providers")] +public partial class AuthEnumerateQuery { - /// Open canvas instance identifier. - [JsonPropertyName("instanceId")] - public string InstanceId { get; set; } = string.Empty; - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; } -/// Canvas action invocation result. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class CanvasActionInvokeResult -{ - /// Provider-supplied action result. - [JsonPropertyName("result")] - public JsonElement? Result { get; set; } -} -/// Canvas action invocation parameters. +/// The accounts variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class CanvasActionInvokeRequest +public partial class AuthEnumerateQueryAccounts : AuthEnumerateQuery { - /// Action name to invoke. - [JsonPropertyName("actionName")] - public string ActionName { get; set; } = string.Empty; - - /// Action input. - [JsonPropertyName("input")] - public JsonElement? Input { get; set; } - - /// Open canvas instance identifier. - [JsonPropertyName("instanceId")] - public string InstanceId { get; set; } = string.Empty; - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// + [JsonIgnore] + public override string Kind => "accounts"; } -/// Internal canvas provider registration parameters. +/// The providers variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class CanvasProviderRegisterRequest +public partial class AuthEnumerateQueryProviders : AuthEnumerateQuery { - /// Canvas contributions supplied by the provider. - [JsonPropertyName("canvases")] - public IList Canvases { get => field ??= []; set; } - - /// Connection identifier for callback routing. - [JsonPropertyName("connectionId")] - public string ConnectionId { get; set; } = string.Empty; - - /// Provider metadata supplied by the host. - [JsonPropertyName("info")] - public JsonElement Info { get; set; } + /// + [JsonIgnore] + public override string Kind => "providers"; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Whether an interactive Entra broker is available on the host; gates Entra availability in the returned list. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("brokerAvailable")] + public bool? BrokerAvailable { get; set; } } -/// Internal canvas provider unregistration parameters. +/// Enumerate request carrying the typed collection query. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class CanvasProviderUnregisterRequest +internal sealed class AccountsEnumerateRequest { - /// Connection identifier to unregister. - [JsonPropertyName("connectionId")] - public string ConnectionId { get; set; } = string.Empty; + /// Which typed accounts collection to enumerate. + [JsonPropertyName("query")] + public AuthEnumerateQuery Query { get => field ??= new(); set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Machine-readable factory run failure. -/// Polymorphic base type discriminated by type. +/// The read result, keyed by the same selector as the query. +/// Polymorphic base type discriminated by kind. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] [JsonPolymorphic( - TypeDiscriminatorPropertyName = "type", + TypeDiscriminatorPropertyName = "kind", UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(FactoryRunFailureFactoryLimitReached), "factory_limit_reached")] -[JsonDerivedType(typeof(FactoryRunFailureFactoryResumeDeclined), "factory_resume_declined")] -[JsonDerivedType(typeof(FactoryRunFailureFactoryDurableFailure), "factory_durable_failure")] -[JsonDerivedType(typeof(FactoryRunFailureFactoryAccountingIncomplete), "factory_accounting_incomplete")] -[JsonDerivedType(typeof(FactoryRunFailureFactoryProviderDisconnected), "factory_provider_disconnected")] -public partial class FactoryRunFailure +[JsonDerivedType(typeof(AuthReadValueActiveAccount), "activeAccount")] +[JsonDerivedType(typeof(AuthReadValueStatus), "status")] +[JsonDerivedType(typeof(AuthReadValueLastErrors), "lastErrors")] +public partial class AuthReadValue { /// The type discriminator. - [JsonPropertyName("type")] - public virtual string Type { get; set; } = string.Empty; + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; } -/// The factory_limit_reached variant of . +/// The activeAccount variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public partial class FactoryRunFailureFactoryLimitReached : FactoryRunFailure +public partial class AuthReadValueActiveAccount : AuthReadValue { /// [JsonIgnore] - public override string Type => "factory_limit_reached"; - - /// Resource ceiling that stopped the run. - [JsonPropertyName("kind")] - public required FactoryRunFailureKind Kind { get; set; } - - /// Factory run identifier. - [JsonPropertyName("runId")] - public required string RunId { get; set; } + public override string Kind => "activeAccount"; - /// Suggested larger ceiling when the runtime can derive one safely. + /// The active account, or absent when not logged in. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - [JsonPropertyName("suggestedValue")] - public double? SuggestedValue { get; set; } - - /// Approved effective ceiling that was reached. - [JsonPropertyName("value")] - public required double Value { get; set; } + [JsonPropertyName("account")] + public AccountStatus? Account { get; set; } } -/// The factory_resume_declined variant of . +/// Neutral authentication status summary. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public partial class FactoryRunFailureFactoryResumeDeclined : FactoryRunFailure +public sealed class AuthStatusDto { - /// - [JsonIgnore] - public override string Type => "factory_resume_declined"; + /// Number of signed-in accounts in the roster. + [JsonPropertyName("accountCount")] + public long AccountCount { get; set; } - /// Human-readable reason the resume did not proceed. - [JsonPropertyName("reason")] - public required string Reason { get; set; } - - /// Factory run identifier whose changed limits were declined. - [JsonPropertyName("runId")] - public required string RunId { get; set; } -} - -/// The factory_durable_failure variant of . -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public partial class FactoryRunFailureFactoryDurableFailure : FactoryRunFailure -{ - /// - [JsonIgnore] - public override string Type => "factory_durable_failure"; + /// Active account host, if authenticated. + [Url] + [StringSyntax(StringSyntaxAttribute.Uri)] + [JsonPropertyName("activeHost")] + public string? ActiveHost { get; set; } - /// Stable failure code. - [JsonPropertyName("code")] - public required string Code { get; set; } + /// Active account login, if authenticated. + [JsonPropertyName("activeLogin")] + public string? ActiveLogin { get; set; } - /// Execution-critical durable operation that failed. - [JsonPropertyName("operation")] - public required FactoryDurableOperation Operation { get; set; } + /// Copilot plan tier of the active account, if known. + [JsonPropertyName("copilotPlan")] + public string? CopilotPlan { get; set; } - /// Factory run identifier. - [JsonPropertyName("runId")] - public required string RunId { get; set; } + /// Whether the session has resolved authentication. + [JsonPropertyName("isAuthenticated")] + public bool IsAuthenticated { get; set; } } -/// The run stopped because its usage accounting could not be completed. -/// The factory_accounting_incomplete variant of . +/// The status variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public partial class FactoryRunFailureFactoryAccountingIncomplete : FactoryRunFailure +public partial class AuthReadValueStatus : AuthReadValue { /// [JsonIgnore] - public override string Type => "factory_accounting_incomplete"; - - /// Confirmed usage in nano-AIU, representing the floor of what the run spent. - [JsonPropertyName("drainedNanoAiu")] - public required long DrainedNanoAiu { get; set; } + public override string Kind => "status"; - /// Factory run identifier. - [JsonPropertyName("runId")] - public required string RunId { get; set; } + /// The neutral authentication status summary. + [JsonPropertyName("status")] + public required AuthStatusDto Status { get; set; } } -/// The extension that owns the factory disconnected while the run was executing, so the host halted it. The run's journaled subagent results are preserved so a resume can reuse them. -/// The factory_provider_disconnected variant of . +/// The lastErrors variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public partial class FactoryRunFailureFactoryProviderDisconnected : FactoryRunFailure +public partial class AuthReadValueLastErrors : AuthReadValue { /// [JsonIgnore] - public override string Type => "factory_provider_disconnected"; + public override string Kind => "lastErrors"; - /// Factory run identifier. - [JsonPropertyName("runId")] - public required string RunId { get; set; } + /// Validation errors from the most recent authentication attempt. + [JsonPropertyName("errors")] + public required IList Errors { get; set; } } -/// Durable metadata describing who initiated a factory pause. -/// Polymorphic base type discriminated by type. +/// Selects which typed accounts datum to read. +/// Polymorphic base type discriminated by kind. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] [JsonPolymorphic( - TypeDiscriminatorPropertyName = "type", + TypeDiscriminatorPropertyName = "kind", UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(FactoryPauseInfoUser), "user")] -[JsonDerivedType(typeof(FactoryPauseInfoCheckpoint), "checkpoint")] -public partial class FactoryPauseInfo +[JsonDerivedType(typeof(AuthReadQueryActiveAccount), "activeAccount")] +[JsonDerivedType(typeof(AuthReadQueryStatus), "status")] +[JsonDerivedType(typeof(AuthReadQueryLastErrors), "lastErrors")] +public partial class AuthReadQuery { /// The type discriminator. - [JsonPropertyName("type")] - public virtual string Type { get; set; } = string.Empty; + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; } -/// The user variant of . +/// The activeAccount variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public partial class FactoryPauseInfoUser : FactoryPauseInfo +public partial class AuthReadQueryActiveAccount : AuthReadQuery { /// [JsonIgnore] - public override string Type => "user"; + public override string Kind => "activeAccount"; } -/// The checkpoint variant of . +/// The status variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public partial class FactoryPauseInfoCheckpoint : FactoryPauseInfo +public partial class AuthReadQueryStatus : AuthReadQuery { /// [JsonIgnore] - public override string Type => "checkpoint"; - - /// Stable author-defined checkpoint key that initiated the pause. - [JsonPropertyName("key")] - public required string Key { get; set; } -} - -/// Complete current or terminal factory run envelope. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryRunResult -{ - /// One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. - [JsonPropertyName("attempt")] - public long? Attempt { get; set; } - - /// Error message for an errored run. - [JsonPropertyName("error")] - public string? Error { get; set; } - - /// Machine-readable failure details for a halted or errored run. - [JsonPropertyName("failure")] - public FactoryRunFailure? Failure { get; set; } - - /// Structured pause initiator metadata for a paused attempt. - [JsonPropertyName("pauseInfo")] - public FactoryPauseInfo? PauseInfo { get; set; } - - /// Reason for a halted or cancelled run. - [JsonPropertyName("reason")] - public string? Reason { get; set; } - - /// Completed factory result. - [JsonPropertyName("result")] - public JsonElement? Result { get; set; } - - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; - - /// Partial journal and progress snapshot for a halted, cancelled, or errored run. - [JsonPropertyName("snapshot")] - public JsonElement? Snapshot { get; set; } - - /// Current or terminal factory run status. - [JsonPropertyName("status")] - public FactoryRunStatus Status { get; set; } -} - -/// Wire-only per-invocation factory resource ceiling overrides. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryRunLimits -{ - /// Maximum AI credits consumed by factory subagents and their descendants. The post-paid ceiling is soft: parallel turns can settle beyond it before the run stops. - [JsonPropertyName("maxAiCredits")] - public double? MaxAiCredits { get; set; } - - /// Maximum number of factory subagents that may run concurrently. - [JsonPropertyName("maxConcurrentSubagents")] - public long? MaxConcurrentSubagents { get; set; } - - /// Maximum total number of factory subagents that may be admitted. - [JsonPropertyName("maxTotalSubagents")] - public long? MaxTotalSubagents { get; set; } - - /// Maximum accumulated active-execution time in seconds. Active execution includes the entire extension body, subprocess waits, queued-agent waits, and sleeps; time between resumed attempts is not counted. - [JsonPropertyName("timeoutSeconds")] - public double? TimeoutSeconds { get; set; } + public override string Kind => "status"; } -/// Options controlling factory invocation. +/// The lastErrors variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class RunOptions +public partial class AuthReadQueryLastErrors : AuthReadQuery { - /// Per-invocation resource ceiling overrides. - [JsonPropertyName("limits")] - public FactoryRunLimits? Limits { get; set; } - - /// Whether to emit factory phase names to the session transcript. - [JsonPropertyName("logPhaseNames")] - public bool? LogPhaseNames { get; set; } - - /// Whether to notify the originating session when the factory completes. - [JsonPropertyName("notifyOnComplete")] - public bool? NotifyOnComplete { get; set; } - - /// Run identifier whose journal and progress should seed this resumed run. - [JsonPropertyName("resumeFromRunId")] - public string? ResumeFromRunId { get; set; } + /// + [JsonIgnore] + public override string Kind => "lastErrors"; } -/// Parameters for invoking a registered factory. +/// Read request carrying the typed datum query. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryRunRequest +internal sealed class AccountsGetRequest { - /// Factory input value. - [JsonPropertyName("args")] - public JsonElement Args { get; set; } - - /// Registered factory name. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; - - /// Factory invocation options. - [JsonPropertyName("options")] - public RunOptions? Options { get; set; } + /// Which typed accounts datum to read. + [JsonPropertyName("query")] + public AuthReadQuery Query { get => field ??= new(); set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Resolved persisted factory identity and resumed run envelope. +/// Result of a non-interactive accounts mutation. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryResumeResult +public sealed class AuthWriteResult { - /// Persisted factory name resolved for the resumed run. - [JsonPropertyName("factoryName")] - public string FactoryName { get; set; } = string.Empty; + /// For a logout, whether other signed-in accounts remain. + [JsonPropertyName("moreUsers")] + public bool? MoreUsers { get; set; } - /// Terminal resumed run envelope. - [JsonPropertyName("run")] - public FactoryRunResult Run { get => field ??= new(); set; } + /// Whether the mutation was applied. + [JsonPropertyName("ok")] + public bool Ok { get; set; } } -/// Parameters for resuming a factory run from its persisted identity. +/// One non-interactive accounts mutation command (the selector is fused with its typed args). +/// Polymorphic base type discriminated by kind. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryResumeRequest +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(AuthWriteSwitchActive), "switchActive")] +[JsonDerivedType(typeof(AuthWriteLogout), "logout")] +[JsonDerivedType(typeof(AuthWriteSetCredentials), "setCredentials")] +public partial class AuthWrite { - /// Optional per-invocation resource ceiling overrides. - [JsonPropertyName("limits")] - public FactoryRunLimits? Limits { get; set; } - - /// Whether to emit factory phase names to the session transcript. - [JsonPropertyName("logPhaseNames")] - public bool? LogPhaseNames { get; set; } - - /// Whether to notify the originating session when the factory completes. - [JsonPropertyName("notifyOnComplete")] - public bool? NotifyOnComplete { get; set; } - - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; } -/// Options for an internal tool-originated factory invocation. + +/// The switchActive variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryToolRunOptions +public partial class AuthWriteSwitchActive : AuthWrite { - /// Per-invocation resource ceiling overrides. - [JsonPropertyName("limits")] - public FactoryRunLimits? Limits { get; set; } + /// + [JsonIgnore] + public override string Kind => "switchActive"; - /// Run identifier whose journal and progress should seed this resumed run. - [JsonPropertyName("resumeFromRunId")] - public string? ResumeFromRunId { get; set; } + /// Opaque selection id of the account to make active. + [JsonPropertyName("selectionId")] + public required string SelectionId { get; set; } } -/// Internal parameters for invoking a registered factory from a tool. +/// The logout variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryToolRunRequest +public partial class AuthWriteLogout : AuthWrite { - /// Factory input value. - [JsonPropertyName("args")] - public JsonElement Args { get; set; } - - /// Registered factory name. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; - - /// Tool-originated factory invocation options. - [JsonPropertyName("options")] - public FactoryToolRunOptions? Options { get; set; } - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// + [JsonIgnore] + public override string Kind => "logout"; - /// Opaque identifier of the originating tool call. - [JsonPropertyName("toolCallId")] - public string? ToolCallId { get; set; } + /// Opaque selection id of the account to log out; absent logs out the active account. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("selectionId")] + public string? SelectionId { get; set; } } -/// Internal parameters for resuming a factory run from a tool. +/// The setCredentials variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryToolResumeRequest +public partial class AuthWriteSetCredentials : AuthWrite { - /// Optional per-invocation resource ceiling overrides. - [JsonPropertyName("limits")] - public FactoryRunLimits? Limits { get; set; } + /// + [JsonIgnore] + public override string Kind => "setCredentials"; - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// Authentication host URL. + [Url] + [StringSyntax(StringSyntaxAttribute.Uri)] + [JsonPropertyName("host")] + public required string Host { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Login/username for the credential. + [JsonPropertyName("login")] + public required string Login { get; set; } - /// Opaque identifier of the originating tool call. - [JsonPropertyName("toolCallId")] - public string? ToolCallId { get; set; } + /// GitHub authentication token to install. + [JsonPropertyName("token")] + public required string Token { get; set; } } -/// Parameters for retrieving a factory run. +/// Mutation request carrying the typed write command. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryGetRunRequest +internal sealed class AccountsSetRequest { - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// The non-interactive mutation command to apply. + [JsonPropertyName("command")] + public AuthWrite Command { get => field ??= new(); set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Declared or approved factory resource ceilings. +/// One step in an interactive login flow. The consumer acts on the step and calls advance to proceed. Browser-open is encoded as two distinct steps by design: `open-url` is CONSUMER-driven (the provider surfaces the authorize URL and the consumer opens it — github.com/GHEC web), while `needs-interaction` is PROVIDER-driven (the provider opens the browser or broker UI itself and does not surface a URL — Entra). +/// Polymorphic base type discriminated by kind. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryDeclaredLimits +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(AuthLoginStepOpenUrl), "open-url")] +[JsonDerivedType(typeof(AuthLoginStepInputRequired), "input-required")] +[JsonDerivedType(typeof(AuthLoginStepAwaiting), "awaiting")] +[JsonDerivedType(typeof(AuthLoginStepNeedsInteraction), "needs-interaction")] +[JsonDerivedType(typeof(AuthLoginStepCompleted), "completed")] +[JsonDerivedType(typeof(AuthLoginStepError), "error")] +public partial class AuthLoginStep { - /// Maximum AI credits consumed by subagents and descendants. - [JsonPropertyName("maxAiCredits")] - public double? MaxAiCredits { get; set; } + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; +} - /// Maximum concurrently active subagents. - [JsonPropertyName("maxConcurrentSubagents")] - public long? MaxConcurrentSubagents { get; set; } - /// Maximum total subagents spawned by the run. - [JsonPropertyName("maxTotalSubagents")] - public long? MaxTotalSubagents { get; set; } +/// The open-url variant of . +[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] +public partial class AuthLoginStepOpenUrl : AuthLoginStep +{ + /// + [JsonIgnore] + public override string Kind => "open-url"; - /// Maximum accumulated active execution time in seconds. - [JsonPropertyName("timeoutSeconds")] - public double? TimeoutSeconds { get; set; } + /// Authorize URL the consumer should open in a browser (consumer-driven browser-open). + [JsonPropertyName("url")] + public required string Url { get; set; } } -/// Durable factory resource consumption. +/// The input-required variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryRunConsumed +public partial class AuthLoginStepInputRequired : AuthLoginStep { - /// Accumulated active execution time in milliseconds. - [JsonPropertyName("activeMs")] - public long ActiveMs { get; set; } - - /// AI usage consumed by the run in nano-AIU. - [JsonPropertyName("nanoAiu")] - public long NanoAiu { get; set; } + /// + [JsonIgnore] + public override string Kind => "input-required"; - /// Total subagents spawned by the run. - [JsonPropertyName("subagents")] - public long Subagents { get; set; } + /// Prompt for the value the provider needs; the consumer supplies it as advance input (e.g. a GitHub Enterprise Cloud host, *.ghe.com). + [JsonPropertyName("prompt")] + public required string Prompt { get; set; } } -/// Current factory phase identity. +/// The awaiting variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryCurrentPhase +public partial class AuthLoginStepAwaiting : AuthLoginStep { - /// Current phase identifier. - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; - - /// Zero-based declared phase ordinal, or null for an undeclared phase. - [JsonPropertyName("ordinal")] - public long? Ordinal { get; set; } + /// + [JsonIgnore] + public override string Kind => "awaiting"; } -/// Prompt-safe terminal factory outcome. +/// The needs-interaction variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryRunTerminal +public partial class AuthLoginStepNeedsInteraction : AuthLoginStep { - /// Human-readable terminal error. - [JsonPropertyName("error")] - public string? Error { get; set; } - - /// Machine-readable terminal failure. - [JsonPropertyName("failure")] - public FactoryRunFailure? Failure { get; set; } - - /// Pause initiator metadata, or null when the run did not pause. - [JsonPropertyName("pauseInfo")] - public FactoryPauseInfo? PauseInfo { get; set; } - - /// Human-readable terminal reason. - [JsonPropertyName("reason")] - public string? Reason { get; set; } - - /// Prompt-safe preview of the completed result. - [JsonPropertyName("resultPreview")] - public string? ResultPreview { get; set; } + /// + [JsonIgnore] + public override string Kind => "needs-interaction"; } -/// Durable factory run summary with read-time live overlays. +/// Terminal result of an interactive login flow. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryRunSummary +public sealed class AuthLoginResultDto { - /// Epoch milliseconds when the current active segment started, or null while inactive. - [JsonPropertyName("activeSegmentStartedAt")] - public long? ActiveSegmentStartedAt { get; set; } - - /// Approved effective resource ceilings, or null until approved. - [JsonPropertyName("approved")] - public FactoryDeclaredLimits? Approved { get; set; } - - /// Whether the durable run state currently passes runtime resume eligibility checks. - [JsonPropertyName("canResume")] - public bool CanResume { get; set; } - - /// Epoch milliseconds when the run completed, or null while nonterminal. - [JsonPropertyName("completedAt")] - public long? CompletedAt { get; set; } - - /// Durable resource consumption. - [JsonPropertyName("consumed")] - public FactoryRunConsumed Consumed { get => field ??= new(); set; } - - /// Epoch milliseconds when the run was created. - [JsonPropertyName("createdAt")] - public long CreatedAt { get; set; } - - /// Current phase identity, or null before any phase is entered. - [JsonPropertyName("currentPhase")] - public FactoryCurrentPhase? CurrentPhase { get; set; } - - /// Resource ceilings declared by the factory. - [JsonPropertyName("declaredLimits")] - public FactoryDeclaredLimits DeclaredLimits { get => field ??= new(); set; } - - /// Number of phases declared by the factory. - [JsonPropertyName("declaredPhaseCount")] - public long DeclaredPhaseCount { get; set; } - - /// Human-readable factory description. - [JsonPropertyName("description")] - public string Description { get; set; } = string.Empty; - - /// Registered factory name. - [JsonPropertyName("factoryName")] - public string FactoryName { get; set; } = string.Empty; - - /// Number of direct factory agents currently live. - [JsonPropertyName("liveAgentCount")] - public long LiveAgentCount { get; set; } - - /// Epoch milliseconds when this live-overlay snapshot was observed. - [JsonPropertyName("observedAt")] - public long ObservedAt { get; set; } - - /// Monotonic durable run revision. - [JsonPropertyName("revision")] - public long Revision { get; set; } - - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// Host that was signed in, when completed. + [Url] + [StringSyntax(StringSyntaxAttribute.Uri)] + [JsonPropertyName("host")] + public string? Host { get; set; } - /// Epoch milliseconds when execution first started, or null before start. - [JsonPropertyName("startedAt")] - public long? StartedAt { get; set; } + /// Login that was signed in, when completed. + [JsonPropertyName("login")] + public string? Login { get; set; } - /// Current factory run status. + /// Terminal disposition of the login. [JsonPropertyName("status")] - public FactoryRunStatus Status { get; set; } - - /// Terminal run outcome, or null while nonterminal. - [JsonPropertyName("terminal")] - public FactoryRunTerminal? Terminal { get; set; } - - /// Total direct factory agents spawned across all attempts. - [JsonPropertyName("totalSpawnedAgentCount")] - public long TotalSpawnedAgentCount { get; set; } - - /// Epoch milliseconds when the durable run was last updated. - [JsonPropertyName("updatedAt")] - public long UpdatedAt { get; set; } + public AuthLoginResultStatus Status { get; set; } } -/// A page of factory runs in durable creation order. +/// The completed variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryListRunsResult +public partial class AuthLoginStepCompleted : AuthLoginStep { - /// Whether terminal runs newer than this page exist. - [JsonPropertyName("hasMoreNewer")] - public bool? HasMoreNewer { get; set; } - - /// Newest terminal-run cursor in this page, or null when the terminal window is empty. - [JsonPropertyName("newestSeq")] - public long? NewestSeq { get; set; } - - /// Oldest terminal-run cursor in this page, or null when the terminal window is empty. - [JsonPropertyName("oldestSeq")] - public long? OldestSeq { get; set; } - - /// Number of terminal runs older than this page. - [JsonPropertyName("omittedOlder")] - public long? OmittedOlder { get; set; } + /// + [JsonIgnore] + public override string Kind => "completed"; - /// Factory run summaries in durable creation order. - [JsonPropertyName("runs")] - public IList Runs { get => field ??= []; set; } + /// The terminal login result. + [JsonPropertyName("result")] + public required AuthLoginResultDto Result { get; set; } } -/// Parameters for paging factory runs. +/// The error variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryListRunsRequest +public partial class AuthLoginStepError : AuthLoginStep { - /// Exclusive forward cursor. - [JsonPropertyName("afterSeq")] - public long? AfterSeq { get; set; } - - /// Exclusive backward cursor. - [JsonPropertyName("beforeSeq")] - public long? BeforeSeq { get; set; } - - /// Maximum terminal runs to return. Defaults to 200 and is capped at 500. - [JsonPropertyName("limit")] - public int? Limit { get; set; } + /// + [JsonIgnore] + public override string Kind => "error"; - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Human-readable failure message. + [JsonPropertyName("message")] + public required string Message { get; set; } } -/// Prompt-safe durable identity and live status for a direct factory agent. +/// A started login flow: its opaque id and first step. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryAgentSummary +public sealed class AuthLoginBegun { - /// Accumulated active agent time in milliseconds. - [JsonPropertyName("activeMs")] - public long ActiveMs { get; set; } - - /// Prompt-safe live activity text. - [JsonPropertyName("activity")] - public string? Activity { get; set; } - - /// Stable direct-agent identifier. - [JsonPropertyName("agentId")] - public string AgentId { get; set; } = string.Empty; - - /// Registered agent type. - [JsonPropertyName("agentType")] - public string AgentType { get; set; } = string.Empty; - - /// Epoch milliseconds when the agent completed. - [JsonPropertyName("completedAt")] - public long? CompletedAt { get; set; } - - /// Friendly, non-unique name intended for display. - [JsonPropertyName("displayName")] - public string? DisplayName { get; set; } - - /// Friendly, non-unique name intended for display. - [JsonPropertyName("label")] - public string Label { get; set; } = string.Empty; - - /// Phase identifier active when the agent was launched, or null. - [JsonPropertyName("phaseId")] - public string? PhaseId { get; set; } - - /// Model requested when the agent was launched. - [JsonPropertyName("requestedModel")] - public string? RequestedModel { get; set; } + /// Opaque flow id used to advance or cancel this login. + [JsonPropertyName("flowId")] + public string FlowId { get; set; } = string.Empty; - /// Concrete model resolved for the agent. - [JsonPropertyName("resolvedModel")] - public string? ResolvedModel { get; set; } - - /// Owning factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; - - /// Epoch milliseconds when the agent started. - [JsonPropertyName("startedAt")] - public long? StartedAt { get; set; } - - /// Current durable or live agent status. - [JsonPropertyName("status")] - public string Status { get; set; } = string.Empty; - - /// Tool-call identifier that launched the agent. - [JsonPropertyName("toolCallId")] - public string ToolCallId { get; set; } = string.Empty; + /// The first step of the flow. + [JsonPropertyName("step")] + public AuthLoginStep Step { get => field ??= new(); set; } } -/// Durable lifecycle and timing for one factory phase. +/// Begin an interactive login flow for a provider kind. Dispatch is kind-only. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryPhaseObservation +internal sealed class AuthLoginBeginRequest { - /// Completed active time accumulated by this phase in milliseconds. - [JsonPropertyName("accumulatedActiveMs")] - public long AccumulatedActiveMs { get; set; } - - /// Epoch milliseconds when this phase completed; for a skipped phase, the synthetic skip timestamp (equal to `startedAt`). - [JsonPropertyName("completedAt")] - public long? CompletedAt { get; set; } - - /// Current live active time for this phase in milliseconds. - [JsonPropertyName("currentActiveMs")] - public long CurrentActiveMs { get; set; } - - /// Optional human-readable phase detail. - [JsonPropertyName("detail")] - public string? Detail { get; set; } - - /// Number of times execution entered this phase. - [JsonPropertyName("entryCount")] - public long EntryCount { get; set; } - - /// Phase identifier. - [JsonPropertyName("id")] - public string Id { get; set; } = string.Empty; - - /// Most recent run attempt that entered this phase, or `0` if the phase has never been entered. - [JsonPropertyName("lastEnteredRunAttempt")] - public long LastEnteredRunAttempt { get; set; } - - /// Direct agents in this phase that are currently live. - [JsonPropertyName("liveAgentCount")] - public long LiveAgentCount { get; set; } - - /// Zero-based declared phase ordinal, or null for an undeclared phase. - [JsonPropertyName("ordinal")] - public long? Ordinal { get; set; } - - /// Epoch milliseconds when this phase first started; for a skipped phase, the synthetic skip timestamp (equal to `completedAt`). - [JsonPropertyName("startedAt")] - public long? StartedAt { get; set; } - - /// Derived lifecycle state of the phase. - [JsonPropertyName("status")] - public FactoryPhaseStatus Status { get; set; } - - /// Human-readable phase title. - [JsonPropertyName("title")] - public string Title { get; set; } = string.Empty; + /// The provider kind to sign in with. + [JsonPropertyName("kind")] + public LoginProviderKind Kind { get; set; } - /// Total direct agents associated with this phase. - [JsonPropertyName("totalAgentCount")] - public long TotalAgentCount { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// One durable factory progress record. +/// Advance an in-flight login flow, optionally fulfilling an input-required step. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryProgressLine +internal sealed class AuthLoginAdvanceRequest { - /// Resume attempt that emitted this record. - [JsonPropertyName("attempt")] - public long Attempt { get; set; } - - /// Progress record kind. - [JsonPropertyName("kind")] - public FactoryLogLineKind Kind { get; set; } + /// Opaque flow id from begin. + [JsonPropertyName("flowId")] + public string FlowId { get; set; } = string.Empty; - /// Phase active when the record was emitted, or null before any phase. - [JsonPropertyName("phaseId")] - public string? PhaseId { get; set; } + /// Neutral input fulfilling a preceding input-required step (e.g. a GHEC host); ignored otherwise. + [JsonPropertyName("input")] + public string? Input { get; set; } - /// Epoch milliseconds when the record was persisted. - [JsonPropertyName("recordedAt")] - public long RecordedAt { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Global monotonic sequence number within the run. - [JsonPropertyName("seq")] - public long Seq { get; set; } +/// Cancel an in-flight login flow. +[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] +internal sealed class AuthLoginCancelRequest +{ + /// Opaque flow id from begin. + [JsonPropertyName("flowId")] + public string FlowId { get; set; } = string.Empty; - /// Prompt-safe progress text. - [JsonPropertyName("text")] - public string Text { get; set; } = string.Empty; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// A bidirectional page of factory progress. +/// A file included in the session debug bundle. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryProgressPage +public sealed class DebugCollectLogsCollectedEntry { - /// Whether progress records newer than this page exist. - [JsonPropertyName("hasMoreNewer")] - public bool HasMoreNewer { get; set; } + /// Relative path of the file in the staged bundle/archive. + [JsonPropertyName("bundlePath")] + public string BundlePath { get; set; } = string.Empty; - /// Whether progress records older than this page exist. - [JsonPropertyName("hasMoreOlder")] - public bool HasMoreOlder { get; set; } + /// Redacted output size in bytes. + [JsonPropertyName("sizeBytes")] + public long SizeBytes { get; set; } - /// Newest sequence number in this page, or null when empty. - [JsonPropertyName("newestSeq")] - public long? NewestSeq { get; set; } + /// Source category for this entry. + [JsonPropertyName("source")] + public DebugCollectLogsSource Source { get; set; } +} - /// Oldest sequence number in this page, or null when empty. - [JsonPropertyName("oldestSeq")] - public long? OldestSeq { get; set; } +/// An optional debug bundle entry that could not be included. +[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] +public sealed class DebugCollectLogsSkippedEntry +{ + /// Relative path requested for this bundle entry. + [JsonPropertyName("bundlePath")] + public string BundlePath { get; set; } = string.Empty; - /// Progress records in sequence order. - [JsonPropertyName("records")] - public IList Records { get => field ??= []; set; } + /// Server-local source path that could not be read. + [JsonPropertyName("path")] + public string? Path { get; set; } - /// Run revision reflected by this page. - [JsonPropertyName("revision")] - public long Revision { get; set; } + /// Reason the entry was skipped. + [JsonPropertyName("reason")] + public string Reason { get; set; } = string.Empty; } -/// Full factory run observability detail. +/// Result of collecting a session debug bundle. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryRunDetail +public sealed class DebugCollectLogsResult { - /// Epoch milliseconds when the current active segment started, or null while inactive. - [JsonPropertyName("activeSegmentStartedAt")] - public long? ActiveSegmentStartedAt { get; set; } + /// Files included in the bundle. + [JsonPropertyName("entries")] + public IList Entries { get => field ??= []; set; } - /// Durable identities and live statuses for direct factory agents. - [JsonPropertyName("agents")] - public IList Agents { get => field ??= []; set; } + /// Destination kind that was written. + [JsonPropertyName("kind")] + public DebugCollectLogsResultKind Kind { get; set; } - /// Approved effective resource ceilings, or null until approved. - [JsonPropertyName("approved")] - public FactoryDeclaredLimits? Approved { get; set; } + /// Actual archive path or staging directory path written. This may differ from the requested path when no-overwrite suffixing or fallback-to-temp-directory was needed. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; - /// Whether the durable run state currently passes runtime resume eligibility checks. - [JsonPropertyName("canResume")] - public bool CanResume { get; set; } + /// Optional files or directories that could not be included. + [JsonPropertyName("skippedEntries")] + public IList? SkippedEntries { get; set; } +} - /// Epoch milliseconds when the run completed, or null while nonterminal. - [JsonPropertyName("completedAt")] - public long? CompletedAt { get; set; } +/// A caller-provided server-local file or directory to include in the debug bundle. +[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] +public sealed class DebugCollectLogsEntry +{ + /// Relative path to use inside the staged bundle/archive. + [JsonPropertyName("bundlePath")] + public string BundlePath { get; set; } = string.Empty; - /// Durable resource consumption. - [JsonPropertyName("consumed")] - public FactoryRunConsumed Consumed { get => field ??= new(); set; } + /// Kind of source path to include. + [JsonPropertyName("kind")] + public DebugCollectLogsEntryKind Kind { get; set; } - /// Epoch milliseconds when the run was created. - [JsonPropertyName("createdAt")] - public long CreatedAt { get; set; } + /// Server-local source path to read. + [JsonPropertyName("path")] + public string Path { get; set; } = string.Empty; - /// Current phase identity, or null before any phase is entered. - [JsonPropertyName("currentPhase")] - public FactoryCurrentPhase? CurrentPhase { get; set; } + /// How text content from this entry should be redacted. Defaults to plain-text. With none, no redaction is applied; the caller must ensure any necessary redaction is performed before this call. + [JsonPropertyName("redaction")] + public DebugCollectLogsRedaction? Redaction { get; set; } - /// Resource ceilings declared by the factory. - [JsonPropertyName("declaredLimits")] - public FactoryDeclaredLimits DeclaredLimits { get => field ??= new(); set; } + /// When true, collection fails if this entry cannot be read. Defaults to false, which records the entry in `skippedEntries`. + [JsonPropertyName("required")] + public bool? Required { get; set; } +} - /// Number of phases declared by the factory. - [JsonPropertyName("declaredPhaseCount")] - public long DeclaredPhaseCount { get; set; } +/// Destination for the session debug bundle. +/// Polymorphic base type discriminated by kind. +[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] +[JsonPolymorphic( + TypeDiscriminatorPropertyName = "kind", + UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] +[JsonDerivedType(typeof(DebugCollectLogsDestinationArchive), "archive")] +[JsonDerivedType(typeof(DebugCollectLogsDestinationDirectory), "directory")] +public partial class DebugCollectLogsDestination +{ + /// The type discriminator. + [JsonPropertyName("kind")] + public virtual string Kind { get; set; } = string.Empty; +} - /// Human-readable factory description. - [JsonPropertyName("description")] - public string Description { get; set; } = string.Empty; - /// Registered factory name. - [JsonPropertyName("factoryName")] - public string FactoryName { get; set; } = string.Empty; +/// The archive variant of . +[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] +public partial class DebugCollectLogsDestinationArchive : DebugCollectLogsDestination +{ + /// + [JsonIgnore] + public override string Kind => "archive"; - /// Number of direct factory agents currently live. - [JsonPropertyName("liveAgentCount")] - public long LiveAgentCount { get; set; } + /// When true, create the archive atomically without overwriting an existing file by appending ` (N)` before the extension as needed. Defaults to false. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("noOverwrite")] + public bool? NoOverwrite { get; set; } - /// Epoch milliseconds when this live-overlay snapshot was observed. - [JsonPropertyName("observedAt")] - public long ObservedAt { get; set; } + /// Absolute or server-relative path for the .tgz archive to create. + [JsonPropertyName("outputPath")] + public required string OutputPath { get; set; } +} - /// Lifecycle and timing observations for each factory phase. - [JsonPropertyName("phases")] - public IList Phases { get => field ??= []; set; } +/// The directory variant of . +[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] +public partial class DebugCollectLogsDestinationDirectory : DebugCollectLogsDestination +{ + /// + [JsonIgnore] + public override string Kind => "directory"; - /// Bidirectional page of durable factory progress. - [JsonPropertyName("progress")] - public FactoryProgressPage Progress { get => field ??= new(); set; } + /// Directory where files should be staged. The directory is created if needed. + [JsonPropertyName("outputDirectory")] + public required string OutputDirectory { get; set; } +} - /// Monotonic durable run revision. - [JsonPropertyName("revision")] - public long Revision { get; set; } +/// Built-in session diagnostics to include in the bundle. Omitted fields default to true. +[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] +public sealed class DebugCollectLogsInclude +{ + /// Server-local path to the current process log. When set, it is included as `process.log` and its directory is searched for prior logs from the same session. + [JsonPropertyName("currentProcessLogPath")] + public string? CurrentProcessLogPath { get; set; } - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// Include the session event log (`events.jsonl`). Defaults to true. + [JsonPropertyName("events")] + public bool? Events { get; set; } - /// Epoch milliseconds when execution first started, or null before start. - [JsonPropertyName("startedAt")] - public long? StartedAt { get; set; } + /// Server-local path to the session's events.jsonl file. Internal callers normally omit this and let the runtime derive it from the session. + [JsonPropertyName("eventsPath")] + public string? EventsPath { get; set; } - /// Current factory run status. - [JsonPropertyName("status")] - public FactoryRunStatus Status { get; set; } + /// Maximum number of previous process logs to include. Defaults to 5. + [JsonPropertyName("previousProcessLogLimit")] + public long? PreviousProcessLogLimit { get; set; } - /// Terminal run outcome, or null while nonterminal. - [JsonPropertyName("terminal")] - public FactoryRunTerminal? Terminal { get; set; } + /// Server-local process log directory to search when `currentProcessLogPath` is unavailable, useful for collecting logs for inactive sessions. + [JsonPropertyName("processLogDirectory")] + public string? ProcessLogDirectory { get; set; } - /// Total direct factory agents spawned across all attempts. - [JsonPropertyName("totalSpawnedAgentCount")] - public long TotalSpawnedAgentCount { get; set; } + /// Include process logs for the session. Defaults to true. + [JsonPropertyName("processLogs")] + public bool? ProcessLogs { get; set; } - /// Epoch milliseconds when the durable run was last updated. - [JsonPropertyName("updatedAt")] - public long UpdatedAt { get; set; } + /// Include interactive shell logs written under the session's `shell-logs` directory. Defaults to true. + [JsonPropertyName("shellLogs")] + public bool? ShellLogs { get; set; } } -/// Parameters for paging factory progress. +/// Options for collecting a session debug bundle with configurable redaction. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryGetRunProgressRequest +internal sealed class DebugCollectLogsRequest { - /// Exclusive forward cursor. - [JsonPropertyName("afterSeq")] - public long? AfterSeq { get; set; } - - /// Exclusive backward cursor. - [JsonPropertyName("beforeSeq")] - public long? BeforeSeq { get; set; } - - /// Maximum records to return. Defaults to 200 and is capped at 500. - [JsonPropertyName("limit")] - public int? Limit { get; set; } + /// Caller-provided server-local files or directories to include in addition to the runtime's built-in session diagnostics. This lets host applications add their own diagnostics without changing the API shape. + [JsonPropertyName("additionalEntries")] + public IList? AdditionalEntries { get; set; } - /// Optional phase identifier used to scope records and cursors. - [JsonPropertyName("phaseId")] - public string? PhaseId { get; set; } + /// Where the bundle should be written. Use `archive` to produce a .tgz, or `directory` to stage files for caller-managed upload/post-processing. + [JsonPropertyName("destination")] + public DebugCollectLogsDestination Destination { get => field ??= new(); set; } - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// Which built-in session diagnostics to include. Omitted fields default to true. + [JsonPropertyName("include")] + public DebugCollectLogsInclude? Include { get; set; } /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Parameters for cancelling a factory run. +/// Canvas action that the agent or host can invoke. To discover the input schema for a particular action, call the list_canvas_capabilities tool. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryCancelRequest +public sealed class CanvasAction { - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// Description of the action. + [JsonPropertyName("description")] + public string? Description { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// JSON Schema for the action input. + [JsonPropertyName("inputSchema")] + public JsonElement? InputSchema { get; set; } + + /// Action name exposed by the canvas provider. + [JsonPropertyName("name")] + public string Name { get; set; } = string.Empty; } -/// Parameters for pausing a running factory. +/// Canvas available in the current session. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryPauseRequest +public sealed class DiscoveredCanvas { - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// Actions the agent or host may invoke on an open instance. + [JsonPropertyName("actions")] + public IList? Actions { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Provider-local canvas identifier. + [JsonPropertyName("canvasId")] + public string CanvasId { get; set; } = string.Empty; + + /// Short, single-sentence description shown to the agent in canvas catalogs. + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] + [MinLength(1)] + [JsonPropertyName("description")] + public string Description { get; set; } = string.Empty; + + /// Human-readable canvas name. + [JsonPropertyName("displayName")] + public string DisplayName { get; set; } = string.Empty; + + /// Owning provider identifier. + [JsonPropertyName("extensionId")] + public string ExtensionId { get; set; } = string.Empty; + + /// Owning extension display name, when available. + [JsonPropertyName("extensionName")] + public string? ExtensionName { get; set; } + + /// Host-local PNG path for the canvas icon, when supplied. + [JsonPropertyName("icon")] + public string? Icon { get; set; } + + /// JSON Schema for canvas open input. + [JsonPropertyName("inputSchema")] + public JsonElement? InputSchema { get; set; } } -/// RPC data type for SessionFactoryPauseAtCheckpoint operations. +/// Declared canvases available in this session. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class SessionFactoryPauseAtCheckpointResult +public sealed class CanvasList { - /// Whether this execution attempt must pause or may continue. - [JsonPropertyName("action")] - public FactoryPauseCheckpointAction Action { get; set; } + /// Declared canvases available in this session. + [JsonPropertyName("canvases")] + public IList Canvases { get => field ??= []; set; } } -/// Parameters for an owned durable pause checkpoint. +/// Identifies the target session. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryPauseCheckpointRequest +internal sealed class SessionCanvasListRequest { - /// Opaque token identifying the execution attempt that reached the checkpoint. - [JsonPropertyName("executionToken")] - public string ExecutionToken { get; set; } = string.Empty; - - /// Stable author-defined checkpoint key. - [JsonPropertyName("key")] - public string Key { get; set; } = string.Empty; - - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; - /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Acknowledgement that a factory request was accepted. +/// Open canvas instance snapshot. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryAckResult +public sealed class OpenCanvasInstance { -} + /// Provider-local canvas identifier. + [JsonPropertyName("canvasId")] + public string CanvasId { get; set; } = string.Empty; -/// One ordered factory progress line. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryLogLine -{ - /// Progress line kind. - [JsonPropertyName("kind")] - public FactoryLogLineKind Kind { get; set; } + /// Owning provider identifier. + [JsonPropertyName("extensionId")] + public string ExtensionId { get; set; } = string.Empty; - /// Monotonic sequence number within the factory run. - [JsonPropertyName("seq")] - public long Seq { get; set; } + /// Owning extension display name, when available. + [JsonPropertyName("extensionName")] + public string? ExtensionName { get; set; } - /// Progress text. - [JsonPropertyName("text")] - public string Text { get; set; } = string.Empty; -} + /// Host-local PNG path for the canvas icon, when supplied. + [JsonPropertyName("icon")] + public string? Icon { get; set; } -/// Parameters for recording factory progress. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryLogRequest -{ - /// Opaque token identifying the current factory execution attempt. - [JsonPropertyName("executionToken")] - public string ExecutionToken { get; set; } = string.Empty; + /// Input supplied when the instance was opened. + [JsonPropertyName("input")] + public JsonElement? Input { get; set; } - /// Ordered progress lines to append. - [JsonPropertyName("lines")] - public IList Lines { get => field ??= []; set; } + /// Stable caller-supplied canvas instance identifier. + [JsonPropertyName("instanceId")] + public string InstanceId { get; set; } = string.Empty; - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// Provider-supplied status text. + [JsonPropertyName("status")] + public string? Status { get; set; } - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; + /// Rendered title. + [JsonPropertyName("title")] + public string? Title { get; set; } + + /// URL for web-rendered canvases. + [JsonPropertyName("url")] + public string? Url { get; set; } } -/// Result of one factory-scoped subagent call. +/// Live open-canvas snapshot. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryAgentResult +public sealed class CanvasListOpenResult { - /// Agent result, omitted when the agent produced no result. - [JsonPropertyName("result")] - public JsonElement? Result { get; set; } + /// Currently open canvas instances. + [JsonPropertyName("openCanvases")] + public IList OpenCanvases { get => field ??= []; set; } } -/// Options for one factory-scoped subagent call. +/// Identifies the target session. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryAgentOptions +internal sealed class SessionCanvasListOpenRequest { - /// Optional built-in or custom agent name whose definition configures the subagent. - [JsonPropertyName("agent")] - public string? Agent { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} - /// Optional context tier override for the subagent. - [JsonPropertyName("contextTier")] - public ContextTier? ContextTier { get; set; } +/// Canvas open parameters. +[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] +internal sealed class CanvasOpenRequest +{ + /// Provider-local canvas identifier. + [JsonPropertyName("canvasId")] + public string CanvasId { get; set; } = string.Empty; - /// Optional label distinguishing otherwise identical memoized agent calls. - [JsonPropertyName("label")] - public string? Label { get; set; } + /// Owning provider identifier. Optional when the canvasId is unique across providers; required to disambiguate when multiple providers register the same canvasId. + [JsonPropertyName("extensionId")] + public string? ExtensionId { get; set; } - /// Optional model identifier for the subagent. - [JsonPropertyName("model")] - public string? Model { get; set; } + /// Canvas open input. + [JsonPropertyName("input")] + public JsonElement? Input { get; set; } - /// Optional reasoning effort override for the subagent. - [JsonPropertyName("reasoningEffort")] - public string? ReasoningEffort { get; set; } + /// Caller-supplied stable instance identifier. + [JsonPropertyName("instanceId")] + public string InstanceId { get; set; } = string.Empty; - /// Optional JSON Schema for structured agent output. - [JsonPropertyName("schema")] - public JsonElement? Schema { get; set; } + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; } -/// Parameters for one factory-scoped subagent call. +/// Canvas close parameters. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryAgentRequest +internal sealed class CanvasCloseRequest { - /// Opaque token identifying the current factory execution attempt. - [JsonPropertyName("executionToken")] - public string ExecutionToken { get; set; } = string.Empty; - - /// Factory run identifier that owns the subagent. - [JsonPropertyName("factoryRunId")] - public string FactoryRunId { get; set; } = string.Empty; - - /// Subagent execution options. - [JsonPropertyName("opts")] - public FactoryAgentOptions Opts { get => field ??= new(); set; } - - /// Prompt to send to the subagent. - [JsonPropertyName("prompt")] - public string Prompt { get; set; } = string.Empty; + /// Open canvas instance identifier. + [JsonPropertyName("instanceId")] + public string InstanceId { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Result of reading a factory journal entry. +/// Canvas action invocation result. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryJournalGetResult +public sealed class CanvasActionInvokeResult { - /// Whether the journal contained the requested key. - [JsonPropertyName("hit")] - public bool Hit { get; set; } - - /// Cached JSON result. The hit field distinguishes a cached JSON null from a miss. - [JsonPropertyName("resultJson")] - public JsonElement? ResultJson { get; set; } + /// Provider-supplied action result. + [JsonPropertyName("result")] + public JsonElement? Result { get; set; } } -/// Parameters for reading a factory journal entry. +/// Canvas action invocation parameters. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryJournalGetRequest +internal sealed class CanvasActionInvokeRequest { - /// Opaque token identifying the current factory execution attempt. - [JsonPropertyName("executionToken")] - public string ExecutionToken { get; set; } = string.Empty; + /// Action name to invoke. + [JsonPropertyName("actionName")] + public string ActionName { get; set; } = string.Empty; - /// Namespaced journal key. - [JsonPropertyName("key")] - public string Key { get; set; } = string.Empty; + /// Action input. + [JsonPropertyName("input")] + public JsonElement? Input { get; set; } - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// Open canvas instance identifier. + [JsonPropertyName("instanceId")] + public string InstanceId { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] public string SessionId { get; set; } = string.Empty; } -/// Parameters for storing a factory journal entry. +/// Internal canvas provider registration parameters. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -internal sealed class FactoryJournalPutRequest +internal sealed class CanvasProviderRegisterRequest { - /// Opaque token identifying the current factory execution attempt. - [JsonPropertyName("executionToken")] - public string ExecutionToken { get; set; } = string.Empty; + /// Canvas contributions supplied by the provider. + [JsonPropertyName("canvases")] + public IList Canvases { get => field ??= []; set; } - /// Namespaced journal key. - [JsonPropertyName("key")] - public string Key { get; set; } = string.Empty; + /// Connection identifier for callback routing. + [JsonPropertyName("connectionId")] + public string ConnectionId { get; set; } = string.Empty; - /// JSON result to memoize. - [JsonPropertyName("resultJson")] - public JsonElement ResultJson { get; set; } + /// Provider metadata supplied by the host. + [JsonPropertyName("info")] + public JsonElement Info { get; set; } - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; + /// Target session identifier. + [JsonPropertyName("sessionId")] + public string SessionId { get; set; } = string.Empty; +} + +/// Internal canvas provider unregistration parameters. +[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] +internal sealed class CanvasProviderUnregisterRequest +{ + /// Connection identifier to unregister. + [JsonPropertyName("connectionId")] + public string ConnectionId { get; set; } = string.Empty; /// Target session identifier. [JsonPropertyName("sessionId")] @@ -9954,6 +9397,14 @@ internal sealed class ModelApplyStartupOverlayRequest [JsonPropertyName("deviceManagedModel")] public string? DeviceManagedModel { get; set; } + /// Context tier paired with the effective organization-managed model. Applies only when that concrete managed model is selected; it is ignored for Auto and for CLI, resume, or user overrides. + [JsonPropertyName("managedContextTier")] + public string? ManagedContextTier { get; set; } + + /// Reasoning effort paired with the effective organization-managed model. Applies only when that concrete managed model is selected; it is ignored for Auto and for CLI, resume, or user overrides. + [JsonPropertyName("managedReasoningEffort")] + public string? ManagedReasoningEffort { get; set; } + /// Startup default model from the enterprise policy helper, when configured. Weakest of the managed sources: it applies only when neither device nor server policy names a model, and an explicit user selection still wins. [JsonPropertyName("policyHelperModel")] public string? PolicyHelperModel { get; set; } @@ -17576,6 +17027,11 @@ public partial class SlashCommandInvocationResultSetModel : SlashCommandInvocati [JsonIgnore] public override string Kind => "set-model"; + /// Auto routing profile selected by the command, when the model is Auto. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("autoTier")] + public AutoTier? AutoTier { get; set; } + /// Model selected by the command. [JsonPropertyName("model")] public required string Model { get; set; } @@ -18378,7 +17834,7 @@ public partial class PermissionDecisionApproveOnce : PermissionDecision [JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalMemory), "memory")] [JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalCustomTool), "custom-tool")] [JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalExtensionManagement), "extension-management")] -[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalFactory), "factory")] +[JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalWorkflow), "workflow")] [JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess), "extension-permission-access")] [JsonDerivedType(typeof(PermissionDecisionApproveForSessionApprovalExtensionEnvAccess), "extension-env-access")] public partial class PermissionDecisionApproveForSessionApproval @@ -18494,16 +17950,16 @@ public partial class PermissionDecisionApproveForSessionApprovalExtensionManagem public string? Operation { get; set; } } -/// Session-scoped factory approval, optionally narrowed by approval key. -/// The factory variant of . +/// Session-scoped workflow approval, optionally narrowed by approval key. +/// The workflow variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForSessionApprovalFactory : PermissionDecisionApproveForSessionApproval +public partial class PermissionDecisionApproveForSessionApprovalWorkflow : PermissionDecisionApproveForSessionApproval { /// [JsonIgnore] - public override string Kind => "factory"; + public override string Kind => "workflow"; - /// Optional factory operation name or canonical approval key; when omitted, the approval covers all factory operations. + /// Optional workflow operation name or canonical approval key; when omitted, the approval covers all workflow operations. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("approvalKey")] public string? ApprovalKey { get; set; } @@ -18575,7 +18031,7 @@ public partial class PermissionDecisionApproveForSession : PermissionDecision [JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalMemory), "memory")] [JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalCustomTool), "custom-tool")] [JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalExtensionManagement), "extension-management")] -[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalFactory), "factory")] +[JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalWorkflow), "workflow")] [JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess), "extension-permission-access")] [JsonDerivedType(typeof(PermissionDecisionApproveForLocationApprovalExtensionEnvAccess), "extension-env-access")] public partial class PermissionDecisionApproveForLocationApproval @@ -18691,16 +18147,16 @@ public partial class PermissionDecisionApproveForLocationApprovalExtensionManage public string? Operation { get; set; } } -/// Location-scoped factory approval, optionally narrowed by approval key. -/// The factory variant of . +/// Location-scoped workflow approval, optionally narrowed by approval key. +/// The workflow variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public partial class PermissionDecisionApproveForLocationApprovalFactory : PermissionDecisionApproveForLocationApproval +public partial class PermissionDecisionApproveForLocationApprovalWorkflow : PermissionDecisionApproveForLocationApproval { /// [JsonIgnore] - public override string Kind => "factory"; + public override string Kind => "workflow"; - /// Optional factory operation name or canonical approval key; when omitted, the approval covers all factory operations. + /// Optional workflow operation name or canonical approval key; when omitted, the approval covers all workflow operations. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("approvalKey")] public string? ApprovalKey { get; set; } @@ -19373,7 +18829,7 @@ public sealed class PermissionsLocationsAddToolApprovalResult [JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsMemory), "memory")] [JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsCustomTool), "custom-tool")] [JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsExtensionManagement), "extension-management")] -[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsFactory), "factory")] +[JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsWorkflow), "workflow")] [JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess), "extension-permission-access")] [JsonDerivedType(typeof(PermissionsLocationsAddToolApprovalDetailsExtensionEnvAccess), "extension-env-access")] public partial class PermissionsLocationsAddToolApprovalDetails @@ -19489,16 +18945,16 @@ public partial class PermissionsLocationsAddToolApprovalDetailsExtensionManageme public string? Operation { get; set; } } -/// Location-persisted factory approval, optionally narrowed by approval key. -/// The factory variant of . +/// Location-persisted workflow approval, optionally narrowed by approval key. +/// The workflow variant of . [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public partial class PermissionsLocationsAddToolApprovalDetailsFactory : PermissionsLocationsAddToolApprovalDetails +public partial class PermissionsLocationsAddToolApprovalDetailsWorkflow : PermissionsLocationsAddToolApprovalDetails { /// [JsonIgnore] - public override string Kind => "factory"; + public override string Kind => "workflow"; - /// Optional factory operation name or canonical approval key; when omitted, the approval covers all factory operations. + /// Optional workflow operation name or canonical approval key; when omitted, the approval covers all workflow operations. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("approvalKey")] public string? ApprovalKey { get; set; } @@ -22314,57 +21770,6 @@ public sealed class ProviderTokenAcquireRequest public string SessionId { get; set; } = string.Empty; } -/// Result returned by an extension factory closure. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryExecuteResult -{ - /// Factory result value. - [JsonPropertyName("result")] - public JsonElement? Result { get; set; } -} - -/// Parameters sent to the owning extension to execute a factory closure. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryExecuteRequest -{ - /// Factory input value. - [JsonPropertyName("args")] - public JsonElement Args { get; set; } - - /// Opaque token identifying this factory execution attempt. - [JsonPropertyName("executionToken")] - public string ExecutionToken { get; set; } = string.Empty; - - /// Registered factory name. - [JsonPropertyName("name")] - public string Name { get; set; } = string.Empty; - - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} - -/// Parameters for cooperatively aborting a factory body. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryAbortRequest -{ - /// Opaque token identifying the execution attempt to abort. - [JsonPropertyName("executionToken")] - public string ExecutionToken { get; set; } = string.Empty; - - /// Factory run identifier. - [JsonPropertyName("runId")] - public string RunId { get; set; } = string.Empty; - - /// Target session identifier. - [JsonPropertyName("sessionId")] - public string SessionId { get; set; } = string.Empty; -} - /// Result returned by an extension workflow closure. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed class WorkflowExecuteResult @@ -28928,112 +28333,52 @@ public override void Write(Utf8JsonWriter writer, AuthInfoType value, JsonSerial } -/// Source category for a collected debug bundle entry. +/// The provider kind stamped on a signed-in account. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct DebugCollectLogsSource : IEquatable +public readonly struct AccountKind : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public DebugCollectLogsSource(string value) + public AccountKind(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Session event log. - public static DebugCollectLogsSource Events { get; } = new("events"); + /// An OAuth github.com account. + public static AccountKind GitHubDotCom { get; } = new("githubDotCom"); - /// Process log for the session. - public static DebugCollectLogsSource ProcessLog { get; } = new("process-log"); + /// A GitHub Enterprise Cloud account — a GitHub account on a non-github.com host, e.g. *.ghe.com. + public static AccountKind Proxima { get; } = new("proxima"); - /// Interactive shell log for the session. - public static DebugCollectLogsSource ShellLog { get; } = new("shell-log"); + /// A GitHub (EMU) account derived from a base Entra identity. + public static AccountKind EntraEmu { get; } = new("entraEmu"); - /// Caller-provided diagnostic entry. - public static DebugCollectLogsSource Additional { get; } = new("additional"); + /// A base Microsoft Entra identity. + public static AccountKind Entra { get; } = new("entra"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(DebugCollectLogsSource left, DebugCollectLogsSource right) => left.Equals(right); + /// A Microsoft 365 Copilot (Loki) inference account derived from the same base Entra identity as an EMU account; its bearer is a Loki-scoped inference token consumed through the model-provider path, not the GitHub switcher. + public static AccountKind Loki { get; } = new("loki"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(DebugCollectLogsSource left, DebugCollectLogsSource right) => !(left == right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AccountKind left, AccountKind right) => left.Equals(right); - /// - public override bool Equals(object? obj) => obj is DebugCollectLogsSource other && Equals(other); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AccountKind left, AccountKind right) => !(left == right); /// - public bool Equals(DebugCollectLogsSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public override bool Equals(object? obj) => obj is AccountKind other && Equals(other); /// - public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - - /// - public override string ToString() => Value; - - /// Provides a for serializing instances. - [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter - { - /// - public override DebugCollectLogsSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); - } - - /// - public override void Write(Utf8JsonWriter writer, DebugCollectLogsSource value, JsonSerializerOptions options) - { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsSource)); - } - } -} - - -/// Destination kind that was written. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -[JsonConverter(typeof(Converter))] -[DebuggerDisplay("{Value,nq}")] -public readonly struct DebugCollectLogsResultKind : IEquatable -{ - private readonly string? _value; - - /// Initializes a new instance of the struct. - /// The value to associate with this . - [JsonConstructor] - public DebugCollectLogsResultKind(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - _value = value; - } - - /// Gets the value associated with this . - public string Value => _value ?? string.Empty; - - /// A .tgz archive was written. - public static DebugCollectLogsResultKind Archive { get; } = new("archive"); - - /// A directory containing the collected files was written. - public static DebugCollectLogsResultKind Directory { get; } = new("directory"); - - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(DebugCollectLogsResultKind left, DebugCollectLogsResultKind right) => left.Equals(right); - - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(DebugCollectLogsResultKind left, DebugCollectLogsResultKind right) => !(left == right); - - /// - public override bool Equals(object? obj) => obj is DebugCollectLogsResultKind other && Equals(other); - - /// - public bool Equals(DebugCollectLogsResultKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(AccountKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -29041,194 +28386,65 @@ public DebugCollectLogsResultKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override DebugCollectLogsResultKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override AccountKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, DebugCollectLogsResultKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, AccountKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsResultKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AccountKind)); } } } -/// Kind of caller-provided debug log entry. +/// A provider a consumer may interactively sign in with. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct DebugCollectLogsEntryKind : IEquatable +public readonly struct LoginProviderKind : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public DebugCollectLogsEntryKind(string value) + public LoginProviderKind(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Include a single server-local file. - public static DebugCollectLogsEntryKind File { get; } = new("file"); + /// OAuth github.com sign-in via the browser (web loopback + PKCE). + public static LoginProviderKind GitHubDotCom { get; } = new("githubDotCom"); - /// Include files from a server-local directory recursively. - public static DebugCollectLogsEntryKind Directory { get; } = new("directory"); + /// A GitHub Enterprise Cloud account — a GitHub account on a non-github.com host, e.g. *.ghe.com; the host is supplied interactively through the neutral input-required step. + public static LoginProviderKind Proxima { get; } = new("proxima"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(DebugCollectLogsEntryKind left, DebugCollectLogsEntryKind right) => left.Equals(right); + /// Microsoft Entra sign-in that derives a GitHub (EMU) credential. + public static LoginProviderKind Entra { get; } = new("entra"); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(DebugCollectLogsEntryKind left, DebugCollectLogsEntryKind right) => !(left == right); - - /// - public override bool Equals(object? obj) => obj is DebugCollectLogsEntryKind other && Equals(other); - - /// - public bool Equals(DebugCollectLogsEntryKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); - - /// - public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); - - /// - public override string ToString() => Value; - - /// Provides a for serializing instances. - [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter - { - /// - public override DebugCollectLogsEntryKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); - } - - /// - public override void Write(Utf8JsonWriter writer, DebugCollectLogsEntryKind value, JsonSerializerOptions options) - { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsEntryKind)); - } - } -} - - -/// How a collected debug entry should be redacted before being staged. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -[JsonConverter(typeof(Converter))] -[DebuggerDisplay("{Value,nq}")] -public readonly struct DebugCollectLogsRedaction : IEquatable -{ - private readonly string? _value; - - /// Initializes a new instance of the struct. - /// The value to associate with this . - [JsonConstructor] - public DebugCollectLogsRedaction(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - _value = value; - } - - /// Gets the value associated with this . - public string Value => _value ?? string.Empty; - - /// Redact the file as plain UTF-8 log text. - public static DebugCollectLogsRedaction PlainText { get; } = new("plain-text"); - - /// Redact each non-empty line as a session event JSON object, falling back to plain-text redaction for malformed lines. - public static DebugCollectLogsRedaction EventsJsonl { get; } = new("events-jsonl"); - - /// No redaction is applied. The caller must ensure any necessary redaction is performed before this call. - public static DebugCollectLogsRedaction None { get; } = new("none"); - - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(DebugCollectLogsRedaction left, DebugCollectLogsRedaction right) => left.Equals(right); - - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(DebugCollectLogsRedaction left, DebugCollectLogsRedaction right) => !(left == right); - - /// - public override bool Equals(object? obj) => obj is DebugCollectLogsRedaction other && Equals(other); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(LoginProviderKind left, LoginProviderKind right) => left.Equals(right); - /// - public bool Equals(DebugCollectLogsRedaction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(LoginProviderKind left, LoginProviderKind right) => !(left == right); /// - public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); + public override bool Equals(object? obj) => obj is LoginProviderKind other && Equals(other); /// - public override string ToString() => Value; - - /// Provides a for serializing instances. - [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter - { - /// - public override DebugCollectLogsRedaction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) - { - return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); - } - - /// - public override void Write(Utf8JsonWriter writer, DebugCollectLogsRedaction value, JsonSerializerOptions options) - { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsRedaction)); - } - } -} - - -/// Cumulative resource ceiling that stopped a factory run. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -[JsonConverter(typeof(Converter))] -[DebuggerDisplay("{Value,nq}")] -public readonly struct FactoryRunFailureKind : IEquatable -{ - private readonly string? _value; - - /// Initializes a new instance of the struct. - /// The value to associate with this . - [JsonConstructor] - public FactoryRunFailureKind(string value) - { - ArgumentException.ThrowIfNullOrWhiteSpace(value); - _value = value; - } - - /// Gets the value associated with this . - public string Value => _value ?? string.Empty; - - /// The run admitted the approved maximum total number of subagents. - public static FactoryRunFailureKind MaxTotalSubagents { get; } = new("maxTotalSubagents"); - - /// The run reached the approved accumulated active-execution time in seconds. - public static FactoryRunFailureKind TimeoutSeconds { get; } = new("timeoutSeconds"); - - /// The run's settled subagent model usage exceeded the approved AI-credit ceiling, or no headroom remained for another subagent. - public static FactoryRunFailureKind MaxAiCredits { get; } = new("maxAiCredits"); - - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(FactoryRunFailureKind left, FactoryRunFailureKind right) => left.Equals(right); - - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(FactoryRunFailureKind left, FactoryRunFailureKind right) => !(left == right); - - /// - public override bool Equals(object? obj) => obj is FactoryRunFailureKind other && Equals(other); - - /// - public bool Equals(FactoryRunFailureKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(LoginProviderKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -29236,89 +28452,65 @@ public FactoryRunFailureKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override FactoryRunFailureKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override LoginProviderKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, FactoryRunFailureKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, LoginProviderKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryRunFailureKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(LoginProviderKind)); } } } -/// Execution-critical factory storage operation. +/// Terminal disposition of a login persistence attempt. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct FactoryDurableOperation : IEquatable +public readonly struct AuthLoginResultStatus : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public FactoryDurableOperation(string value) + public AuthLoginResultStatus(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Creating the durable run and declared phases. - public static FactoryDurableOperation CreateRun { get; } = new("createRun"); - - /// Persisting the transition to running. - public static FactoryDurableOperation MarkRunStarted { get; } = new("markRunStarted"); + /// The credential was persisted and the account is signed in. + public static AuthLoginResultStatus Completed { get; } = new("completed"); - /// Persisting the terminal run envelope. - public static FactoryDurableOperation FinishRun { get; } = new("finishRun"); + /// Persistence needs explicit consent to store the token in plaintext. + public static AuthLoginResultStatus NeedsPlaintextConsent { get; } = new("needs-plaintext-consent"); - /// Persisting subagent admission accounting. - public static FactoryDurableOperation ReserveAgent { get; } = new("reserveAgent"); - - /// Rolling back an uncommitted subagent admission. - public static FactoryDurableOperation ReleaseAgent { get; } = new("releaseAgent"); - - /// Persisting an idempotent model-usage charge. - public static FactoryDurableOperation ChargeCredit { get; } = new("chargeCredit"); - - /// Persisting active execution time. - public static FactoryDurableOperation AddElapsed { get; } = new("addElapsed"); - - /// Reading the authoritative AI-credit total. - public static FactoryDurableOperation ReconcileCreditTotal { get; } = new("reconcileCreditTotal"); - - /// Reading a journal entry without treating storage failure as a cache miss. - public static FactoryDurableOperation JournalGet { get; } = new("journalGet"); - - /// Persisting a journal entry before reporting success. - public static FactoryDurableOperation JournalPut { get; } = new("journalPut"); - - /// Renewing the durable owner lease that proves this process still owns the run. - public static FactoryDurableOperation RefreshLease { get; } = new("refreshLease"); + /// The user declined plaintext persistence. + public static AuthLoginResultStatus Declined { get; } = new("declined"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(FactoryDurableOperation left, FactoryDurableOperation right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(AuthLoginResultStatus left, AuthLoginResultStatus right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(FactoryDurableOperation left, FactoryDurableOperation right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(AuthLoginResultStatus left, AuthLoginResultStatus right) => !(left == right); /// - public override bool Equals(object? obj) => obj is FactoryDurableOperation other && Equals(other); + public override bool Equals(object? obj) => obj is AuthLoginResultStatus other && Equals(other); /// - public bool Equals(FactoryDurableOperation other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(AuthLoginResultStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -29326,77 +28518,68 @@ public FactoryDurableOperation(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override FactoryDurableOperation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override AuthLoginResultStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, FactoryDurableOperation value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, AuthLoginResultStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryDurableOperation)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(AuthLoginResultStatus)); } } } -/// Current or terminal state of a factory run. +/// Source category for a collected debug bundle entry. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct FactoryRunStatus : IEquatable +public readonly struct DebugCollectLogsSource : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public FactoryRunStatus(string value) + public DebugCollectLogsSource(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The run was minted and is awaiting approval. - public static FactoryRunStatus Pending { get; } = new("pending"); - - /// The run is executing. - public static FactoryRunStatus Running { get; } = new("running"); - - /// The run completed successfully. - public static FactoryRunStatus Completed { get; } = new("completed"); - - /// The run was interrupted while resource budget remained. - public static FactoryRunStatus Halted { get; } = new("halted"); + /// Session event log. + public static DebugCollectLogsSource Events { get; } = new("events"); - /// The current attempt stopped intentionally and the run may be resumed. - public static FactoryRunStatus Paused { get; } = new("paused"); + /// Process log for the session. + public static DebugCollectLogsSource ProcessLog { get; } = new("process-log"); - /// The run was cancelled before completion. - public static FactoryRunStatus Cancelled { get; } = new("cancelled"); + /// Interactive shell log for the session. + public static DebugCollectLogsSource ShellLog { get; } = new("shell-log"); - /// The factory body failed or reached a cumulative resource ceiling. - public static FactoryRunStatus Error { get; } = new("error"); + /// Caller-provided diagnostic entry. + public static DebugCollectLogsSource Additional { get; } = new("additional"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(FactoryRunStatus left, FactoryRunStatus right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DebugCollectLogsSource left, DebugCollectLogsSource right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(FactoryRunStatus left, FactoryRunStatus right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DebugCollectLogsSource left, DebugCollectLogsSource right) => !(left == right); /// - public override bool Equals(object? obj) => obj is FactoryRunStatus other && Equals(other); + public override bool Equals(object? obj) => obj is DebugCollectLogsSource other && Equals(other); /// - public bool Equals(FactoryRunStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(DebugCollectLogsSource other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -29404,68 +28587,62 @@ public FactoryRunStatus(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override FactoryRunStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override DebugCollectLogsSource Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, FactoryRunStatus value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, DebugCollectLogsSource value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryRunStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsSource)); } } } -/// Derived lifecycle state of a factory phase. +/// Destination kind that was written. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct FactoryPhaseStatus : IEquatable +public readonly struct DebugCollectLogsResultKind : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public FactoryPhaseStatus(string value) + public DebugCollectLogsResultKind(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The phase has not been entered yet. - public static FactoryPhaseStatus Pending { get; } = new("pending"); - - /// The phase is currently entered and accumulating active time. - public static FactoryPhaseStatus Active { get; } = new("active"); - - /// The phase was entered and has since been closed. - public static FactoryPhaseStatus Completed { get; } = new("completed"); + /// A .tgz archive was written. + public static DebugCollectLogsResultKind Archive { get; } = new("archive"); - /// The phase was never entered because a later phase was entered or the run reached a terminal state. - public static FactoryPhaseStatus Skipped { get; } = new("skipped"); + /// A directory containing the collected files was written. + public static DebugCollectLogsResultKind Directory { get; } = new("directory"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(FactoryPhaseStatus left, FactoryPhaseStatus right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DebugCollectLogsResultKind left, DebugCollectLogsResultKind right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(FactoryPhaseStatus left, FactoryPhaseStatus right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DebugCollectLogsResultKind left, DebugCollectLogsResultKind right) => !(left == right); /// - public override bool Equals(object? obj) => obj is FactoryPhaseStatus other && Equals(other); + public override bool Equals(object? obj) => obj is DebugCollectLogsResultKind other && Equals(other); /// - public bool Equals(FactoryPhaseStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(DebugCollectLogsResultKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -29473,62 +28650,62 @@ public FactoryPhaseStatus(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override FactoryPhaseStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override DebugCollectLogsResultKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, FactoryPhaseStatus value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, DebugCollectLogsResultKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryPhaseStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsResultKind)); } } } -/// Kind of factory progress line. +/// Kind of caller-provided debug log entry. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct FactoryLogLineKind : IEquatable +public readonly struct DebugCollectLogsEntryKind : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public FactoryLogLineKind(string value) + public DebugCollectLogsEntryKind(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// A narrator log line. - public static FactoryLogLineKind Log { get; } = new("log"); + /// Include a single server-local file. + public static DebugCollectLogsEntryKind File { get; } = new("file"); - /// A named factory phase marker. - public static FactoryLogLineKind Phase { get; } = new("phase"); + /// Include files from a server-local directory recursively. + public static DebugCollectLogsEntryKind Directory { get; } = new("directory"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(FactoryLogLineKind left, FactoryLogLineKind right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DebugCollectLogsEntryKind left, DebugCollectLogsEntryKind right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(FactoryLogLineKind left, FactoryLogLineKind right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DebugCollectLogsEntryKind left, DebugCollectLogsEntryKind right) => !(left == right); /// - public override bool Equals(object? obj) => obj is FactoryLogLineKind other && Equals(other); + public override bool Equals(object? obj) => obj is DebugCollectLogsEntryKind other && Equals(other); /// - public bool Equals(FactoryLogLineKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(DebugCollectLogsEntryKind other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -29536,62 +28713,65 @@ public FactoryLogLineKind(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override FactoryLogLineKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override DebugCollectLogsEntryKind Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, FactoryLogLineKind value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, DebugCollectLogsEntryKind value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryLogLineKind)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsEntryKind)); } } } -/// Action the runtime selected for a durable factory pause checkpoint. +/// How a collected debug entry should be redacted before being staged. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct FactoryPauseCheckpointAction : IEquatable +public readonly struct DebugCollectLogsRedaction : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public FactoryPauseCheckpointAction(string value) + public DebugCollectLogsRedaction(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The checkpoint was committed by a prior paused attempt, so execution may continue. - public static FactoryPauseCheckpointAction Continue { get; } = new("continue"); + /// Redact the file as plain UTF-8 log text. + public static DebugCollectLogsRedaction PlainText { get; } = new("plain-text"); - /// This attempt claimed the checkpoint and must cooperatively stop. - public static FactoryPauseCheckpointAction Pause { get; } = new("pause"); + /// Redact each non-empty line as a session event JSON object, falling back to plain-text redaction for malformed lines. + public static DebugCollectLogsRedaction EventsJsonl { get; } = new("events-jsonl"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(FactoryPauseCheckpointAction left, FactoryPauseCheckpointAction right) => left.Equals(right); + /// No redaction is applied. The caller must ensure any necessary redaction is performed before this call. + public static DebugCollectLogsRedaction None { get; } = new("none"); + + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(DebugCollectLogsRedaction left, DebugCollectLogsRedaction right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(FactoryPauseCheckpointAction left, FactoryPauseCheckpointAction right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(DebugCollectLogsRedaction left, DebugCollectLogsRedaction right) => !(left == right); /// - public override bool Equals(object? obj) => obj is FactoryPauseCheckpointAction other && Equals(other); + public override bool Equals(object? obj) => obj is DebugCollectLogsRedaction other && Equals(other); /// - public bool Equals(FactoryPauseCheckpointAction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(DebugCollectLogsRedaction other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -29599,20 +28779,20 @@ public FactoryPauseCheckpointAction(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override FactoryPauseCheckpointAction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override DebugCollectLogsRedaction Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, FactoryPauseCheckpointAction value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, DebugCollectLogsRedaction value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryPauseCheckpointAction)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(DebugCollectLogsRedaction)); } } } @@ -35122,7 +34302,7 @@ public PermissionModeSource(string value) /// The mode was set at startup by the `defaultPermissionMode` user setting. public static PermissionModeSource UserSetting { get; } = new("user_setting"); - /// The mode was set at startup by authenticated organization targeting. + /// Historical compatibility value for runtimes that selected Assisted mode through organization targeting. Current runtimes do not produce this source. public static PermissionModeSource OrganizationTargeting { get; } = new("organization_targeting"); /// The mode was set through an RPC caller. @@ -38585,20 +37765,20 @@ internal SessionRpc(CopilotSession session) Interlocked.CompareExchange(ref field, new(_session), null) ?? field; - /// Debug APIs. - public DebugApi Debug => + /// Accounts APIs. + public AccountsApi Accounts => field ?? Interlocked.CompareExchange(ref field, new(_session), null) ?? field; - /// Canvas APIs. - public CanvasApi Canvas => + /// Debug APIs. + public DebugApi Debug => field ?? Interlocked.CompareExchange(ref field, new(_session), null) ?? field; - /// Factory APIs. - public FactoryApi Factory => + /// Canvas APIs. + public CanvasApi Canvas => field ?? Interlocked.CompareExchange(ref field, new(_session), null) ?? field; @@ -39161,6 +38341,113 @@ internal async Task> LastAuthErrorsAsync(Cancellation } } +/// Provides session-scoped Accounts APIs. +[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] +public sealed class AccountsApi +{ + private readonly CopilotSession _session; + + internal AccountsApi(CopilotSession session) + { + _session = session; + } + + /// Enumerate a typed accounts collection: the signed-in accounts, or the providers offered for interactive login. + /// Which typed accounts collection to enumerate. + /// The to monitor for cancellation requests. The default is . + /// The enumerated collection, keyed by the same selector as the query. + public async Task EnumerateAsync(AuthEnumerateQuery query, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(query); + _session.ThrowIfDisposed(); + + var request = new AccountsEnumerateRequest { SessionId = _session.SessionId, Query = query }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.accounts.enumerate", [request], cancellationToken); + } + + /// Read one typed accounts datum: the active account, a neutral status summary, or the last authentication errors. + /// Which typed accounts datum to read. + /// The to monitor for cancellation requests. The default is . + /// The read result, keyed by the same selector as the query. + public async Task GetAsync(AuthReadQuery query, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(query); + _session.ThrowIfDisposed(); + + var request = new AccountsGetRequest { SessionId = _session.SessionId, Query = query }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.accounts.get", [request], cancellationToken); + } + + /// Apply one non-interactive accounts mutation: switch the active account, log an account out, or set credentials from a token. + /// The non-interactive mutation command to apply. + /// The to monitor for cancellation requests. The default is . + /// Result of a non-interactive accounts mutation. + public async Task SetAsync(AuthWrite command, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(command); + _session.ThrowIfDisposed(); + + var request = new AccountsSetRequest { SessionId = _session.SessionId, Command = command }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.accounts.set", [request], cancellationToken); + } + + /// Login APIs. + public AccountsLoginApi Login => + field ?? + Interlocked.CompareExchange(ref field, new(_session), null) ?? + field; +} + +/// Provides session-scoped AccountsLogin APIs. +[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] +public sealed class AccountsLoginApi +{ + private readonly CopilotSession _session; + + internal AccountsLoginApi(CopilotSession session) + { + _session = session; + } + + /// Begin an interactive login flow for a provider kind (dispatch is kind-only) and return its opaque flow id and first step. + /// The provider kind to sign in with. + /// The to monitor for cancellation requests. The default is . + /// A started login flow: its opaque id and first step. + public async Task BeginAsync(LoginProviderKind kind, CancellationToken cancellationToken = default) + { + _session.ThrowIfDisposed(); + + var request = new AuthLoginBeginRequest { SessionId = _session.SessionId, Kind = kind }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.accounts.login.begin", [request], cancellationToken); + } + + /// Advance an in-flight login flow, optionally fulfilling an input-required step, and return the next step. + /// Opaque flow id from begin. + /// Neutral input fulfilling a preceding input-required step (e.g. a GHEC host); ignored otherwise. + /// The to monitor for cancellation requests. The default is . + /// One step in an interactive login flow. The consumer acts on the step and calls advance to proceed. Browser-open is encoded as two distinct steps by design: `open-url` is CONSUMER-driven (the provider surfaces the authorize URL and the consumer opens it — github.com/GHEC web), while `needs-interaction` is PROVIDER-driven (the provider opens the browser or broker UI itself and does not surface a URL — Entra). + public async Task AdvanceAsync(string flowId, string? input = null, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(flowId); + _session.ThrowIfDisposed(); + + var request = new AuthLoginAdvanceRequest { SessionId = _session.SessionId, FlowId = flowId, Input = input }; + return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.accounts.login.advance", [request], cancellationToken); + } + + /// Cancel an in-flight login flow and release its resources. + /// Opaque flow id from begin. + /// The to monitor for cancellation requests. The default is . + public async Task CancelAsync(string flowId, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(flowId); + _session.ThrowIfDisposed(); + + var request = new AuthLoginCancelRequest { SessionId = _session.SessionId, FlowId = flowId }; + await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.accounts.login.cancel", [request], cancellationToken); + } +} + /// Provides session-scoped Debug APIs. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed class DebugApi @@ -39331,271 +38618,6 @@ internal async Task UnregisterAsync(string connectionId, CancellationToken cance } } -/// Provides session-scoped Factory APIs. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryApi -{ - private readonly CopilotSession _session; - - internal FactoryApi(CopilotSession session) - { - _session = session; - } - - /// Runs a registered factory by name at the top level. - /// Registered factory name. - /// Factory input value. - /// Factory invocation options. - /// The to monitor for cancellation requests. The default is . - /// Complete current or terminal factory run envelope. - public async Task RunAsync(string name, object args, RunOptions? options = null, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(name); - ArgumentNullException.ThrowIfNull(args); - _session.ThrowIfDisposed(); - - var request = new FactoryRunRequest { SessionId = _session.SessionId, Name = name, Args = CopilotClient.ToJsonElementForWire(args)!.Value, Options = options }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.run", [request], cancellationToken); - } - - /// Resumes a factory run using its persisted name, arguments, journal, and accounting. - /// Factory run identifier. - /// Optional per-invocation resource ceiling overrides. - /// Whether to notify the originating session when the factory completes. - /// Whether to emit factory phase names to the session transcript. - /// The to monitor for cancellation requests. The default is . - /// Resolved persisted factory identity and resumed run envelope. - public async Task ResumeAsync(string runId, FactoryRunLimits? limits = null, bool? notifyOnComplete = null, bool? logPhaseNames = null, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(runId); - _session.ThrowIfDisposed(); - - var request = new FactoryResumeRequest { SessionId = _session.SessionId, RunId = runId, Limits = limits, NotifyOnComplete = notifyOnComplete, LogPhaseNames = logPhaseNames }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.resume", [request], cancellationToken); - } - - /// Internal tool-originated factory invocation. - /// Registered factory name. - /// Factory input value. - /// Tool-originated factory invocation options. - /// Opaque identifier of the originating tool call. - /// The to monitor for cancellation requests. The default is . - /// Complete current or terminal factory run envelope. - internal async Task RunFromToolAsync(string name, object args, FactoryToolRunOptions? options = null, string? toolCallId = null, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(name); - ArgumentNullException.ThrowIfNull(args); - _session.ThrowIfDisposed(); - - var request = new FactoryToolRunRequest { SessionId = _session.SessionId, Name = name, Args = CopilotClient.ToJsonElementForWire(args)!.Value, Options = options, ToolCallId = toolCallId }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.runFromTool", [request], cancellationToken); - } - - /// Internal tool-originated factory resume. - /// Factory run identifier. - /// Optional per-invocation resource ceiling overrides. - /// Opaque identifier of the originating tool call. - /// The to monitor for cancellation requests. The default is . - /// Resolved persisted factory identity and resumed run envelope. - internal async Task ResumeFromToolAsync(string runId, FactoryRunLimits? limits = null, string? toolCallId = null, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(runId); - _session.ThrowIfDisposed(); - - var request = new FactoryToolResumeRequest { SessionId = _session.SessionId, RunId = runId, Limits = limits, ToolCallId = toolCallId }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.resumeFromTool", [request], cancellationToken); - } - - /// Gets the current or settled envelope for a factory run. - /// Factory run identifier. - /// The to monitor for cancellation requests. The default is . - /// Complete current or terminal factory run envelope. - public async Task GetRunAsync(string runId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(runId); - _session.ThrowIfDisposed(); - - var request = new FactoryGetRunRequest { SessionId = _session.SessionId, RunId = runId }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.getRun", [request], cancellationToken); - } - - /// Lists durable factory runs for this session in creation order. - /// Exclusive forward cursor. - /// Exclusive backward cursor. - /// Maximum terminal runs to return. Defaults to 200 and is capped at 500. - /// The to monitor for cancellation requests. The default is . - /// A page of factory runs in durable creation order. - public async Task ListRunsAsync(long? afterSeq = null, long? beforeSeq = null, int? limit = null, CancellationToken cancellationToken = default) - { - _session.ThrowIfDisposed(); - - var request = new FactoryListRunsRequest { SessionId = _session.SessionId, AfterSeq = afterSeq, BeforeSeq = beforeSeq, Limit = limit }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.listRuns", [request], cancellationToken); - } - - /// Gets durable and live observability detail for one factory run. - /// Factory run identifier. - /// The to monitor for cancellation requests. The default is . - /// Full factory run observability detail. - public async Task GetRunDetailAsync(string runId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(runId); - _session.ThrowIfDisposed(); - - var request = new FactoryGetRunRequest { SessionId = _session.SessionId, RunId = runId }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.getRunDetail", [request], cancellationToken); - } - - /// Pages durable progress for one factory run. - /// Factory run identifier. - /// Optional phase identifier used to scope records and cursors. - /// Exclusive forward cursor. - /// Exclusive backward cursor. - /// Maximum records to return. Defaults to 200 and is capped at 500. - /// The to monitor for cancellation requests. The default is . - /// A bidirectional page of factory progress. - public async Task GetRunProgressAsync(string runId, string? phaseId = null, long? afterSeq = null, long? beforeSeq = null, int? limit = null, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(runId); - _session.ThrowIfDisposed(); - - var request = new FactoryGetRunProgressRequest { SessionId = _session.SessionId, RunId = runId, PhaseId = phaseId, AfterSeq = afterSeq, BeforeSeq = beforeSeq, Limit = limit }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.getRunProgress", [request], cancellationToken); - } - - /// Requests cancellation of a factory run and returns its run envelope. - /// Factory run identifier. - /// The to monitor for cancellation requests. The default is . - /// Complete current or terminal factory run envelope. - public async Task CancelAsync(string runId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(runId); - _session.ThrowIfDisposed(); - - var request = new FactoryCancelRequest { SessionId = _session.SessionId, RunId = runId }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.cancel", [request], cancellationToken); - } - - /// Pauses a running factory and returns its settled run envelope. - /// Factory run identifier. - /// The to monitor for cancellation requests. The default is . - /// Complete current or terminal factory run envelope. - public async Task PauseAsync(string runId, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(runId); - _session.ThrowIfDisposed(); - - var request = new FactoryPauseRequest { SessionId = _session.SessionId, RunId = runId }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.pause", [request], cancellationToken); - } - - /// Atomically pauses an owned factory attempt at a durable checkpoint. - /// Factory run identifier. - /// Opaque token identifying the execution attempt that reached the checkpoint. - /// Stable author-defined checkpoint key. - /// The to monitor for cancellation requests. The default is . - internal async Task PauseAtCheckpointAsync(string runId, string executionToken, string key, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(runId); - ArgumentNullException.ThrowIfNull(executionToken); - ArgumentNullException.ThrowIfNull(key); - _session.ThrowIfDisposed(); - - var request = new FactoryPauseCheckpointRequest { SessionId = _session.SessionId, RunId = runId, ExecutionToken = executionToken, Key = key }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.pauseAtCheckpoint", [request], cancellationToken); - } - - /// Records a batch of ordered factory progress lines. - /// Factory run identifier. - /// Opaque token identifying the current factory execution attempt. - /// Ordered progress lines to append. - /// The to monitor for cancellation requests. The default is . - /// Acknowledgement that a factory request was accepted. - public async Task LogAsync(string runId, string executionToken, IList lines, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(runId); - ArgumentNullException.ThrowIfNull(executionToken); - ArgumentNullException.ThrowIfNull(lines); - _session.ThrowIfDisposed(); - - var request = new FactoryLogRequest { SessionId = _session.SessionId, RunId = runId, ExecutionToken = executionToken, Lines = lines }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.log", [request], cancellationToken); - } - - /// Runs one factory-scoped subagent and returns its result. - /// Factory run identifier that owns the subagent. - /// Opaque token identifying the current factory execution attempt. - /// Prompt to send to the subagent. - /// Subagent execution options. - /// The to monitor for cancellation requests. The default is . - /// Result of one factory-scoped subagent call. - public async Task AgentAsync(string factoryRunId, string executionToken, string prompt, FactoryAgentOptions opts, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(factoryRunId); - ArgumentNullException.ThrowIfNull(executionToken); - ArgumentNullException.ThrowIfNull(prompt); - ArgumentNullException.ThrowIfNull(opts); - _session.ThrowIfDisposed(); - - var request = new FactoryAgentRequest { SessionId = _session.SessionId, FactoryRunId = factoryRunId, ExecutionToken = executionToken, Prompt = prompt, Opts = opts }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.agent", [request], cancellationToken); - } - - /// Journal APIs. - public FactoryJournalApi Journal => - field ?? - Interlocked.CompareExchange(ref field, new(_session), null) ?? - field; -} - -/// Provides session-scoped FactoryJournal APIs. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed class FactoryJournalApi -{ - private readonly CopilotSession _session; - - internal FactoryJournalApi(CopilotSession session) - { - _session = session; - } - - /// Reads a memoized factory journal entry. - /// Factory run identifier. - /// Opaque token identifying the current factory execution attempt. - /// Namespaced journal key. - /// The to monitor for cancellation requests. The default is . - /// Result of reading a factory journal entry. - public async Task GetAsync(string runId, string executionToken, string key, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(runId); - ArgumentNullException.ThrowIfNull(executionToken); - ArgumentNullException.ThrowIfNull(key); - _session.ThrowIfDisposed(); - - var request = new FactoryJournalGetRequest { SessionId = _session.SessionId, RunId = runId, ExecutionToken = executionToken, Key = key }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.journal.get", [request], cancellationToken); - } - - /// Stores a memoized factory journal entry. - /// Factory run identifier. - /// Opaque token identifying the current factory execution attempt. - /// Namespaced journal key. - /// JSON result to memoize. - /// The to monitor for cancellation requests. The default is . - /// Acknowledgement that a factory request was accepted. - public async Task PutAsync(string runId, string executionToken, string key, object resultJson, CancellationToken cancellationToken = default) - { - ArgumentNullException.ThrowIfNull(runId); - ArgumentNullException.ThrowIfNull(executionToken); - ArgumentNullException.ThrowIfNull(key); - ArgumentNullException.ThrowIfNull(resultJson); - _session.ThrowIfDisposed(); - - var request = new FactoryJournalPutRequest { SessionId = _session.SessionId, RunId = runId, ExecutionToken = executionToken, Key = key, ResultJson = CopilotClient.ToJsonElementForWire(resultJson)!.Value }; - return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.factory.journal.put", [request], cancellationToken); - } -} - /// Provides session-scoped Workflow APIs. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed class WorkflowApi @@ -39934,13 +38956,15 @@ public async Task SwitchAutoTierAsync(AutoTier? autoT /// Auto routing preference selected by repository settings, when configured. Applied only when the overlay selects the Auto model; beside a concrete model it stays dormant. /// Model explicitly selected by the CLI, when provided. /// Whether the overlay is being applied while resuming a deferred session. + /// Reasoning effort paired with the effective organization-managed model. Applies only when that concrete managed model is selected; it is ignored for Auto and for CLI, resume, or user overrides. + /// Context tier paired with the effective organization-managed model. Applies only when that concrete managed model is selected; it is ignored for Auto and for CLI, resume, or user overrides. /// The to monitor for cancellation requests. The default is . /// The model identifier active on the session after the switch. - internal async Task ApplyStartupOverlayAsync(string? deviceManagedModel = null, string? serverManagedModel = null, string? policyHelperModel = null, AutoTier? autoTier = null, string? repoModel = null, string? repoReasoningEffort = null, string? repoContextTier = null, string? repoAutoTier = null, string? cliModel = null, bool? deferredResume = null, CancellationToken cancellationToken = default) + internal async Task ApplyStartupOverlayAsync(string? deviceManagedModel = null, string? serverManagedModel = null, string? policyHelperModel = null, AutoTier? autoTier = null, string? repoModel = null, string? repoReasoningEffort = null, string? repoContextTier = null, string? repoAutoTier = null, string? cliModel = null, bool? deferredResume = null, string? managedReasoningEffort = null, string? managedContextTier = null, CancellationToken cancellationToken = default) { _session.ThrowIfDisposed(); - var request = new ModelApplyStartupOverlayRequest { SessionId = _session.SessionId, DeviceManagedModel = deviceManagedModel, ServerManagedModel = serverManagedModel, PolicyHelperModel = policyHelperModel, AutoTier = autoTier, RepoModel = repoModel, RepoReasoningEffort = repoReasoningEffort, RepoContextTier = repoContextTier, RepoAutoTier = repoAutoTier, CliModel = cliModel, DeferredResume = deferredResume }; + var request = new ModelApplyStartupOverlayRequest { SessionId = _session.SessionId, DeviceManagedModel = deviceManagedModel, ServerManagedModel = serverManagedModel, PolicyHelperModel = policyHelperModel, AutoTier = autoTier, RepoModel = repoModel, RepoReasoningEffort = repoReasoningEffort, RepoContextTier = repoContextTier, RepoAutoTier = repoAutoTier, CliModel = cliModel, DeferredResume = deferredResume, ManagedReasoningEffort = managedReasoningEffort, ManagedContextTier = managedContextTier }; return await CopilotClient.InvokeRpcAsync(_session.Rpc, "session.model.applyStartupOverlay", [request], cancellationToken); } @@ -43838,22 +42862,6 @@ public interface IProviderTokenHandler Task GetTokenAsync(ProviderTokenAcquireRequest request, CancellationToken cancellationToken = default); } -/// Handles `factory` client session API methods. -[Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public interface IFactoryHandler -{ - /// Asks the owning extension connection to execute a registered factory closure. - /// Parameters sent to the owning extension to execute a factory closure. - /// The to monitor for cancellation requests. The default is . - /// Result returned by an extension factory closure. - Task ExecuteAsync(FactoryExecuteRequest request, CancellationToken cancellationToken = default); - /// Asks the owning extension connection to abort a running factory cooperatively. - /// Parameters for cooperatively aborting a factory body. - /// The to monitor for cancellation requests. The default is . - /// Acknowledgement that a factory request was accepted. - Task AbortAsync(FactoryAbortRequest request, CancellationToken cancellationToken = default); -} - /// Handles `workflow` client session API methods. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public interface IWorkflowHandler @@ -43978,9 +42986,6 @@ public sealed class ClientSessionApiHandlers /// Optional handler for ProviderToken client session API methods. public IProviderTokenHandler? ProviderToken { get; set; } - /// Optional handler for Factory client session API methods. - public IFactoryHandler? Factory { get; set; } - /// Optional handler for Workflow client session API methods. public IWorkflowHandler? Workflow { get; set; } @@ -44010,18 +43015,6 @@ public static void RegisterClientSessionApiHandlers(JsonRpc rpc, Func>)(async (request, cancellationToken) => - { - var handler = getHandlers(request.SessionId).Factory; - if (handler is null) throw new InvalidOperationException($"No factory handler registered for session: {request.SessionId}"); - return await handler.ExecuteAsync(request, cancellationToken); - }), singleObjectParam: true); - rpc.SetLocalRpcMethod("factory.abort", (Func>)(async (request, cancellationToken) => - { - var handler = getHandlers(request.SessionId).Factory; - if (handler is null) throw new InvalidOperationException($"No factory handler registered for session: {request.SessionId}"); - return await handler.AbortAsync(request, cancellationToken); - }), singleObjectParam: true); rpc.SetLocalRpcMethod("workflow.execute", (Func>)(async (request, cancellationToken) => { var handler = getHandlers(request.SessionId).Workflow; @@ -44393,15 +43386,6 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.ExternalToolCompletedEvent), TypeInfoPropertyName = "SessionEventsExternalToolCompletedEvent")] [JsonSerializable(typeof(GitHub.Copilot.ExternalToolRequestedData), TypeInfoPropertyName = "SessionEventsExternalToolRequestedData")] [JsonSerializable(typeof(GitHub.Copilot.ExternalToolRequestedEvent), TypeInfoPropertyName = "SessionEventsExternalToolRequestedEvent")] -[JsonSerializable(typeof(GitHub.Copilot.FactoryPermissionOperation), TypeInfoPropertyName = "SessionEventsFactoryPermissionOperation")] -[JsonSerializable(typeof(GitHub.Copilot.FactoryPermissionPhase), TypeInfoPropertyName = "SessionEventsFactoryPermissionPhase")] -[JsonSerializable(typeof(GitHub.Copilot.FactoryRunSettledData), TypeInfoPropertyName = "SessionEventsFactoryRunSettledData")] -[JsonSerializable(typeof(GitHub.Copilot.FactoryRunSettledEvent), TypeInfoPropertyName = "SessionEventsFactoryRunSettledEvent")] -[JsonSerializable(typeof(GitHub.Copilot.FactoryRunSettledStatus), TypeInfoPropertyName = "SessionEventsFactoryRunSettledStatus")] -[JsonSerializable(typeof(GitHub.Copilot.FactoryRunStartedData), TypeInfoPropertyName = "SessionEventsFactoryRunStartedData")] -[JsonSerializable(typeof(GitHub.Copilot.FactoryRunStartedEvent), TypeInfoPropertyName = "SessionEventsFactoryRunStartedEvent")] -[JsonSerializable(typeof(GitHub.Copilot.FactoryRunUpdatedData), TypeInfoPropertyName = "SessionEventsFactoryRunUpdatedData")] -[JsonSerializable(typeof(GitHub.Copilot.FactoryRunUpdatedEvent), TypeInfoPropertyName = "SessionEventsFactoryRunUpdatedEvent")] [JsonSerializable(typeof(GitHub.Copilot.FusionAttribution), TypeInfoPropertyName = "SessionEventsFusionAttribution")] [JsonSerializable(typeof(GitHub.Copilot.FusionConversationScope), TypeInfoPropertyName = "SessionEventsFusionConversationScope")] [JsonSerializable(typeof(GitHub.Copilot.FusionFollowUpAction), TypeInfoPropertyName = "SessionEventsFusionFollowUpAction")] @@ -44507,7 +43491,6 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequestExtensionEnvAccess), TypeInfoPropertyName = "SessionEventsPermissionPromptRequestExtensionEnvAccess")] [JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequestExtensionManagement), TypeInfoPropertyName = "SessionEventsPermissionPromptRequestExtensionManagement")] [JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequestExtensionPermissionAccess), TypeInfoPropertyName = "SessionEventsPermissionPromptRequestExtensionPermissionAccess")] -[JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequestFactory), TypeInfoPropertyName = "SessionEventsPermissionPromptRequestFactory")] [JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequestHook), TypeInfoPropertyName = "SessionEventsPermissionPromptRequestHook")] [JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequestMcp), TypeInfoPropertyName = "SessionEventsPermissionPromptRequestMcp")] [JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequestMemory), TypeInfoPropertyName = "SessionEventsPermissionPromptRequestMemory")] @@ -44515,6 +43498,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequestPathAccessKind), TypeInfoPropertyName = "SessionEventsPermissionPromptRequestPathAccessKind")] [JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequestRead), TypeInfoPropertyName = "SessionEventsPermissionPromptRequestRead")] [JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequestUrl), TypeInfoPropertyName = "SessionEventsPermissionPromptRequestUrl")] +[JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequestWorkflow), TypeInfoPropertyName = "SessionEventsPermissionPromptRequestWorkflow")] [JsonSerializable(typeof(GitHub.Copilot.PermissionPromptRequestWrite), TypeInfoPropertyName = "SessionEventsPermissionPromptRequestWrite")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRecommendation), TypeInfoPropertyName = "SessionEventsPermissionRecommendation")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRecoveryAttempt), TypeInfoPropertyName = "SessionEventsPermissionRecoveryAttempt")] @@ -44530,7 +43514,6 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestExtensionEnvAccess), TypeInfoPropertyName = "SessionEventsPermissionRequestExtensionEnvAccess")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestExtensionManagement), TypeInfoPropertyName = "SessionEventsPermissionRequestExtensionManagement")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestExtensionPermissionAccess), TypeInfoPropertyName = "SessionEventsPermissionRequestExtensionPermissionAccess")] -[JsonSerializable(typeof(GitHub.Copilot.PermissionRequestFactory), TypeInfoPropertyName = "SessionEventsPermissionRequestFactory")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestHook), TypeInfoPropertyName = "SessionEventsPermissionRequestHook")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestMcp), TypeInfoPropertyName = "SessionEventsPermissionRequestMcp")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestMemory), TypeInfoPropertyName = "SessionEventsPermissionRequestMemory")] @@ -44543,6 +43526,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestShellCommandSegment), TypeInfoPropertyName = "SessionEventsPermissionRequestShellCommandSegment")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestShellPossibleUrl), TypeInfoPropertyName = "SessionEventsPermissionRequestShellPossibleUrl")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestUrl), TypeInfoPropertyName = "SessionEventsPermissionRequestUrl")] +[JsonSerializable(typeof(GitHub.Copilot.PermissionRequestWorkflow), TypeInfoPropertyName = "SessionEventsPermissionRequestWorkflow")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestWrite), TypeInfoPropertyName = "SessionEventsPermissionRequestWrite")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestedData), TypeInfoPropertyName = "SessionEventsPermissionRequestedData")] [JsonSerializable(typeof(GitHub.Copilot.PermissionRequestedEvent), TypeInfoPropertyName = "SessionEventsPermissionRequestedEvent")] @@ -44631,14 +43615,14 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.SystemNotificationAgentIdle), TypeInfoPropertyName = "SessionEventsSystemNotificationAgentIdle")] [JsonSerializable(typeof(GitHub.Copilot.SystemNotificationData), TypeInfoPropertyName = "SessionEventsSystemNotificationData")] [JsonSerializable(typeof(GitHub.Copilot.SystemNotificationEvent), TypeInfoPropertyName = "SessionEventsSystemNotificationEvent")] -[JsonSerializable(typeof(GitHub.Copilot.SystemNotificationFactoryCompleted), TypeInfoPropertyName = "SessionEventsSystemNotificationFactoryCompleted")] -[JsonSerializable(typeof(GitHub.Copilot.SystemNotificationFactoryCompletedStatus), TypeInfoPropertyName = "SessionEventsSystemNotificationFactoryCompletedStatus")] -[JsonSerializable(typeof(GitHub.Copilot.SystemNotificationFactoryPauseInfo), TypeInfoPropertyName = "SessionEventsSystemNotificationFactoryPauseInfo")] [JsonSerializable(typeof(GitHub.Copilot.SystemNotificationInstructionDiscovered), TypeInfoPropertyName = "SessionEventsSystemNotificationInstructionDiscovered")] [JsonSerializable(typeof(GitHub.Copilot.SystemNotificationNewInboxMessage), TypeInfoPropertyName = "SessionEventsSystemNotificationNewInboxMessage")] [JsonSerializable(typeof(GitHub.Copilot.SystemNotificationShellCompleted), TypeInfoPropertyName = "SessionEventsSystemNotificationShellCompleted")] [JsonSerializable(typeof(GitHub.Copilot.SystemNotificationShellDetachedCompleted), TypeInfoPropertyName = "SessionEventsSystemNotificationShellDetachedCompleted")] [JsonSerializable(typeof(GitHub.Copilot.SystemNotificationUnclassified), TypeInfoPropertyName = "SessionEventsSystemNotificationUnclassified")] +[JsonSerializable(typeof(GitHub.Copilot.SystemNotificationWorkflowCompleted), TypeInfoPropertyName = "SessionEventsSystemNotificationWorkflowCompleted")] +[JsonSerializable(typeof(GitHub.Copilot.SystemNotificationWorkflowCompletedStatus), TypeInfoPropertyName = "SessionEventsSystemNotificationWorkflowCompletedStatus")] +[JsonSerializable(typeof(GitHub.Copilot.SystemNotificationWorkflowPauseInfo), TypeInfoPropertyName = "SessionEventsSystemNotificationWorkflowPauseInfo")] [JsonSerializable(typeof(GitHub.Copilot.TaskBlocker), TypeInfoPropertyName = "SessionEventsTaskBlocker")] [JsonSerializable(typeof(GitHub.Copilot.TaskBlockerKind), TypeInfoPropertyName = "SessionEventsTaskBlockerKind")] [JsonSerializable(typeof(GitHub.Copilot.TaskCompletionOutcome), TypeInfoPropertyName = "SessionEventsTaskCompletionOutcome")] @@ -44700,12 +43684,21 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalExtensionEnvAccess), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalExtensionEnvAccess")] [JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalExtensionManagement), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalExtensionManagement")] [JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalExtensionPermissionAccess), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalExtensionPermissionAccess")] -[JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalFactory), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalFactory")] [JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalMcp), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalMcp")] [JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalMemory), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalMemory")] [JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalRead), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalRead")] +[JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalWorkflow), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalWorkflow")] [JsonSerializable(typeof(GitHub.Copilot.UserToolSessionApprovalWrite), TypeInfoPropertyName = "SessionEventsUserToolSessionApprovalWrite")] [JsonSerializable(typeof(GitHub.Copilot.Verbosity), TypeInfoPropertyName = "SessionEventsVerbosity")] +[JsonSerializable(typeof(GitHub.Copilot.WorkflowPermissionOperation), TypeInfoPropertyName = "SessionEventsWorkflowPermissionOperation")] +[JsonSerializable(typeof(GitHub.Copilot.WorkflowPermissionPhase), TypeInfoPropertyName = "SessionEventsWorkflowPermissionPhase")] +[JsonSerializable(typeof(GitHub.Copilot.WorkflowRunSettledData), TypeInfoPropertyName = "SessionEventsWorkflowRunSettledData")] +[JsonSerializable(typeof(GitHub.Copilot.WorkflowRunSettledEvent), TypeInfoPropertyName = "SessionEventsWorkflowRunSettledEvent")] +[JsonSerializable(typeof(GitHub.Copilot.WorkflowRunSettledStatus), TypeInfoPropertyName = "SessionEventsWorkflowRunSettledStatus")] +[JsonSerializable(typeof(GitHub.Copilot.WorkflowRunStartedData), TypeInfoPropertyName = "SessionEventsWorkflowRunStartedData")] +[JsonSerializable(typeof(GitHub.Copilot.WorkflowRunStartedEvent), TypeInfoPropertyName = "SessionEventsWorkflowRunStartedEvent")] +[JsonSerializable(typeof(GitHub.Copilot.WorkflowRunUpdatedData), TypeInfoPropertyName = "SessionEventsWorkflowRunUpdatedData")] +[JsonSerializable(typeof(GitHub.Copilot.WorkflowRunUpdatedEvent), TypeInfoPropertyName = "SessionEventsWorkflowRunUpdatedEvent")] [JsonSerializable(typeof(GitHub.Copilot.WorkingDirectoryContext), TypeInfoPropertyName = "SessionEventsWorkingDirectoryContext")] [JsonSerializable(typeof(GitHub.Copilot.WorkingDirectoryContextHostType), TypeInfoPropertyName = "SessionEventsWorkingDirectoryContextHostType")] [JsonSerializable(typeof(GitHub.Copilot.WorkspaceFileChangedOperation), TypeInfoPropertyName = "SessionEventsWorkspaceFileChangedOperation")] @@ -44720,6 +43713,10 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(AccountLogoutRequest))] [JsonSerializable(typeof(AccountLogoutResult))] [JsonSerializable(typeof(AccountQuotaSnapshot))] +[JsonSerializable(typeof(AccountStatus))] +[JsonSerializable(typeof(AccountsEnumerateRequest))] +[JsonSerializable(typeof(AccountsGetRequest))] +[JsonSerializable(typeof(AccountsSetRequest))] [JsonSerializable(typeof(AgentDiscoveryPath))] [JsonSerializable(typeof(AgentDiscoveryPathList))] [JsonSerializable(typeof(AgentGetCurrentResult))] @@ -44735,9 +43732,22 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(AgentSetPromptRequest))] [JsonSerializable(typeof(AgentsDiscoverRequest))] [JsonSerializable(typeof(AgentsGetDiscoveryPathsRequest))] +[JsonSerializable(typeof(AuthEnumerateQuery))] +[JsonSerializable(typeof(AuthEnumerateValue))] [JsonSerializable(typeof(AuthIdentity))] [JsonSerializable(typeof(AuthInfo))] +[JsonSerializable(typeof(AuthLoginAdvanceRequest))] +[JsonSerializable(typeof(AuthLoginBeginRequest))] +[JsonSerializable(typeof(AuthLoginBegun))] +[JsonSerializable(typeof(AuthLoginCancelRequest))] +[JsonSerializable(typeof(AuthLoginResultDto))] +[JsonSerializable(typeof(AuthLoginStep))] +[JsonSerializable(typeof(AuthReadQuery))] +[JsonSerializable(typeof(AuthReadValue))] +[JsonSerializable(typeof(AuthStatusDto))] [JsonSerializable(typeof(AuthValidationError))] +[JsonSerializable(typeof(AuthWrite))] +[JsonSerializable(typeof(AuthWriteResult))] [JsonSerializable(typeof(AutopilotObjectiveCreditLimit))] [JsonSerializable(typeof(AutopilotObjectiveGetStateResult))] [JsonSerializable(typeof(AutopilotObjectiveState))] @@ -44867,45 +43877,6 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(ExternalToolTextResultForLlmBinaryResultsForLlm))] [JsonSerializable(typeof(ExternalToolTextResultForLlmContent))] [JsonSerializable(typeof(ExternalToolTextResultForLlmContentResourceLinkIcon))] -[JsonSerializable(typeof(FactoryAbortRequest))] -[JsonSerializable(typeof(FactoryAckResult))] -[JsonSerializable(typeof(FactoryAgentOptions))] -[JsonSerializable(typeof(FactoryAgentRequest))] -[JsonSerializable(typeof(FactoryAgentResult))] -[JsonSerializable(typeof(FactoryAgentSummary))] -[JsonSerializable(typeof(FactoryCancelRequest))] -[JsonSerializable(typeof(FactoryCurrentPhase))] -[JsonSerializable(typeof(FactoryDeclaredLimits))] -[JsonSerializable(typeof(FactoryExecuteRequest))] -[JsonSerializable(typeof(FactoryExecuteResult))] -[JsonSerializable(typeof(FactoryGetRunProgressRequest))] -[JsonSerializable(typeof(FactoryGetRunRequest))] -[JsonSerializable(typeof(FactoryJournalGetRequest))] -[JsonSerializable(typeof(FactoryJournalGetResult))] -[JsonSerializable(typeof(FactoryJournalPutRequest))] -[JsonSerializable(typeof(FactoryListRunsRequest))] -[JsonSerializable(typeof(FactoryListRunsResult))] -[JsonSerializable(typeof(FactoryLogLine))] -[JsonSerializable(typeof(FactoryLogRequest))] -[JsonSerializable(typeof(FactoryPauseCheckpointRequest))] -[JsonSerializable(typeof(FactoryPauseInfo))] -[JsonSerializable(typeof(FactoryPauseRequest))] -[JsonSerializable(typeof(FactoryPhaseObservation))] -[JsonSerializable(typeof(FactoryProgressLine))] -[JsonSerializable(typeof(FactoryProgressPage))] -[JsonSerializable(typeof(FactoryResumeRequest))] -[JsonSerializable(typeof(FactoryResumeResult))] -[JsonSerializable(typeof(FactoryRunConsumed))] -[JsonSerializable(typeof(FactoryRunDetail))] -[JsonSerializable(typeof(FactoryRunFailure))] -[JsonSerializable(typeof(FactoryRunLimits))] -[JsonSerializable(typeof(FactoryRunRequest))] -[JsonSerializable(typeof(FactoryRunResult))] -[JsonSerializable(typeof(FactoryRunSummary))] -[JsonSerializable(typeof(FactoryRunTerminal))] -[JsonSerializable(typeof(FactoryToolResumeRequest))] -[JsonSerializable(typeof(FactoryToolRunOptions))] -[JsonSerializable(typeof(FactoryToolRunRequest))] [JsonSerializable(typeof(FleetStartRequest))] [JsonSerializable(typeof(FleetStartResult))] [JsonSerializable(typeof(FolderTrustAddParams))] @@ -45233,6 +44204,7 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(ProviderAddResult))] [JsonSerializable(typeof(ProviderConfig))] [JsonSerializable(typeof(ProviderConfigAzure))] +[JsonSerializable(typeof(ProviderDescriptor))] [JsonSerializable(typeof(ProviderEndpoint))] [JsonSerializable(typeof(ProviderModelConfig))] [JsonSerializable(typeof(ProviderSessionToken))] @@ -45295,7 +44267,6 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(RemoteSessionMetadataRepository))] [JsonSerializable(typeof(RemoteSessionMetadataValue))] [JsonSerializable(typeof(ResponseFormat))] -[JsonSerializable(typeof(RunOptions))] [JsonSerializable(typeof(SandboxConfig))] [JsonSerializable(typeof(SandboxConfigAuth))] [JsonSerializable(typeof(SandboxConfigUserPolicy))] @@ -45362,7 +44333,6 @@ public static void RegisterClientGlobalApiHandlers(JsonRpc rpc, ClientGlobalApiH [JsonSerializable(typeof(SessionEventLogTailRequest))] [JsonSerializable(typeof(SessionExtensionsListRequest))] [JsonSerializable(typeof(SessionExtensionsReloadRequest))] -[JsonSerializable(typeof(SessionFactoryPauseAtCheckpointResult))] [JsonSerializable(typeof(SessionFsAppendFileRequest))] [JsonSerializable(typeof(SessionFsError))] [JsonSerializable(typeof(SessionFsExistsRequest))] diff --git a/dotnet/src/Generated/SessionEvents.cs b/dotnet/src/Generated/SessionEvents.cs index 5c3618c35d..c7646d208d 100644 --- a/dotnet/src/Generated/SessionEvents.cs +++ b/dotnet/src/Generated/SessionEvents.cs @@ -57,9 +57,6 @@ namespace GitHub.Copilot; [JsonDerivedType(typeof(ExitPlanModeRequestedEvent), "exit_plan_mode.requested")] [JsonDerivedType(typeof(ExternalToolCompletedEvent), "external_tool.completed")] [JsonDerivedType(typeof(ExternalToolRequestedEvent), "external_tool.requested")] -[JsonDerivedType(typeof(FactoryRunSettledEvent), "factory.run_settled")] -[JsonDerivedType(typeof(FactoryRunStartedEvent), "factory.run_started")] -[JsonDerivedType(typeof(FactoryRunUpdatedEvent), "factory.run_updated")] [JsonDerivedType(typeof(HookEndEvent), "hook.end")] [JsonDerivedType(typeof(HookProgressEvent), "hook.progress")] [JsonDerivedType(typeof(HookStartEvent), "hook.start")] @@ -173,6 +170,9 @@ namespace GitHub.Copilot; [JsonDerivedType(typeof(UserInputCompletedEvent), "user_input.completed")] [JsonDerivedType(typeof(UserInputRequestedEvent), "user_input.requested")] [JsonDerivedType(typeof(UserMessageEvent), "user.message")] +[JsonDerivedType(typeof(WorkflowRunSettledEvent), "workflow.run_settled")] +[JsonDerivedType(typeof(WorkflowRunStartedEvent), "workflow.run_started")] +[JsonDerivedType(typeof(WorkflowRunUpdatedEvent), "workflow.run_updated")] public partial class SessionEvent { /// Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. @@ -1426,7 +1426,7 @@ public sealed partial class PermissionCompletedEvent : SessionEvent public required PermissionCompletedData Data { get; set; } } -/// Records that a live authorization record from an earlier human decision in this session contained a permission proposal, so it ran without another prompt. This mints no authority: it accounts for one more effect against the prior grant, which is what lets a replayed session agree with the live one about how much of that grant is left. +/// Historical decode-only receipt from the retired Assisted Permissions authorization extractor. Current runtimes ignore it for permission decisions. /// Represents the permission.carriedForward event. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed partial class PermissionCarriedForwardEvent : SessionEvent @@ -1440,7 +1440,7 @@ public sealed partial class PermissionCarriedForwardEvent : SessionEvent public required PermissionCarriedForwardData Data { get; set; } } -/// Freezes one blinded, verbatim-verified authorization claim the runtime minted from a human user message, so a resumed session re-establishes the same grant deterministically instead of re-running the extraction model. This mints no authority on its own: it records what a blinded proposer pointed at and the trusted discriminator the runtime established, and deterministic establishment runs on replay. Persisted so recorded authority survives compaction and process resume. +/// Historical decode-only claim from the retired Assisted Permissions authorization extractor. Current runtimes preserve the payload but do not establish authority from it. /// Represents the permission.messageAuthorization event. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed partial class PermissionMessageAuthorizationEvent : SessionEvent @@ -1454,7 +1454,7 @@ public sealed partial class PermissionMessageAuthorizationEvent : SessionEvent public required PermissionMessageAuthorizationData Data { get; set; } } -/// Records that one human turn has been read by the blinded authorization proposer, whether or not it minted anything, so a resumed session does not re-run the extraction model on a turn the live session already read. Also records whether that pass activates ongoing extraction; contextual-assent-only passes do not, so unrelated future messages remain outside extraction. +/// Historical decode-only extractor progress marker. Current runtimes do not run or resume extraction from it. /// Represents the permission.messageAuthorizationRead event. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed partial class PermissionMessageAuthorizationReadEvent : SessionEvent @@ -1468,7 +1468,7 @@ public sealed partial class PermissionMessageAuthorizationReadEvent : SessionEve public required PermissionMessageAuthorizationReadData Data { get; set; } } -/// Records that message-backed authorization could not safely represent one human turn before compaction. The runtime may compact the original message after this marker is durable, but message-derived carry-forward and assisted auto-approval remain disabled for the rest of the session so subsequent commands continue through the ordinary permission prompt. +/// Historical decode-only degradation marker from the retired extractor. Current runtimes ignore it for permission decisions. /// Represents the permission.messageAuthorizationDegraded event. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed partial class PermissionMessageAuthorizationDegradedEvent : SessionEvent @@ -1482,7 +1482,7 @@ public sealed partial class PermissionMessageAuthorizationDegradedEvent : Sessio public required PermissionMessageAuthorizationDegradedData Data { get; set; } } -/// Records that deterministic text recognition found likely assent in the human turn immediately following a root Autopilot permission request that was blocked because no interactive response was available. This event grants no authority; its model-facing projection only suggests retrying the unchanged operation. +/// Historical decode-only contextual-assent marker. Current runtimes do not project it into the conversation or permission flow. /// Represents the permission.assentDetected event. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed partial class PermissionAssentDetectedEvent : SessionEvent @@ -1496,7 +1496,7 @@ public sealed partial class PermissionAssentDetectedEvent : SessionEvent public required PermissionAssentDetectedData Data { get; set; } } -/// Freezes a blinded contextual authorization proposal whose verbatim human span was deterministically bound to the immediately preceding blocked permission request. The event carries no action fields; replay re-derives the exact action from the earlier permission request and mints a one-shot message grant only when the binding and span still verify. +/// Historical decode-only contextual authorization claim. Current runtimes preserve the payload but do not establish authority from it. /// Represents the permission.contextualAuthorization event. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed partial class PermissionContextualAuthorizationEvent : SessionEvent @@ -1904,46 +1904,46 @@ public sealed partial class SessionBackgroundTasksChangedEvent : SessionEvent public required SessionBackgroundTasksChangedData Data { get; set; } } -/// Ephemeral invalidation signal for a changed factory run. -/// Represents the factory.run_updated event. +/// Ephemeral invalidation signal for a changed workflow run. +/// Represents the workflow.run_updated event. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed partial class FactoryRunUpdatedEvent : SessionEvent +public sealed partial class WorkflowRunUpdatedEvent : SessionEvent { /// [JsonIgnore] - public override string Type => "factory.run_updated"; + public override string Type => "workflow.run_updated"; - /// The factory.run_updated event payload. + /// The workflow.run_updated event payload. [JsonPropertyName("data")] - public required FactoryRunUpdatedData Data { get; set; } + public required WorkflowRunUpdatedData Data { get; set; } } -/// Ephemeral signal that a factory run attempt began executing. -/// Represents the factory.run_started event. +/// Ephemeral signal that a workflow run attempt began executing. +/// Represents the workflow.run_started event. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed partial class FactoryRunStartedEvent : SessionEvent +public sealed partial class WorkflowRunStartedEvent : SessionEvent { /// [JsonIgnore] - public override string Type => "factory.run_started"; + public override string Type => "workflow.run_started"; - /// The factory.run_started event payload. + /// The workflow.run_started event payload. [JsonPropertyName("data")] - public required FactoryRunStartedData Data { get; set; } + public required WorkflowRunStartedData Data { get; set; } } -/// Ephemeral signal that a factory run reached a terminal status. -/// Represents the factory.run_settled event. +/// Ephemeral signal that a workflow run reached a terminal status. +/// Represents the workflow.run_settled event. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed partial class FactoryRunSettledEvent : SessionEvent +public sealed partial class WorkflowRunSettledEvent : SessionEvent { /// [JsonIgnore] - public override string Type => "factory.run_settled"; + public override string Type => "workflow.run_settled"; - /// The factory.run_settled event payload. + /// The workflow.run_settled event payload. [JsonPropertyName("data")] - public required FactoryRunSettledData Data { get; set; } + public required WorkflowRunSettledData Data { get; set; } } /// Payload of `session.skills_loaded` listing resolved skill metadata. @@ -3105,12 +3105,18 @@ public sealed partial class SessionCompactionStartData /// Conversation compaction results including success status, metrics, and optional error details. public sealed partial class SessionCompactionCompleteData { - /// Authoritative active-factory reminder appended to the compacted context. + /// Legacy active-workflow reminder retained for replay compatibility. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonInclude] [JsonPropertyName("activeFactorySummary")] internal string? ActiveFactorySummary { get; set; } + /// Authoritative active-workflow reminder appended to the compacted context. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonInclude] + [JsonPropertyName("activeWorkflowSummary")] + internal string? ActiveWorkflowSummary { get; set; } + /// Canonical model identifier used for model-specific behavior when replaying compaction. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("behaviorModelId")] @@ -5228,7 +5234,7 @@ public sealed partial class SubagentStartedData [JsonPropertyName("executionMode")] public string? ExecutionMode { get; set; } - /// Root id of the factory run that spawned this sub-agent, when it was spawned by one. + /// Legacy root id of the workflow run that spawned this sub-agent. New consumers should use workflowRunId. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("factoryRunId")] public string? FactoryRunId { get; set; } @@ -5253,7 +5259,7 @@ public sealed partial class SubagentStartedData [JsonPropertyName("resumable")] public bool? Resumable { get; set; } - /// Where the model input for this sub-agent came from. Present when the task planner resolved the launch (the task tool and factory agents); absent for sub-agents created through other runtime paths. + /// Where the model input for this sub-agent came from. Present when the task planner resolved the launch (the task tool and workflow agents); absent for sub-agents created through other runtime paths. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("taskModelSource")] public SubagentTaskModelSource? TaskModelSource { get; set; } @@ -5261,6 +5267,11 @@ public sealed partial class SubagentStartedData /// Tool call ID of the parent tool invocation that spawned this sub-agent. [JsonPropertyName("toolCallId")] public required string ToolCallId { get; set; } + + /// Root id of the workflow run that spawned this sub-agent, when it was spawned by one. + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("workflowRunId")] + public string? WorkflowRunId { get; set; } } /// Resolved runtime configuration for a configured sub-agent. @@ -5684,7 +5695,7 @@ public sealed partial class PermissionCompletedData public string? ToolCallId { get; set; } } -/// Records that a live authorization record from an earlier human decision in this session contained a permission proposal, so it ran without another prompt. This mints no authority: it accounts for one more effect against the prior grant, which is what lets a replayed session agree with the live one about how much of that grant is left. +/// Historical decode-only receipt from the retired Assisted Permissions authorization extractor. Current runtimes ignore it for permission decisions. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed partial class PermissionCarriedForwardData { @@ -5709,7 +5720,7 @@ public sealed partial class PermissionCarriedForwardData public required string ToolCallId { get; set; } } -/// Freezes one blinded, verbatim-verified authorization claim the runtime minted from a human user message, so a resumed session re-establishes the same grant deterministically instead of re-running the extraction model. This mints no authority on its own: it records what a blinded proposer pointed at and the trusted discriminator the runtime established, and deterministic establishment runs on replay. Persisted so recorded authority survives compaction and process resume. +/// Historical decode-only claim from the retired Assisted Permissions authorization extractor. Current runtimes preserve the payload but do not establish authority from it. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed partial class PermissionMessageAuthorizationData { @@ -5762,7 +5773,7 @@ public sealed partial class PermissionMessageAuthorizationData public JsonElement? World { get; set; } } -/// Records that one human turn has been read by the blinded authorization proposer, whether or not it minted anything, so a resumed session does not re-run the extraction model on a turn the live session already read. Also records whether that pass activates ongoing extraction; contextual-assent-only passes do not, so unrelated future messages remain outside extraction. +/// Historical decode-only extractor progress marker. Current runtimes do not run or resume extraction from it. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed partial class PermissionMessageAuthorizationReadData { @@ -5778,7 +5789,7 @@ public sealed partial class PermissionMessageAuthorizationReadData public required long TurnIndex { get; set; } } -/// Records that message-backed authorization could not safely represent one human turn before compaction. The runtime may compact the original message after this marker is durable, but message-derived carry-forward and assisted auto-approval remain disabled for the rest of the session so subsequent commands continue through the ordinary permission prompt. +/// Historical decode-only degradation marker from the retired extractor. Current runtimes ignore it for permission decisions. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed partial class PermissionMessageAuthorizationDegradedData { @@ -5788,7 +5799,7 @@ public sealed partial class PermissionMessageAuthorizationDegradedData public required long TurnIndex { get; set; } } -/// Records that deterministic text recognition found likely assent in the human turn immediately following a root Autopilot permission request that was blocked because no interactive response was available. This event grants no authority; its model-facing projection only suggests retrying the unchanged operation. +/// Historical decode-only contextual-assent marker. Current runtimes do not project it into the conversation or permission flow. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed partial class PermissionAssentDetectedData { @@ -5803,7 +5814,7 @@ public sealed partial class PermissionAssentDetectedData public required long TurnIndex { get; set; } } -/// Freezes a blinded contextual authorization proposal whose verbatim human span was deterministically bound to the immediately preceding blocked permission request. The event carries no action fields; replay re-derives the exact action from the earlier permission request and mints a one-shot message grant only when the binding and span still verify. +/// Historical decode-only contextual authorization claim. Current runtimes preserve the payload but do not establish authority from it. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] public sealed partial class PermissionContextualAuthorizationData { @@ -6501,39 +6512,39 @@ public sealed partial class SessionBackgroundTasksChangedData { } -/// Ephemeral invalidation signal for a changed factory run. +/// Ephemeral invalidation signal for a changed workflow run. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed partial class FactoryRunUpdatedData +public sealed partial class WorkflowRunUpdatedData { /// Monotonic revision now available for the run. [JsonPropertyName("revision")] public required long Revision { get; set; } - /// Factory run identifier. + /// Workflow run identifier. [JsonPropertyName("runId")] public required string RunId { get; set; } } -/// Ephemeral signal that a factory run attempt began executing. +/// Ephemeral signal that a workflow run attempt began executing. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed partial class FactoryRunStartedData +public sealed partial class WorkflowRunStartedData { /// Attempt number this start committed; a resumed run increments it. [JsonPropertyName("attempt")] public required long Attempt { get; set; } - /// Name of the factory this run executes. Low cardinality by construction. - [JsonPropertyName("factoryName")] - public required string FactoryName { get; set; } - - /// Identifier of the factory run that started. + /// Identifier of the workflow run that started. [JsonPropertyName("runId")] public required string RunId { get; set; } + + /// Name of the workflow this run executes. Low cardinality by construction. + [JsonPropertyName("workflowName")] + public required string WorkflowName { get; set; } } -/// Ephemeral signal that a factory run reached a terminal status. +/// Ephemeral signal that a workflow run reached a terminal status. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] -public sealed partial class FactoryRunSettledData +public sealed partial class WorkflowRunSettledData { /// AI credits this run consumed, in nano-AIU. [JsonPropertyName("consumedNanoAiu")] @@ -6547,18 +6558,18 @@ public sealed partial class FactoryRunSettledData [JsonPropertyName("elapsedMs")] public required long ElapsedMs { get; set; } - /// Typed failure class recorded on the run, when it failed with one (e.g. `factory_limit_reached`). + /// Typed failure class recorded on the run, when it failed with one (e.g. `workflow_limit_reached`). [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("failureType")] public string? FailureType { get; set; } - /// Identifier of the factory run that settled. + /// Identifier of the workflow run that settled. [JsonPropertyName("runId")] public required string RunId { get; set; } /// Terminal status the run committed. [JsonPropertyName("status")] - public required FactoryRunSettledStatus Status { get; set; } + public required WorkflowRunSettledStatus Status { get; set; } } /// Payload of `session.skills_loaded` listing resolved skill metadata. @@ -10063,16 +10074,16 @@ public sealed partial class SystemNotificationInstructionDiscovered : SystemNoti public required string TriggerTool { get; set; } } -/// The user variant of . -public sealed partial class SystemNotificationFactoryPauseInfoUser : SystemNotificationFactoryPauseInfo +/// The user variant of . +public sealed partial class SystemNotificationWorkflowPauseInfoUser : SystemNotificationWorkflowPauseInfo { /// [JsonIgnore] public override string Type => "user"; } -/// The checkpoint variant of . -public sealed partial class SystemNotificationFactoryPauseInfoCheckpoint : SystemNotificationFactoryPauseInfo +/// The checkpoint variant of . +public sealed partial class SystemNotificationWorkflowPauseInfoCheckpoint : SystemNotificationWorkflowPauseInfo { /// [JsonIgnore] @@ -10083,14 +10094,14 @@ public sealed partial class SystemNotificationFactoryPauseInfoCheckpoint : Syste public required string Key { get; set; } } -/// Durable metadata describing who initiated a factory pause. +/// Durable metadata describing who initiated a workflow pause. /// Polymorphic base type discriminated by type. [JsonPolymorphic( TypeDiscriminatorPropertyName = "type", UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FallBackToBaseType)] -[JsonDerivedType(typeof(SystemNotificationFactoryPauseInfoUser), "user")] -[JsonDerivedType(typeof(SystemNotificationFactoryPauseInfoCheckpoint), "checkpoint")] -public partial class SystemNotificationFactoryPauseInfo +[JsonDerivedType(typeof(SystemNotificationWorkflowPauseInfoUser), "user")] +[JsonDerivedType(typeof(SystemNotificationWorkflowPauseInfoCheckpoint), "checkpoint")] +public partial class SystemNotificationWorkflowPauseInfo { /// The type discriminator. [JsonPropertyName("type")] @@ -10098,13 +10109,13 @@ public partial class SystemNotificationFactoryPauseInfo } -/// System notification metadata for a factory execution attempt that reached a terminal state. -/// The factory_completed variant of . -public sealed partial class SystemNotificationFactoryCompleted : SystemNotification +/// System notification metadata for a workflow execution attempt that reached a terminal state. +/// The workflow_completed variant of . +public sealed partial class SystemNotificationWorkflowCompleted : SystemNotification { /// [JsonIgnore] - public override string Type => "factory_completed"; + public override string Type => "workflow_completed"; /// Execution attempt that reached this terminal state. [JsonPropertyName("attempt")] @@ -10122,10 +10133,6 @@ public sealed partial class SystemNotificationFactoryCompleted : SystemNotificat [JsonPropertyName("elapsedMs")] public required long ElapsedMs { get; set; } - /// Persisted factory name. - [JsonPropertyName("factoryName")] - public required string FactoryName { get; set; } - /// Machine-readable terminal failure details, when present. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("failure")] @@ -10134,7 +10141,7 @@ public sealed partial class SystemNotificationFactoryCompleted : SystemNotificat /// Pause initiator metadata when this attempt settled as paused. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("pauseInfo")] - public SystemNotificationFactoryPauseInfo? PauseInfo { get; set; } + public SystemNotificationWorkflowPauseInfo? PauseInfo { get; set; } /// Bounded prompt-safe preview of the completed result. [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Safe for generated string properties: JSON Schema minLength/maxLength map to string length validation, not reflection over trimmed Count members")] @@ -10143,18 +10150,22 @@ public sealed partial class SystemNotificationFactoryCompleted : SystemNotificat [JsonPropertyName("resultPreview")] public string? ResultPreview { get; set; } - /// Actionable run_factory resume guidance for a resource-limit failure. + /// Actionable run_dynamic_workflow resume guidance for a resource-limit failure. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("retryGuidance")] public string? RetryGuidance { get; set; } - /// Factory run identifier. + /// Workflow run identifier. [JsonPropertyName("runId")] public required string RunId { get; set; } /// Terminal status reached by this execution attempt. [JsonPropertyName("status")] - public required SystemNotificationFactoryCompletedStatus Status { get; set; } + public required SystemNotificationWorkflowCompletedStatus Status { get; set; } + + /// Persisted workflow name. + [JsonPropertyName("workflowName")] + public required string WorkflowName { get; set; } } /// System notification metadata from an external host that does not match a runtime-owned notification kind. @@ -10182,7 +10193,7 @@ public sealed partial class SystemNotificationUnclassified : SystemNotification [JsonDerivedType(typeof(SystemNotificationShellCompleted), "shell_completed")] [JsonDerivedType(typeof(SystemNotificationShellDetachedCompleted), "shell_detached_completed")] [JsonDerivedType(typeof(SystemNotificationInstructionDiscovered), "instruction_discovered")] -[JsonDerivedType(typeof(SystemNotificationFactoryCompleted), "factory_completed")] +[JsonDerivedType(typeof(SystemNotificationWorkflowCompleted), "workflow_completed")] [JsonDerivedType(typeof(SystemNotificationUnclassified), "unclassified")] public partial class SystemNotification { @@ -10703,9 +10714,9 @@ public sealed partial class PermissionRequestExtensionManagement : PermissionReq public string? ToolCallId { get; set; } } -/// A declared phase shown in a factory permission prompt. -/// Nested data type for FactoryPermissionPhase. -public sealed partial class FactoryPermissionPhase +/// A declared phase shown in a workflow permission prompt. +/// Nested data type for WorkflowPermissionPhase. +public sealed partial class WorkflowPermissionPhase { /// Optional phase detail. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -10717,46 +10728,55 @@ public sealed partial class FactoryPermissionPhase public required string Title { get; set; } } -/// Factory run or authoring permission request. -/// The factory variant of . -public sealed partial class PermissionRequestFactory : PermissionRequest +/// Workflow run or authoring permission request. +/// The workflow variant of . +public sealed partial class PermissionRequestWorkflow : PermissionRequest { /// [JsonIgnore] - public override string Kind => "factory"; + public override string Kind => "workflow"; - /// Canonical key used for scoped factory approvals. + /// Canonical key used for scoped workflow approvals. [JsonPropertyName("approvalKey")] public required string ApprovalKey { get; set; } - /// Whether this factory is eligible for persistent approval. + /// Whether this workflow is eligible for persistent approval. [JsonPropertyName("canPersistApproval")] public required bool CanPersistApproval { get; set; } - /// Factory-declared AI-credit limit before any run/resume caller override is applied. + /// Workflow-declared AI-credit limit before any run/resume caller override is applied. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("declaredMaxAiCredits")] public double? DeclaredMaxAiCredits { get; set; } - /// Factory-declared concurrent-subagent limit before any run/resume caller override is applied. + /// Workflow-declared concurrent-subagent limit before any run/resume caller override is applied. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("declaredMaxConcurrentSubagents")] public long? DeclaredMaxConcurrentSubagents { get; set; } - /// Factory-declared total-subagent limit before any run/resume caller override is applied. + /// Workflow-declared total-subagent limit before any run/resume caller override is applied. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("declaredMaxTotalSubagents")] public long? DeclaredMaxTotalSubagents { get; set; } - /// Factory-declared active-time limit in seconds before any run/resume caller override is applied. + /// Workflow-declared active-time limit in seconds before any run/resume caller override is applied. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("declaredTimeoutSeconds")] public double? DeclaredTimeoutSeconds { get; set; } - /// Factory description. + /// Workflow description. [JsonPropertyName("description")] public required string Description { get; set; } + /// + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + [JsonPropertyName("managedApprovalRequired")] + public override bool? ManagedApprovalRequired + { + get => base.ManagedApprovalRequired; + set => base.ManagedApprovalRequired = value; + } + /// Effective AI-credit limit; omitted means unlimited. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("maxAiCredits")] @@ -10772,17 +10792,17 @@ public sealed partial class PermissionRequestFactory : PermissionRequest [JsonPropertyName("maxTotalSubagents")] public long? MaxTotalSubagents { get; set; } - /// Factory name. + /// Workflow name. [JsonPropertyName("name")] public required string Name { get; set; } - /// Factory operation, either run or author. + /// Workflow operation, either run or author. [JsonPropertyName("operation")] - public required FactoryPermissionOperation Operation { get; set; } + public required WorkflowPermissionOperation Operation { get; set; } - /// Declared factory phases. + /// Declared workflow phases. [JsonPropertyName("phases")] - public required FactoryPermissionPhase[] Phases { get; set; } + public required WorkflowPermissionPhase[] Phases { get; set; } /// Effective active-time limit in seconds; omitted means unlimited. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -10853,7 +10873,7 @@ public sealed partial class PermissionRequestExtensionEnvAccess : PermissionRequ [JsonDerivedType(typeof(PermissionRequestCustomTool), "custom-tool")] [JsonDerivedType(typeof(PermissionRequestHook), "hook")] [JsonDerivedType(typeof(PermissionRequestExtensionManagement), "extension-management")] -[JsonDerivedType(typeof(PermissionRequestFactory), "factory")] +[JsonDerivedType(typeof(PermissionRequestWorkflow), "workflow")] [JsonDerivedType(typeof(PermissionRequestExtensionPermissionAccess), "extension-permission-access")] [JsonDerivedType(typeof(PermissionRequestExtensionEnvAccess), "extension-env-access")] public partial class PermissionRequest @@ -11290,15 +11310,15 @@ public sealed partial class PermissionPromptRequestExtensionManagement : Permiss public string? ToolCallId { get; set; } } -/// Factory run or authoring permission prompt. -/// The factory variant of . -public sealed partial class PermissionPromptRequestFactory : PermissionPromptRequest +/// Workflow run or authoring permission prompt. +/// The workflow variant of . +public sealed partial class PermissionPromptRequestWorkflow : PermissionPromptRequest { /// [JsonIgnore] - public override string Kind => "factory"; + public override string Kind => "workflow"; - /// Canonical key used for scoped factory approvals. + /// Canonical key used for scoped workflow approvals. [JsonPropertyName("approvalKey")] public required string ApprovalKey { get; set; } @@ -11308,31 +11328,31 @@ public sealed partial class PermissionPromptRequestFactory : PermissionPromptReq [JsonPropertyName("assistedApproval")] public PermissionAssistedApproval? AssistedApproval { get; set; } - /// Whether this factory is eligible for persistent approval. + /// Whether this workflow is eligible for persistent approval. [JsonPropertyName("canPersistApproval")] public required bool CanPersistApproval { get; set; } - /// Factory-declared AI-credit limit before any run/resume caller override is applied. + /// Workflow-declared AI-credit limit before any run/resume caller override is applied. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("declaredMaxAiCredits")] public double? DeclaredMaxAiCredits { get; set; } - /// Factory-declared concurrent-subagent limit before any run/resume caller override is applied. + /// Workflow-declared concurrent-subagent limit before any run/resume caller override is applied. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("declaredMaxConcurrentSubagents")] public long? DeclaredMaxConcurrentSubagents { get; set; } - /// Factory-declared total-subagent limit before any run/resume caller override is applied. + /// Workflow-declared total-subagent limit before any run/resume caller override is applied. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("declaredMaxTotalSubagents")] public long? DeclaredMaxTotalSubagents { get; set; } - /// Factory-declared active-time limit in seconds before any run/resume caller override is applied. + /// Workflow-declared active-time limit in seconds before any run/resume caller override is applied. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("declaredTimeoutSeconds")] public double? DeclaredTimeoutSeconds { get; set; } - /// Factory description. + /// Workflow description. [JsonPropertyName("description")] public required string Description { get; set; } @@ -11356,17 +11376,17 @@ public sealed partial class PermissionPromptRequestFactory : PermissionPromptReq [JsonPropertyName("maxTotalSubagents")] public long? MaxTotalSubagents { get; set; } - /// Factory name. + /// Workflow name. [JsonPropertyName("name")] public required string Name { get; set; } - /// Factory operation, either run or author. + /// Workflow operation, either run or author. [JsonPropertyName("operation")] - public required FactoryPermissionOperation Operation { get; set; } + public required WorkflowPermissionOperation Operation { get; set; } - /// Declared factory phases. + /// Declared workflow phases. [JsonPropertyName("phases")] - public required FactoryPermissionPhase[] Phases { get; set; } + public required WorkflowPermissionPhase[] Phases { get; set; } /// Effective active-time limit in seconds; omitted means unlimited. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] @@ -11450,7 +11470,7 @@ public sealed partial class PermissionPromptRequestExtensionEnvAccess : Permissi [JsonDerivedType(typeof(PermissionPromptRequestPath), "path")] [JsonDerivedType(typeof(PermissionPromptRequestHook), "hook")] [JsonDerivedType(typeof(PermissionPromptRequestExtensionManagement), "extension-management")] -[JsonDerivedType(typeof(PermissionPromptRequestFactory), "factory")] +[JsonDerivedType(typeof(PermissionPromptRequestWorkflow), "workflow")] [JsonDerivedType(typeof(PermissionPromptRequestExtensionPermissionAccess), "extension-permission-access")] [JsonDerivedType(typeof(PermissionPromptRequestExtensionEnvAccess), "extension-env-access")] public partial class PermissionPromptRequest @@ -11559,15 +11579,15 @@ public sealed partial class UserToolSessionApprovalExtensionManagement : UserToo public string? Operation { get; set; } } -/// Session-scoped factory approval, optionally narrowed by approval key. -/// The factory variant of . -public sealed partial class UserToolSessionApprovalFactory : UserToolSessionApproval +/// Session-scoped workflow approval, optionally narrowed by approval key. +/// The workflow variant of . +public sealed partial class UserToolSessionApprovalWorkflow : UserToolSessionApproval { /// [JsonIgnore] - public override string Kind => "factory"; + public override string Kind => "workflow"; - /// Optional factory operation name or canonical approval key. + /// Optional workflow operation name or canonical approval key. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] [JsonPropertyName("approvalKey")] public string? ApprovalKey { get; set; } @@ -11615,7 +11635,7 @@ public sealed partial class UserToolSessionApprovalExtensionEnvAccess : UserTool [JsonDerivedType(typeof(UserToolSessionApprovalMemory), "memory")] [JsonDerivedType(typeof(UserToolSessionApprovalCustomTool), "custom-tool")] [JsonDerivedType(typeof(UserToolSessionApprovalExtensionManagement), "extension-management")] -[JsonDerivedType(typeof(UserToolSessionApprovalFactory), "factory")] +[JsonDerivedType(typeof(UserToolSessionApprovalWorkflow), "workflow")] [JsonDerivedType(typeof(UserToolSessionApprovalExtensionPermissionAccess), "extension-permission-access")] [JsonDerivedType(typeof(UserToolSessionApprovalExtensionEnvAccess), "extension-env-access")] public partial class UserToolSessionApproval @@ -13260,6 +13280,9 @@ public ModelChangeSource(string value) /// An SDK or RPC caller selected the model. public static ModelChangeSource Sdk { get; } = new("sdk"); + /// The user accepted a CAPI-issued Auto tier recommendation. + public static ModelChangeSource AutoTierRecommendation { get; } = new("auto_tier_recommendation"); + /// Returns a value indicating whether two instances are equivalent. public static bool operator ==(ModelChangeSource left, ModelChangeSource right) => left.Equals(right); @@ -17873,51 +17896,51 @@ public override void Write(Utf8JsonWriter writer, SystemNotificationAgentComplet } } -/// Terminal status reached by a factory execution attempt. +/// Terminal status reached by a workflow execution attempt. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct SystemNotificationFactoryCompletedStatus : IEquatable +public readonly struct SystemNotificationWorkflowCompletedStatus : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public SystemNotificationFactoryCompletedStatus(string value) + public SystemNotificationWorkflowCompletedStatus(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The factory completed successfully. - public static SystemNotificationFactoryCompletedStatus Completed { get; } = new("completed"); + /// The workflow completed successfully. + public static SystemNotificationWorkflowCompletedStatus Completed { get; } = new("completed"); - /// The factory was halted. - public static SystemNotificationFactoryCompletedStatus Halted { get; } = new("halted"); + /// The workflow was halted. + public static SystemNotificationWorkflowCompletedStatus Halted { get; } = new("halted"); - /// The factory attempt paused intentionally. - public static SystemNotificationFactoryCompletedStatus Paused { get; } = new("paused"); + /// The workflow attempt paused intentionally. + public static SystemNotificationWorkflowCompletedStatus Paused { get; } = new("paused"); - /// The factory was cancelled. - public static SystemNotificationFactoryCompletedStatus Cancelled { get; } = new("cancelled"); + /// The workflow was cancelled. + public static SystemNotificationWorkflowCompletedStatus Cancelled { get; } = new("cancelled"); - /// The factory failed. - public static SystemNotificationFactoryCompletedStatus Error { get; } = new("error"); + /// The workflow failed. + public static SystemNotificationWorkflowCompletedStatus Error { get; } = new("error"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(SystemNotificationFactoryCompletedStatus left, SystemNotificationFactoryCompletedStatus right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(SystemNotificationWorkflowCompletedStatus left, SystemNotificationWorkflowCompletedStatus right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(SystemNotificationFactoryCompletedStatus left, SystemNotificationFactoryCompletedStatus right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(SystemNotificationWorkflowCompletedStatus left, SystemNotificationWorkflowCompletedStatus right) => !(left == right); /// - public override bool Equals(object? obj) => obj is SystemNotificationFactoryCompletedStatus other && Equals(other); + public override bool Equals(object? obj) => obj is SystemNotificationWorkflowCompletedStatus other && Equals(other); /// - public bool Equals(SystemNotificationFactoryCompletedStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(SystemNotificationWorkflowCompletedStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -17925,20 +17948,20 @@ public SystemNotificationFactoryCompletedStatus(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override SystemNotificationFactoryCompletedStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override SystemNotificationWorkflowCompletedStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, SystemNotificationFactoryCompletedStatus value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, SystemNotificationWorkflowCompletedStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SystemNotificationFactoryCompletedStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(SystemNotificationWorkflowCompletedStatus)); } } } @@ -18600,42 +18623,42 @@ public override void Write(Utf8JsonWriter writer, PermissionRequestMemoryScope v } } -/// Operation gated by a factory permission request. +/// Operation gated by a workflow permission request. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct FactoryPermissionOperation : IEquatable +public readonly struct WorkflowPermissionOperation : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public FactoryPermissionOperation(string value) + public WorkflowPermissionOperation(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// Running a registered factory, which spends subagents, active time, and AI credits under the approved limits. - public static FactoryPermissionOperation Run { get; } = new("run"); + /// Running a registered workflow, which spends subagents, active time, and AI credits under the approved limits. + public static WorkflowPermissionOperation Run { get; } = new("run"); - /// Authoring a factory, which writes JavaScript into a session-scoped extension and loads it. - public static FactoryPermissionOperation Author { get; } = new("author"); + /// Authoring a workflow, which writes JavaScript into a session-scoped extension and loads it. + public static WorkflowPermissionOperation Author { get; } = new("author"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(FactoryPermissionOperation left, FactoryPermissionOperation right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(WorkflowPermissionOperation left, WorkflowPermissionOperation right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(FactoryPermissionOperation left, FactoryPermissionOperation right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(WorkflowPermissionOperation left, WorkflowPermissionOperation right) => !(left == right); /// - public override bool Equals(object? obj) => obj is FactoryPermissionOperation other && Equals(other); + public override bool Equals(object? obj) => obj is WorkflowPermissionOperation other && Equals(other); /// - public bool Equals(FactoryPermissionOperation other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(WorkflowPermissionOperation other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -18643,20 +18666,20 @@ public FactoryPermissionOperation(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override FactoryPermissionOperation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override WorkflowPermissionOperation Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, FactoryPermissionOperation value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, WorkflowPermissionOperation value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryPermissionOperation)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkflowPermissionOperation)); } } } @@ -18756,7 +18779,7 @@ public PermissionDecisionSource(string value) /// The host denied the request because no interactive user response was available. public static PermissionDecisionSource UnattendedFallback { get; } = new("unattended_fallback"); - /// A live authorization record from an earlier human decision in this session contained the proposal, so it ran without another prompt. This is not a new human decision and never mints authority of its own. + /// Historical compatibility value for sessions created while authorization carry-forward was executable. Current runtimes do not produce this source. public static PermissionDecisionSource AuthorizationCarryForward { get; } = new("authorization_carry_forward"); /// Returns a value indicating whether two instances are equivalent. @@ -18795,7 +18818,7 @@ public override void Write(Utf8JsonWriter writer, PermissionDecisionSource value } } -/// Which direction a message-backed authorization claim moves authority in. +/// Direction stored in a historical extractor claim. Current runtimes do not apply it. [Experimental(global::GitHub.Copilot.Diagnostics.Experimental)] [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] @@ -18815,10 +18838,10 @@ public PermissionMessageAuthorizationPolarity(string value) /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The human's words authorized an effect. + /// Historical claim recorded as a grant. public static PermissionMessageAuthorizationPolarity Grant { get; } = new("grant"); - /// The human's words refused an effect. + /// Historical claim recorded as a denial. public static PermissionMessageAuthorizationPolarity Denial { get; } = new("denial"); /// Returns a value indicating whether two instances are equivalent. @@ -19778,51 +19801,51 @@ public override void Write(Utf8JsonWriter writer, ExitPlanModeAction value, Json } } -/// Terminal status a factory run committed. A settled run is never `pending` or `running`, so those two members of the run-status domain are deliberately absent. +/// Terminal status a workflow run committed. A settled run is never `pending` or `running`, so those two members of the run-status domain are deliberately absent. [JsonConverter(typeof(Converter))] [DebuggerDisplay("{Value,nq}")] -public readonly struct FactoryRunSettledStatus : IEquatable +public readonly struct WorkflowRunSettledStatus : IEquatable { private readonly string? _value; - /// Initializes a new instance of the struct. - /// The value to associate with this . + /// Initializes a new instance of the struct. + /// The value to associate with this . [JsonConstructor] - public FactoryRunSettledStatus(string value) + public WorkflowRunSettledStatus(string value) { ArgumentException.ThrowIfNullOrWhiteSpace(value); _value = value; } - /// Gets the value associated with this . + /// Gets the value associated with this . public string Value => _value ?? string.Empty; - /// The factory body resolved and its result was committed. - public static FactoryRunSettledStatus Completed { get; } = new("completed"); + /// The workflow body resolved and its result was committed. + public static WorkflowRunSettledStatus Completed { get; } = new("completed"); /// The run was stopped by a limit, an approval refusal or another policy decision. - public static FactoryRunSettledStatus Halted { get; } = new("halted"); + public static WorkflowRunSettledStatus Halted { get; } = new("halted"); /// The attempt paused intentionally while preserving resumable run state. - public static FactoryRunSettledStatus Paused { get; } = new("paused"); + public static WorkflowRunSettledStatus Paused { get; } = new("paused"); /// The run was cancelled by its caller or by session disposal. - public static FactoryRunSettledStatus Cancelled { get; } = new("cancelled"); + public static WorkflowRunSettledStatus Cancelled { get; } = new("cancelled"); /// The run failed, with `failureType` carrying the class when it has one. - public static FactoryRunSettledStatus Error { get; } = new("error"); + public static WorkflowRunSettledStatus Error { get; } = new("error"); - /// Returns a value indicating whether two instances are equivalent. - public static bool operator ==(FactoryRunSettledStatus left, FactoryRunSettledStatus right) => left.Equals(right); + /// Returns a value indicating whether two instances are equivalent. + public static bool operator ==(WorkflowRunSettledStatus left, WorkflowRunSettledStatus right) => left.Equals(right); - /// Returns a value indicating whether two instances are not equivalent. - public static bool operator !=(FactoryRunSettledStatus left, FactoryRunSettledStatus right) => !(left == right); + /// Returns a value indicating whether two instances are not equivalent. + public static bool operator !=(WorkflowRunSettledStatus left, WorkflowRunSettledStatus right) => !(left == right); /// - public override bool Equals(object? obj) => obj is FactoryRunSettledStatus other && Equals(other); + public override bool Equals(object? obj) => obj is WorkflowRunSettledStatus other && Equals(other); /// - public bool Equals(FactoryRunSettledStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); + public bool Equals(WorkflowRunSettledStatus other) => string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase); /// public override int GetHashCode() => StringComparer.OrdinalIgnoreCase.GetHashCode(Value); @@ -19830,20 +19853,20 @@ public FactoryRunSettledStatus(string value) /// public override string ToString() => Value; - /// Provides a for serializing instances. + /// Provides a for serializing instances. [EditorBrowsable(EditorBrowsableState.Never)] - public sealed class Converter : JsonConverter + public sealed class Converter : JsonConverter { /// - public override FactoryRunSettledStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override WorkflowRunSettledStatus Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return new(GeneratedStringEnumJson.ReadValue(ref reader, typeToConvert)); } /// - public override void Write(Utf8JsonWriter writer, FactoryRunSettledStatus value, JsonSerializerOptions options) + public override void Write(Utf8JsonWriter writer, WorkflowRunSettledStatus value, JsonSerializerOptions options) { - GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(FactoryRunSettledStatus)); + GeneratedStringEnumJson.WriteValue(writer, value.Value, typeof(WorkflowRunSettledStatus)); } } } @@ -20322,13 +20345,6 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(ExternalToolCompletedEvent))] [JsonSerializable(typeof(ExternalToolRequestedData))] [JsonSerializable(typeof(ExternalToolRequestedEvent))] -[JsonSerializable(typeof(FactoryPermissionPhase))] -[JsonSerializable(typeof(FactoryRunSettledData))] -[JsonSerializable(typeof(FactoryRunSettledEvent))] -[JsonSerializable(typeof(FactoryRunStartedData))] -[JsonSerializable(typeof(FactoryRunStartedEvent))] -[JsonSerializable(typeof(FactoryRunUpdatedData))] -[JsonSerializable(typeof(FactoryRunUpdatedEvent))] [JsonSerializable(typeof(FusionAttribution))] [JsonSerializable(typeof(FusionFollowUpRecommendation))] [JsonSerializable(typeof(FusionPhasePlanStep))] @@ -20402,13 +20418,13 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(PermissionPromptRequestExtensionEnvAccess))] [JsonSerializable(typeof(PermissionPromptRequestExtensionManagement))] [JsonSerializable(typeof(PermissionPromptRequestExtensionPermissionAccess))] -[JsonSerializable(typeof(PermissionPromptRequestFactory))] [JsonSerializable(typeof(PermissionPromptRequestHook))] [JsonSerializable(typeof(PermissionPromptRequestMcp))] [JsonSerializable(typeof(PermissionPromptRequestMemory))] [JsonSerializable(typeof(PermissionPromptRequestPath))] [JsonSerializable(typeof(PermissionPromptRequestRead))] [JsonSerializable(typeof(PermissionPromptRequestUrl))] +[JsonSerializable(typeof(PermissionPromptRequestWorkflow))] [JsonSerializable(typeof(PermissionPromptRequestWrite))] [JsonSerializable(typeof(PermissionRecoveryAttempt))] [JsonSerializable(typeof(PermissionRecoveryData))] @@ -20417,7 +20433,6 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(PermissionRequestExtensionEnvAccess))] [JsonSerializable(typeof(PermissionRequestExtensionManagement))] [JsonSerializable(typeof(PermissionRequestExtensionPermissionAccess))] -[JsonSerializable(typeof(PermissionRequestFactory))] [JsonSerializable(typeof(PermissionRequestHook))] [JsonSerializable(typeof(PermissionRequestMcp))] [JsonSerializable(typeof(PermissionRequestMemory))] @@ -20427,6 +20442,7 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(PermissionRequestShellCommandSegment))] [JsonSerializable(typeof(PermissionRequestShellPossibleUrl))] [JsonSerializable(typeof(PermissionRequestUrl))] +[JsonSerializable(typeof(PermissionRequestWorkflow))] [JsonSerializable(typeof(PermissionRequestWrite))] [JsonSerializable(typeof(PermissionRequestedData))] [JsonSerializable(typeof(PermissionRequestedEvent))] @@ -20632,15 +20648,15 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(SystemNotificationAgentIdle))] [JsonSerializable(typeof(SystemNotificationData))] [JsonSerializable(typeof(SystemNotificationEvent))] -[JsonSerializable(typeof(SystemNotificationFactoryCompleted))] -[JsonSerializable(typeof(SystemNotificationFactoryPauseInfo))] -[JsonSerializable(typeof(SystemNotificationFactoryPauseInfoCheckpoint))] -[JsonSerializable(typeof(SystemNotificationFactoryPauseInfoUser))] [JsonSerializable(typeof(SystemNotificationInstructionDiscovered))] [JsonSerializable(typeof(SystemNotificationNewInboxMessage))] [JsonSerializable(typeof(SystemNotificationShellCompleted))] [JsonSerializable(typeof(SystemNotificationShellDetachedCompleted))] [JsonSerializable(typeof(SystemNotificationUnclassified))] +[JsonSerializable(typeof(SystemNotificationWorkflowCompleted))] +[JsonSerializable(typeof(SystemNotificationWorkflowPauseInfo))] +[JsonSerializable(typeof(SystemNotificationWorkflowPauseInfoCheckpoint))] +[JsonSerializable(typeof(SystemNotificationWorkflowPauseInfoUser))] [JsonSerializable(typeof(TaskBlocker))] [JsonSerializable(typeof(ToolExecutionCompleteContent))] [JsonSerializable(typeof(ToolExecutionCompleteContentAudio))] @@ -20698,11 +20714,18 @@ public override void Write(Utf8JsonWriter writer, ExtensionsLoadedExtensionStatu [JsonSerializable(typeof(UserToolSessionApprovalExtensionEnvAccess))] [JsonSerializable(typeof(UserToolSessionApprovalExtensionManagement))] [JsonSerializable(typeof(UserToolSessionApprovalExtensionPermissionAccess))] -[JsonSerializable(typeof(UserToolSessionApprovalFactory))] [JsonSerializable(typeof(UserToolSessionApprovalMcp))] [JsonSerializable(typeof(UserToolSessionApprovalMemory))] [JsonSerializable(typeof(UserToolSessionApprovalRead))] +[JsonSerializable(typeof(UserToolSessionApprovalWorkflow))] [JsonSerializable(typeof(UserToolSessionApprovalWrite))] +[JsonSerializable(typeof(WorkflowPermissionPhase))] +[JsonSerializable(typeof(WorkflowRunSettledData))] +[JsonSerializable(typeof(WorkflowRunSettledEvent))] +[JsonSerializable(typeof(WorkflowRunStartedData))] +[JsonSerializable(typeof(WorkflowRunStartedEvent))] +[JsonSerializable(typeof(WorkflowRunUpdatedData))] +[JsonSerializable(typeof(WorkflowRunUpdatedEvent))] [JsonSerializable(typeof(WorkingDirectoryContext))] [JsonSerializable(typeof(JsonElement))] internal sealed partial class SessionEventsJsonContext : JsonSerializerContext; \ No newline at end of file diff --git a/dotnet/test/E2E/RpcExtensionsLoadedE2ETests.cs b/dotnet/test/E2E/RpcExtensionsLoadedE2ETests.cs index 3d017d8165..d1e7a3cb49 100644 --- a/dotnet/test/E2E/RpcExtensionsLoadedE2ETests.cs +++ b/dotnet/test/E2E/RpcExtensionsLoadedE2ETests.cs @@ -153,22 +153,24 @@ private static async Task InitializeGitRepositoryAsync(string projectDir) /// after session create returns, and list calls can report an empty list /// until setup finishes. /// - private static async Task WaitForExtensionAsync( + private async Task WaitForExtensionAsync( CopilotSession session, string extensionId, ExtensionStatus expectedStatus, TimeSpan? timeout = null) { RpcExtension? lastSeen = null; + string lastExtensions = ""; await TestHelper.WaitForConditionAsync( async () => { var list = await session.Rpc.Extensions.ListAsync(); + lastExtensions = string.Join(", ", list.Extensions.Select(extension => $"{extension.Id}: {extension.Status}")); lastSeen = list.Extensions.FirstOrDefault(e => string.Equals(e.Id, extensionId, StringComparison.Ordinal)); return lastSeen != null && lastSeen.Status == expectedStatus; }, timeout: timeout ?? ExtensionStartupTimeout, - timeoutMessage: $"Extension '{extensionId}' did not reach status '{expectedStatus}' (last seen: {lastSeen?.Status.ToString() ?? ""}).", + timeoutMessageFactory: () => $"Extension '{extensionId}' did not reach status '{expectedStatus}' (last seen: {lastSeen?.Status.ToString() ?? ""}; listed: [{lastExtensions}]; launch markers: {TestHelper.ExtensionLaunchMarkers(Ctx.HomeDir, extensionId)}).", transientExceptionFilter: ex => ex.ToString().Contains("Extensions not available", StringComparison.OrdinalIgnoreCase), pollInterval: TimeSpan.FromMilliseconds(100)); diff --git a/dotnet/test/E2E/RpcSurfaceCoverageE2ETests.cs b/dotnet/test/E2E/RpcSurfaceCoverageE2ETests.cs index b969e970aa..a82c01d201 100644 --- a/dotnet/test/E2E/RpcSurfaceCoverageE2ETests.cs +++ b/dotnet/test/E2E/RpcSurfaceCoverageE2ETests.cs @@ -245,18 +245,18 @@ public async Task Session_Control_And_State_Rpcs_Project_All_Result_Properties() } [Fact] - public async Task Factory_Rpcs_Project_Run_Journal_And_Agent_State() + public async Task Workflow_Rpcs_Project_Run_Journal_And_Agent_State() { var (client, capturePath) = await CreateClientAsync(); await using (client) await using (var session = await Ctx.CreateSessionAsync(client, new SessionConfig())) { - var run = await session.Rpc.Factory.RunAsync( - "rpc-factory", + var run = await session.Rpc.Workflow.RunAsync( + "rpc-workflow", ParseJson("""{ "input": 42 }"""), - new RunOptions + new WorkflowRunOptions { - Limits = new FactoryRunLimits + Limits = new WorkflowRunLimits { MaxAiCredits = 2.5, MaxConcurrentSubagents = 2, @@ -266,47 +266,47 @@ public async Task Factory_Rpcs_Project_Run_Journal_And_Agent_State() LogPhaseNames = true, NotifyOnComplete = false, }); - Assert.Equal("factory-run-1", run.RunId); - Assert.Equal(FactoryRunStatus.Running, run.Status); + Assert.Equal("workflow-run-1", run.RunId); + Assert.Equal(WorkflowRunStatus.Running, run.Status); Assert.Equal(1, run.Attempt); Assert.Equal("running", run.Result!.Value.GetProperty("value").GetString()); Assert.Equal(1, run.Snapshot!.Value.GetProperty("step").GetInt32()); - var resumed = await session.Rpc.Factory.ResumeAsync( - "factory-run-1", - new FactoryRunLimits { MaxTotalSubagents = 8 }, + var resumed = await session.Rpc.Workflow.ResumeAsync( + "workflow-run-1", + new WorkflowRunLimits { MaxTotalSubagents = 8 }, notifyOnComplete: true, logPhaseNames: false); - Assert.Equal("rpc-factory", resumed.FactoryName); - Assert.Equal(FactoryRunStatus.Running, resumed.Run.Status); + Assert.Equal("rpc-workflow", resumed.WorkflowName); + Assert.Equal(WorkflowRunStatus.Running, resumed.Run.Status); Assert.Equal(2, resumed.Run.Attempt); - var current = await session.Rpc.Factory.GetRunAsync("factory-run-1"); - Assert.Equal("factory-run-1", current.RunId); - Assert.Equal(FactoryRunStatus.Running, current.Status); + var current = await session.Rpc.Workflow.GetRunAsync("workflow-run-1"); + Assert.Equal("workflow-run-1", current.RunId); + Assert.Equal(WorkflowRunStatus.Running, current.Status); - var paused = await session.Rpc.Factory.PauseAsync("factory-run-1"); - Assert.Equal(FactoryRunStatus.Paused, paused.Status); + var paused = await session.Rpc.Workflow.PauseAsync("workflow-run-1"); + Assert.Equal(WorkflowRunStatus.Paused, paused.Status); Assert.Equal("caller requested pause", paused.Reason); Assert.Equal(2, paused.Snapshot!.Value.GetProperty("step").GetInt32()); - await session.Rpc.Factory.LogAsync( - "factory-run-1", + await session.Rpc.Workflow.LogAsync( + "workflow-run-1", "execution-token-1", [ - new FactoryLogLine + new WorkflowLogLine { - Kind = FactoryLogLineKind.Log, + Kind = WorkflowLogLineKind.Log, Seq = 7, - Text = "Factory progress", + Text = "Workflow progress", }, ]); - var agent = await session.Rpc.Factory.AgentAsync( - "factory-run-1", + var agent = await session.Rpc.Workflow.AgentAsync( + "workflow-run-1", "execution-token-1", "Complete the RPC task.", - new FactoryAgentOptions + new WorkflowAgentOptions { Agent = "explore", Label = "rpc-agent", @@ -315,15 +315,15 @@ await session.Rpc.Factory.LogAsync( }); Assert.Equal("agent-result", agent.Result!.Value.GetProperty("answer").GetString()); - var journal = await session.Rpc.Factory.Journal.GetAsync( - "factory-run-1", + var journal = await session.Rpc.Workflow.Journal.GetAsync( + "workflow-run-1", "execution-token-1", "checkpoint"); Assert.True(journal.Hit); Assert.Equal(7, journal.ResultJson!.Value.GetProperty("checkpoint").GetInt32()); - await session.Rpc.Factory.Journal.PutAsync( - "factory-run-1", + await session.Rpc.Workflow.Journal.PutAsync( + "workflow-run-1", "execution-token-1", "checkpoint", ParseJson("""{ "checkpoint": 8 }""")); @@ -332,28 +332,28 @@ await session.Rpc.Factory.Journal.PutAsync( var requests = await RpcSurfaceTestCli.ReadRequestsAsync(capturePath); AssertCalledExactlyOnce( requests, - "session.factory.run", - "session.factory.resume", - "session.factory.getRun", - "session.factory.pause", - "session.factory.log", - "session.factory.agent", - "session.factory.journal.get", - "session.factory.journal.put"); - - var runRequest = GetParams(FindRequest(requests, "session.factory.run")); + "session.workflow.run", + "session.workflow.resume", + "session.workflow.getRun", + "session.workflow.pause", + "session.workflow.log", + "session.workflow.agent", + "session.workflow.journal.get", + "session.workflow.journal.put"); + + var runRequest = GetParams(FindRequest(requests, "session.workflow.run")); Assert.Equal(42, runRequest.GetProperty("args").GetProperty("input").GetInt32()); Assert.Equal(2.5, runRequest.GetProperty("options").GetProperty("limits").GetProperty("maxAiCredits").GetDouble()); Assert.True(runRequest.GetProperty("options").GetProperty("logPhaseNames").GetBoolean()); - var factoryLog = GetParams(FindRequest(requests, "session.factory.log")); + var factoryLog = GetParams(FindRequest(requests, "session.workflow.log")); Assert.Equal("execution-token-1", factoryLog.GetProperty("executionToken").GetString()); var line = Assert.Single(factoryLog.GetProperty("lines").EnumerateArray()); Assert.Equal("log", line.GetProperty("kind").GetString()); Assert.Equal(7, line.GetProperty("seq").GetInt64()); - Assert.Equal("Factory progress", line.GetProperty("text").GetString()); + Assert.Equal("Workflow progress", line.GetProperty("text").GetString()); - var journalPut = GetParams(FindRequest(requests, "session.factory.journal.put")); + var journalPut = GetParams(FindRequest(requests, "session.workflow.journal.put")); Assert.Equal("checkpoint", journalPut.GetProperty("key").GetString()); Assert.Equal(8, journalPut.GetProperty("resultJson").GetProperty("checkpoint").GetInt32()); } diff --git a/dotnet/test/E2E/RpcSurfaceTestCli.cs b/dotnet/test/E2E/RpcSurfaceTestCli.cs index 9fba398804..db822cf574 100644 --- a/dotnet/test/E2E/RpcSurfaceTestCli.cs +++ b/dotnet/test/E2E/RpcSurfaceTestCli.cs @@ -182,45 +182,45 @@ function handle(message) { }] }); return; - case "session.factory.run": - case "session.factory.getRun": + case "session.workflow.run": + case "session.workflow.getRun": writeResponse(message.id, { - runId: "factory-run-1", + runId: "workflow-run-1", status: "running", attempt: 1, result: { value: "running" }, snapshot: { step: 1 } }); return; - case "session.factory.pause": + case "session.workflow.pause": writeResponse(message.id, { - runId: "factory-run-1", + runId: "workflow-run-1", status: "paused", attempt: 1, reason: "caller requested pause", snapshot: { step: 2 } }); return; - case "session.factory.resume": + case "session.workflow.resume": writeResponse(message.id, { - factoryName: "rpc-factory", + workflowName: "rpc-workflow", run: { - runId: "factory-run-1", + runId: "workflow-run-1", status: "running", attempt: 2, snapshot: { step: 3 } } }); return; - case "session.factory.log": - case "session.factory.journal.put": + case "session.workflow.log": + case "session.workflow.journal.put": case "session.tools.set": writeResponse(message.id, {}); return; - case "session.factory.agent": + case "session.workflow.agent": writeResponse(message.id, { result: { answer: "agent-result" } }); return; - case "session.factory.journal.get": + case "session.workflow.journal.get": writeResponse(message.id, { hit: true, resultJson: { checkpoint: 7 } }); return; case "session.history.clearContext": diff --git a/dotnet/test/E2E/ScenarioTestingJsExtensionBridgeE2ETests.cs b/dotnet/test/E2E/ScenarioTestingJsExtensionBridgeE2ETests.cs index b714f32444..76d0cb784b 100644 --- a/dotnet/test/E2E/ScenarioTestingJsExtensionBridgeE2ETests.cs +++ b/dotnet/test/E2E/ScenarioTestingJsExtensionBridgeE2ETests.cs @@ -304,24 +304,26 @@ private async Task CreateExtensionFixtureAsync( $"{source.Value}:{extensionName}"); } - private static async Task WaitForExtensionAsync( + private async Task WaitForExtensionAsync( CopilotSession session, string extensionId, ExtensionStatus expectedStatus = default) { expectedStatus = expectedStatus == default ? ExtensionStatus.Running : expectedStatus; RpcExtension? extension = null; + string lastExtensions = ""; await TestHelper.WaitForConditionAsync( async () => { var list = await session.Rpc.Extensions.ListAsync(); + lastExtensions = string.Join(", ", list.Extensions.Select(item => $"{item.Id}: {item.Status}")); extension = list.Extensions.FirstOrDefault( item => string.Equals(item.Id, extensionId, StringComparison.Ordinal)); return extension?.Status == expectedStatus; }, timeout: ExtensionTimeout, pollInterval: TimeSpan.FromMilliseconds(100), - timeoutMessage: $"Timed out waiting for extension '{extensionId}'.", + timeoutMessageFactory: () => $"Timed out waiting for extension '{extensionId}' (listed: [{lastExtensions}]; launch markers: {TestHelper.ExtensionLaunchMarkers(Ctx.HomeDir, extensionId)}).", transientExceptionFilter: ex => ex.ToString().Contains("Extensions not available", StringComparison.OrdinalIgnoreCase)); return extension!; diff --git a/dotnet/test/E2E/ScenarioTestingServerControlE2ETests.cs b/dotnet/test/E2E/ScenarioTestingServerControlE2ETests.cs index bf3e2cb7e8..1fe2d6a8e9 100644 --- a/dotnet/test/E2E/ScenarioTestingServerControlE2ETests.cs +++ b/dotnet/test/E2E/ScenarioTestingServerControlE2ETests.cs @@ -76,22 +76,22 @@ public async Task Should_Observe_Page_And_Cancel_Factory_Run() await using var client = Ctx.CreateClient(options: CreateFakeCliOptions(cliPath, capturePath)); await using var session = await Ctx.CreateSessionAsync(client, new SessionConfig()); - var runs = await session.Rpc.Factory.ListRunsAsync(afterSeq: 3, beforeSeq: 20, limit: 10); + var runs = await session.Rpc.Workflow.ListRunsAsync(afterSeq: 3, beforeSeq: 20, limit: 10); var summary = Assert.Single(runs.Runs); - Assert.Equal("factory-run-1", summary.RunId); - Assert.Equal("scenario-factory", summary.FactoryName); - Assert.Equal(FactoryRunStatus.Running, summary.Status); + Assert.Equal("workflow-run-1", summary.RunId); + Assert.Equal("scenario-workflow", summary.WorkflowName); + Assert.Equal(WorkflowRunStatus.Running, summary.Status); Assert.Equal(7, runs.OldestSeq); Assert.Equal(7, runs.NewestSeq); Assert.False(runs.HasMoreNewer); - var detail = await session.Rpc.Factory.GetRunDetailAsync(summary.RunId); + var detail = await session.Rpc.Workflow.GetRunDetailAsync(summary.RunId); Assert.Equal(summary.RunId, detail.RunId); - Assert.Equal(summary.FactoryName, detail.FactoryName); - Assert.Equal(FactoryRunStatus.Running, detail.Status); + Assert.Equal(summary.WorkflowName, detail.WorkflowName); + Assert.Equal(WorkflowRunStatus.Running, detail.Status); Assert.Equal(4, detail.Revision); - var progress = await session.Rpc.Factory.GetRunProgressAsync( + var progress = await session.Rpc.Workflow.GetRunProgressAsync( summary.RunId, phaseId: "verify", afterSeq: 5, @@ -100,16 +100,16 @@ public async Task Should_Observe_Page_And_Cancel_Factory_Run() var line = Assert.Single(progress.Records); Assert.Equal(12, line.Seq); Assert.Equal("verify", line.PhaseId); - Assert.Equal(FactoryLogLineKind.Log, line.Kind); + Assert.Equal(WorkflowLogLineKind.Log, line.Kind); Assert.Equal("Validation complete", line.Text); - var cancelled = await session.Rpc.Factory.CancelAsync(summary.RunId); + var cancelled = await session.Rpc.Workflow.CancelAsync(summary.RunId); Assert.Equal(summary.RunId, cancelled.RunId); - Assert.Equal(FactoryRunStatus.Cancelled, cancelled.Status); + Assert.Equal(WorkflowRunStatus.Cancelled, cancelled.Status); Assert.Equal("cancelled by user", cancelled.Reason); var requests = await ScenarioTestingTestCli.ReadRequestsAsync(capturePath); - var list = Assert.Single(requests, request => GetMethod(request) == "session.factory.listRuns") + var list = Assert.Single(requests, request => GetMethod(request) == "session.workflow.listRuns") .GetProperty("params"); Assert.Equal(3, list.GetProperty("afterSeq").GetInt64()); Assert.Equal(20, list.GetProperty("beforeSeq").GetInt64()); @@ -117,8 +117,8 @@ public async Task Should_Observe_Page_And_Cancel_Factory_Run() var progressRequest = Assert.Single( requests, - request => GetMethod(request) == "session.factory.getRunProgress").GetProperty("params"); - Assert.Equal("factory-run-1", progressRequest.GetProperty("runId").GetString()); + request => GetMethod(request) == "session.workflow.getRunProgress").GetProperty("params"); + Assert.Equal("workflow-run-1", progressRequest.GetProperty("runId").GetString()); Assert.Equal("verify", progressRequest.GetProperty("phaseId").GetString()); Assert.Equal(5, progressRequest.GetProperty("afterSeq").GetInt64()); Assert.Equal(20, progressRequest.GetProperty("beforeSeq").GetInt64()); diff --git a/dotnet/test/E2E/ScenarioTestingTestCli.cs b/dotnet/test/E2E/ScenarioTestingTestCli.cs index 12c6bd8e7a..4e12090dc7 100644 --- a/dotnet/test/E2E/ScenarioTestingTestCli.cs +++ b/dotnet/test/E2E/ScenarioTestingTestCli.cs @@ -201,12 +201,12 @@ function handleMessage(message) { return; } - if (message.method === "session.factory.listRuns") { + if (message.method === "session.workflow.listRuns") { writeResponse(message.id, { runs: [{ - runId: "factory-run-1", - factoryName: "scenario-factory", - description: "Scenario factory", + runId: "workflow-run-1", + workflowName: "scenario-workflow", + description: "Scenario workflow", status: "running", revision: 4, createdAt: 1000, @@ -224,11 +224,11 @@ function handleMessage(message) { return; } - if (message.method === "session.factory.getRunDetail") { + if (message.method === "session.workflow.getRunDetail") { writeResponse(message.id, { - runId: "factory-run-1", - factoryName: "scenario-factory", - description: "Scenario factory", + runId: "workflow-run-1", + workflowName: "scenario-workflow", + description: "Scenario workflow", status: "running", revision: 4, createdAt: 1000, @@ -247,7 +247,7 @@ function handleMessage(message) { return; } - if (message.method === "session.factory.getRunProgress") { + if (message.method === "session.workflow.getRunProgress") { writeResponse(message.id, { records: [{ seq: 12, @@ -266,9 +266,9 @@ function handleMessage(message) { return; } - if (message.method === "session.factory.cancel") { + if (message.method === "session.workflow.cancel") { writeResponse(message.id, { - runId: "factory-run-1", + runId: "workflow-run-1", status: "cancelled", reason: "cancelled by user", attempt: 1 diff --git a/dotnet/test/Harness/TestHelper.cs b/dotnet/test/Harness/TestHelper.cs index 76045bfbb0..fa40656b73 100644 --- a/dotnet/test/Harness/TestHelper.cs +++ b/dotnet/test/Harness/TestHelper.cs @@ -72,7 +72,8 @@ public static async Task WaitForConditionAsync( TimeSpan? timeout = null, string? timeoutMessage = null, Func? transientExceptionFilter = null, - TimeSpan? pollInterval = null) + TimeSpan? pollInterval = null, + Func? timeoutMessageFactory = null) { using var cts = new CancellationTokenSource(timeout ?? DefaultEventTimeout); Exception? lastTransientException = null; @@ -115,11 +116,47 @@ public static async Task WaitForConditionAsync( lastTransientException = ex; } + var message = timeoutMessageFactory?.Invoke() ?? timeoutMessage ?? "Timed out waiting for condition."; throw lastTransientException is null - ? new TimeoutException(timeoutMessage ?? "Timed out waiting for condition.") - : new TimeoutException(timeoutMessage ?? "Timed out waiting for condition.", lastTransientException); + ? new TimeoutException(message) + : new TimeoutException(message, lastTransientException); } public static bool IsTransientFileSystemException(Exception exception) => exception is IOException or UnauthorizedAccessException; + + public static string ExtensionLaunchMarkers(string homeDir, string extensionId) + { + try + { + var logsDir = Path.Join(homeDir, "logs"); + if (!Directory.Exists(logsDir)) + { + return ""; + } + + var extensionName = extensionId[(extensionId.LastIndexOf(':') + 1)..]; + var launches = new List(); + foreach (var path in Directory.EnumerateFiles(logsDir, "process-*.log")) + { + using var reader = new StreamReader(path); + if (reader.ReadLine()?.Contains(extensionName, StringComparison.Ordinal) != true) + { + continue; + } + + var markers = File.ReadLines(path) + .Where(line => line.StartsWith("=== ", StringComparison.Ordinal) + && !line.Contains("module=", StringComparison.Ordinal)); + var summary = string.Join("; ", markers); + launches.Add(summary.Length == 0 ? "" : summary); + } + + return launches.Count == 0 ? "" : string.Join(" | ", launches); + } + catch (Exception error) when (error is IOException or UnauthorizedAccessException) + { + return $""; + } + } } diff --git a/go/internal/e2e/rpc_generated_surface_gaps_e2e_test.go b/go/internal/e2e/rpc_generated_surface_gaps_e2e_test.go index 99d9c0a4b1..63993058a4 100644 --- a/go/internal/e2e/rpc_generated_surface_gaps_e2e_test.go +++ b/go/internal/e2e/rpc_generated_surface_gaps_e2e_test.go @@ -56,18 +56,18 @@ func TestGeneratedRPCSurfaceGapsE2E(t *testing.T) { {"session completion triggers", "session.completions.getTriggerCharacters", (*rpc.CompletionsAPI).GetTriggerCharacters, session(func(r *rpc.SessionRPC) any { return r.Completions }), false}, {"session content exclusion paths", "session.contentExclusion.checkPaths", (*rpc.ContentExclusionAPI).CheckPaths, session(func(r *rpc.SessionRPC) any { return r.ContentExclusion }), false}, {"session debug logs", "session.debug.collectLogs", (*rpc.DebugAPI).CollectLogs, session(func(r *rpc.SessionRPC) any { return r.Debug }), false}, - {"session factory agent", "session.factory.agent", (*rpc.FactoryAPI).Agent, session(func(r *rpc.SessionRPC) any { return r.Factory }), false}, - {"session factory cancel", "session.factory.cancel", (*rpc.FactoryAPI).Cancel, session(func(r *rpc.SessionRPC) any { return r.Factory }), false}, - {"session factory get run", "session.factory.getRun", (*rpc.FactoryAPI).GetRun, session(func(r *rpc.SessionRPC) any { return r.Factory }), false}, - {"session factory detail", "session.factory.getRunDetail", (*rpc.FactoryAPI).GetRunDetail, session(func(r *rpc.SessionRPC) any { return r.Factory }), false}, - {"session factory progress", "session.factory.getRunProgress", (*rpc.FactoryAPI).GetRunProgress, session(func(r *rpc.SessionRPC) any { return r.Factory }), false}, - {"session factory list runs", "session.factory.listRuns", (*rpc.FactoryAPI).ListRuns, session(func(r *rpc.SessionRPC) any { return r.Factory }), false}, - {"session factory log", "session.factory.log", (*rpc.FactoryAPI).Log, session(func(r *rpc.SessionRPC) any { return r.Factory }), false}, - {"session factory pause", "session.factory.pause", (*rpc.FactoryAPI).Pause, session(func(r *rpc.SessionRPC) any { return r.Factory }), false}, - {"session factory resume", "session.factory.resume", (*rpc.FactoryAPI).Resume, session(func(r *rpc.SessionRPC) any { return r.Factory }), false}, - {"session factory run", "session.factory.run", (*rpc.FactoryAPI).Run, session(func(r *rpc.SessionRPC) any { return r.Factory }), false}, - {"session factory journal get", "session.factory.journal.get", (*rpc.FactoryJournalAPI).Get, session(func(r *rpc.SessionRPC) any { return r.Factory.Journal() }), false}, - {"session factory journal put", "session.factory.journal.put", (*rpc.FactoryJournalAPI).Put, session(func(r *rpc.SessionRPC) any { return r.Factory.Journal() }), false}, + {"session workflow agent", "session.workflow.agent", (*rpc.WorkflowAPI).Agent, session(func(r *rpc.SessionRPC) any { return r.Workflow }), false}, + {"session workflow cancel", "session.workflow.cancel", (*rpc.WorkflowAPI).Cancel, session(func(r *rpc.SessionRPC) any { return r.Workflow }), false}, + {"session workflow get run", "session.workflow.getRun", (*rpc.WorkflowAPI).GetRun, session(func(r *rpc.SessionRPC) any { return r.Workflow }), false}, + {"session workflow detail", "session.workflow.getRunDetail", (*rpc.WorkflowAPI).GetRunDetail, session(func(r *rpc.SessionRPC) any { return r.Workflow }), false}, + {"session workflow progress", "session.workflow.getRunProgress", (*rpc.WorkflowAPI).GetRunProgress, session(func(r *rpc.SessionRPC) any { return r.Workflow }), false}, + {"session workflow list runs", "session.workflow.listRuns", (*rpc.WorkflowAPI).ListRuns, session(func(r *rpc.SessionRPC) any { return r.Workflow }), false}, + {"session workflow log", "session.workflow.log", (*rpc.WorkflowAPI).Log, session(func(r *rpc.SessionRPC) any { return r.Workflow }), false}, + {"session workflow pause", "session.workflow.pause", (*rpc.WorkflowAPI).Pause, session(func(r *rpc.SessionRPC) any { return r.Workflow }), false}, + {"session workflow resume", "session.workflow.resume", (*rpc.WorkflowAPI).Resume, session(func(r *rpc.SessionRPC) any { return r.Workflow }), false}, + {"session workflow run", "session.workflow.run", (*rpc.WorkflowAPI).Run, session(func(r *rpc.SessionRPC) any { return r.Workflow }), false}, + {"session workflow journal get", "session.workflow.journal.get", (*rpc.WorkflowJournalAPI).Get, session(func(r *rpc.SessionRPC) any { return r.Workflow.Journal() }), false}, + {"session workflow journal put", "session.workflow.journal.put", (*rpc.WorkflowJournalAPI).Put, session(func(r *rpc.SessionRPC) any { return r.Workflow.Journal() }), false}, {"session history clear context", "session.history.clearContext", (*rpc.HistoryAPI).ClearContext, session(func(r *rpc.SessionRPC) any { return r.History }), false}, {"session limit prediction", "session.limitPrediction.predict", (*rpc.LimitPredictionAPI).Predict, session(func(r *rpc.SessionRPC) any { return r.LimitPrediction }), false}, {"session mcp loading background", "session.mcp.moveLoadingToBackground", (*rpc.MCPAPI).MoveLoadingToBackground, session(func(r *rpc.SessionRPC) any { return r.MCP }), false}, @@ -213,20 +213,20 @@ func generatedRPCRequest(wire string) string { return `{"paths":["/tmp/rpc-workspace/file.txt"]}` case "session.debug.collectLogs": return `{"destination":{"kind":"directory","outputDirectory":"/tmp/rpc-debug"},"include":{"events":true,"processLogs":false,"shellLogs":true},"additionalEntries":[{"bundlePath":"host/diagnostic.txt","kind":"file","path":"/tmp/diagnostic.txt","required":true}]}` - case "session.factory.run": - return `{"name":"rpc-factory","args":{"input":42},"options":{"limits":{"maxAiCredits":2.5,"maxConcurrentSubagents":2,"maxTotalSubagents":4,"timeoutSeconds":30},"logPhaseNames":true,"notifyOnComplete":false}}` - case "session.factory.resume": - return `{"runId":"factory-run-1","limits":{"maxTotalSubagents":8},"notifyOnComplete":true,"logPhaseNames":false}` - case "session.factory.getRun", "session.factory.pause": - return `{"runId":"factory-run-1"}` - case "session.factory.log": - return `{"runId":"factory-run-1","executionToken":"execution-token-1","lines":[{"kind":"log","seq":7,"text":"Factory progress"}]}` - case "session.factory.agent": - return `{"factoryRunId":"factory-run-1","executionToken":"execution-token-1","prompt":"Complete the RPC task.","opts":{"agent":"explore","label":"rpc-agent","model":"model-a","reasoningEffort":"high"}}` - case "session.factory.journal.get": - return `{"runId":"factory-run-1","executionToken":"execution-token-1","key":"checkpoint"}` - case "session.factory.journal.put": - return `{"runId":"factory-run-1","executionToken":"execution-token-1","key":"checkpoint","resultJson":{"checkpoint":8}}` + case "session.workflow.run": + return `{"name":"rpc-workflow","args":{"input":42},"options":{"limits":{"maxAiCredits":2.5,"maxConcurrentSubagents":2,"maxTotalSubagents":4,"timeoutSeconds":30},"logPhaseNames":true,"notifyOnComplete":false}}` + case "session.workflow.resume": + return `{"runId":"workflow-run-1","limits":{"maxTotalSubagents":8},"notifyOnComplete":true,"logPhaseNames":false}` + case "session.workflow.getRun", "session.workflow.pause": + return `{"runId":"workflow-run-1"}` + case "session.workflow.log": + return `{"runId":"workflow-run-1","executionToken":"execution-token-1","lines":[{"kind":"log","seq":7,"text":"Workflow progress"}]}` + case "session.workflow.agent": + return `{"workflowRunId":"workflow-run-1","executionToken":"execution-token-1","prompt":"Complete the RPC task.","opts":{"agent":"explore","label":"rpc-agent","model":"model-a","reasoningEffort":"high"}}` + case "session.workflow.journal.get": + return `{"runId":"workflow-run-1","executionToken":"execution-token-1","key":"checkpoint"}` + case "session.workflow.journal.put": + return `{"runId":"workflow-run-1","executionToken":"execution-token-1","key":"checkpoint","resultJson":{"checkpoint":8}}` case "session.history.clearContext": return `{"prompt":"Reset context."}` case "session.limitPrediction.predict": @@ -306,15 +306,15 @@ func generatedRPCResponse(wire string) string { return `{"available":true,"checks":[{"path":"/tmp/rpc-workspace/file.txt","excluded":false}]}` case "session.debug.collectLogs": return `{"kind":"directory","path":"/tmp/rpc-debug","entries":[{"bundlePath":"host/diagnostic.txt","sizeBytes":123,"source":"additional"}],"skippedEntries":[{"bundlePath":"host/missing.txt","path":"/tmp/missing.txt","reason":"not found"}]}` - case "session.factory.run", "session.factory.getRun": - return `{"runId":"factory-run-1","status":"running","attempt":1,"result":{"value":"running"},"snapshot":{"step":1}}` - case "session.factory.pause": - return `{"runId":"factory-run-1","status":"paused","attempt":1,"reason":"caller requested pause","snapshot":{"step":2}}` - case "session.factory.resume": - return `{"factoryName":"rpc-factory","run":{"runId":"factory-run-1","status":"running","attempt":2,"snapshot":{"step":3}}}` - case "session.factory.agent": + case "session.workflow.run", "session.workflow.getRun": + return `{"runId":"workflow-run-1","status":"running","attempt":1,"result":{"value":"running"},"snapshot":{"step":1}}` + case "session.workflow.pause": + return `{"runId":"workflow-run-1","status":"paused","attempt":1,"reason":"caller requested pause","snapshot":{"step":2}}` + case "session.workflow.resume": + return `{"workflowName":"rpc-workflow","run":{"runId":"workflow-run-1","status":"running","attempt":2,"snapshot":{"step":3}}}` + case "session.workflow.agent": return `{"result":{"answer":"agent-result"}}` - case "session.factory.journal.get": + case "session.workflow.journal.get": return `{"hit":true,"resultJson":{"checkpoint":7}}` case "session.history.clearContext": return `{"messagesCleared":4}` diff --git a/go/internal/e2e/scenario_testing_server_control_e2e_test.go b/go/internal/e2e/scenario_testing_server_control_e2e_test.go index 656bcf82f2..4d6ca62075 100644 --- a/go/internal/e2e/scenario_testing_server_control_e2e_test.go +++ b/go/internal/e2e/scenario_testing_server_control_e2e_test.go @@ -93,11 +93,11 @@ func TestScenarioTestingServerControlE2E(t *testing.T) { } }) - t.Run("observes pages and cancels factory run", func(t *testing.T) { + t.Run("observes pages and cancels workflow run", func(t *testing.T) { fixture := newGeneratedRPCFixture(t, t.Context()) var mu sync.Mutex captured := map[string]map[string]any{} - setFactoryHandler := func(method string, result any) { + setWorkflowHandler := func(method string, result any) { fixture.server.SetRequestHandler(method, func(request json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { var params map[string]any if err := json.Unmarshal(request, ¶ms); err != nil { @@ -109,23 +109,23 @@ func TestScenarioTestingServerControlE2E(t *testing.T) { return mustJSON(t, result), nil }) } - setFactoryHandler("session.factory.listRuns", map[string]any{ + setWorkflowHandler("session.workflow.listRuns", map[string]any{ "runs": []any{map[string]any{ - "runId": "factory-run-1", - "factoryName": "scenario-factory", - "status": "running", + "runId": "workflow-run-1", + "workflowName": "scenario-workflow", + "status": "running", }}, "oldestSeq": 7, "newestSeq": 7, "hasMoreNewer": false, }) - setFactoryHandler("session.factory.getRunDetail", map[string]any{ - "runId": "factory-run-1", - "factoryName": "scenario-factory", - "status": "running", - "revision": 4, + setWorkflowHandler("session.workflow.getRunDetail", map[string]any{ + "runId": "workflow-run-1", + "workflowName": "scenario-workflow", + "status": "running", + "revision": 4, }) - setFactoryHandler("session.factory.getRunProgress", map[string]any{ + setWorkflowHandler("session.workflow.getRunProgress", map[string]any{ "records": []any{map[string]any{ "attempt": 1, "kind": "log", @@ -136,79 +136,79 @@ func TestScenarioTestingServerControlE2E(t *testing.T) { }}, "revision": 4, }) - setFactoryHandler("session.factory.cancel", map[string]any{ - "runId": "factory-run-1", + setWorkflowHandler("session.workflow.cancel", map[string]any{ + "runId": "workflow-run-1", "status": "cancelled", "reason": "cancelled by user", }) after, before, limit := int64(3), int64(20), int32(10) - runs, err := fixture.session.RPC.Factory.ListRuns(t.Context(), &rpc.FactoryListRunsRequest{ + runs, err := fixture.session.RPC.Workflow.ListRuns(t.Context(), &rpc.WorkflowListRunsRequest{ AfterSeq: &after, BeforeSeq: &before, Limit: &limit, }) if err != nil { - t.Fatalf("Factory.ListRuns failed: %v", err) + t.Fatalf("Workflow.ListRuns failed: %v", err) } - if len(runs.Runs) != 1 || runs.Runs[0].RunID != "factory-run-1" || - runs.Runs[0].FactoryName != "scenario-factory" || runs.Runs[0].Status != rpc.FactoryRunStatusRunning || + if len(runs.Runs) != 1 || runs.Runs[0].RunID != "workflow-run-1" || + runs.Runs[0].WorkflowName != "scenario-workflow" || runs.Runs[0].Status != rpc.WorkflowRunStatusRunning || runs.OldestSeq == nil || *runs.OldestSeq != 7 || runs.NewestSeq == nil || *runs.NewestSeq != 7 || runs.HasMoreNewer == nil || *runs.HasMoreNewer { - t.Fatalf("Unexpected factory run page: %#v", runs) + t.Fatalf("Unexpected workflow run page: %#v", runs) } - detail, err := fixture.session.RPC.Factory.GetRunDetail(t.Context(), &rpc.FactoryGetRunRequest{RunID: "factory-run-1"}) + detail, err := fixture.session.RPC.Workflow.GetRunDetail(t.Context(), &rpc.WorkflowGetRunRequest{RunID: "workflow-run-1"}) if err != nil { - t.Fatalf("Factory.GetRunDetail failed: %v", err) + t.Fatalf("Workflow.GetRunDetail failed: %v", err) } - if detail.RunID != "factory-run-1" || detail.FactoryName != "scenario-factory" || - detail.Status != rpc.FactoryRunStatusRunning || detail.Revision != 4 { - t.Fatalf("Unexpected factory detail: %#v", detail) + if detail.RunID != "workflow-run-1" || detail.WorkflowName != "scenario-workflow" || + detail.Status != rpc.WorkflowRunStatusRunning || detail.Revision != 4 { + t.Fatalf("Unexpected workflow detail: %#v", detail) } progressAfter, progressBefore, progressLimit := int64(5), int64(20), int32(25) phaseID := "verify" - progress, err := fixture.session.RPC.Factory.GetRunProgress(t.Context(), &rpc.FactoryGetRunProgressRequest{ - RunID: "factory-run-1", + progress, err := fixture.session.RPC.Workflow.GetRunProgress(t.Context(), &rpc.WorkflowGetRunProgressRequest{ + RunID: "workflow-run-1", PhaseID: &phaseID, AfterSeq: &progressAfter, BeforeSeq: &progressBefore, Limit: &progressLimit, }) if err != nil { - t.Fatalf("Factory.GetRunProgress failed: %v", err) + t.Fatalf("Workflow.GetRunProgress failed: %v", err) } if len(progress.Records) != 1 || progress.Records[0].Seq != 12 || progress.Records[0].PhaseID == nil || *progress.Records[0].PhaseID != "verify" || - progress.Records[0].Kind != rpc.FactoryLogLineKindLog || + progress.Records[0].Kind != rpc.WorkflowLogLineKindLog || progress.Records[0].Text != "Validation complete" { - t.Fatalf("Unexpected factory progress: %#v", progress) + t.Fatalf("Unexpected workflow progress: %#v", progress) } - cancelled, err := fixture.session.RPC.Factory.Cancel(t.Context(), &rpc.FactoryCancelRequest{RunID: "factory-run-1"}) + cancelled, err := fixture.session.RPC.Workflow.Cancel(t.Context(), &rpc.WorkflowCancelRequest{RunID: "workflow-run-1"}) if err != nil { - t.Fatalf("Factory.Cancel failed: %v", err) + t.Fatalf("Workflow.Cancel failed: %v", err) } - if cancelled.RunID != "factory-run-1" || cancelled.Status != rpc.FactoryRunStatusCancelled || + if cancelled.RunID != "workflow-run-1" || cancelled.Status != rpc.WorkflowRunStatusCancelled || cancelled.Reason == nil || *cancelled.Reason != "cancelled by user" { - t.Fatalf("Unexpected cancelled factory run: %#v", cancelled) + t.Fatalf("Unexpected cancelled workflow run: %#v", cancelled) } mu.Lock() defer mu.Unlock() - assertJSONSubset(t, "session.factory.listRuns", map[string]any{ + assertJSONSubset(t, "session.workflow.listRuns", map[string]any{ "afterSeq": float64(3), "beforeSeq": float64(20), "limit": float64(10), - }, captured["session.factory.listRuns"]) - assertJSONSubset(t, "session.factory.getRunProgress", map[string]any{ - "runId": "factory-run-1", + }, captured["session.workflow.listRuns"]) + assertJSONSubset(t, "session.workflow.getRunProgress", map[string]any{ + "runId": "workflow-run-1", "phaseId": "verify", "afterSeq": float64(5), "beforeSeq": float64(20), "limit": float64(25), - }, captured["session.factory.getRunProgress"]) + }, captured["session.workflow.getRunProgress"]) }) t.Run("reads autopilot state and enables remote mode", func(t *testing.T) { diff --git a/go/rpc/permission_request_managed_approval.go b/go/rpc/permission_request_managed_approval.go index d1bfa37356..6724e2f430 100644 --- a/go/rpc/permission_request_managed_approval.go +++ b/go/rpc/permission_request_managed_approval.go @@ -34,7 +34,7 @@ func (r PermissionRequestExtensionPermissionAccess) RequiresManagedApproval() bo // RequiresManagedApproval reports whether managed policy requires an explicit // human decision for this request. -func (r PermissionRequestFactory) RequiresManagedApproval() bool { +func (r PermissionRequestWorkflow) RequiresManagedApproval() bool { return managedApprovalRequired(r.ManagedApprovalRequired) } diff --git a/go/rpc/zrpc.go b/go/rpc/zrpc.go index 42550be80e..ce4bdc8164 100644 --- a/go/rpc/zrpc.go +++ b/go/rpc/zrpc.go @@ -138,6 +138,49 @@ type AccountQuotaSnapshot struct { UsedRequests int64 `json:"usedRequests"` } +// Enumerate request carrying the typed collection query. +// Experimental: AccountsEnumerateRequest is part of an experimental API and may change or +// be removed. +type AccountsEnumerateRequest struct { + // Which typed accounts collection to enumerate. + Query AuthEnumerateQuery `json:"query"` +} + +// Read request carrying the typed datum query. +// Experimental: AccountsGetRequest is part of an experimental API and may change or be +// removed. +type AccountsGetRequest struct { + // Which typed accounts datum to read. + Query AuthReadQuery `json:"query"` +} + +// Mutation request carrying the typed write command. +// Experimental: AccountsSetRequest is part of an experimental API and may change or be +// removed. +type AccountsSetRequest struct { + // The non-interactive mutation command to apply. + Command AuthWrite `json:"command"` +} + +// One signed-in account in the roster forest. +// Experimental: AccountStatus is part of an experimental API and may change or be removed. +type AccountStatus struct { + // Whether this is the active account. + Active bool `json:"active"` + // Opaque id of the account this one was derived from (e.g. an EMU account's base Entra + // identity); absent for a root account. Matches the base identity account's selectionId, + // forming the derivation edge. + DerivedFrom *string `json:"derivedFrom,omitempty"` + // Authentication host URL. + Host string `json:"host"` + // The provider kind of this account. + Kind AccountKind `json:"kind"` + // Authenticated login/username. + Login string `json:"login"` + // Opaque selection id used to switch to, or log out, this account. + SelectionID string `json:"selectionId"` +} + // Canonical directory where custom agents can be discovered or created, with scope, // preference, and optional project path. // Experimental: AgentDiscoveryPath is part of an experimental API and may change or be @@ -867,6 +910,82 @@ type AttachmentSelectionDetailsStart struct { Line int64 `json:"line"` } +// Selects which accounts collection to enumerate. A no-arg selector is the empty-payload +// variant. +// Experimental: AuthEnumerateQuery is part of an experimental API and may change or be +// removed. +type AuthEnumerateQuery interface { + authEnumerateQuery() + Kind() AuthEnumerateQueryKind +} + +type RawAuthEnumerateQueryData struct { + Discriminator AuthEnumerateQueryKind + Raw json.RawMessage +} + +func (RawAuthEnumerateQueryData) authEnumerateQuery() {} +func (r RawAuthEnumerateQueryData) Kind() AuthEnumerateQueryKind { + return r.Discriminator +} + +type AuthEnumerateQueryAccounts struct { +} + +func (AuthEnumerateQueryAccounts) authEnumerateQuery() {} +func (AuthEnumerateQueryAccounts) Kind() AuthEnumerateQueryKind { + return AuthEnumerateQueryKindAccounts +} + +type AuthEnumerateQueryProviders struct { + // Whether an interactive Entra broker is available on the host; gates Entra availability in + // the returned list. + BrokerAvailable *bool `json:"brokerAvailable,omitempty"` +} + +func (AuthEnumerateQueryProviders) authEnumerateQuery() {} +func (AuthEnumerateQueryProviders) Kind() AuthEnumerateQueryKind { + return AuthEnumerateQueryKindProviders +} + +// The enumerated collection, keyed by the same selector as the query. +// Experimental: AuthEnumerateValue is part of an experimental API and may change or be +// removed. +type AuthEnumerateValue interface { + authEnumerateValue() + Kind() AuthEnumerateValueKind +} + +type RawAuthEnumerateValueData struct { + Discriminator AuthEnumerateValueKind + Raw json.RawMessage +} + +func (RawAuthEnumerateValueData) authEnumerateValue() {} +func (r RawAuthEnumerateValueData) Kind() AuthEnumerateValueKind { + return r.Discriminator +} + +type AuthEnumerateValueAccounts struct { + // The signed-in account forest; empty when not logged in. + Items []AccountStatus `json:"items"` +} + +func (AuthEnumerateValueAccounts) authEnumerateValue() {} +func (AuthEnumerateValueAccounts) Kind() AuthEnumerateValueKind { + return AuthEnumerateValueKindAccounts +} + +type AuthEnumerateValueProviders struct { + // The providers offered for interactive login. + Items []ProviderDescriptor `json:"items"` +} + +func (AuthEnumerateValueProviders) authEnumerateValue() {} +func (AuthEnumerateValueProviders) Kind() AuthEnumerateValueKind { + return AuthEnumerateValueKindProviders +} + // Credential-free authentication identity safe to expose to hosts and user interfaces. // Experimental: AuthIdentity is part of an experimental API and may change or be removed. type AuthIdentity struct { @@ -1062,6 +1181,235 @@ func (UserAuthInfo) Type() AuthInfoType { return AuthInfoTypeUser } +// Advance an in-flight login flow, optionally fulfilling an input-required step. +// Experimental: AuthLoginAdvanceRequest is part of an experimental API and may change or be +// removed. +type AuthLoginAdvanceRequest struct { + // Opaque flow id from begin. + FlowID string `json:"flowId"` + // Neutral input fulfilling a preceding input-required step (e.g. a GHEC host); ignored + // otherwise. + Input *string `json:"input,omitempty"` +} + +// Begin an interactive login flow for a provider kind. Dispatch is kind-only. +// Experimental: AuthLoginBeginRequest is part of an experimental API and may change or be +// removed. +type AuthLoginBeginRequest struct { + // The provider kind to sign in with. + Kind LoginProviderKind `json:"kind"` +} + +// A started login flow: its opaque id and first step. +// Experimental: AuthLoginBegun is part of an experimental API and may change or be removed. +type AuthLoginBegun struct { + // Opaque flow id used to advance or cancel this login. + FlowID string `json:"flowId"` + // The first step of the flow. + Step AuthLoginStep `json:"step"` +} + +// Cancel an in-flight login flow. +// Experimental: AuthLoginCancelRequest is part of an experimental API and may change or be +// removed. +type AuthLoginCancelRequest struct { + // Opaque flow id from begin. + FlowID string `json:"flowId"` +} + +// Terminal result of an interactive login flow. +// Experimental: AuthLoginResultDto is part of an experimental API and may change or be +// removed. +type AuthLoginResultDto struct { + // Host that was signed in, when completed. + Host *string `json:"host,omitempty"` + // Login that was signed in, when completed. + Login *string `json:"login,omitempty"` + // Terminal disposition of the login. + Status AuthLoginResultStatus `json:"status"` +} + +// One step in an interactive login flow. The consumer acts on the step and calls advance to +// proceed. Browser-open is encoded as two distinct steps by design: `open-url` is +// CONSUMER-driven (the provider surfaces the authorize URL and the consumer opens it — +// github.com/GHEC web), while `needs-interaction` is PROVIDER-driven (the provider opens +// the browser or broker UI itself and does not surface a URL — Entra). +// Experimental: AuthLoginStep is part of an experimental API and may change or be removed. +type AuthLoginStep interface { + authLoginStep() + Kind() AuthLoginStepKind +} + +type RawAuthLoginStepData struct { + Discriminator AuthLoginStepKind + Raw json.RawMessage +} + +func (RawAuthLoginStepData) authLoginStep() {} +func (r RawAuthLoginStepData) Kind() AuthLoginStepKind { + return r.Discriminator +} + +type AuthLoginStepAwaiting struct { +} + +func (AuthLoginStepAwaiting) authLoginStep() {} +func (AuthLoginStepAwaiting) Kind() AuthLoginStepKind { + return AuthLoginStepKindAwaiting +} + +type AuthLoginStepCompleted struct { + // The terminal login result. + Result AuthLoginResultDto `json:"result"` +} + +func (AuthLoginStepCompleted) authLoginStep() {} +func (AuthLoginStepCompleted) Kind() AuthLoginStepKind { + return AuthLoginStepKindCompleted +} + +type AuthLoginStepError struct { + // Human-readable failure message. + Message string `json:"message"` +} + +func (AuthLoginStepError) authLoginStep() {} +func (AuthLoginStepError) Kind() AuthLoginStepKind { + return AuthLoginStepKindError +} + +type AuthLoginStepInputRequired struct { + // Prompt for the value the provider needs; the consumer supplies it as advance input (e.g. + // a GitHub Enterprise Cloud host, *.ghe.com). + Prompt string `json:"prompt"` +} + +func (AuthLoginStepInputRequired) authLoginStep() {} +func (AuthLoginStepInputRequired) Kind() AuthLoginStepKind { + return AuthLoginStepKindInputRequired +} + +type AuthLoginStepNeedsInteraction struct { +} + +func (AuthLoginStepNeedsInteraction) authLoginStep() {} +func (AuthLoginStepNeedsInteraction) Kind() AuthLoginStepKind { + return AuthLoginStepKindNeedsInteraction +} + +type AuthLoginStepOpenURL struct { + // Authorize URL the consumer should open in a browser (consumer-driven browser-open). + URL string `json:"url"` +} + +func (AuthLoginStepOpenURL) authLoginStep() {} +func (AuthLoginStepOpenURL) Kind() AuthLoginStepKind { + return AuthLoginStepKindOpenURL +} + +// Selects which typed accounts datum to read. +// Experimental: AuthReadQuery is part of an experimental API and may change or be removed. +type AuthReadQuery interface { + authReadQuery() + Kind() AuthReadQueryKind +} + +type RawAuthReadQueryData struct { + Discriminator AuthReadQueryKind + Raw json.RawMessage +} + +func (RawAuthReadQueryData) authReadQuery() {} +func (r RawAuthReadQueryData) Kind() AuthReadQueryKind { + return r.Discriminator +} + +type AuthReadQueryActiveAccount struct { +} + +func (AuthReadQueryActiveAccount) authReadQuery() {} +func (AuthReadQueryActiveAccount) Kind() AuthReadQueryKind { + return AuthReadQueryKindActiveAccount +} + +type AuthReadQueryLastErrors struct { +} + +func (AuthReadQueryLastErrors) authReadQuery() {} +func (AuthReadQueryLastErrors) Kind() AuthReadQueryKind { + return AuthReadQueryKindLastErrors +} + +type AuthReadQueryStatus struct { +} + +func (AuthReadQueryStatus) authReadQuery() {} +func (AuthReadQueryStatus) Kind() AuthReadQueryKind { + return AuthReadQueryKindStatus +} + +// The read result, keyed by the same selector as the query. +// Experimental: AuthReadValue is part of an experimental API and may change or be removed. +type AuthReadValue interface { + authReadValue() + Kind() AuthReadValueKind +} + +type RawAuthReadValueData struct { + Discriminator AuthReadValueKind + Raw json.RawMessage +} + +func (RawAuthReadValueData) authReadValue() {} +func (r RawAuthReadValueData) Kind() AuthReadValueKind { + return r.Discriminator +} + +type AuthReadValueActiveAccount struct { + // The active account, or absent when not logged in. + Account *AccountStatus `json:"account,omitempty"` +} + +func (AuthReadValueActiveAccount) authReadValue() {} +func (AuthReadValueActiveAccount) Kind() AuthReadValueKind { + return AuthReadValueKindActiveAccount +} + +type AuthReadValueLastErrors struct { + // Validation errors from the most recent authentication attempt. + Errors []AuthValidationError `json:"errors"` +} + +func (AuthReadValueLastErrors) authReadValue() {} +func (AuthReadValueLastErrors) Kind() AuthReadValueKind { + return AuthReadValueKindLastErrors +} + +type AuthReadValueStatus struct { + // The neutral authentication status summary. + Status AuthStatusDto `json:"status"` +} + +func (AuthReadValueStatus) authReadValue() {} +func (AuthReadValueStatus) Kind() AuthReadValueKind { + return AuthReadValueKindStatus +} + +// Neutral authentication status summary. +// Experimental: AuthStatusDto is part of an experimental API and may change or be removed. +type AuthStatusDto struct { + // Number of signed-in accounts in the roster. + AccountCount int64 `json:"accountCount"` + // Active account host, if authenticated. + ActiveHost *string `json:"activeHost,omitempty"` + // Active account login, if authenticated. + ActiveLogin *string `json:"activeLogin,omitempty"` + // Copilot plan tier of the active account, if known. + CopilotPlan *string `json:"copilotPlan,omitempty"` + // Whether the session has resolved authentication. + IsAuthenticated bool `json:"isAuthenticated"` +} + // Validation error from an authentication attempt. // Experimental: AuthValidationError is part of an experimental API and may change or be // removed. @@ -1077,6 +1425,66 @@ type AuthValidationError struct { // removed. type AuthValidationErrors []AuthValidationError +// One non-interactive accounts mutation command (the selector is fused with its typed args). +// Experimental: AuthWrite is part of an experimental API and may change or be removed. +type AuthWrite interface { + authWrite() + Kind() AuthWriteKind +} + +type RawAuthWriteData struct { + Discriminator AuthWriteKind + Raw json.RawMessage +} + +func (RawAuthWriteData) authWrite() {} +func (r RawAuthWriteData) Kind() AuthWriteKind { + return r.Discriminator +} + +type AuthWriteLogout struct { + // Opaque selection id of the account to log out; absent logs out the active account. + SelectionID *string `json:"selectionId,omitempty"` +} + +func (AuthWriteLogout) authWrite() {} +func (AuthWriteLogout) Kind() AuthWriteKind { + return AuthWriteKindLogout +} + +type AuthWriteSetCredentials struct { + // Authentication host URL. + Host string `json:"host"` + // Login/username for the credential. + Login string `json:"login"` + // GitHub authentication token to install. + Token string `json:"token"` +} + +func (AuthWriteSetCredentials) authWrite() {} +func (AuthWriteSetCredentials) Kind() AuthWriteKind { + return AuthWriteKindSetCredentials +} + +type AuthWriteSwitchActive struct { + // Opaque selection id of the account to make active. + SelectionID string `json:"selectionId"` +} + +func (AuthWriteSwitchActive) authWrite() {} +func (AuthWriteSwitchActive) Kind() AuthWriteKind { + return AuthWriteKindSwitchActive +} + +// Result of a non-interactive accounts mutation. +// Experimental: AuthWriteResult is part of an experimental API and may change or be removed. +type AuthWriteResult struct { + // For a logout, whether other signed-in accounts remain. + MoreUsers *bool `json:"moreUsers,omitempty"` + // Whether the mutation was applied. + Ok bool `json:"ok"` +} + // Current per-window credit limit and consumption for an autopilot objective. // Experimental: AutopilotObjectiveCreditLimit is part of an experimental API and may change // or be removed. @@ -4058,730 +4466,6 @@ type ExternalToolTextResultForLlmContentResourceLinkIcon struct { Theme *ExternalToolTextResultForLlmContentResourceLinkIconTheme `json:"theme,omitempty"` } -// Parameters for cooperatively aborting a factory body. -// Experimental: FactoryAbortRequest is part of an experimental API and may change or be -// removed. -type FactoryAbortRequest struct { - // Opaque token identifying the execution attempt to abort. - ExecutionToken string `json:"executionToken"` - // Factory run identifier. - RunID string `json:"runId"` - // Target session identifier - SessionID string `json:"sessionId"` -} - -// Acknowledgement that a factory request was accepted. -// Experimental: FactoryAckResult is part of an experimental API and may change or be -// removed. -type FactoryAckResult struct { -} - -// Options for one factory-scoped subagent call. -// Experimental: FactoryAgentOptions is part of an experimental API and may change or be -// removed. -type FactoryAgentOptions struct { - // Optional built-in or custom agent name whose definition configures the subagent. - Agent *string `json:"agent,omitempty"` - // Optional context tier override for the subagent. - ContextTier *ContextTier `json:"contextTier,omitempty"` - // Optional label distinguishing otherwise identical memoized agent calls. - Label *string `json:"label,omitempty"` - // Optional model identifier for the subagent. - Model *string `json:"model,omitempty"` - // Optional reasoning effort override for the subagent. - ReasoningEffort *string `json:"reasoningEffort,omitempty"` - // Optional JSON Schema for structured agent output. - Schema any `json:"schema,omitempty"` -} - -// Parameters for one factory-scoped subagent call. -// Experimental: FactoryAgentRequest is part of an experimental API and may change or be -// removed. -type FactoryAgentRequest struct { - // Opaque token identifying the current factory execution attempt. - ExecutionToken string `json:"executionToken"` - // Factory run identifier that owns the subagent. - FactoryRunID string `json:"factoryRunId"` - // Subagent execution options. - Opts FactoryAgentOptions `json:"opts"` - // Prompt to send to the subagent. - Prompt string `json:"prompt"` -} - -// Result of one factory-scoped subagent call. -// Experimental: FactoryAgentResult is part of an experimental API and may change or be -// removed. -type FactoryAgentResult struct { - // Agent result, omitted when the agent produced no result. - Result any `json:"result,omitempty"` -} - -// Prompt-safe durable identity and live status for a direct factory agent. -// Experimental: FactoryAgentSummary is part of an experimental API and may change or be -// removed. -type FactoryAgentSummary struct { - // Accumulated active agent time in milliseconds. - ActiveMs int64 `json:"activeMs"` - // Prompt-safe live activity text. - Activity *string `json:"activity,omitempty"` - // Stable direct-agent identifier. - AgentID string `json:"agentId"` - // Registered agent type. - AgentType string `json:"agentType"` - // Epoch milliseconds when the agent completed. - CompletedAt *int64 `json:"completedAt,omitempty"` - // Friendly, non-unique name intended for display - DisplayName *string `json:"displayName,omitempty"` - // Friendly, non-unique name intended for display - Label string `json:"label"` - // Phase identifier active when the agent was launched, or null. - PhaseID *string `json:"phaseId"` - // Model requested when the agent was launched. - RequestedModel *string `json:"requestedModel,omitempty"` - // Concrete model resolved for the agent. - ResolvedModel *string `json:"resolvedModel,omitempty"` - // Owning factory run identifier. - RunID string `json:"runId"` - // Epoch milliseconds when the agent started. - StartedAt *int64 `json:"startedAt,omitempty"` - // Current durable or live agent status. - Status string `json:"status"` - // Tool-call identifier that launched the agent. - ToolCallID string `json:"toolCallId"` -} - -// Parameters for cancelling a factory run. -// Experimental: FactoryCancelRequest is part of an experimental API and may change or be -// removed. -type FactoryCancelRequest struct { - // Factory run identifier. - RunID string `json:"runId"` -} - -// Current factory phase identity. -// Experimental: FactoryCurrentPhase is part of an experimental API and may change or be -// removed. -type FactoryCurrentPhase struct { - // Current phase identifier. - ID string `json:"id"` - // Zero-based declared phase ordinal, or null for an undeclared phase. - Ordinal *int64 `json:"ordinal"` -} - -// Declared or approved factory resource ceilings. -// Experimental: FactoryDeclaredLimits is part of an experimental API and may change or be -// removed. -type FactoryDeclaredLimits struct { - // Maximum AI credits consumed by subagents and descendants. - MaxAiCredits *float64 `json:"maxAiCredits,omitempty"` - // Maximum concurrently active subagents. - MaxConcurrentSubagents *int64 `json:"maxConcurrentSubagents,omitempty"` - // Maximum total subagents spawned by the run. - MaxTotalSubagents *int64 `json:"maxTotalSubagents,omitempty"` - // Maximum accumulated active execution time in seconds. - TimeoutSeconds *float64 `json:"timeoutSeconds,omitempty"` -} - -// Parameters sent to the owning extension to execute a factory closure. -// Experimental: FactoryExecuteRequest is part of an experimental API and may change or be -// removed. -type FactoryExecuteRequest struct { - // Factory input value. - Args any `json:"args"` - // Opaque token identifying this factory execution attempt. - ExecutionToken string `json:"executionToken"` - // Registered factory name. - Name string `json:"name"` - // Factory run identifier. - RunID string `json:"runId"` - // Target session identifier - SessionID string `json:"sessionId"` -} - -// Result returned by an extension factory closure. -// Experimental: FactoryExecuteResult is part of an experimental API and may change or be -// removed. -type FactoryExecuteResult struct { - // Factory result value. - Result any `json:"result,omitempty"` -} - -// Parameters for paging factory progress. -// Experimental: FactoryGetRunProgressRequest is part of an experimental API and may change -// or be removed. -type FactoryGetRunProgressRequest struct { - // Exclusive forward cursor. - AfterSeq *int64 `json:"afterSeq,omitempty"` - // Exclusive backward cursor. - BeforeSeq *int64 `json:"beforeSeq,omitempty"` - // Maximum records to return. Defaults to 200 and is capped at 500. - Limit *int32 `json:"limit,omitempty"` - // Optional phase identifier used to scope records and cursors. - PhaseID *string `json:"phaseId,omitempty"` - // Factory run identifier. - RunID string `json:"runId"` -} - -// Parameters for retrieving a factory run. -// Experimental: FactoryGetRunRequest is part of an experimental API and may change or be -// removed. -type FactoryGetRunRequest struct { - // Factory run identifier. - RunID string `json:"runId"` -} - -// Parameters for reading a factory journal entry. -// Experimental: FactoryJournalGetRequest is part of an experimental API and may change or -// be removed. -type FactoryJournalGetRequest struct { - // Opaque token identifying the current factory execution attempt. - ExecutionToken string `json:"executionToken"` - // Namespaced journal key. - Key string `json:"key"` - // Factory run identifier. - RunID string `json:"runId"` -} - -// Result of reading a factory journal entry. -// Experimental: FactoryJournalGetResult is part of an experimental API and may change or be -// removed. -type FactoryJournalGetResult struct { - // Whether the journal contained the requested key. - Hit bool `json:"hit"` - // Cached JSON result. The hit field distinguishes a cached JSON null from a miss. - ResultJSON any `json:"resultJson,omitempty"` -} - -// Parameters for storing a factory journal entry. -// Experimental: FactoryJournalPutRequest is part of an experimental API and may change or -// be removed. -type FactoryJournalPutRequest struct { - // Opaque token identifying the current factory execution attempt. - ExecutionToken string `json:"executionToken"` - // Namespaced journal key. - Key string `json:"key"` - // JSON result to memoize. - ResultJSON any `json:"resultJson"` - // Factory run identifier. - RunID string `json:"runId"` -} - -// Parameters for paging factory runs. -// Experimental: FactoryListRunsRequest is part of an experimental API and may change or be -// removed. -type FactoryListRunsRequest struct { - // Exclusive forward cursor. - AfterSeq *int64 `json:"afterSeq,omitempty"` - // Exclusive backward cursor. - BeforeSeq *int64 `json:"beforeSeq,omitempty"` - // Maximum terminal runs to return. Defaults to 200 and is capped at 500. - Limit *int32 `json:"limit,omitempty"` -} - -// A page of factory runs in durable creation order. -// Experimental: FactoryListRunsResult is part of an experimental API and may change or be -// removed. -type FactoryListRunsResult struct { - // Whether terminal runs newer than this page exist. - HasMoreNewer *bool `json:"hasMoreNewer,omitempty"` - // Newest terminal-run cursor in this page, or null when the terminal window is empty. - NewestSeq *int64 `json:"newestSeq,omitempty"` - // Oldest terminal-run cursor in this page, or null when the terminal window is empty. - OldestSeq *int64 `json:"oldestSeq,omitempty"` - // Number of terminal runs older than this page. - OmittedOlder *int64 `json:"omittedOlder,omitempty"` - // Factory run summaries in durable creation order. - Runs []FactoryRunSummary `json:"runs"` -} - -// One ordered factory progress line. -// Experimental: FactoryLogLine is part of an experimental API and may change or be removed. -type FactoryLogLine struct { - // Progress line kind. - Kind FactoryLogLineKind `json:"kind"` - // Monotonic sequence number within the factory run. - Seq int64 `json:"seq"` - // Progress text. - Text string `json:"text"` -} - -// Parameters for recording factory progress. -// Experimental: FactoryLogRequest is part of an experimental API and may change or be -// removed. -type FactoryLogRequest struct { - // Opaque token identifying the current factory execution attempt. - ExecutionToken string `json:"executionToken"` - // Ordered progress lines to append. - Lines []FactoryLogLine `json:"lines"` - // Factory run identifier. - RunID string `json:"runId"` -} - -// Parameters for an owned durable pause checkpoint. -// Experimental: FactoryPauseCheckpointRequest is part of an experimental API and may change -// or be removed. -type FactoryPauseCheckpointRequest struct { - // Opaque token identifying the execution attempt that reached the checkpoint. - ExecutionToken string `json:"executionToken"` - // Stable author-defined checkpoint key. - Key string `json:"key"` - // Factory run identifier. - RunID string `json:"runId"` -} - -// Experimental: FactoryPauseCheckpointResult is part of an experimental API and may change -// or be removed. -type FactoryPauseCheckpointResult struct { - // Whether this execution attempt must pause or may continue. - Action FactoryPauseCheckpointAction `json:"action"` -} - -// Durable metadata describing who initiated a factory pause. -// Experimental: FactoryPauseInfo is part of an experimental API and may change or be -// removed. -type FactoryPauseInfo interface { - factoryPauseInfo() - Type() FactoryPauseInfoType -} - -type RawFactoryPauseInfoData struct { - Discriminator FactoryPauseInfoType - Raw json.RawMessage -} - -func (RawFactoryPauseInfoData) factoryPauseInfo() {} -func (r RawFactoryPauseInfoData) Type() FactoryPauseInfoType { - return r.Discriminator -} - -type FactoryPauseInfoCheckpoint struct { - // Stable author-defined checkpoint key that initiated the pause. - Key string `json:"key"` -} - -func (FactoryPauseInfoCheckpoint) factoryPauseInfo() {} -func (FactoryPauseInfoCheckpoint) Type() FactoryPauseInfoType { - return FactoryPauseInfoTypeCheckpoint -} - -type FactoryPauseInfoUser struct { -} - -func (FactoryPauseInfoUser) factoryPauseInfo() {} -func (FactoryPauseInfoUser) Type() FactoryPauseInfoType { - return FactoryPauseInfoTypeUser -} - -// Parameters for pausing a running factory. -// Experimental: FactoryPauseRequest is part of an experimental API and may change or be -// removed. -type FactoryPauseRequest struct { - // Factory run identifier. - RunID string `json:"runId"` -} - -// Durable lifecycle and timing for one factory phase. -// Experimental: FactoryPhaseObservation is part of an experimental API and may change or be -// removed. -type FactoryPhaseObservation struct { - // Completed active time accumulated by this phase in milliseconds. - AccumulatedActiveMs int64 `json:"accumulatedActiveMs"` - // Epoch milliseconds when this phase completed; for a skipped phase, the synthetic skip - // timestamp (equal to `startedAt`). - CompletedAt *int64 `json:"completedAt,omitempty"` - // Current live active time for this phase in milliseconds. - CurrentActiveMs int64 `json:"currentActiveMs"` - // Optional human-readable phase detail. - Detail *string `json:"detail,omitempty"` - // Number of times execution entered this phase. - EntryCount int64 `json:"entryCount"` - // Phase identifier. - ID string `json:"id"` - // Most recent run attempt that entered this phase, or `0` if the phase has never been - // entered. - LastEnteredRunAttempt int64 `json:"lastEnteredRunAttempt"` - // Direct agents in this phase that are currently live. - LiveAgentCount int64 `json:"liveAgentCount"` - // Zero-based declared phase ordinal, or null for an undeclared phase. - Ordinal *int64 `json:"ordinal"` - // Epoch milliseconds when this phase first started; for a skipped phase, the synthetic skip - // timestamp (equal to `completedAt`). - StartedAt *int64 `json:"startedAt,omitempty"` - // Derived lifecycle state of the phase. - Status FactoryPhaseStatus `json:"status"` - // Human-readable phase title. - Title string `json:"title"` - // Total direct agents associated with this phase. - TotalAgentCount int64 `json:"totalAgentCount"` -} - -// One durable factory progress record. -// Experimental: FactoryProgressLine is part of an experimental API and may change or be -// removed. -type FactoryProgressLine struct { - // Resume attempt that emitted this record. - Attempt int64 `json:"attempt"` - // Progress record kind. - Kind FactoryLogLineKind `json:"kind"` - // Phase active when the record was emitted, or null before any phase. - PhaseID *string `json:"phaseId"` - // Epoch milliseconds when the record was persisted. - RecordedAt int64 `json:"recordedAt"` - // Global monotonic sequence number within the run. - Seq int64 `json:"seq"` - // Prompt-safe progress text. - Text string `json:"text"` -} - -// A bidirectional page of factory progress. -// Experimental: FactoryProgressPage is part of an experimental API and may change or be -// removed. -type FactoryProgressPage struct { - // Whether progress records newer than this page exist. - HasMoreNewer bool `json:"hasMoreNewer"` - // Whether progress records older than this page exist. - HasMoreOlder bool `json:"hasMoreOlder"` - // Newest sequence number in this page, or null when empty. - NewestSeq *int64 `json:"newestSeq"` - // Oldest sequence number in this page, or null when empty. - OldestSeq *int64 `json:"oldestSeq"` - // Progress records in sequence order. - Records []FactoryProgressLine `json:"records"` - // Run revision reflected by this page. - Revision int64 `json:"revision"` -} - -// Parameters for resuming a factory run from its persisted identity. -// Experimental: FactoryResumeRequest is part of an experimental API and may change or be -// removed. -type FactoryResumeRequest struct { - // Optional per-invocation resource ceiling overrides. - Limits *FactoryRunLimits `json:"limits,omitempty"` - // Whether to emit factory phase names to the session transcript. - LogPhaseNames *bool `json:"logPhaseNames,omitempty"` - // Whether to notify the originating session when the factory completes. - NotifyOnComplete *bool `json:"notifyOnComplete,omitempty"` - // Factory run identifier. - RunID string `json:"runId"` -} - -// Resolved persisted factory identity and resumed run envelope. -// Experimental: FactoryResumeResult is part of an experimental API and may change or be -// removed. -type FactoryResumeResult struct { - // Persisted factory name resolved for the resumed run. - FactoryName string `json:"factoryName"` - // Terminal resumed run envelope. - Run FactoryRunResult `json:"run"` -} - -// Durable factory resource consumption. -// Experimental: FactoryRunConsumed is part of an experimental API and may change or be -// removed. -type FactoryRunConsumed struct { - // Accumulated active execution time in milliseconds. - ActiveMs int64 `json:"activeMs"` - // AI usage consumed by the run in nano-AIU. - NanoAiu int64 `json:"nanoAiu"` - // Total subagents spawned by the run. - Subagents int64 `json:"subagents"` -} - -// Full factory run observability detail. -// Experimental: FactoryRunDetail is part of an experimental API and may change or be -// removed. -type FactoryRunDetail struct { - // Epoch milliseconds when the current active segment started, or null while inactive. - ActiveSegmentStartedAt *int64 `json:"activeSegmentStartedAt"` - // Durable identities and live statuses for direct factory agents. - Agents []FactoryAgentSummary `json:"agents"` - // Approved effective resource ceilings, or null until approved. - Approved *FactoryDeclaredLimits `json:"approved"` - // Whether the durable run state currently passes runtime resume eligibility checks. - CanResume bool `json:"canResume"` - // Epoch milliseconds when the run completed, or null while nonterminal. - CompletedAt *int64 `json:"completedAt"` - // Durable resource consumption. - Consumed FactoryRunConsumed `json:"consumed"` - // Epoch milliseconds when the run was created. - CreatedAt int64 `json:"createdAt"` - // Current phase identity, or null before any phase is entered. - CurrentPhase *FactoryCurrentPhase `json:"currentPhase"` - // Resource ceilings declared by the factory. - DeclaredLimits FactoryDeclaredLimits `json:"declaredLimits"` - // Number of phases declared by the factory. - DeclaredPhaseCount int64 `json:"declaredPhaseCount"` - // Human-readable factory description. - Description string `json:"description"` - // Registered factory name. - FactoryName string `json:"factoryName"` - // Number of direct factory agents currently live. - LiveAgentCount int64 `json:"liveAgentCount"` - // Epoch milliseconds when this live-overlay snapshot was observed. - ObservedAt int64 `json:"observedAt"` - // Lifecycle and timing observations for each factory phase. - Phases []FactoryPhaseObservation `json:"phases"` - // Bidirectional page of durable factory progress. - Progress FactoryProgressPage `json:"progress"` - // Monotonic durable run revision. - Revision int64 `json:"revision"` - // Factory run identifier. - RunID string `json:"runId"` - // Epoch milliseconds when execution first started, or null before start. - StartedAt *int64 `json:"startedAt"` - // Current factory run status. - Status FactoryRunStatus `json:"status"` - // Terminal run outcome, or null while nonterminal. - Terminal *FactoryRunTerminal `json:"terminal"` - // Total direct factory agents spawned across all attempts. - TotalSpawnedAgentCount int64 `json:"totalSpawnedAgentCount"` - // Epoch milliseconds when the durable run was last updated. - UpdatedAt int64 `json:"updatedAt"` -} - -// Machine-readable factory run failure. -// Experimental: FactoryRunFailure is part of an experimental API and may change or be -// removed. -type FactoryRunFailure interface { - factoryRunFailure() - Type() FactoryRunFailureType -} - -type RawFactoryRunFailureData struct { - Discriminator FactoryRunFailureType - Raw json.RawMessage -} - -func (RawFactoryRunFailureData) factoryRunFailure() {} -func (r RawFactoryRunFailureData) Type() FactoryRunFailureType { - return r.Discriminator -} - -// The run stopped because its usage accounting could not be completed. -type FactoryRunFailureFactoryAccountingIncomplete struct { - // Confirmed usage in nano-AIU, representing the floor of what the run spent. - DrainedNanoAiu int64 `json:"drainedNanoAiu"` - // Factory run identifier. - RunID string `json:"runId"` -} - -func (FactoryRunFailureFactoryAccountingIncomplete) factoryRunFailure() {} -func (FactoryRunFailureFactoryAccountingIncomplete) Type() FactoryRunFailureType { - return FactoryRunFailureTypeFactoryAccountingIncomplete -} - -type FactoryRunFailureFactoryDurableFailure struct { - // Stable failure code. - Code string `json:"code"` - // Execution-critical durable operation that failed. - Operation FactoryDurableOperation `json:"operation"` - // Factory run identifier. - RunID string `json:"runId"` -} - -func (FactoryRunFailureFactoryDurableFailure) factoryRunFailure() {} -func (FactoryRunFailureFactoryDurableFailure) Type() FactoryRunFailureType { - return FactoryRunFailureTypeFactoryDurableFailure -} - -type FactoryRunFailureFactoryLimitReached struct { - // Resource ceiling that stopped the run. - Kind FactoryRunFailureKind `json:"kind"` - // Factory run identifier. - RunID string `json:"runId"` - // Suggested larger ceiling when the runtime can derive one safely. - SuggestedValue *float64 `json:"suggestedValue,omitempty"` - // Approved effective ceiling that was reached. - Value float64 `json:"value"` -} - -func (FactoryRunFailureFactoryLimitReached) factoryRunFailure() {} -func (FactoryRunFailureFactoryLimitReached) Type() FactoryRunFailureType { - return FactoryRunFailureTypeFactoryLimitReached -} - -// The extension that owns the factory disconnected while the run was executing, so the host -// halted it. The run's journaled subagent results are preserved so a resume can reuse them. -type FactoryRunFailureFactoryProviderDisconnected struct { - // Factory run identifier. - RunID string `json:"runId"` -} - -func (FactoryRunFailureFactoryProviderDisconnected) factoryRunFailure() {} -func (FactoryRunFailureFactoryProviderDisconnected) Type() FactoryRunFailureType { - return FactoryRunFailureTypeFactoryProviderDisconnected -} - -type FactoryRunFailureFactoryResumeDeclined struct { - // Human-readable reason the resume did not proceed. - Reason string `json:"reason"` - // Factory run identifier whose changed limits were declined. - RunID string `json:"runId"` -} - -func (FactoryRunFailureFactoryResumeDeclined) factoryRunFailure() {} -func (FactoryRunFailureFactoryResumeDeclined) Type() FactoryRunFailureType { - return FactoryRunFailureTypeFactoryResumeDeclined -} - -// Wire-only per-invocation factory resource ceiling overrides. -// Experimental: FactoryRunLimits is part of an experimental API and may change or be -// removed. -type FactoryRunLimits struct { - // Maximum AI credits consumed by factory subagents and their descendants. The post-paid - // ceiling is soft: parallel turns can settle beyond it before the run stops. - MaxAiCredits *float64 `json:"maxAiCredits,omitempty"` - // Maximum number of factory subagents that may run concurrently. - MaxConcurrentSubagents *int64 `json:"maxConcurrentSubagents,omitempty"` - // Maximum total number of factory subagents that may be admitted. - MaxTotalSubagents *int64 `json:"maxTotalSubagents,omitempty"` - // Maximum accumulated active-execution time in seconds. Active execution includes the - // entire extension body, subprocess waits, queued-agent waits, and sleeps; time between - // resumed attempts is not counted. - TimeoutSeconds *float64 `json:"timeoutSeconds,omitempty"` -} - -// Parameters for invoking a registered factory. -// Experimental: FactoryRunRequest is part of an experimental API and may change or be -// removed. -type FactoryRunRequest struct { - // Factory input value. - Args any `json:"args"` - // Registered factory name. - Name string `json:"name"` - // Factory invocation options. - Options *RunOptions `json:"options,omitempty"` -} - -// Complete current or terminal factory run envelope. -// Experimental: FactoryRunResult is part of an experimental API and may change or be -// removed. -type FactoryRunResult struct { - // One-based execution attempt represented by this envelope. Absent before the first attempt - // starts or when returned by an older runtime. - Attempt *int64 `json:"attempt,omitempty"` - // Error message for an errored run. - Error *string `json:"error,omitempty"` - // Machine-readable failure details for a halted or errored run. - Failure FactoryRunFailure `json:"failure,omitempty"` - // Structured pause initiator metadata for a paused attempt. - PauseInfo FactoryPauseInfo `json:"pauseInfo,omitempty"` - // Reason for a halted or cancelled run. - Reason *string `json:"reason,omitempty"` - // Completed factory result. - Result any `json:"result,omitempty"` - // Factory run identifier. - RunID string `json:"runId"` - // Partial journal and progress snapshot for a halted, cancelled, or errored run. - Snapshot any `json:"snapshot,omitempty"` - // Current or terminal factory run status. - Status FactoryRunStatus `json:"status"` -} - -// Durable factory run summary with read-time live overlays. -// Experimental: FactoryRunSummary is part of an experimental API and may change or be -// removed. -type FactoryRunSummary struct { - // Epoch milliseconds when the current active segment started, or null while inactive. - ActiveSegmentStartedAt *int64 `json:"activeSegmentStartedAt"` - // Approved effective resource ceilings, or null until approved. - Approved *FactoryDeclaredLimits `json:"approved"` - // Whether the durable run state currently passes runtime resume eligibility checks. - CanResume bool `json:"canResume"` - // Epoch milliseconds when the run completed, or null while nonterminal. - CompletedAt *int64 `json:"completedAt"` - // Durable resource consumption. - Consumed FactoryRunConsumed `json:"consumed"` - // Epoch milliseconds when the run was created. - CreatedAt int64 `json:"createdAt"` - // Current phase identity, or null before any phase is entered. - CurrentPhase *FactoryCurrentPhase `json:"currentPhase"` - // Resource ceilings declared by the factory. - DeclaredLimits FactoryDeclaredLimits `json:"declaredLimits"` - // Number of phases declared by the factory. - DeclaredPhaseCount int64 `json:"declaredPhaseCount"` - // Human-readable factory description. - Description string `json:"description"` - // Registered factory name. - FactoryName string `json:"factoryName"` - // Number of direct factory agents currently live. - LiveAgentCount int64 `json:"liveAgentCount"` - // Epoch milliseconds when this live-overlay snapshot was observed. - ObservedAt int64 `json:"observedAt"` - // Monotonic durable run revision. - Revision int64 `json:"revision"` - // Factory run identifier. - RunID string `json:"runId"` - // Epoch milliseconds when execution first started, or null before start. - StartedAt *int64 `json:"startedAt"` - // Current factory run status. - Status FactoryRunStatus `json:"status"` - // Terminal run outcome, or null while nonterminal. - Terminal *FactoryRunTerminal `json:"terminal"` - // Total direct factory agents spawned across all attempts. - TotalSpawnedAgentCount int64 `json:"totalSpawnedAgentCount"` - // Epoch milliseconds when the durable run was last updated. - UpdatedAt int64 `json:"updatedAt"` -} - -// Prompt-safe terminal factory outcome. -// Experimental: FactoryRunTerminal is part of an experimental API and may change or be -// removed. -type FactoryRunTerminal struct { - // Human-readable terminal error. - Error *string `json:"error,omitempty"` - // Machine-readable terminal failure. - Failure FactoryRunFailure `json:"failure,omitempty"` - // Pause initiator metadata, or null when the run did not pause. - PauseInfo FactoryPauseInfo `json:"pauseInfo"` - // Human-readable terminal reason. - Reason *string `json:"reason,omitempty"` - // Prompt-safe preview of the completed result. - ResultPreview *string `json:"resultPreview,omitempty"` -} - -// Internal parameters for resuming a factory run from a tool. -// Experimental: FactoryToolResumeRequest is part of an experimental API and may change or -// be removed. -// Internal: FactoryToolResumeRequest is an internal SDK API and is not part of the public -// surface. -type FactoryToolResumeRequest struct { - // Optional per-invocation resource ceiling overrides. - Limits *FactoryRunLimits `json:"limits,omitempty"` - // Factory run identifier. - RunID string `json:"runId"` - // Opaque identifier of the originating tool call. - ToolCallID *string `json:"toolCallId,omitempty"` -} - -// Options for an internal tool-originated factory invocation. -// Experimental: FactoryToolRunOptions is part of an experimental API and may change or be -// removed. -// Internal: FactoryToolRunOptions is an internal SDK API and is not part of the public -// surface. -type FactoryToolRunOptions struct { - // Per-invocation resource ceiling overrides. - Limits *FactoryRunLimits `json:"limits,omitempty"` - // Run identifier whose journal and progress should seed this resumed run. - ResumeFromRunID *string `json:"resumeFromRunId,omitempty"` -} - -// Internal parameters for invoking a registered factory from a tool. -// Experimental: FactoryToolRunRequest is part of an experimental API and may change or be -// removed. -// Internal: FactoryToolRunRequest is an internal SDK API and is not part of the public -// surface. -type FactoryToolRunRequest struct { - // Factory input value. - Args any `json:"args"` - // Registered factory name. - Name string `json:"name"` - // Tool-originated factory invocation options. - Options *FactoryToolRunOptions `json:"options,omitempty"` - // Opaque identifier of the originating tool call. - ToolCallID *string `json:"toolCallId,omitempty"` -} - // Content filtering mode to apply to all tools, or a map of tool name to content filtering // mode. // Experimental: FilterMapping is part of an experimental API and may change or be removed. @@ -8232,6 +7916,14 @@ type ModelApplyStartupOverlayRequest struct { DeferredResume *bool `json:"deferredResume,omitempty"` // Model required by device-managed policy, when configured. DeviceManagedModel *string `json:"deviceManagedModel,omitempty"` + // Context tier paired with the effective organization-managed model. Applies only when that + // concrete managed model is selected; it is ignored for Auto and for CLI, resume, or user + // overrides. + ManagedContextTier *string `json:"managedContextTier,omitempty"` + // Reasoning effort paired with the effective organization-managed model. Applies only when + // that concrete managed model is selected; it is ignored for Auto and for CLI, resume, or + // user overrides. + ManagedReasoningEffort *string `json:"managedReasoningEffort,omitempty"` // Startup default model from the enterprise policy helper, when configured. Weakest of the // managed sources: it applies only when neither device nor server policy names a model, and // an explicit user selection still wins. @@ -9243,21 +8935,6 @@ func (PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess) Kin return PermissionDecisionApproveForLocationApprovalKindExtensionPermissionAccess } -// Location-scoped factory approval, optionally narrowed by approval key. -// Experimental: PermissionDecisionApproveForLocationApprovalFactory is part of an -// experimental API and may change or be removed. -type PermissionDecisionApproveForLocationApprovalFactory struct { - // Optional factory operation name or canonical approval key; when omitted, the approval - // covers all factory operations. - ApprovalKey *string `json:"approvalKey,omitempty"` -} - -func (PermissionDecisionApproveForLocationApprovalFactory) permissionDecisionApproveForLocationApproval() { -} -func (PermissionDecisionApproveForLocationApprovalFactory) Kind() PermissionDecisionApproveForLocationApprovalKind { - return PermissionDecisionApproveForLocationApprovalKindFactory -} - // Location-scoped approval details for an MCP server tool, or all tools on the server when // `toolName` is null. // Experimental: PermissionDecisionApproveForLocationApprovalMCP is part of an experimental @@ -9313,6 +8990,21 @@ func (PermissionDecisionApproveForLocationApprovalRead) Kind() PermissionDecisio return PermissionDecisionApproveForLocationApprovalKindRead } +// Location-scoped workflow approval, optionally narrowed by approval key. +// Experimental: PermissionDecisionApproveForLocationApprovalWorkflow is part of an +// experimental API and may change or be removed. +type PermissionDecisionApproveForLocationApprovalWorkflow struct { + // Optional workflow operation name or canonical approval key; when omitted, the approval + // covers all workflow operations. + ApprovalKey *string `json:"approvalKey,omitempty"` +} + +func (PermissionDecisionApproveForLocationApprovalWorkflow) permissionDecisionApproveForLocationApproval() { +} +func (PermissionDecisionApproveForLocationApprovalWorkflow) Kind() PermissionDecisionApproveForLocationApprovalKind { + return PermissionDecisionApproveForLocationApprovalKindWorkflow +} + // Location-scoped approval details for filesystem write operations. // Experimental: PermissionDecisionApproveForLocationApprovalWrite is part of an // experimental API and may change or be removed. @@ -9421,21 +9113,6 @@ func (PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess) Kind return PermissionDecisionApproveForSessionApprovalKindExtensionPermissionAccess } -// Session-scoped factory approval, optionally narrowed by approval key. -// Experimental: PermissionDecisionApproveForSessionApprovalFactory is part of an -// experimental API and may change or be removed. -type PermissionDecisionApproveForSessionApprovalFactory struct { - // Optional factory operation name or canonical approval key; when omitted, the approval - // covers all factory operations. - ApprovalKey *string `json:"approvalKey,omitempty"` -} - -func (PermissionDecisionApproveForSessionApprovalFactory) permissionDecisionApproveForSessionApproval() { -} -func (PermissionDecisionApproveForSessionApprovalFactory) Kind() PermissionDecisionApproveForSessionApprovalKind { - return PermissionDecisionApproveForSessionApprovalKindFactory -} - // Session-scoped approval details for an MCP server tool, or all tools on the server when // `toolName` is null. // Experimental: PermissionDecisionApproveForSessionApprovalMCP is part of an experimental @@ -9490,6 +9167,21 @@ func (PermissionDecisionApproveForSessionApprovalRead) Kind() PermissionDecision return PermissionDecisionApproveForSessionApprovalKindRead } +// Session-scoped workflow approval, optionally narrowed by approval key. +// Experimental: PermissionDecisionApproveForSessionApprovalWorkflow is part of an +// experimental API and may change or be removed. +type PermissionDecisionApproveForSessionApprovalWorkflow struct { + // Optional workflow operation name or canonical approval key; when omitted, the approval + // covers all workflow operations. + ApprovalKey *string `json:"approvalKey,omitempty"` +} + +func (PermissionDecisionApproveForSessionApprovalWorkflow) permissionDecisionApproveForSessionApproval() { +} +func (PermissionDecisionApproveForSessionApprovalWorkflow) Kind() PermissionDecisionApproveForSessionApprovalKind { + return PermissionDecisionApproveForSessionApprovalKindWorkflow +} + // Session-scoped approval details for filesystem write operations. // Experimental: PermissionDecisionApproveForSessionApprovalWrite is part of an experimental // API and may change or be removed. @@ -9949,21 +9641,6 @@ func (PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess) Kind( return PermissionsLocationsAddToolApprovalDetailsKindExtensionPermissionAccess } -// Location-persisted factory approval, optionally narrowed by approval key. -// Experimental: PermissionsLocationsAddToolApprovalDetailsFactory is part of an -// experimental API and may change or be removed. -type PermissionsLocationsAddToolApprovalDetailsFactory struct { - // Optional factory operation name or canonical approval key; when omitted, the approval - // covers all factory operations. - ApprovalKey *string `json:"approvalKey,omitempty"` -} - -func (PermissionsLocationsAddToolApprovalDetailsFactory) permissionsLocationsAddToolApprovalDetails() { -} -func (PermissionsLocationsAddToolApprovalDetailsFactory) Kind() PermissionsLocationsAddToolApprovalDetailsKind { - return PermissionsLocationsAddToolApprovalDetailsKindFactory -} - // Location-persisted tool approval details for an MCP server tool, or all tools when // `toolName` is null. // Experimental: PermissionsLocationsAddToolApprovalDetailsMCP is part of an experimental @@ -10017,6 +9694,21 @@ func (PermissionsLocationsAddToolApprovalDetailsRead) Kind() PermissionsLocation return PermissionsLocationsAddToolApprovalDetailsKindRead } +// Location-persisted workflow approval, optionally narrowed by approval key. +// Experimental: PermissionsLocationsAddToolApprovalDetailsWorkflow is part of an +// experimental API and may change or be removed. +type PermissionsLocationsAddToolApprovalDetailsWorkflow struct { + // Optional workflow operation name or canonical approval key; when omitted, the approval + // covers all workflow operations. + ApprovalKey *string `json:"approvalKey,omitempty"` +} + +func (PermissionsLocationsAddToolApprovalDetailsWorkflow) permissionsLocationsAddToolApprovalDetails() { +} +func (PermissionsLocationsAddToolApprovalDetailsWorkflow) Kind() PermissionsLocationsAddToolApprovalDetailsKind { + return PermissionsLocationsAddToolApprovalDetailsKindWorkflow +} + // Location-persisted tool approval details for filesystem write operations. // Experimental: PermissionsLocationsAddToolApprovalDetailsWrite is part of an experimental // API and may change or be removed. @@ -10752,6 +10444,18 @@ type ProviderConfigAzure struct { APIVersion *string `json:"apiVersion,omitempty"` } +// A provider offered for interactive login. +// Experimental: ProviderDescriptor is part of an experimental API and may change or be +// removed. +type ProviderDescriptor struct { + // Whether this provider is currently available to sign in with. + Available bool `json:"available"` + // The neutral provider kind. + Kind LoginProviderKind `json:"kind"` + // Human-readable menu label, owned by the runtime so every consumer renders identical text. + Label string `json:"label"` +} + // A snapshot of the provider endpoint the session is currently configured to talk to. // Experimental: ProviderEndpoint is part of an experimental API and may change or be // removed. @@ -11894,19 +11598,6 @@ type ResponseFormat struct { Type ResponseFormatType `json:"type"` } -// Options controlling factory invocation. -// Experimental: RunOptions is part of an experimental API and may change or be removed. -type RunOptions struct { - // Per-invocation resource ceiling overrides. - Limits *FactoryRunLimits `json:"limits,omitempty"` - // Whether to emit factory phase names to the session transcript. - LogPhaseNames *bool `json:"logPhaseNames,omitempty"` - // Whether to notify the originating session when the factory completes. - NotifyOnComplete *bool `json:"notifyOnComplete,omitempty"` - // Run identifier whose journal and progress should seed this resumed run. - ResumeFromRunID *string `json:"resumeFromRunId,omitempty"` -} - // Experimental: RuntimeShutdownResult is part of an experimental API and may change or be // removed. type RuntimeShutdownResult struct { @@ -12548,6 +12239,11 @@ type ServerSkillList struct { Skills []ServerSkill `json:"skills"` } +// Experimental: SessionAccountsLoginCancelResult is part of an experimental API and may +// change or be removed. +type SessionAccountsLoginCancelResult struct { +} + // Current activity flags for the session. // Experimental: SessionActivity is part of an experimental API and may change or be removed. type SessionActivity struct { @@ -12877,13 +12573,6 @@ type SessionExtensionsReloadResult struct { type SessionExtensionsSendAttachmentsToMessageResult struct { } -// Experimental: SessionFactoryPauseAtCheckpointResult is part of an experimental API and -// may change or be removed. -type SessionFactoryPauseAtCheckpointResult struct { - // Whether this execution attempt must pause or may continue. - Action FactoryPauseCheckpointAction `json:"action"` -} - // File path, content to append, and optional mode for the client-provided session // filesystem. Implementations create parent directories as needed. // Experimental: SessionFSAppendFileRequest is part of an experimental API and may change or @@ -15879,6 +15568,8 @@ func (SlashCommandSelectSubcommandResult) Kind() SlashCommandInvocationResultKin // Experimental: SlashCommandSetModelResult is part of an experimental API and may change or // be removed. type SlashCommandSetModelResult struct { + // Auto routing profile selected by the command, when the model is Auto. + AutoTier *AutoTier `json:"autoTier,omitempty"` // Model selected by the command. Model string `json:"model"` // Reasoning effort selected for the model. @@ -17622,19 +17313,6 @@ func (UserToolSessionApprovalExtensionPermissionAccess) Kind() UserToolSessionAp return UserToolSessionApprovalKindExtensionPermissionAccess } -// Session-scoped factory approval, optionally narrowed by approval key. -// Experimental: UserToolSessionApprovalFactory is part of an experimental API and may -// change or be removed. -type UserToolSessionApprovalFactory struct { - // Optional factory operation name or canonical approval key - ApprovalKey *string `json:"approvalKey,omitempty"` -} - -func (UserToolSessionApprovalFactory) userToolSessionApproval() {} -func (UserToolSessionApprovalFactory) Kind() UserToolSessionApprovalKind { - return UserToolSessionApprovalKindFactory -} - // Session-scoped tool-approval rule for an MCP server tool, or all tools on the server when // `toolName` is null. // Experimental: UserToolSessionApprovalMCP is part of an experimental API and may change or @@ -17673,6 +17351,19 @@ func (UserToolSessionApprovalRead) Kind() UserToolSessionApprovalKind { return UserToolSessionApprovalKindRead } +// Session-scoped workflow approval, optionally narrowed by approval key. +// Experimental: UserToolSessionApprovalWorkflow is part of an experimental API and may +// change or be removed. +type UserToolSessionApprovalWorkflow struct { + // Optional workflow operation name or canonical approval key + ApprovalKey *string `json:"approvalKey,omitempty"` +} + +func (UserToolSessionApprovalWorkflow) userToolSessionApproval() {} +func (UserToolSessionApprovalWorkflow) Kind() UserToolSessionApprovalKind { + return UserToolSessionApprovalKindWorkflow +} + // Session-scoped tool-approval rule for filesystem write operations. // Experimental: UserToolSessionApprovalWrite is part of an experimental API and may change // or be removed. @@ -18846,6 +18537,26 @@ const ( AbortReasonUserInitiated AbortReason = "user_initiated" ) +// The provider kind stamped on a signed-in account. +// Experimental: AccountKind is part of an experimental API and may change or be removed. +type AccountKind string + +const ( + // A base Microsoft Entra identity. + AccountKindEntra AccountKind = "entra" + // A GitHub (EMU) account derived from a base Entra identity. + AccountKindEntraEmu AccountKind = "entraEmu" + // An OAuth github.com account. + AccountKindGitHubDotCom AccountKind = "githubDotCom" + // A Microsoft 365 Copilot (Loki) inference account derived from the same base Entra + // identity as an EMU account; its bearer is a Loki-scoped inference token consumed through + // the model-provider path, not the GitHub switcher. + AccountKindLoki AccountKind = "loki" + // A GitHub Enterprise Cloud account — a GitHub account on a non-github.com host, e.g. + // *.ghe.com. + AccountKindProxima AccountKind = "proxima" +) + // Resolved Anthropic adaptive-thinking capability for a model. // Experimental: AdaptiveThinkingSupport is part of an experimental API and may change or be // removed. @@ -19079,6 +18790,26 @@ const ( AttachmentTypeSelection AttachmentType = "selection" ) +// Kind discriminator for AuthEnumerateQuery. +// Experimental: AuthEnumerateQueryKind is part of an experimental API and may change or be +// removed. +type AuthEnumerateQueryKind string + +const ( + AuthEnumerateQueryKindAccounts AuthEnumerateQueryKind = "accounts" + AuthEnumerateQueryKindProviders AuthEnumerateQueryKind = "providers" +) + +// Kind discriminator for AuthEnumerateValue. +// Experimental: AuthEnumerateValueKind is part of an experimental API and may change or be +// removed. +type AuthEnumerateValueKind string + +const ( + AuthEnumerateValueKindAccounts AuthEnumerateValueKind = "accounts" + AuthEnumerateValueKindProviders AuthEnumerateValueKind = "providers" +) + // Type discriminator for AuthInfo. // Experimental: AuthInfoType is part of an experimental API and may change or be removed. type AuthInfoType string @@ -19094,6 +18825,66 @@ const ( AuthInfoTypeUser AuthInfoType = "user" ) +// Terminal disposition of a login persistence attempt. +// Experimental: AuthLoginResultStatus is part of an experimental API and may change or be +// removed. +type AuthLoginResultStatus string + +const ( + // The credential was persisted and the account is signed in. + AuthLoginResultStatusCompleted AuthLoginResultStatus = "completed" + // The user declined plaintext persistence. + AuthLoginResultStatusDeclined AuthLoginResultStatus = "declined" + // Persistence needs explicit consent to store the token in plaintext. + AuthLoginResultStatusNeedsPlaintextConsent AuthLoginResultStatus = "needs-plaintext-consent" +) + +// Kind discriminator for AuthLoginStep. +// Experimental: AuthLoginStepKind is part of an experimental API and may change or be +// removed. +type AuthLoginStepKind string + +const ( + AuthLoginStepKindAwaiting AuthLoginStepKind = "awaiting" + AuthLoginStepKindCompleted AuthLoginStepKind = "completed" + AuthLoginStepKindError AuthLoginStepKind = "error" + AuthLoginStepKindInputRequired AuthLoginStepKind = "input-required" + AuthLoginStepKindNeedsInteraction AuthLoginStepKind = "needs-interaction" + AuthLoginStepKindOpenURL AuthLoginStepKind = "open-url" +) + +// Kind discriminator for AuthReadQuery. +// Experimental: AuthReadQueryKind is part of an experimental API and may change or be +// removed. +type AuthReadQueryKind string + +const ( + AuthReadQueryKindActiveAccount AuthReadQueryKind = "activeAccount" + AuthReadQueryKindLastErrors AuthReadQueryKind = "lastErrors" + AuthReadQueryKindStatus AuthReadQueryKind = "status" +) + +// Kind discriminator for AuthReadValue. +// Experimental: AuthReadValueKind is part of an experimental API and may change or be +// removed. +type AuthReadValueKind string + +const ( + AuthReadValueKindActiveAccount AuthReadValueKind = "activeAccount" + AuthReadValueKindLastErrors AuthReadValueKind = "lastErrors" + AuthReadValueKindStatus AuthReadValueKind = "status" +) + +// Kind discriminator for AuthWrite. +// Experimental: AuthWriteKind is part of an experimental API and may change or be removed. +type AuthWriteKind string + +const ( + AuthWriteKindLogout AuthWriteKind = "logout" + AuthWriteKindSetCredentials AuthWriteKind = "setCredentials" + AuthWriteKindSwitchActive AuthWriteKind = "switchActive" +) + // Current normalized autopilot objective lifecycle status. // Experimental: AutopilotObjectiveStatus is part of an experimental API and may change or // be removed. @@ -20177,133 +19968,6 @@ const ( ExternalToolTextResultForLlmContentTypeText ExternalToolTextResultForLlmContentType = "text" ) -// Execution-critical factory storage operation. -// Experimental: FactoryDurableOperation is part of an experimental API and may change or be -// removed. -type FactoryDurableOperation string - -const ( - // Persisting active execution time. - FactoryDurableOperationAddElapsed FactoryDurableOperation = "addElapsed" - // Persisting an idempotent model-usage charge. - FactoryDurableOperationChargeCredit FactoryDurableOperation = "chargeCredit" - // Creating the durable run and declared phases. - FactoryDurableOperationCreateRun FactoryDurableOperation = "createRun" - // Persisting the terminal run envelope. - FactoryDurableOperationFinishRun FactoryDurableOperation = "finishRun" - // Reading a journal entry without treating storage failure as a cache miss. - FactoryDurableOperationJournalGet FactoryDurableOperation = "journalGet" - // Persisting a journal entry before reporting success. - FactoryDurableOperationJournalPut FactoryDurableOperation = "journalPut" - // Persisting the transition to running. - FactoryDurableOperationMarkRunStarted FactoryDurableOperation = "markRunStarted" - // Reading the authoritative AI-credit total. - FactoryDurableOperationReconcileCreditTotal FactoryDurableOperation = "reconcileCreditTotal" - // Renewing the durable owner lease that proves this process still owns the run. - FactoryDurableOperationRefreshLease FactoryDurableOperation = "refreshLease" - // Rolling back an uncommitted subagent admission. - FactoryDurableOperationReleaseAgent FactoryDurableOperation = "releaseAgent" - // Persisting subagent admission accounting. - FactoryDurableOperationReserveAgent FactoryDurableOperation = "reserveAgent" -) - -// Kind of factory progress line. -// Experimental: FactoryLogLineKind is part of an experimental API and may change or be -// removed. -type FactoryLogLineKind string - -const ( - // A narrator log line. - FactoryLogLineKindLog FactoryLogLineKind = "log" - // A named factory phase marker. - FactoryLogLineKindPhase FactoryLogLineKind = "phase" -) - -// Action the runtime selected for a durable factory pause checkpoint. -// Experimental: FactoryPauseCheckpointAction is part of an experimental API and may change -// or be removed. -type FactoryPauseCheckpointAction string - -const ( - // The checkpoint was committed by a prior paused attempt, so execution may continue. - FactoryPauseCheckpointActionContinue FactoryPauseCheckpointAction = "continue" - // This attempt claimed the checkpoint and must cooperatively stop. - FactoryPauseCheckpointActionPause FactoryPauseCheckpointAction = "pause" -) - -// Type discriminator for FactoryPauseInfo. -type FactoryPauseInfoType string - -const ( - FactoryPauseInfoTypeCheckpoint FactoryPauseInfoType = "checkpoint" - FactoryPauseInfoTypeUser FactoryPauseInfoType = "user" -) - -// Derived lifecycle state of a factory phase. -// Experimental: FactoryPhaseStatus is part of an experimental API and may change or be -// removed. -type FactoryPhaseStatus string - -const ( - // The phase is currently entered and accumulating active time. - FactoryPhaseStatusActive FactoryPhaseStatus = "active" - // The phase was entered and has since been closed. - FactoryPhaseStatusCompleted FactoryPhaseStatus = "completed" - // The phase has not been entered yet. - FactoryPhaseStatusPending FactoryPhaseStatus = "pending" - // The phase was never entered because a later phase was entered or the run reached a - // terminal state. - FactoryPhaseStatusSkipped FactoryPhaseStatus = "skipped" -) - -// Cumulative resource ceiling that stopped a factory run. -// Experimental: FactoryRunFailureKind is part of an experimental API and may change or be -// removed. -type FactoryRunFailureKind string - -const ( - // The run's settled subagent model usage exceeded the approved AI-credit ceiling, or no - // headroom remained for another subagent. - FactoryRunFailureKindMaxAiCredits FactoryRunFailureKind = "maxAiCredits" - // The run admitted the approved maximum total number of subagents. - FactoryRunFailureKindMaxTotalSubagents FactoryRunFailureKind = "maxTotalSubagents" - // The run reached the approved accumulated active-execution time in seconds. - FactoryRunFailureKindTimeoutSeconds FactoryRunFailureKind = "timeoutSeconds" -) - -// Type discriminator for FactoryRunFailure. -type FactoryRunFailureType string - -const ( - FactoryRunFailureTypeFactoryAccountingIncomplete FactoryRunFailureType = "factory_accounting_incomplete" - FactoryRunFailureTypeFactoryDurableFailure FactoryRunFailureType = "factory_durable_failure" - FactoryRunFailureTypeFactoryLimitReached FactoryRunFailureType = "factory_limit_reached" - FactoryRunFailureTypeFactoryProviderDisconnected FactoryRunFailureType = "factory_provider_disconnected" - FactoryRunFailureTypeFactoryResumeDeclined FactoryRunFailureType = "factory_resume_declined" -) - -// Current or terminal state of a factory run. -// Experimental: FactoryRunStatus is part of an experimental API and may change or be -// removed. -type FactoryRunStatus string - -const ( - // The run was cancelled before completion. - FactoryRunStatusCancelled FactoryRunStatus = "cancelled" - // The run completed successfully. - FactoryRunStatusCompleted FactoryRunStatus = "completed" - // The factory body failed or reached a cumulative resource ceiling. - FactoryRunStatusError FactoryRunStatus = "error" - // The run was interrupted while resource budget remained. - FactoryRunStatusHalted FactoryRunStatus = "halted" - // The current attempt stopped intentionally and the run may be resumed. - FactoryRunStatusPaused FactoryRunStatus = "paused" - // The run was minted and is awaiting approval. - FactoryRunStatusPending FactoryRunStatus = "pending" - // The run is executing. - FactoryRunStatusRunning FactoryRunStatus = "running" -) - // Why the runtime is requesting a GitHub credential. // Experimental: GitHubTokenAcquireReason is part of an experimental API and may change or // be removed. @@ -20619,6 +20283,21 @@ const ( LlmInferenceHTTPRequestStartTransportWebsocket LlmInferenceHTTPRequestStartTransport = "websocket" ) +// A provider a consumer may interactively sign in with. +// Experimental: LoginProviderKind is part of an experimental API and may change or be +// removed. +type LoginProviderKind string + +const ( + // Microsoft Entra sign-in that derives a GitHub (EMU) credential. + LoginProviderKindEntra LoginProviderKind = "entra" + // OAuth github.com sign-in via the browser (web loopback + PKCE). + LoginProviderKindGitHubDotCom LoginProviderKind = "githubDotCom" + // A GitHub Enterprise Cloud account — a GitHub account on a non-github.com host, e.g. + // *.ghe.com; the host is supplied interactively through the neutral input-required step. + LoginProviderKindProxima LoginProviderKind = "proxima" +) + // Summary of which managed-settings channels contributed to the effective session policy. // Use the per-channel booleans for exact provenance. // Experimental: ManagedSettingsResolvedSource is part of an experimental API and may change @@ -21289,6 +20968,8 @@ const ( // The runtime selected the model automatically, such as rate-limit recovery or refusal // fallback. ModelChangeSourceAutomatic ModelChangeSource = "automatic" + // The user accepted a CAPI-issued Auto tier recommendation. + ModelChangeSourceAutoTierRecommendation ModelChangeSource = "auto_tier_recommendation" // The user selected the promoted model from the changeboarding card or its keyboard // shortcut. ModelChangeSourceChangeboardingShortcut ModelChangeSource = "changeboarding_shortcut" @@ -21465,11 +21146,11 @@ const ( PermissionDecisionApproveForLocationApprovalKindExtensionEnvAccess PermissionDecisionApproveForLocationApprovalKind = "extension-env-access" PermissionDecisionApproveForLocationApprovalKindExtensionManagement PermissionDecisionApproveForLocationApprovalKind = "extension-management" PermissionDecisionApproveForLocationApprovalKindExtensionPermissionAccess PermissionDecisionApproveForLocationApprovalKind = "extension-permission-access" - PermissionDecisionApproveForLocationApprovalKindFactory PermissionDecisionApproveForLocationApprovalKind = "factory" PermissionDecisionApproveForLocationApprovalKindMCP PermissionDecisionApproveForLocationApprovalKind = "mcp" PermissionDecisionApproveForLocationApprovalKindMCPSampling PermissionDecisionApproveForLocationApprovalKind = "mcp-sampling" PermissionDecisionApproveForLocationApprovalKindMemory PermissionDecisionApproveForLocationApprovalKind = "memory" PermissionDecisionApproveForLocationApprovalKindRead PermissionDecisionApproveForLocationApprovalKind = "read" + PermissionDecisionApproveForLocationApprovalKindWorkflow PermissionDecisionApproveForLocationApprovalKind = "workflow" PermissionDecisionApproveForLocationApprovalKindWrite PermissionDecisionApproveForLocationApprovalKind = "write" ) @@ -21482,11 +21163,11 @@ const ( PermissionDecisionApproveForSessionApprovalKindExtensionEnvAccess PermissionDecisionApproveForSessionApprovalKind = "extension-env-access" PermissionDecisionApproveForSessionApprovalKindExtensionManagement PermissionDecisionApproveForSessionApprovalKind = "extension-management" PermissionDecisionApproveForSessionApprovalKindExtensionPermissionAccess PermissionDecisionApproveForSessionApprovalKind = "extension-permission-access" - PermissionDecisionApproveForSessionApprovalKindFactory PermissionDecisionApproveForSessionApprovalKind = "factory" PermissionDecisionApproveForSessionApprovalKindMCP PermissionDecisionApproveForSessionApprovalKind = "mcp" PermissionDecisionApproveForSessionApprovalKindMCPSampling PermissionDecisionApproveForSessionApprovalKind = "mcp-sampling" PermissionDecisionApproveForSessionApprovalKindMemory PermissionDecisionApproveForSessionApprovalKind = "memory" PermissionDecisionApproveForSessionApprovalKindRead PermissionDecisionApproveForSessionApprovalKind = "read" + PermissionDecisionApproveForSessionApprovalKindWorkflow PermissionDecisionApproveForSessionApprovalKind = "workflow" PermissionDecisionApproveForSessionApprovalKindWrite PermissionDecisionApproveForSessionApprovalKind = "write" ) @@ -21533,9 +21214,8 @@ type PermissionDecisionSource string const ( // The response followed the assisted-approval judge recommendation. PermissionDecisionSourceAssistedApproval PermissionDecisionSource = "assisted_approval" - // A live authorization record from an earlier human decision in this session contained the - // proposal, so it ran without another prompt. This is not a new human decision and never - // mints authority of its own. + // Historical compatibility value for sessions created while authorization carry-forward was + // executable. Current runtimes do not produce this source. PermissionDecisionSourceAuthorizationCarryForward PermissionDecisionSource = "authorization_carry_forward" // The host applied a standing policy or override rather than a judge recommendation or // human decision. @@ -21601,7 +21281,8 @@ const ( PermissionModeSourceAutopilotConfirmation PermissionModeSource = "autopilot_confirmation" // The mode was set from a CLI command-line flag. PermissionModeSourceCLIFlag PermissionModeSource = "cli_flag" - // The mode was set at startup by authenticated organization targeting. + // Historical compatibility value for runtimes that selected Assisted mode through + // organization targeting. Current runtimes do not produce this source. PermissionModeSourceOrganizationTargeting PermissionModeSource = "organization_targeting" // The mode was set through an RPC caller. PermissionModeSourceRPC PermissionModeSource = "rpc" @@ -21753,11 +21434,11 @@ const ( PermissionsLocationsAddToolApprovalDetailsKindExtensionEnvAccess PermissionsLocationsAddToolApprovalDetailsKind = "extension-env-access" PermissionsLocationsAddToolApprovalDetailsKindExtensionManagement PermissionsLocationsAddToolApprovalDetailsKind = "extension-management" PermissionsLocationsAddToolApprovalDetailsKindExtensionPermissionAccess PermissionsLocationsAddToolApprovalDetailsKind = "extension-permission-access" - PermissionsLocationsAddToolApprovalDetailsKindFactory PermissionsLocationsAddToolApprovalDetailsKind = "factory" PermissionsLocationsAddToolApprovalDetailsKindMCP PermissionsLocationsAddToolApprovalDetailsKind = "mcp" PermissionsLocationsAddToolApprovalDetailsKindMCPSampling PermissionsLocationsAddToolApprovalDetailsKind = "mcp-sampling" PermissionsLocationsAddToolApprovalDetailsKindMemory PermissionsLocationsAddToolApprovalDetailsKind = "memory" PermissionsLocationsAddToolApprovalDetailsKindRead PermissionsLocationsAddToolApprovalDetailsKind = "read" + PermissionsLocationsAddToolApprovalDetailsKindWorkflow PermissionsLocationsAddToolApprovalDetailsKind = "workflow" PermissionsLocationsAddToolApprovalDetailsKindWrite PermissionsLocationsAddToolApprovalDetailsKind = "write" ) @@ -23087,10 +22768,10 @@ const ( UserToolSessionApprovalKindExtensionEnvAccess UserToolSessionApprovalKind = "extension-env-access" UserToolSessionApprovalKindExtensionManagement UserToolSessionApprovalKind = "extension-management" UserToolSessionApprovalKindExtensionPermissionAccess UserToolSessionApprovalKind = "extension-permission-access" - UserToolSessionApprovalKindFactory UserToolSessionApprovalKind = "factory" UserToolSessionApprovalKindMCP UserToolSessionApprovalKind = "mcp" UserToolSessionApprovalKindMemory UserToolSessionApprovalKind = "memory" UserToolSessionApprovalKindRead UserToolSessionApprovalKind = "read" + UserToolSessionApprovalKindWorkflow UserToolSessionApprovalKind = "workflow" UserToolSessionApprovalKindWrite UserToolSessionApprovalKind = "write" ) @@ -25413,6 +25094,165 @@ type sessionAPI struct { sessionID string } +// Experimental: AccountsAPI contains experimental APIs that may change or be removed. +type AccountsAPI sessionAPI + +// Enumerate a typed accounts collection: the signed-in accounts, or the providers offered +// for interactive login. +// +// RPC method: session.accounts.enumerate. +// +// Parameters: Enumerate request carrying the typed collection query. +// +// Returns: The enumerated collection, keyed by the same selector as the query. +func (a *AccountsAPI) Enumerate(ctx context.Context, params *AccountsEnumerateRequest) (AuthEnumerateValue, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["query"] = params.Query + } + raw, err := a.client.Request(ctx, "session.accounts.enumerate", req) + if err != nil { + return nil, err + } + result, err := unmarshalAuthEnumerateValue(raw) + if err != nil { + return nil, err + } + return result, nil +} + +// Get read one typed accounts datum: the active account, a neutral status summary, or the +// last authentication errors. +// +// RPC method: session.accounts.get. +// +// Parameters: Read request carrying the typed datum query. +// +// Returns: The read result, keyed by the same selector as the query. +func (a *AccountsAPI) Get(ctx context.Context, params *AccountsGetRequest) (AuthReadValue, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["query"] = params.Query + } + raw, err := a.client.Request(ctx, "session.accounts.get", req) + if err != nil { + return nil, err + } + result, err := unmarshalAuthReadValue(raw) + if err != nil { + return nil, err + } + return result, nil +} + +// Set apply one non-interactive accounts mutation: switch the active account, log an +// account out, or set credentials from a token. +// +// RPC method: session.accounts.set. +// +// Parameters: Mutation request carrying the typed write command. +// +// Returns: Result of a non-interactive accounts mutation. +func (a *AccountsAPI) Set(ctx context.Context, params *AccountsSetRequest) (*AuthWriteResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["command"] = params.Command + } + raw, err := a.client.Request(ctx, "session.accounts.set", req) + if err != nil { + return nil, err + } + var result AuthWriteResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Experimental: AccountsLoginAPI contains experimental APIs that may change or be removed. +type AccountsLoginAPI sessionAPI + +// Advance an in-flight login flow, optionally fulfilling an input-required step, and return +// the next step. +// +// RPC method: session.accounts.login.advance. +// +// Parameters: Advance an in-flight login flow, optionally fulfilling an input-required step. +// +// Returns: One step in an interactive login flow. The consumer acts on the step and calls +// advance to proceed. Browser-open is encoded as two distinct steps by design: `open-url` +// is CONSUMER-driven (the provider surfaces the authorize URL and the consumer opens it — +// github.com/GHEC web), while `needs-interaction` is PROVIDER-driven (the provider opens +// the browser or broker UI itself and does not surface a URL — Entra). +func (a *AccountsLoginAPI) Advance(ctx context.Context, params *AuthLoginAdvanceRequest) (AuthLoginStep, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["flowId"] = params.FlowID + if params.Input != nil { + req["input"] = *params.Input + } + } + raw, err := a.client.Request(ctx, "session.accounts.login.advance", req) + if err != nil { + return nil, err + } + result, err := unmarshalAuthLoginStep(raw) + if err != nil { + return nil, err + } + return result, nil +} + +// Begin an interactive login flow for a provider kind (dispatch is kind-only) and return +// its opaque flow id and first step. +// +// RPC method: session.accounts.login.begin. +// +// Parameters: Begin an interactive login flow for a provider kind. Dispatch is kind-only. +// +// Returns: A started login flow: its opaque id and first step. +func (a *AccountsLoginAPI) Begin(ctx context.Context, params *AuthLoginBeginRequest) (*AuthLoginBegun, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["kind"] = params.Kind + } + raw, err := a.client.Request(ctx, "session.accounts.login.begin", req) + if err != nil { + return nil, err + } + var result AuthLoginBegun + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Cancel an in-flight login flow and release its resources. +// +// RPC method: session.accounts.login.cancel. +// +// Parameters: Cancel an in-flight login flow. +func (a *AccountsLoginAPI) Cancel(ctx context.Context, params *AuthLoginCancelRequest) (*SessionAccountsLoginCancelResult, error) { + req := map[string]any{"sessionId": a.sessionID} + if params != nil { + req["flowId"] = params.FlowID + } + raw, err := a.client.Request(ctx, "session.accounts.login.cancel", req) + if err != nil { + return nil, err + } + var result SessionAccountsLoginCancelResult + if err := json.Unmarshal(raw, &result); err != nil { + return nil, err + } + return &result, nil +} + +// Experimental: Login returns experimental APIs that may change or be removed. +func (s *AccountsAPI) Login() *AccountsLoginAPI { + return (*AccountsLoginAPI)(s) +} + // Experimental: AgentAPI contains experimental APIs that may change or be removed. type AgentAPI sessionAPI @@ -26525,336 +26365,6 @@ func (a *ExtensionsAPI) SendAttachmentsToMessage(ctx context.Context, params *Se return &result, nil } -// Experimental: FactoryAPI contains experimental APIs that may change or be removed. -type FactoryAPI sessionAPI - -// Agent runs one factory-scoped subagent and returns its result. -// -// RPC method: session.factory.agent. -// -// Parameters: Parameters for one factory-scoped subagent call. -// -// Returns: Result of one factory-scoped subagent call. -func (a *FactoryAPI) Agent(ctx context.Context, params *FactoryAgentRequest) (*FactoryAgentResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["executionToken"] = params.ExecutionToken - req["factoryRunId"] = params.FactoryRunID - req["opts"] = params.Opts - req["prompt"] = params.Prompt - } - raw, err := a.client.Request(ctx, "session.factory.agent", req) - if err != nil { - return nil, err - } - var result FactoryAgentResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// Cancel requests cancellation of a factory run and returns its run envelope. -// -// RPC method: session.factory.cancel. -// -// Parameters: Parameters for cancelling a factory run. -// -// Returns: Complete current or terminal factory run envelope. -func (a *FactoryAPI) Cancel(ctx context.Context, params *FactoryCancelRequest) (*FactoryRunResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["runId"] = params.RunID - } - raw, err := a.client.Request(ctx, "session.factory.cancel", req) - if err != nil { - return nil, err - } - var result FactoryRunResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// GetRun gets the current or settled envelope for a factory run. -// -// RPC method: session.factory.getRun. -// -// Parameters: Parameters for retrieving a factory run. -// -// Returns: Complete current or terminal factory run envelope. -func (a *FactoryAPI) GetRun(ctx context.Context, params *FactoryGetRunRequest) (*FactoryRunResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["runId"] = params.RunID - } - raw, err := a.client.Request(ctx, "session.factory.getRun", req) - if err != nil { - return nil, err - } - var result FactoryRunResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// GetRunDetail gets durable and live observability detail for one factory run. -// -// RPC method: session.factory.getRunDetail. -// -// Parameters: Parameters for retrieving a factory run. -// -// Returns: Full factory run observability detail. -func (a *FactoryAPI) GetRunDetail(ctx context.Context, params *FactoryGetRunRequest) (*FactoryRunDetail, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["runId"] = params.RunID - } - raw, err := a.client.Request(ctx, "session.factory.getRunDetail", req) - if err != nil { - return nil, err - } - var result FactoryRunDetail - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// GetRunProgress pages durable progress for one factory run. -// -// RPC method: session.factory.getRunProgress. -// -// Parameters: Parameters for paging factory progress. -// -// Returns: A bidirectional page of factory progress. -func (a *FactoryAPI) GetRunProgress(ctx context.Context, params *FactoryGetRunProgressRequest) (*FactoryProgressPage, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - if params.AfterSeq != nil { - req["afterSeq"] = *params.AfterSeq - } - if params.BeforeSeq != nil { - req["beforeSeq"] = *params.BeforeSeq - } - if params.Limit != nil { - req["limit"] = *params.Limit - } - if params.PhaseID != nil { - req["phaseId"] = *params.PhaseID - } - req["runId"] = params.RunID - } - raw, err := a.client.Request(ctx, "session.factory.getRunProgress", req) - if err != nil { - return nil, err - } - var result FactoryProgressPage - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// ListRuns lists durable factory runs for this session in creation order. -// -// RPC method: session.factory.listRuns. -// -// Parameters: Parameters for paging factory runs. -// -// Returns: A page of factory runs in durable creation order. -func (a *FactoryAPI) ListRuns(ctx context.Context, params *FactoryListRunsRequest) (*FactoryListRunsResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - if params.AfterSeq != nil { - req["afterSeq"] = *params.AfterSeq - } - if params.BeforeSeq != nil { - req["beforeSeq"] = *params.BeforeSeq - } - if params.Limit != nil { - req["limit"] = *params.Limit - } - } - raw, err := a.client.Request(ctx, "session.factory.listRuns", req) - if err != nil { - return nil, err - } - var result FactoryListRunsResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// Log records a batch of ordered factory progress lines. -// -// RPC method: session.factory.log. -// -// Parameters: Parameters for recording factory progress. -// -// Returns: Acknowledgement that a factory request was accepted. -func (a *FactoryAPI) Log(ctx context.Context, params *FactoryLogRequest) (*FactoryAckResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["executionToken"] = params.ExecutionToken - req["lines"] = params.Lines - req["runId"] = params.RunID - } - raw, err := a.client.Request(ctx, "session.factory.log", req) - if err != nil { - return nil, err - } - var result FactoryAckResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// Pauses a running factory and returns its settled run envelope. -// -// RPC method: session.factory.pause. -// -// Parameters: Parameters for pausing a running factory. -// -// Returns: Complete current or terminal factory run envelope. -func (a *FactoryAPI) Pause(ctx context.Context, params *FactoryPauseRequest) (*FactoryRunResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["runId"] = params.RunID - } - raw, err := a.client.Request(ctx, "session.factory.pause", req) - if err != nil { - return nil, err - } - var result FactoryRunResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// Resumes a factory run using its persisted name, arguments, journal, and accounting. -// -// RPC method: session.factory.resume. -// -// Parameters: Parameters for resuming a factory run from its persisted identity. -// -// Returns: Resolved persisted factory identity and resumed run envelope. -func (a *FactoryAPI) Resume(ctx context.Context, params *FactoryResumeRequest) (*FactoryResumeResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - if params.Limits != nil { - req["limits"] = *params.Limits - } - if params.LogPhaseNames != nil { - req["logPhaseNames"] = *params.LogPhaseNames - } - if params.NotifyOnComplete != nil { - req["notifyOnComplete"] = *params.NotifyOnComplete - } - req["runId"] = params.RunID - } - raw, err := a.client.Request(ctx, "session.factory.resume", req) - if err != nil { - return nil, err - } - var result FactoryResumeResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// Runs a registered factory by name at the top level. -// -// RPC method: session.factory.run. -// -// Parameters: Parameters for invoking a registered factory. -// -// Returns: Complete current or terminal factory run envelope. -func (a *FactoryAPI) Run(ctx context.Context, params *FactoryRunRequest) (*FactoryRunResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["args"] = params.Args - req["name"] = params.Name - if params.Options != nil { - req["options"] = *params.Options - } - } - raw, err := a.client.Request(ctx, "session.factory.run", req) - if err != nil { - return nil, err - } - var result FactoryRunResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// Experimental: FactoryJournalAPI contains experimental APIs that may change or be removed. -type FactoryJournalAPI sessionAPI - -// Get reads a memoized factory journal entry. -// -// RPC method: session.factory.journal.get. -// -// Parameters: Parameters for reading a factory journal entry. -// -// Returns: Result of reading a factory journal entry. -func (a *FactoryJournalAPI) Get(ctx context.Context, params *FactoryJournalGetRequest) (*FactoryJournalGetResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["executionToken"] = params.ExecutionToken - req["key"] = params.Key - req["runId"] = params.RunID - } - raw, err := a.client.Request(ctx, "session.factory.journal.get", req) - if err != nil { - return nil, err - } - var result FactoryJournalGetResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// Put stores a memoized factory journal entry. -// -// RPC method: session.factory.journal.put. -// -// Parameters: Parameters for storing a factory journal entry. -// -// Returns: Acknowledgement that a factory request was accepted. -func (a *FactoryJournalAPI) Put(ctx context.Context, params *FactoryJournalPutRequest) (*FactoryAckResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["executionToken"] = params.ExecutionToken - req["key"] = params.Key - req["resultJson"] = params.ResultJSON - req["runId"] = params.RunID - } - raw, err := a.client.Request(ctx, "session.factory.journal.put", req) - if err != nil { - return nil, err - } - var result FactoryAckResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// Experimental: Journal returns experimental APIs that may change or be removed. -func (s *FactoryAPI) Journal() *FactoryJournalAPI { - return (*FactoryJournalAPI)(s) -} - // Experimental: FleetAPI contains experimental APIs that may change or be removed. type FleetAPI sessionAPI @@ -32450,6 +31960,7 @@ type SessionRPC struct { // Reuse a single struct instead of allocating one for each service on the heap. common sessionAPI + Accounts *AccountsAPI Agent *AgentAPI AutopilotObjective *AutopilotObjectiveAPI Canvas *CanvasAPI @@ -32462,7 +31973,6 @@ type SessionRPC struct { Diagnostics *DiagnosticsAPI EventLog *EventLogAPI Extensions *ExtensionsAPI - Factory *FactoryAPI Fleet *FleetAPI GitHubAuth *GitHubAuthAPI History *HistoryAPI @@ -32787,6 +32297,7 @@ func (a *SessionRPC) Suspend(ctx context.Context) (*SessionSuspendResult, error) func NewSessionRPC(client *jsonrpc2.Client, sessionID string) *SessionRPC { r := &SessionRPC{} r.common = sessionAPI{client: client, sessionID: sessionID} + r.Accounts = (*AccountsAPI)(&r.common) r.Agent = (*AgentAPI)(&r.common) r.AutopilotObjective = (*AutopilotObjectiveAPI)(&r.common) r.Canvas = (*CanvasAPI)(&r.common) @@ -32799,7 +32310,6 @@ func NewSessionRPC(client *jsonrpc2.Client, sessionID string) *SessionRPC { r.Diagnostics = (*DiagnosticsAPI)(&r.common) r.EventLog = (*EventLogAPI)(&r.common) r.Extensions = (*ExtensionsAPI)(&r.common) - r.Factory = (*FactoryAPI)(&r.common) r.Fleet = (*FleetAPI)(&r.common) r.GitHubAuth = (*GitHubAuthAPI)(&r.common) r.History = (*HistoryAPI)(&r.common) @@ -32986,97 +32496,6 @@ func (a *InternalConnectorsAPI) WithdrawProjection(ctx context.Context) (*Connec return &result, nil } -// Experimental: InternalFactoryAPI contains experimental APIs that may change or be removed. -type InternalFactoryAPI internalSessionAPI - -// PauseAtCheckpoint atomically pauses an owned factory attempt at a durable checkpoint. -// -// RPC method: session.factory.pauseAtCheckpoint. -// -// Parameters: Parameters for an owned durable pause checkpoint. -// Internal: PauseAtCheckpoint is part of the SDK's internal handshake/plumbing; external -// callers should not use it. -func (a *InternalFactoryAPI) PauseAtCheckpoint(ctx context.Context, params *FactoryPauseCheckpointRequest) (*SessionFactoryPauseAtCheckpointResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["executionToken"] = params.ExecutionToken - req["key"] = params.Key - req["runId"] = params.RunID - } - raw, err := a.client.Request(ctx, "session.factory.pauseAtCheckpoint", req) - if err != nil { - return nil, err - } - var result SessionFactoryPauseAtCheckpointResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// ResumeFromTool internal tool-originated factory resume. -// -// RPC method: session.factory.resumeFromTool. -// -// Parameters: Internal parameters for resuming a factory run from a tool. -// -// Returns: Resolved persisted factory identity and resumed run envelope. -// Internal: ResumeFromTool is part of the SDK's internal handshake/plumbing; external -// callers should not use it. -func (a *InternalFactoryAPI) ResumeFromTool(ctx context.Context, params *FactoryToolResumeRequest) (*FactoryResumeResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - if params.Limits != nil { - req["limits"] = *params.Limits - } - req["runId"] = params.RunID - if params.ToolCallID != nil { - req["toolCallId"] = *params.ToolCallID - } - } - raw, err := a.client.Request(ctx, "session.factory.resumeFromTool", req) - if err != nil { - return nil, err - } - var result FactoryResumeResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - -// RunFromTool internal tool-originated factory invocation. -// -// RPC method: session.factory.runFromTool. -// -// Parameters: Internal parameters for invoking a registered factory from a tool. -// -// Returns: Complete current or terminal factory run envelope. -// Internal: RunFromTool is part of the SDK's internal handshake/plumbing; external callers -// should not use it. -func (a *InternalFactoryAPI) RunFromTool(ctx context.Context, params *FactoryToolRunRequest) (*FactoryRunResult, error) { - req := map[string]any{"sessionId": a.sessionID} - if params != nil { - req["args"] = params.Args - req["name"] = params.Name - if params.Options != nil { - req["options"] = *params.Options - } - if params.ToolCallID != nil { - req["toolCallId"] = *params.ToolCallID - } - } - raw, err := a.client.Request(ctx, "session.factory.runFromTool", req) - if err != nil { - return nil, err - } - var result FactoryRunResult - if err := json.Unmarshal(raw, &result); err != nil { - return nil, err - } - return &result, nil -} - // Experimental: InternalGitHubAuthAPI contains experimental APIs that may change or be // removed. type InternalGitHubAuthAPI internalSessionAPI @@ -33407,6 +32826,12 @@ func (a *InternalModelAPI) ApplyStartupOverlay(ctx context.Context, params *Mode if params.DeviceManagedModel != nil { req["deviceManagedModel"] = *params.DeviceManagedModel } + if params.ManagedContextTier != nil { + req["managedContextTier"] = *params.ManagedContextTier + } + if params.ManagedReasoningEffort != nil { + req["managedReasoningEffort"] = *params.ManagedReasoningEffort + } if params.PolicyHelperModel != nil { req["policyHelperModel"] = *params.PolicyHelperModel } @@ -33978,7 +33403,6 @@ type InternalSessionRPC struct { Canvas *InternalCanvasAPI Commands *InternalCommandsAPI Connectors *InternalConnectorsAPI - Factory *InternalFactoryAPI GitHubAuth *InternalGitHubAuthAPI MCP *InternalMCPAPI Model *InternalModelAPI @@ -34026,7 +33450,6 @@ func NewInternalSessionRPC(client *jsonrpc2.Client, sessionID string) *InternalS r.Canvas = (*InternalCanvasAPI)(&r.common) r.Commands = (*InternalCommandsAPI)(&r.common) r.Connectors = (*InternalConnectorsAPI)(&r.common) - r.Factory = (*InternalFactoryAPI)(&r.common) r.GitHubAuth = (*InternalGitHubAuthAPI)(&r.common) r.MCP = (*InternalMCPAPI)(&r.common) r.Model = (*InternalModelAPI)(&r.common) @@ -34063,26 +33486,6 @@ type CanvasHandler interface { Open(request *CanvasProviderOpenRequest) (*CanvasProviderOpenResult, error) } -// Experimental: FactoryHandler contains experimental APIs that may change or be removed. -type FactoryHandler interface { - // Abort asks the owning extension connection to abort a running factory cooperatively. - // - // RPC method: factory.abort. - // - // Parameters: Parameters for cooperatively aborting a factory body. - // - // Returns: Acknowledgement that a factory request was accepted. - Abort(request *FactoryAbortRequest) (*FactoryAckResult, error) - // Execute asks the owning extension connection to execute a registered factory closure. - // - // RPC method: factory.execute. - // - // Parameters: Parameters sent to the owning extension to execute a factory closure. - // - // Returns: Result returned by an extension factory closure. - Execute(request *FactoryExecuteRequest) (*FactoryExecuteResult, error) -} - // Experimental: ProviderTokenHandler contains experimental APIs that may change or be // removed. type ProviderTokenHandler interface { @@ -34272,7 +33675,6 @@ type WorkflowHandler interface { // ClientSessionAPIHandlers provides all client session API handler groups for a session. type ClientSessionAPIHandlers struct { Canvas CanvasHandler - Factory FactoryHandler ProviderToken ProviderTokenHandler SessionFS SessionFSHandler Tasks TasksHandler @@ -34350,44 +33752,6 @@ func RegisterClientSessionAPIHandlers(client *jsonrpc2.Client, getHandlers func( } return raw, nil }) - client.SetRequestHandler("factory.abort", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { - var request FactoryAbortRequest - if err := json.Unmarshal(params, &request); err != nil { - return nil, &jsonrpc2.Error{Code: -32602, Message: fmt.Sprintf("Invalid params: %v", err)} - } - handlers := getHandlers(request.SessionID) - if handlers == nil || handlers.Factory == nil { - return nil, &jsonrpc2.Error{Code: -32603, Message: fmt.Sprintf("No factory handler registered for session: %s", request.SessionID)} - } - result, err := handlers.Factory.Abort(&request) - if err != nil { - return nil, clientSessionHandlerError(err) - } - raw, err := json.Marshal(result) - if err != nil { - return nil, &jsonrpc2.Error{Code: -32603, Message: fmt.Sprintf("Failed to marshal response: %v", err)} - } - return raw, nil - }) - client.SetRequestHandler("factory.execute", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { - var request FactoryExecuteRequest - if err := json.Unmarshal(params, &request); err != nil { - return nil, &jsonrpc2.Error{Code: -32602, Message: fmt.Sprintf("Invalid params: %v", err)} - } - handlers := getHandlers(request.SessionID) - if handlers == nil || handlers.Factory == nil { - return nil, &jsonrpc2.Error{Code: -32603, Message: fmt.Sprintf("No factory handler registered for session: %s", request.SessionID)} - } - result, err := handlers.Factory.Execute(&request) - if err != nil { - return nil, clientSessionHandlerError(err) - } - raw, err := json.Marshal(result) - if err != nil { - return nil, &jsonrpc2.Error{Code: -32603, Message: fmt.Sprintf("Failed to marshal response: %v", err)} - } - return raw, nil - }) client.SetRequestHandler("providerToken.getToken", func(params json.RawMessage) (json.RawMessage, *jsonrpc2.Error) { var request ProviderTokenAcquireRequest if err := json.Unmarshal(params, &request); err != nil { diff --git a/go/rpc/zrpc_encoding.go b/go/rpc/zrpc_encoding.go index 97d51702da..84da52c224 100644 --- a/go/rpc/zrpc_encoding.go +++ b/go/rpc/zrpc_encoding.go @@ -235,6 +235,283 @@ func (r *AccountLogoutRequest) UnmarshalJSON(data []byte) error { return nil } +func unmarshalAuthEnumerateQuery(data []byte) (AuthEnumerateQuery, error) { + if string(data) == "null" { + return nil, nil + } + type rawUnion struct { + Kind AuthEnumerateQueryKind `json:"kind"` + } + var raw rawUnion + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + + switch raw.Kind { + case AuthEnumerateQueryKindAccounts: + var d AuthEnumerateQueryAccounts + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthEnumerateQueryKindProviders: + var d AuthEnumerateQueryProviders + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + default: + return &RawAuthEnumerateQueryData{Discriminator: raw.Kind, Raw: data}, nil + } +} + +func (r RawAuthEnumerateQueryData) MarshalJSON() ([]byte, error) { + if r.Raw != nil { + return r.Raw, nil + } + return json.Marshal(struct { + Kind AuthEnumerateQueryKind `json:"kind"` + }{ + Kind: r.Discriminator, + }) +} + +func (r AuthEnumerateQueryAccounts) MarshalJSON() ([]byte, error) { + type alias AuthEnumerateQueryAccounts + return json.Marshal(struct { + Kind AuthEnumerateQueryKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r AuthEnumerateQueryProviders) MarshalJSON() ([]byte, error) { + type alias AuthEnumerateQueryProviders + return json.Marshal(struct { + Kind AuthEnumerateQueryKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r *AccountsEnumerateRequest) UnmarshalJSON(data []byte) error { + type rawAccountsEnumerateRequest struct { + Query json.RawMessage `json:"query"` + } + var raw rawAccountsEnumerateRequest + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + if raw.Query != nil { + value, err := unmarshalAuthEnumerateQuery(raw.Query) + if err != nil { + return err + } + r.Query = value + } + return nil +} + +func unmarshalAuthReadQuery(data []byte) (AuthReadQuery, error) { + if string(data) == "null" { + return nil, nil + } + type rawUnion struct { + Kind AuthReadQueryKind `json:"kind"` + } + var raw rawUnion + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + + switch raw.Kind { + case AuthReadQueryKindActiveAccount: + var d AuthReadQueryActiveAccount + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthReadQueryKindLastErrors: + var d AuthReadQueryLastErrors + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthReadQueryKindStatus: + var d AuthReadQueryStatus + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + default: + return &RawAuthReadQueryData{Discriminator: raw.Kind, Raw: data}, nil + } +} + +func (r RawAuthReadQueryData) MarshalJSON() ([]byte, error) { + if r.Raw != nil { + return r.Raw, nil + } + return json.Marshal(struct { + Kind AuthReadQueryKind `json:"kind"` + }{ + Kind: r.Discriminator, + }) +} + +func (r AuthReadQueryActiveAccount) MarshalJSON() ([]byte, error) { + type alias AuthReadQueryActiveAccount + return json.Marshal(struct { + Kind AuthReadQueryKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r AuthReadQueryLastErrors) MarshalJSON() ([]byte, error) { + type alias AuthReadQueryLastErrors + return json.Marshal(struct { + Kind AuthReadQueryKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r AuthReadQueryStatus) MarshalJSON() ([]byte, error) { + type alias AuthReadQueryStatus + return json.Marshal(struct { + Kind AuthReadQueryKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r *AccountsGetRequest) UnmarshalJSON(data []byte) error { + type rawAccountsGetRequest struct { + Query json.RawMessage `json:"query"` + } + var raw rawAccountsGetRequest + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + if raw.Query != nil { + value, err := unmarshalAuthReadQuery(raw.Query) + if err != nil { + return err + } + r.Query = value + } + return nil +} + +func unmarshalAuthWrite(data []byte) (AuthWrite, error) { + if string(data) == "null" { + return nil, nil + } + type rawUnion struct { + Kind AuthWriteKind `json:"kind"` + } + var raw rawUnion + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + + switch raw.Kind { + case AuthWriteKindLogout: + var d AuthWriteLogout + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthWriteKindSetCredentials: + var d AuthWriteSetCredentials + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthWriteKindSwitchActive: + var d AuthWriteSwitchActive + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + default: + return &RawAuthWriteData{Discriminator: raw.Kind, Raw: data}, nil + } +} + +func (r RawAuthWriteData) MarshalJSON() ([]byte, error) { + if r.Raw != nil { + return r.Raw, nil + } + return json.Marshal(struct { + Kind AuthWriteKind `json:"kind"` + }{ + Kind: r.Discriminator, + }) +} + +func (r AuthWriteLogout) MarshalJSON() ([]byte, error) { + type alias AuthWriteLogout + return json.Marshal(struct { + Kind AuthWriteKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r AuthWriteSetCredentials) MarshalJSON() ([]byte, error) { + type alias AuthWriteSetCredentials + return json.Marshal(struct { + Kind AuthWriteKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r AuthWriteSwitchActive) MarshalJSON() ([]byte, error) { + type alias AuthWriteSwitchActive + return json.Marshal(struct { + Kind AuthWriteKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r *AccountsSetRequest) UnmarshalJSON(data []byte) error { + type rawAccountsSetRequest struct { + Command json.RawMessage `json:"command"` + } + var raw rawAccountsSetRequest + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + if raw.Command != nil { + value, err := unmarshalAuthWrite(raw.Command) + if err != nil { + return err + } + r.Command = value + } + return nil +} + func unmarshalAgentRegistrySpawnResult(data []byte) (AgentRegistrySpawnResult, error) { if string(data) == "null" { return nil, nil @@ -528,90 +805,384 @@ func (r AttachmentGitHubFile) MarshalJSON() ([]byte, error) { }) } -func (r AttachmentGitHubFileDiff) MarshalJSON() ([]byte, error) { - type alias AttachmentGitHubFileDiff +func (r AttachmentGitHubFileDiff) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubFileDiff + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubReference) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubReference + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubRelease) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubRelease + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubRepository) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubRepository + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubSnippet) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubSnippet + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubTreeComparison) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubTreeComparison + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentGitHubURL) MarshalJSON() ([]byte, error) { + type alias AttachmentGitHubURL + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r AttachmentSelection) MarshalJSON() ([]byte, error) { + type alias AttachmentSelection + return json.Marshal(struct { + Type AttachmentType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func unmarshalAuthEnumerateValue(data []byte) (AuthEnumerateValue, error) { + if string(data) == "null" { + return nil, nil + } + type rawUnion struct { + Kind AuthEnumerateValueKind `json:"kind"` + } + var raw rawUnion + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + + switch raw.Kind { + case AuthEnumerateValueKindAccounts: + var d AuthEnumerateValueAccounts + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthEnumerateValueKindProviders: + var d AuthEnumerateValueProviders + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + default: + return &RawAuthEnumerateValueData{Discriminator: raw.Kind, Raw: data}, nil + } +} + +func (r RawAuthEnumerateValueData) MarshalJSON() ([]byte, error) { + if r.Raw != nil { + return r.Raw, nil + } + return json.Marshal(struct { + Kind AuthEnumerateValueKind `json:"kind"` + }{ + Kind: r.Discriminator, + }) +} + +func (r AuthEnumerateValueAccounts) MarshalJSON() ([]byte, error) { + type alias AuthEnumerateValueAccounts + return json.Marshal(struct { + Kind AuthEnumerateValueKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r AuthEnumerateValueProviders) MarshalJSON() ([]byte, error) { + type alias AuthEnumerateValueProviders + return json.Marshal(struct { + Kind AuthEnumerateValueKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func unmarshalAuthLoginStep(data []byte) (AuthLoginStep, error) { + if string(data) == "null" { + return nil, nil + } + type rawUnion struct { + Kind AuthLoginStepKind `json:"kind"` + } + var raw rawUnion + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + + switch raw.Kind { + case AuthLoginStepKindAwaiting: + var d AuthLoginStepAwaiting + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthLoginStepKindCompleted: + var d AuthLoginStepCompleted + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthLoginStepKindError: + var d AuthLoginStepError + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthLoginStepKindInputRequired: + var d AuthLoginStepInputRequired + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthLoginStepKindNeedsInteraction: + var d AuthLoginStepNeedsInteraction + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthLoginStepKindOpenURL: + var d AuthLoginStepOpenURL + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + default: + return &RawAuthLoginStepData{Discriminator: raw.Kind, Raw: data}, nil + } +} + +func (r RawAuthLoginStepData) MarshalJSON() ([]byte, error) { + if r.Raw != nil { + return r.Raw, nil + } + return json.Marshal(struct { + Kind AuthLoginStepKind `json:"kind"` + }{ + Kind: r.Discriminator, + }) +} + +func (r AuthLoginStepAwaiting) MarshalJSON() ([]byte, error) { + type alias AuthLoginStepAwaiting + return json.Marshal(struct { + Kind AuthLoginStepKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r AuthLoginStepCompleted) MarshalJSON() ([]byte, error) { + type alias AuthLoginStepCompleted + return json.Marshal(struct { + Kind AuthLoginStepKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + +func (r AuthLoginStepError) MarshalJSON() ([]byte, error) { + type alias AuthLoginStepError return json.Marshal(struct { - Type AttachmentType `json:"type"` + Kind AuthLoginStepKind `json:"kind"` alias }{ - Type: r.Type(), + Kind: r.Kind(), alias: alias(r), }) } -func (r AttachmentGitHubReference) MarshalJSON() ([]byte, error) { - type alias AttachmentGitHubReference +func (r AuthLoginStepInputRequired) MarshalJSON() ([]byte, error) { + type alias AuthLoginStepInputRequired return json.Marshal(struct { - Type AttachmentType `json:"type"` + Kind AuthLoginStepKind `json:"kind"` alias }{ - Type: r.Type(), + Kind: r.Kind(), alias: alias(r), }) } -func (r AttachmentGitHubRelease) MarshalJSON() ([]byte, error) { - type alias AttachmentGitHubRelease +func (r AuthLoginStepNeedsInteraction) MarshalJSON() ([]byte, error) { + type alias AuthLoginStepNeedsInteraction return json.Marshal(struct { - Type AttachmentType `json:"type"` + Kind AuthLoginStepKind `json:"kind"` alias }{ - Type: r.Type(), + Kind: r.Kind(), alias: alias(r), }) } -func (r AttachmentGitHubRepository) MarshalJSON() ([]byte, error) { - type alias AttachmentGitHubRepository +func (r AuthLoginStepOpenURL) MarshalJSON() ([]byte, error) { + type alias AuthLoginStepOpenURL return json.Marshal(struct { - Type AttachmentType `json:"type"` + Kind AuthLoginStepKind `json:"kind"` alias }{ - Type: r.Type(), + Kind: r.Kind(), alias: alias(r), }) } -func (r AttachmentGitHubSnippet) MarshalJSON() ([]byte, error) { - type alias AttachmentGitHubSnippet +func (r *AuthLoginBegun) UnmarshalJSON(data []byte) error { + type rawAuthLoginBegun struct { + FlowID string `json:"flowId"` + Step json.RawMessage `json:"step"` + } + var raw rawAuthLoginBegun + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + r.FlowID = raw.FlowID + if raw.Step != nil { + value, err := unmarshalAuthLoginStep(raw.Step) + if err != nil { + return err + } + r.Step = value + } + return nil +} + +func unmarshalAuthReadValue(data []byte) (AuthReadValue, error) { + if string(data) == "null" { + return nil, nil + } + type rawUnion struct { + Kind AuthReadValueKind `json:"kind"` + } + var raw rawUnion + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + + switch raw.Kind { + case AuthReadValueKindActiveAccount: + var d AuthReadValueActiveAccount + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthReadValueKindLastErrors: + var d AuthReadValueLastErrors + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + case AuthReadValueKindStatus: + var d AuthReadValueStatus + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil + default: + return &RawAuthReadValueData{Discriminator: raw.Kind, Raw: data}, nil + } +} + +func (r RawAuthReadValueData) MarshalJSON() ([]byte, error) { + if r.Raw != nil { + return r.Raw, nil + } return json.Marshal(struct { - Type AttachmentType `json:"type"` - alias + Kind AuthReadValueKind `json:"kind"` }{ - Type: r.Type(), - alias: alias(r), + Kind: r.Discriminator, }) } -func (r AttachmentGitHubTreeComparison) MarshalJSON() ([]byte, error) { - type alias AttachmentGitHubTreeComparison +func (r AuthReadValueActiveAccount) MarshalJSON() ([]byte, error) { + type alias AuthReadValueActiveAccount return json.Marshal(struct { - Type AttachmentType `json:"type"` + Kind AuthReadValueKind `json:"kind"` alias }{ - Type: r.Type(), + Kind: r.Kind(), alias: alias(r), }) } -func (r AttachmentGitHubURL) MarshalJSON() ([]byte, error) { - type alias AttachmentGitHubURL +func (r AuthReadValueLastErrors) MarshalJSON() ([]byte, error) { + type alias AuthReadValueLastErrors return json.Marshal(struct { - Type AttachmentType `json:"type"` + Kind AuthReadValueKind `json:"kind"` alias }{ - Type: r.Type(), + Kind: r.Kind(), alias: alias(r), }) } -func (r AttachmentSelection) MarshalJSON() ([]byte, error) { - type alias AttachmentSelection +func (r AuthReadValueStatus) MarshalJSON() ([]byte, error) { + type alias AuthReadValueStatus return json.Marshal(struct { - Type AttachmentType `json:"type"` + Kind AuthReadValueKind `json:"kind"` alias }{ - Type: r.Type(), + Kind: r.Kind(), alias: alias(r), }) } @@ -2160,241 +2731,51 @@ func unmarshalExternalToolTextResultForLlmContentResourceDetails(data []byte) (E return nil, nil } if matchesExternalToolTextResultForLlmContentResourceDetailsEmbeddedBlobResourceContents(data) { - var d EmbeddedBlobResourceContents - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil - } - if matchesExternalToolTextResultForLlmContentResourceDetailsEmbeddedTextResourceContents(data) { - var d EmbeddedTextResourceContents - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil - } - return &RawExternalToolTextResultForLlmContentResourceDetailsData{Raw: data}, nil -} - -func (r RawExternalToolTextResultForLlmContentResourceDetailsData) MarshalJSON() ([]byte, error) { - if r.Raw != nil { - return r.Raw, nil - } - return []byte("null"), nil -} - -func (r *ExternalToolTextResultForLlmContentResource) UnmarshalJSON(data []byte) error { - type rawExternalToolTextResultForLlmContentResource struct { - Resource json.RawMessage `json:"resource"` - } - var raw rawExternalToolTextResultForLlmContentResource - if err := json.Unmarshal(data, &raw); err != nil { - return err - } - if raw.Resource != nil { - value, err := unmarshalExternalToolTextResultForLlmContentResourceDetails(raw.Resource) - if err != nil { - return err - } - r.Resource = value - } - return nil -} - -func (r ExternalToolTextResultForLlmContentResource) MarshalJSON() ([]byte, error) { - type alias ExternalToolTextResultForLlmContentResource - return json.Marshal(struct { - Type ExternalToolTextResultForLlmContentType `json:"type"` - alias - }{ - Type: r.Type(), - alias: alias(r), - }) -} - -func (r ExternalToolTextResultForLlmContentResourceLink) MarshalJSON() ([]byte, error) { - type alias ExternalToolTextResultForLlmContentResourceLink - return json.Marshal(struct { - Type ExternalToolTextResultForLlmContentType `json:"type"` - alias - }{ - Type: r.Type(), - alias: alias(r), - }) -} - -func (r ExternalToolTextResultForLlmContentShellExit) MarshalJSON() ([]byte, error) { - type alias ExternalToolTextResultForLlmContentShellExit - return json.Marshal(struct { - Type ExternalToolTextResultForLlmContentType `json:"type"` - alias - }{ - Type: r.Type(), - alias: alias(r), - }) -} - -func (r ExternalToolTextResultForLlmContentTerminal) MarshalJSON() ([]byte, error) { - type alias ExternalToolTextResultForLlmContentTerminal - return json.Marshal(struct { - Type ExternalToolTextResultForLlmContentType `json:"type"` - alias - }{ - Type: r.Type(), - alias: alias(r), - }) -} - -func (r ExternalToolTextResultForLlmContentText) MarshalJSON() ([]byte, error) { - type alias ExternalToolTextResultForLlmContentText - return json.Marshal(struct { - Type ExternalToolTextResultForLlmContentType `json:"type"` - alias - }{ - Type: r.Type(), - alias: alias(r), - }) -} - -func (r *ExternalToolTextResultForLlm) UnmarshalJSON(data []byte) error { - type rawExternalToolTextResultForLlm struct { - BinaryResultsForLlm []ExternalToolTextResultForLlmBinaryResultsForLlm `json:"binaryResultsForLlm,omitzero"` - Contents []json.RawMessage `json:"contents,omitzero"` - Error *string `json:"error,omitempty"` - ResultType *string `json:"resultType,omitempty"` - SessionLog *string `json:"sessionLog,omitempty"` - TextResultForLlm string `json:"textResultForLlm"` - ToolReferences []string `json:"toolReferences,omitzero"` - ToolTelemetry map[string]any `json:"toolTelemetry,omitzero"` - } - var raw rawExternalToolTextResultForLlm - if err := json.Unmarshal(data, &raw); err != nil { - return err - } - r.BinaryResultsForLlm = raw.BinaryResultsForLlm - if raw.Contents != nil { - r.Contents = make([]ExternalToolTextResultForLlmContent, 0, len(raw.Contents)) - for _, rawItem := range raw.Contents { - value, err := unmarshalExternalToolTextResultForLlmContent(rawItem) - if err != nil { - return err - } - r.Contents = append(r.Contents, value) - } - } - r.Error = raw.Error - r.ResultType = raw.ResultType - r.SessionLog = raw.SessionLog - r.TextResultForLlm = raw.TextResultForLlm - r.ToolReferences = raw.ToolReferences - r.ToolTelemetry = raw.ToolTelemetry - return nil -} - -func unmarshalExternalToolResult(data []byte) (ExternalToolResult, error) { - if string(data) == "null" { - return nil, nil - } - { - var value string - if err := json.Unmarshal(data, &value); err == nil { - return ExternalToolStringResult(value), nil - } - } - { - var value ExternalToolTextResultForLlm - if err := json.Unmarshal(data, &value); err == nil { - return &value, nil - } - } - return nil, errors.New("data did not match any union variant for ExternalToolResult") -} - -func unmarshalFactoryRunFailure(data []byte) (FactoryRunFailure, error) { - if string(data) == "null" { - return nil, nil - } - type rawUnion struct { - Type FactoryRunFailureType `json:"type"` - } - var raw rawUnion - if err := json.Unmarshal(data, &raw); err != nil { - return nil, err - } - - switch raw.Type { - case FactoryRunFailureTypeFactoryAccountingIncomplete: - var d FactoryRunFailureFactoryAccountingIncomplete - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil - case FactoryRunFailureTypeFactoryDurableFailure: - var d FactoryRunFailureFactoryDurableFailure - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil - case FactoryRunFailureTypeFactoryLimitReached: - var d FactoryRunFailureFactoryLimitReached - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil - case FactoryRunFailureTypeFactoryProviderDisconnected: - var d FactoryRunFailureFactoryProviderDisconnected + var d EmbeddedBlobResourceContents if err := json.Unmarshal(data, &d); err != nil { return nil, err } return &d, nil - case FactoryRunFailureTypeFactoryResumeDeclined: - var d FactoryRunFailureFactoryResumeDeclined + } + if matchesExternalToolTextResultForLlmContentResourceDetailsEmbeddedTextResourceContents(data) { + var d EmbeddedTextResourceContents if err := json.Unmarshal(data, &d); err != nil { return nil, err } return &d, nil - default: - return &RawFactoryRunFailureData{Discriminator: raw.Type, Raw: data}, nil } + return &RawExternalToolTextResultForLlmContentResourceDetailsData{Raw: data}, nil } -func (r RawFactoryRunFailureData) MarshalJSON() ([]byte, error) { +func (r RawExternalToolTextResultForLlmContentResourceDetailsData) MarshalJSON() ([]byte, error) { if r.Raw != nil { return r.Raw, nil } - return json.Marshal(struct { - Type FactoryRunFailureType `json:"type"` - }{ - Type: r.Discriminator, - }) -} - -func (r FactoryRunFailureFactoryAccountingIncomplete) MarshalJSON() ([]byte, error) { - type alias FactoryRunFailureFactoryAccountingIncomplete - return json.Marshal(struct { - Type FactoryRunFailureType `json:"type"` - alias - }{ - Type: r.Type(), - alias: alias(r), - }) + return []byte("null"), nil } -func (r FactoryRunFailureFactoryDurableFailure) MarshalJSON() ([]byte, error) { - type alias FactoryRunFailureFactoryDurableFailure - return json.Marshal(struct { - Type FactoryRunFailureType `json:"type"` - alias - }{ - Type: r.Type(), - alias: alias(r), - }) +func (r *ExternalToolTextResultForLlmContentResource) UnmarshalJSON(data []byte) error { + type rawExternalToolTextResultForLlmContentResource struct { + Resource json.RawMessage `json:"resource"` + } + var raw rawExternalToolTextResultForLlmContentResource + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + if raw.Resource != nil { + value, err := unmarshalExternalToolTextResultForLlmContentResourceDetails(raw.Resource) + if err != nil { + return err + } + r.Resource = value + } + return nil } -func (r FactoryRunFailureFactoryLimitReached) MarshalJSON() ([]byte, error) { - type alias FactoryRunFailureFactoryLimitReached +func (r ExternalToolTextResultForLlmContentResource) MarshalJSON() ([]byte, error) { + type alias ExternalToolTextResultForLlmContentResource return json.Marshal(struct { - Type FactoryRunFailureType `json:"type"` + Type ExternalToolTextResultForLlmContentType `json:"type"` alias }{ Type: r.Type(), @@ -2402,10 +2783,10 @@ func (r FactoryRunFailureFactoryLimitReached) MarshalJSON() ([]byte, error) { }) } -func (r FactoryRunFailureFactoryProviderDisconnected) MarshalJSON() ([]byte, error) { - type alias FactoryRunFailureFactoryProviderDisconnected +func (r ExternalToolTextResultForLlmContentResourceLink) MarshalJSON() ([]byte, error) { + type alias ExternalToolTextResultForLlmContentResourceLink return json.Marshal(struct { - Type FactoryRunFailureType `json:"type"` + Type ExternalToolTextResultForLlmContentType `json:"type"` alias }{ Type: r.Type(), @@ -2413,10 +2794,10 @@ func (r FactoryRunFailureFactoryProviderDisconnected) MarshalJSON() ([]byte, err }) } -func (r FactoryRunFailureFactoryResumeDeclined) MarshalJSON() ([]byte, error) { - type alias FactoryRunFailureFactoryResumeDeclined +func (r ExternalToolTextResultForLlmContentShellExit) MarshalJSON() ([]byte, error) { + type alias ExternalToolTextResultForLlmContentShellExit return json.Marshal(struct { - Type FactoryRunFailureType `json:"type"` + Type ExternalToolTextResultForLlmContentType `json:"type"` alias }{ Type: r.Type(), @@ -2424,51 +2805,10 @@ func (r FactoryRunFailureFactoryResumeDeclined) MarshalJSON() ([]byte, error) { }) } -func unmarshalFactoryPauseInfo(data []byte) (FactoryPauseInfo, error) { - if string(data) == "null" { - return nil, nil - } - type rawUnion struct { - Type FactoryPauseInfoType `json:"type"` - } - var raw rawUnion - if err := json.Unmarshal(data, &raw); err != nil { - return nil, err - } - - switch raw.Type { - case FactoryPauseInfoTypeCheckpoint: - var d FactoryPauseInfoCheckpoint - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil - case FactoryPauseInfoTypeUser: - var d FactoryPauseInfoUser - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil - default: - return &RawFactoryPauseInfoData{Discriminator: raw.Type, Raw: data}, nil - } -} - -func (r RawFactoryPauseInfoData) MarshalJSON() ([]byte, error) { - if r.Raw != nil { - return r.Raw, nil - } - return json.Marshal(struct { - Type FactoryPauseInfoType `json:"type"` - }{ - Type: r.Discriminator, - }) -} - -func (r FactoryPauseInfoCheckpoint) MarshalJSON() ([]byte, error) { - type alias FactoryPauseInfoCheckpoint +func (r ExternalToolTextResultForLlmContentTerminal) MarshalJSON() ([]byte, error) { + type alias ExternalToolTextResultForLlmContentTerminal return json.Marshal(struct { - Type FactoryPauseInfoType `json:"type"` + Type ExternalToolTextResultForLlmContentType `json:"type"` alias }{ Type: r.Type(), @@ -2476,10 +2816,10 @@ func (r FactoryPauseInfoCheckpoint) MarshalJSON() ([]byte, error) { }) } -func (r FactoryPauseInfoUser) MarshalJSON() ([]byte, error) { - type alias FactoryPauseInfoUser +func (r ExternalToolTextResultForLlmContentText) MarshalJSON() ([]byte, error) { + type alias ExternalToolTextResultForLlmContentText return json.Marshal(struct { - Type FactoryPauseInfoType `json:"type"` + Type ExternalToolTextResultForLlmContentType `json:"type"` alias }{ Type: r.Type(), @@ -2487,76 +2827,58 @@ func (r FactoryPauseInfoUser) MarshalJSON() ([]byte, error) { }) } -func (r *FactoryRunTerminal) UnmarshalJSON(data []byte) error { - type rawFactoryRunTerminal struct { - Error *string `json:"error,omitempty"` - Failure json.RawMessage `json:"failure,omitempty"` - PauseInfo json.RawMessage `json:"pauseInfo"` - Reason *string `json:"reason,omitempty"` - ResultPreview *string `json:"resultPreview,omitempty"` +func (r *ExternalToolTextResultForLlm) UnmarshalJSON(data []byte) error { + type rawExternalToolTextResultForLlm struct { + BinaryResultsForLlm []ExternalToolTextResultForLlmBinaryResultsForLlm `json:"binaryResultsForLlm,omitzero"` + Contents []json.RawMessage `json:"contents,omitzero"` + Error *string `json:"error,omitempty"` + ResultType *string `json:"resultType,omitempty"` + SessionLog *string `json:"sessionLog,omitempty"` + TextResultForLlm string `json:"textResultForLlm"` + ToolReferences []string `json:"toolReferences,omitzero"` + ToolTelemetry map[string]any `json:"toolTelemetry,omitzero"` } - var raw rawFactoryRunTerminal + var raw rawExternalToolTextResultForLlm if err := json.Unmarshal(data, &raw); err != nil { return err } - r.Error = raw.Error - if raw.Failure != nil { - value, err := unmarshalFactoryRunFailure(raw.Failure) - if err != nil { - return err - } - r.Failure = value - } - if raw.PauseInfo != nil { - value, err := unmarshalFactoryPauseInfo(raw.PauseInfo) - if err != nil { - return err + r.BinaryResultsForLlm = raw.BinaryResultsForLlm + if raw.Contents != nil { + r.Contents = make([]ExternalToolTextResultForLlmContent, 0, len(raw.Contents)) + for _, rawItem := range raw.Contents { + value, err := unmarshalExternalToolTextResultForLlmContent(rawItem) + if err != nil { + return err + } + r.Contents = append(r.Contents, value) } - r.PauseInfo = value } - r.Reason = raw.Reason - r.ResultPreview = raw.ResultPreview + r.Error = raw.Error + r.ResultType = raw.ResultType + r.SessionLog = raw.SessionLog + r.TextResultForLlm = raw.TextResultForLlm + r.ToolReferences = raw.ToolReferences + r.ToolTelemetry = raw.ToolTelemetry return nil } -func (r *FactoryRunResult) UnmarshalJSON(data []byte) error { - type rawFactoryRunResult struct { - Attempt *int64 `json:"attempt,omitempty"` - Error *string `json:"error,omitempty"` - Failure json.RawMessage `json:"failure,omitempty"` - PauseInfo json.RawMessage `json:"pauseInfo,omitempty"` - Reason *string `json:"reason,omitempty"` - Result any `json:"result,omitempty"` - RunID string `json:"runId"` - Snapshot any `json:"snapshot,omitempty"` - Status FactoryRunStatus `json:"status"` - } - var raw rawFactoryRunResult - if err := json.Unmarshal(data, &raw); err != nil { - return err +func unmarshalExternalToolResult(data []byte) (ExternalToolResult, error) { + if string(data) == "null" { + return nil, nil } - r.Attempt = raw.Attempt - r.Error = raw.Error - if raw.Failure != nil { - value, err := unmarshalFactoryRunFailure(raw.Failure) - if err != nil { - return err + { + var value string + if err := json.Unmarshal(data, &value); err == nil { + return ExternalToolStringResult(value), nil } - r.Failure = value } - if raw.PauseInfo != nil { - value, err := unmarshalFactoryPauseInfo(raw.PauseInfo) - if err != nil { - return err + { + var value ExternalToolTextResultForLlm + if err := json.Unmarshal(data, &value); err == nil { + return &value, nil } - r.PauseInfo = value } - r.Reason = raw.Reason - r.Result = raw.Result - r.RunID = raw.RunID - r.Snapshot = raw.Snapshot - r.Status = raw.Status - return nil + return nil, errors.New("data did not match any union variant for ExternalToolResult") } func unmarshalFilterMapping(data []byte) (FilterMapping, error) { @@ -4353,12 +4675,6 @@ func unmarshalUserToolSessionApproval(data []byte) (UserToolSessionApproval, err return nil, err } return &d, nil - case UserToolSessionApprovalKindFactory: - var d UserToolSessionApprovalFactory - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil case UserToolSessionApprovalKindMCP: var d UserToolSessionApprovalMCP if err := json.Unmarshal(data, &d); err != nil { @@ -4377,6 +4693,12 @@ func unmarshalUserToolSessionApproval(data []byte) (UserToolSessionApproval, err return nil, err } return &d, nil + case UserToolSessionApprovalKindWorkflow: + var d UserToolSessionApprovalWorkflow + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case UserToolSessionApprovalKindWrite: var d UserToolSessionApprovalWrite if err := json.Unmarshal(data, &d); err != nil { @@ -4454,8 +4776,8 @@ func (r UserToolSessionApprovalExtensionPermissionAccess) MarshalJSON() ([]byte, }) } -func (r UserToolSessionApprovalFactory) MarshalJSON() ([]byte, error) { - type alias UserToolSessionApprovalFactory +func (r UserToolSessionApprovalMCP) MarshalJSON() ([]byte, error) { + type alias UserToolSessionApprovalMCP return json.Marshal(struct { Kind UserToolSessionApprovalKind `json:"kind"` alias @@ -4465,8 +4787,8 @@ func (r UserToolSessionApprovalFactory) MarshalJSON() ([]byte, error) { }) } -func (r UserToolSessionApprovalMCP) MarshalJSON() ([]byte, error) { - type alias UserToolSessionApprovalMCP +func (r UserToolSessionApprovalMemory) MarshalJSON() ([]byte, error) { + type alias UserToolSessionApprovalMemory return json.Marshal(struct { Kind UserToolSessionApprovalKind `json:"kind"` alias @@ -4476,8 +4798,8 @@ func (r UserToolSessionApprovalMCP) MarshalJSON() ([]byte, error) { }) } -func (r UserToolSessionApprovalMemory) MarshalJSON() ([]byte, error) { - type alias UserToolSessionApprovalMemory +func (r UserToolSessionApprovalRead) MarshalJSON() ([]byte, error) { + type alias UserToolSessionApprovalRead return json.Marshal(struct { Kind UserToolSessionApprovalKind `json:"kind"` alias @@ -4487,8 +4809,8 @@ func (r UserToolSessionApprovalMemory) MarshalJSON() ([]byte, error) { }) } -func (r UserToolSessionApprovalRead) MarshalJSON() ([]byte, error) { - type alias UserToolSessionApprovalRead +func (r UserToolSessionApprovalWorkflow) MarshalJSON() ([]byte, error) { + type alias UserToolSessionApprovalWorkflow return json.Marshal(struct { Kind UserToolSessionApprovalKind `json:"kind"` alias @@ -4612,12 +4934,6 @@ func unmarshalPermissionDecisionApproveForLocationApproval(data []byte) (Permiss return nil, err } return &d, nil - case PermissionDecisionApproveForLocationApprovalKindFactory: - var d PermissionDecisionApproveForLocationApprovalFactory - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil case PermissionDecisionApproveForLocationApprovalKindMCP: var d PermissionDecisionApproveForLocationApprovalMCP if err := json.Unmarshal(data, &d); err != nil { @@ -4642,6 +4958,12 @@ func unmarshalPermissionDecisionApproveForLocationApproval(data []byte) (Permiss return nil, err } return &d, nil + case PermissionDecisionApproveForLocationApprovalKindWorkflow: + var d PermissionDecisionApproveForLocationApprovalWorkflow + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case PermissionDecisionApproveForLocationApprovalKindWrite: var d PermissionDecisionApproveForLocationApprovalWrite if err := json.Unmarshal(data, &d); err != nil { @@ -4719,8 +5041,8 @@ func (r PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess) M }) } -func (r PermissionDecisionApproveForLocationApprovalFactory) MarshalJSON() ([]byte, error) { - type alias PermissionDecisionApproveForLocationApprovalFactory +func (r PermissionDecisionApproveForLocationApprovalMCP) MarshalJSON() ([]byte, error) { + type alias PermissionDecisionApproveForLocationApprovalMCP return json.Marshal(struct { Kind PermissionDecisionApproveForLocationApprovalKind `json:"kind"` alias @@ -4730,8 +5052,8 @@ func (r PermissionDecisionApproveForLocationApprovalFactory) MarshalJSON() ([]by }) } -func (r PermissionDecisionApproveForLocationApprovalMCP) MarshalJSON() ([]byte, error) { - type alias PermissionDecisionApproveForLocationApprovalMCP +func (r PermissionDecisionApproveForLocationApprovalMCPSampling) MarshalJSON() ([]byte, error) { + type alias PermissionDecisionApproveForLocationApprovalMCPSampling return json.Marshal(struct { Kind PermissionDecisionApproveForLocationApprovalKind `json:"kind"` alias @@ -4741,8 +5063,8 @@ func (r PermissionDecisionApproveForLocationApprovalMCP) MarshalJSON() ([]byte, }) } -func (r PermissionDecisionApproveForLocationApprovalMCPSampling) MarshalJSON() ([]byte, error) { - type alias PermissionDecisionApproveForLocationApprovalMCPSampling +func (r PermissionDecisionApproveForLocationApprovalMemory) MarshalJSON() ([]byte, error) { + type alias PermissionDecisionApproveForLocationApprovalMemory return json.Marshal(struct { Kind PermissionDecisionApproveForLocationApprovalKind `json:"kind"` alias @@ -4752,8 +5074,8 @@ func (r PermissionDecisionApproveForLocationApprovalMCPSampling) MarshalJSON() ( }) } -func (r PermissionDecisionApproveForLocationApprovalMemory) MarshalJSON() ([]byte, error) { - type alias PermissionDecisionApproveForLocationApprovalMemory +func (r PermissionDecisionApproveForLocationApprovalRead) MarshalJSON() ([]byte, error) { + type alias PermissionDecisionApproveForLocationApprovalRead return json.Marshal(struct { Kind PermissionDecisionApproveForLocationApprovalKind `json:"kind"` alias @@ -4763,8 +5085,8 @@ func (r PermissionDecisionApproveForLocationApprovalMemory) MarshalJSON() ([]byt }) } -func (r PermissionDecisionApproveForLocationApprovalRead) MarshalJSON() ([]byte, error) { - type alias PermissionDecisionApproveForLocationApprovalRead +func (r PermissionDecisionApproveForLocationApprovalWorkflow) MarshalJSON() ([]byte, error) { + type alias PermissionDecisionApproveForLocationApprovalWorkflow return json.Marshal(struct { Kind PermissionDecisionApproveForLocationApprovalKind `json:"kind"` alias @@ -4859,12 +5181,6 @@ func unmarshalPermissionDecisionApproveForSessionApproval(data []byte) (Permissi return nil, err } return &d, nil - case PermissionDecisionApproveForSessionApprovalKindFactory: - var d PermissionDecisionApproveForSessionApprovalFactory - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil case PermissionDecisionApproveForSessionApprovalKindMCP: var d PermissionDecisionApproveForSessionApprovalMCP if err := json.Unmarshal(data, &d); err != nil { @@ -4889,6 +5205,12 @@ func unmarshalPermissionDecisionApproveForSessionApproval(data []byte) (Permissi return nil, err } return &d, nil + case PermissionDecisionApproveForSessionApprovalKindWorkflow: + var d PermissionDecisionApproveForSessionApprovalWorkflow + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case PermissionDecisionApproveForSessionApprovalKindWrite: var d PermissionDecisionApproveForSessionApprovalWrite if err := json.Unmarshal(data, &d); err != nil { @@ -4966,8 +5288,8 @@ func (r PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess) Ma }) } -func (r PermissionDecisionApproveForSessionApprovalFactory) MarshalJSON() ([]byte, error) { - type alias PermissionDecisionApproveForSessionApprovalFactory +func (r PermissionDecisionApproveForSessionApprovalMCP) MarshalJSON() ([]byte, error) { + type alias PermissionDecisionApproveForSessionApprovalMCP return json.Marshal(struct { Kind PermissionDecisionApproveForSessionApprovalKind `json:"kind"` alias @@ -4977,8 +5299,8 @@ func (r PermissionDecisionApproveForSessionApprovalFactory) MarshalJSON() ([]byt }) } -func (r PermissionDecisionApproveForSessionApprovalMCP) MarshalJSON() ([]byte, error) { - type alias PermissionDecisionApproveForSessionApprovalMCP +func (r PermissionDecisionApproveForSessionApprovalMCPSampling) MarshalJSON() ([]byte, error) { + type alias PermissionDecisionApproveForSessionApprovalMCPSampling return json.Marshal(struct { Kind PermissionDecisionApproveForSessionApprovalKind `json:"kind"` alias @@ -4988,8 +5310,8 @@ func (r PermissionDecisionApproveForSessionApprovalMCP) MarshalJSON() ([]byte, e }) } -func (r PermissionDecisionApproveForSessionApprovalMCPSampling) MarshalJSON() ([]byte, error) { - type alias PermissionDecisionApproveForSessionApprovalMCPSampling +func (r PermissionDecisionApproveForSessionApprovalMemory) MarshalJSON() ([]byte, error) { + type alias PermissionDecisionApproveForSessionApprovalMemory return json.Marshal(struct { Kind PermissionDecisionApproveForSessionApprovalKind `json:"kind"` alias @@ -4999,8 +5321,8 @@ func (r PermissionDecisionApproveForSessionApprovalMCPSampling) MarshalJSON() ([ }) } -func (r PermissionDecisionApproveForSessionApprovalMemory) MarshalJSON() ([]byte, error) { - type alias PermissionDecisionApproveForSessionApprovalMemory +func (r PermissionDecisionApproveForSessionApprovalRead) MarshalJSON() ([]byte, error) { + type alias PermissionDecisionApproveForSessionApprovalRead return json.Marshal(struct { Kind PermissionDecisionApproveForSessionApprovalKind `json:"kind"` alias @@ -5010,8 +5332,8 @@ func (r PermissionDecisionApproveForSessionApprovalMemory) MarshalJSON() ([]byte }) } -func (r PermissionDecisionApproveForSessionApprovalRead) MarshalJSON() ([]byte, error) { - type alias PermissionDecisionApproveForSessionApprovalRead +func (r PermissionDecisionApproveForSessionApprovalWorkflow) MarshalJSON() ([]byte, error) { + type alias PermissionDecisionApproveForSessionApprovalWorkflow return json.Marshal(struct { Kind PermissionDecisionApproveForSessionApprovalKind `json:"kind"` alias @@ -5238,12 +5560,6 @@ func unmarshalPermissionsLocationsAddToolApprovalDetails(data []byte) (Permissio return nil, err } return &d, nil - case PermissionsLocationsAddToolApprovalDetailsKindFactory: - var d PermissionsLocationsAddToolApprovalDetailsFactory - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil case PermissionsLocationsAddToolApprovalDetailsKindMCP: var d PermissionsLocationsAddToolApprovalDetailsMCP if err := json.Unmarshal(data, &d); err != nil { @@ -5268,6 +5584,12 @@ func unmarshalPermissionsLocationsAddToolApprovalDetails(data []byte) (Permissio return nil, err } return &d, nil + case PermissionsLocationsAddToolApprovalDetailsKindWorkflow: + var d PermissionsLocationsAddToolApprovalDetailsWorkflow + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case PermissionsLocationsAddToolApprovalDetailsKindWrite: var d PermissionsLocationsAddToolApprovalDetailsWrite if err := json.Unmarshal(data, &d); err != nil { @@ -5345,8 +5667,8 @@ func (r PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess) Mar }) } -func (r PermissionsLocationsAddToolApprovalDetailsFactory) MarshalJSON() ([]byte, error) { - type alias PermissionsLocationsAddToolApprovalDetailsFactory +func (r PermissionsLocationsAddToolApprovalDetailsMCP) MarshalJSON() ([]byte, error) { + type alias PermissionsLocationsAddToolApprovalDetailsMCP return json.Marshal(struct { Kind PermissionsLocationsAddToolApprovalDetailsKind `json:"kind"` alias @@ -5356,8 +5678,8 @@ func (r PermissionsLocationsAddToolApprovalDetailsFactory) MarshalJSON() ([]byte }) } -func (r PermissionsLocationsAddToolApprovalDetailsMCP) MarshalJSON() ([]byte, error) { - type alias PermissionsLocationsAddToolApprovalDetailsMCP +func (r PermissionsLocationsAddToolApprovalDetailsMCPSampling) MarshalJSON() ([]byte, error) { + type alias PermissionsLocationsAddToolApprovalDetailsMCPSampling return json.Marshal(struct { Kind PermissionsLocationsAddToolApprovalDetailsKind `json:"kind"` alias @@ -5367,8 +5689,8 @@ func (r PermissionsLocationsAddToolApprovalDetailsMCP) MarshalJSON() ([]byte, er }) } -func (r PermissionsLocationsAddToolApprovalDetailsMCPSampling) MarshalJSON() ([]byte, error) { - type alias PermissionsLocationsAddToolApprovalDetailsMCPSampling +func (r PermissionsLocationsAddToolApprovalDetailsMemory) MarshalJSON() ([]byte, error) { + type alias PermissionsLocationsAddToolApprovalDetailsMemory return json.Marshal(struct { Kind PermissionsLocationsAddToolApprovalDetailsKind `json:"kind"` alias @@ -5378,8 +5700,8 @@ func (r PermissionsLocationsAddToolApprovalDetailsMCPSampling) MarshalJSON() ([] }) } -func (r PermissionsLocationsAddToolApprovalDetailsMemory) MarshalJSON() ([]byte, error) { - type alias PermissionsLocationsAddToolApprovalDetailsMemory +func (r PermissionsLocationsAddToolApprovalDetailsRead) MarshalJSON() ([]byte, error) { + type alias PermissionsLocationsAddToolApprovalDetailsRead return json.Marshal(struct { Kind PermissionsLocationsAddToolApprovalDetailsKind `json:"kind"` alias @@ -5389,8 +5711,8 @@ func (r PermissionsLocationsAddToolApprovalDetailsMemory) MarshalJSON() ([]byte, }) } -func (r PermissionsLocationsAddToolApprovalDetailsRead) MarshalJSON() ([]byte, error) { - type alias PermissionsLocationsAddToolApprovalDetailsRead +func (r PermissionsLocationsAddToolApprovalDetailsWorkflow) MarshalJSON() ([]byte, error) { + type alias PermissionsLocationsAddToolApprovalDetailsWorkflow return json.Marshal(struct { Kind PermissionsLocationsAddToolApprovalDetailsKind `json:"kind"` alias diff --git a/go/rpc/zsession_encoding.go b/go/rpc/zsession_encoding.go index a840934e39..c4e9734912 100644 --- a/go/rpc/zsession_encoding.go +++ b/go/rpc/zsession_encoding.go @@ -233,24 +233,6 @@ func (e *SessionEvent) UnmarshalJSON(data []byte) error { return err } e.Data = &d - case SessionEventTypeFactoryRunSettled: - var d FactoryRunSettledData - if err := json.Unmarshal(raw.Data, &d); err != nil { - return err - } - e.Data = &d - case SessionEventTypeFactoryRunStarted: - var d FactoryRunStartedData - if err := json.Unmarshal(raw.Data, &d); err != nil { - return err - } - e.Data = &d - case SessionEventTypeFactoryRunUpdated: - var d FactoryRunUpdatedData - if err := json.Unmarshal(raw.Data, &d); err != nil { - return err - } - e.Data = &d case SessionEventTypeHookEnd: var d HookEndData if err := json.Unmarshal(raw.Data, &d); err != nil { @@ -929,6 +911,24 @@ func (e *SessionEvent) UnmarshalJSON(data []byte) error { return err } e.Data = &d + case SessionEventTypeWorkflowRunSettled: + var d WorkflowRunSettledData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d + case SessionEventTypeWorkflowRunStarted: + var d WorkflowRunStartedData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d + case SessionEventTypeWorkflowRunUpdated: + var d WorkflowRunUpdatedData + if err := json.Unmarshal(raw.Data, &d); err != nil { + return err + } + e.Data = &d default: e.Data = &RawSessionEventData{EventType: raw.Type, Raw: raw.Data} } @@ -1584,12 +1584,6 @@ func unmarshalSystemNotification(data []byte) (SystemNotification, error) { return nil, err } return &d, nil - case SystemNotificationTypeFactoryCompleted: - var d SystemNotificationFactoryCompleted - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil case SystemNotificationTypeInstructionDiscovered: var d SystemNotificationInstructionDiscovered if err := json.Unmarshal(data, &d); err != nil { @@ -1620,6 +1614,12 @@ func unmarshalSystemNotification(data []byte) (SystemNotification, error) { return nil, err } return &d, nil + case SystemNotificationTypeWorkflowCompleted: + var d SystemNotificationWorkflowCompleted + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil default: return &RawSystemNotification{Discriminator: raw.Type, Raw: data}, nil } @@ -1658,12 +1658,67 @@ func (r SystemNotificationAgentIdle) MarshalJSON() ([]byte, error) { }) } -func unmarshalSystemNotificationFactoryPauseInfo(data []byte) (SystemNotificationFactoryPauseInfo, error) { +func (r SystemNotificationInstructionDiscovered) MarshalJSON() ([]byte, error) { + type alias SystemNotificationInstructionDiscovered + return json.Marshal(struct { + Type SystemNotificationType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r SystemNotificationNewInboxMessage) MarshalJSON() ([]byte, error) { + type alias SystemNotificationNewInboxMessage + return json.Marshal(struct { + Type SystemNotificationType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r SystemNotificationShellCompleted) MarshalJSON() ([]byte, error) { + type alias SystemNotificationShellCompleted + return json.Marshal(struct { + Type SystemNotificationType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r SystemNotificationShellDetachedCompleted) MarshalJSON() ([]byte, error) { + type alias SystemNotificationShellDetachedCompleted + return json.Marshal(struct { + Type SystemNotificationType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func (r SystemNotificationUnclassified) MarshalJSON() ([]byte, error) { + type alias SystemNotificationUnclassified + return json.Marshal(struct { + Type SystemNotificationType `json:"type"` + alias + }{ + Type: r.Type(), + alias: alias(r), + }) +} + +func unmarshalSystemNotificationWorkflowPauseInfo(data []byte) (SystemNotificationWorkflowPauseInfo, error) { if string(data) == "null" { return nil, nil } type rawUnion struct { - Type SystemNotificationFactoryPauseInfoType `json:"type"` + Type SystemNotificationWorkflowPauseInfoType `json:"type"` } var raw rawUnion if err := json.Unmarshal(data, &raw); err != nil { @@ -1671,38 +1726,38 @@ func unmarshalSystemNotificationFactoryPauseInfo(data []byte) (SystemNotificatio } switch raw.Type { - case SystemNotificationFactoryPauseInfoTypeCheckpoint: - var d SystemNotificationFactoryPauseInfoCheckpoint + case SystemNotificationWorkflowPauseInfoTypeCheckpoint: + var d SystemNotificationWorkflowPauseInfoCheckpoint if err := json.Unmarshal(data, &d); err != nil { return nil, err } return &d, nil - case SystemNotificationFactoryPauseInfoTypeUser: - var d SystemNotificationFactoryPauseInfoUser + case SystemNotificationWorkflowPauseInfoTypeUser: + var d SystemNotificationWorkflowPauseInfoUser if err := json.Unmarshal(data, &d); err != nil { return nil, err } return &d, nil default: - return &RawSystemNotificationFactoryPauseInfo{Discriminator: raw.Type, Raw: data}, nil + return &RawSystemNotificationWorkflowPauseInfo{Discriminator: raw.Type, Raw: data}, nil } } -func (r RawSystemNotificationFactoryPauseInfo) MarshalJSON() ([]byte, error) { +func (r RawSystemNotificationWorkflowPauseInfo) MarshalJSON() ([]byte, error) { if r.Raw != nil { return r.Raw, nil } return json.Marshal(struct { - Type SystemNotificationFactoryPauseInfoType `json:"type"` + Type SystemNotificationWorkflowPauseInfoType `json:"type"` }{ Type: r.Discriminator, }) } -func (r SystemNotificationFactoryPauseInfoCheckpoint) MarshalJSON() ([]byte, error) { - type alias SystemNotificationFactoryPauseInfoCheckpoint +func (r SystemNotificationWorkflowPauseInfoCheckpoint) MarshalJSON() ([]byte, error) { + type alias SystemNotificationWorkflowPauseInfoCheckpoint return json.Marshal(struct { - Type SystemNotificationFactoryPauseInfoType `json:"type"` + Type SystemNotificationWorkflowPauseInfoType `json:"type"` alias }{ Type: r.Type(), @@ -1710,10 +1765,10 @@ func (r SystemNotificationFactoryPauseInfoCheckpoint) MarshalJSON() ([]byte, err }) } -func (r SystemNotificationFactoryPauseInfoUser) MarshalJSON() ([]byte, error) { - type alias SystemNotificationFactoryPauseInfoUser +func (r SystemNotificationWorkflowPauseInfoUser) MarshalJSON() ([]byte, error) { + type alias SystemNotificationWorkflowPauseInfoUser return json.Marshal(struct { - Type SystemNotificationFactoryPauseInfoType `json:"type"` + Type SystemNotificationWorkflowPauseInfoType `json:"type"` alias }{ Type: r.Type(), @@ -1721,21 +1776,21 @@ func (r SystemNotificationFactoryPauseInfoUser) MarshalJSON() ([]byte, error) { }) } -func (r *SystemNotificationFactoryCompleted) UnmarshalJSON(data []byte) error { - type rawSystemNotificationFactoryCompleted struct { - Attempt int64 `json:"attempt"` - ConsumedNanoAiu int64 `json:"consumedNanoAiu"` - ConsumedSubagents int64 `json:"consumedSubagents"` - ElapsedMs int64 `json:"elapsedMs"` - FactoryName string `json:"factoryName"` - Failure any `json:"failure,omitempty"` - PauseInfo json.RawMessage `json:"pauseInfo,omitempty"` - ResultPreview *string `json:"resultPreview,omitempty"` - RetryGuidance *string `json:"retryGuidance,omitempty"` - RunID string `json:"runId"` - Status SystemNotificationFactoryCompletedStatus `json:"status"` +func (r *SystemNotificationWorkflowCompleted) UnmarshalJSON(data []byte) error { + type rawSystemNotificationWorkflowCompleted struct { + Attempt int64 `json:"attempt"` + ConsumedNanoAiu int64 `json:"consumedNanoAiu"` + ConsumedSubagents int64 `json:"consumedSubagents"` + ElapsedMs int64 `json:"elapsedMs"` + Failure any `json:"failure,omitempty"` + PauseInfo json.RawMessage `json:"pauseInfo,omitempty"` + ResultPreview *string `json:"resultPreview,omitempty"` + RetryGuidance *string `json:"retryGuidance,omitempty"` + RunID string `json:"runId"` + Status SystemNotificationWorkflowCompletedStatus `json:"status"` + WorkflowName string `json:"workflowName"` } - var raw rawSystemNotificationFactoryCompleted + var raw rawSystemNotificationWorkflowCompleted if err := json.Unmarshal(data, &raw); err != nil { return err } @@ -1743,10 +1798,9 @@ func (r *SystemNotificationFactoryCompleted) UnmarshalJSON(data []byte) error { r.ConsumedNanoAiu = raw.ConsumedNanoAiu r.ConsumedSubagents = raw.ConsumedSubagents r.ElapsedMs = raw.ElapsedMs - r.FactoryName = raw.FactoryName r.Failure = raw.Failure if raw.PauseInfo != nil { - value, err := unmarshalSystemNotificationFactoryPauseInfo(raw.PauseInfo) + value, err := unmarshalSystemNotificationWorkflowPauseInfo(raw.PauseInfo) if err != nil { return err } @@ -1756,66 +1810,12 @@ func (r *SystemNotificationFactoryCompleted) UnmarshalJSON(data []byte) error { r.RetryGuidance = raw.RetryGuidance r.RunID = raw.RunID r.Status = raw.Status + r.WorkflowName = raw.WorkflowName return nil } -func (r SystemNotificationFactoryCompleted) MarshalJSON() ([]byte, error) { - type alias SystemNotificationFactoryCompleted - return json.Marshal(struct { - Type SystemNotificationType `json:"type"` - alias - }{ - Type: r.Type(), - alias: alias(r), - }) -} - -func (r SystemNotificationInstructionDiscovered) MarshalJSON() ([]byte, error) { - type alias SystemNotificationInstructionDiscovered - return json.Marshal(struct { - Type SystemNotificationType `json:"type"` - alias - }{ - Type: r.Type(), - alias: alias(r), - }) -} - -func (r SystemNotificationNewInboxMessage) MarshalJSON() ([]byte, error) { - type alias SystemNotificationNewInboxMessage - return json.Marshal(struct { - Type SystemNotificationType `json:"type"` - alias - }{ - Type: r.Type(), - alias: alias(r), - }) -} - -func (r SystemNotificationShellCompleted) MarshalJSON() ([]byte, error) { - type alias SystemNotificationShellCompleted - return json.Marshal(struct { - Type SystemNotificationType `json:"type"` - alias - }{ - Type: r.Type(), - alias: alias(r), - }) -} - -func (r SystemNotificationShellDetachedCompleted) MarshalJSON() ([]byte, error) { - type alias SystemNotificationShellDetachedCompleted - return json.Marshal(struct { - Type SystemNotificationType `json:"type"` - alias - }{ - Type: r.Type(), - alias: alias(r), - }) -} - -func (r SystemNotificationUnclassified) MarshalJSON() ([]byte, error) { - type alias SystemNotificationUnclassified +func (r SystemNotificationWorkflowCompleted) MarshalJSON() ([]byte, error) { + type alias SystemNotificationWorkflowCompleted return json.Marshal(struct { Type SystemNotificationType `json:"type"` alias @@ -1884,12 +1884,6 @@ func unmarshalPermissionRequest(data []byte) (PermissionRequest, error) { return nil, err } return &d, nil - case PermissionRequestKindFactory: - var d PermissionRequestFactory - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil case PermissionRequestKindHook: var d PermissionRequestHook if err := json.Unmarshal(data, &d); err != nil { @@ -1926,6 +1920,12 @@ func unmarshalPermissionRequest(data []byte) (PermissionRequest, error) { return nil, err } return &d, nil + case PermissionRequestKindWorkflow: + var d PermissionRequestWorkflow + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case PermissionRequestKindWrite: var d PermissionRequestWrite if err := json.Unmarshal(data, &d); err != nil { @@ -1992,17 +1992,6 @@ func (r PermissionRequestExtensionPermissionAccess) MarshalJSON() ([]byte, error }) } -func (r PermissionRequestFactory) MarshalJSON() ([]byte, error) { - type alias PermissionRequestFactory - return json.Marshal(struct { - Kind PermissionRequestKind `json:"kind"` - alias - }{ - Kind: r.Kind(), - alias: alias(r), - }) -} - func (r PermissionRequestHook) MarshalJSON() ([]byte, error) { type alias PermissionRequestHook return json.Marshal(struct { @@ -2069,6 +2058,17 @@ func (r PermissionRequestURL) MarshalJSON() ([]byte, error) { }) } +func (r PermissionRequestWorkflow) MarshalJSON() ([]byte, error) { + type alias PermissionRequestWorkflow + return json.Marshal(struct { + Kind PermissionRequestKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + func (r PermissionRequestWrite) MarshalJSON() ([]byte, error) { type alias PermissionRequestWrite return json.Marshal(struct { @@ -2123,12 +2123,6 @@ func unmarshalPermissionPromptRequest(data []byte) (PermissionPromptRequest, err return nil, err } return &d, nil - case PermissionPromptRequestKindFactory: - var d PermissionPromptRequestFactory - if err := json.Unmarshal(data, &d); err != nil { - return nil, err - } - return &d, nil case PermissionPromptRequestKindHook: var d PermissionPromptRequestHook if err := json.Unmarshal(data, &d); err != nil { @@ -2165,6 +2159,12 @@ func unmarshalPermissionPromptRequest(data []byte) (PermissionPromptRequest, err return nil, err } return &d, nil + case PermissionPromptRequestKindWorkflow: + var d PermissionPromptRequestWorkflow + if err := json.Unmarshal(data, &d); err != nil { + return nil, err + } + return &d, nil case PermissionPromptRequestKindWrite: var d PermissionPromptRequestWrite if err := json.Unmarshal(data, &d); err != nil { @@ -2242,17 +2242,6 @@ func (r PermissionPromptRequestExtensionPermissionAccess) MarshalJSON() ([]byte, }) } -func (r PermissionPromptRequestFactory) MarshalJSON() ([]byte, error) { - type alias PermissionPromptRequestFactory - return json.Marshal(struct { - Kind PermissionPromptRequestKind `json:"kind"` - alias - }{ - Kind: r.Kind(), - alias: alias(r), - }) -} - func (r PermissionPromptRequestHook) MarshalJSON() ([]byte, error) { type alias PermissionPromptRequestHook return json.Marshal(struct { @@ -2319,6 +2308,17 @@ func (r PermissionPromptRequestURL) MarshalJSON() ([]byte, error) { }) } +func (r PermissionPromptRequestWorkflow) MarshalJSON() ([]byte, error) { + type alias PermissionPromptRequestWorkflow + return json.Marshal(struct { + Kind PermissionPromptRequestKind `json:"kind"` + alias + }{ + Kind: r.Kind(), + alias: alias(r), + }) +} + func (r PermissionPromptRequestWrite) MarshalJSON() ([]byte, error) { type alias PermissionPromptRequestWrite return json.Marshal(struct { diff --git a/go/rpc/zsession_events.go b/go/rpc/zsession_events.go index 3d341cb51e..6572555aca 100644 --- a/go/rpc/zsession_events.go +++ b/go/rpc/zsession_events.go @@ -94,30 +94,21 @@ const ( SessionEventTypeExitPlanModeRequested SessionEventType = "exit_plan_mode.requested" SessionEventTypeExternalToolCompleted SessionEventType = "external_tool.completed" SessionEventTypeExternalToolRequested SessionEventType = "external_tool.requested" - // Experimental: SessionEventTypeFactoryRunSettled identifies an experimental event that may - // change or be removed. - SessionEventTypeFactoryRunSettled SessionEventType = "factory.run_settled" - // Experimental: SessionEventTypeFactoryRunStarted identifies an experimental event that may - // change or be removed. - SessionEventTypeFactoryRunStarted SessionEventType = "factory.run_started" - // Experimental: SessionEventTypeFactoryRunUpdated identifies an experimental event that may - // change or be removed. - SessionEventTypeFactoryRunUpdated SessionEventType = "factory.run_updated" - SessionEventTypeHookEnd SessionEventType = "hook.end" - SessionEventTypeHookProgress SessionEventType = "hook.progress" - SessionEventTypeHookStart SessionEventType = "hook.start" - SessionEventTypeMCPAppToolCallComplete SessionEventType = "mcp_app.tool_call_complete" - SessionEventTypeMCPHeadersRefreshCompleted SessionEventType = "mcp.headers_refresh_completed" - SessionEventTypeMCPHeadersRefreshRequired SessionEventType = "mcp.headers_refresh_required" - SessionEventTypeMCPOauthCompleted SessionEventType = "mcp.oauth_completed" - SessionEventTypeMCPOauthRequired SessionEventType = "mcp.oauth_required" - SessionEventTypeMCPPromptsListChanged SessionEventType = "mcp.prompts.list_changed" - SessionEventTypeMCPResourcesListChanged SessionEventType = "mcp.resources.list_changed" - SessionEventTypeMCPToolsListChanged SessionEventType = "mcp.tools.list_changed" - SessionEventTypeModelCallFailure SessionEventType = "model.call_failure" - SessionEventTypeModelCallFinished SessionEventType = "model.call_finished" - SessionEventTypeModelCallStart SessionEventType = "model.call_start" - SessionEventTypePendingMessagesModified SessionEventType = "pending_messages.modified" + SessionEventTypeHookEnd SessionEventType = "hook.end" + SessionEventTypeHookProgress SessionEventType = "hook.progress" + SessionEventTypeHookStart SessionEventType = "hook.start" + SessionEventTypeMCPAppToolCallComplete SessionEventType = "mcp_app.tool_call_complete" + SessionEventTypeMCPHeadersRefreshCompleted SessionEventType = "mcp.headers_refresh_completed" + SessionEventTypeMCPHeadersRefreshRequired SessionEventType = "mcp.headers_refresh_required" + SessionEventTypeMCPOauthCompleted SessionEventType = "mcp.oauth_completed" + SessionEventTypeMCPOauthRequired SessionEventType = "mcp.oauth_required" + SessionEventTypeMCPPromptsListChanged SessionEventType = "mcp.prompts.list_changed" + SessionEventTypeMCPResourcesListChanged SessionEventType = "mcp.resources.list_changed" + SessionEventTypeMCPToolsListChanged SessionEventType = "mcp.tools.list_changed" + SessionEventTypeModelCallFailure SessionEventType = "model.call_failure" + SessionEventTypeModelCallFinished SessionEventType = "model.call_finished" + SessionEventTypeModelCallStart SessionEventType = "model.call_start" + SessionEventTypePendingMessagesModified SessionEventType = "pending_messages.modified" // Experimental: SessionEventTypePermissionAssentDetected identifies an experimental event // that may change or be removed. SessionEventTypePermissionAssentDetected SessionEventType = "permission.assentDetected" @@ -270,6 +261,15 @@ const ( SessionEventTypeUserInputCompleted SessionEventType = "user_input.completed" SessionEventTypeUserInputRequested SessionEventType = "user_input.requested" SessionEventTypeUserMessage SessionEventType = "user.message" + // Experimental: SessionEventTypeWorkflowRunSettled identifies an experimental event that + // may change or be removed. + SessionEventTypeWorkflowRunSettled SessionEventType = "workflow.run_settled" + // Experimental: SessionEventTypeWorkflowRunStarted identifies an experimental event that + // may change or be removed. + SessionEventTypeWorkflowRunStarted SessionEventType = "workflow.run_started" + // Experimental: SessionEventTypeWorkflowRunUpdated identifies an experimental event that + // may change or be removed. + SessionEventTypeWorkflowRunUpdated SessionEventType = "workflow.run_updated" ) // A detected loss of a previously cached prompt prefix @@ -639,9 +639,12 @@ func (*SessionContextClearedData) Type() SessionEventType { // Conversation compaction results including success status, metrics, and optional error details type SessionCompactionCompleteData struct { - // Authoritative active-factory reminder appended to the compacted context + // Legacy active-workflow reminder retained for replay compatibility // Internal: ActiveFactorySummary is part of the SDK's internal API surface and is not intended for external use. ActiveFactorySummary *string `json:"activeFactorySummary,omitempty"` + // Authoritative active-workflow reminder appended to the compacted context + // Internal: ActiveWorkflowSummary is part of the SDK's internal API surface and is not intended for external use. + ActiveWorkflowSummary *string `json:"activeWorkflowSummary,omitempty"` // Canonical model identifier used for model-specific behavior when replaying compaction BehaviorModelID *string `json:"behaviorModelId,omitempty"` // Checkpoint snapshot number created for recovery @@ -912,17 +915,17 @@ func (*SessionManagedSettingsResolvedData) Type() SessionEventType { return SessionEventTypeSessionManagedSettingsResolved } -// Ephemeral invalidation signal for a changed factory run. -// Experimental: FactoryRunUpdatedData is part of an experimental API and may change or be removed. -type FactoryRunUpdatedData struct { +// Ephemeral invalidation signal for a changed workflow run. +// Experimental: WorkflowRunUpdatedData is part of an experimental API and may change or be removed. +type WorkflowRunUpdatedData struct { // Monotonic revision now available for the run. Revision int64 `json:"revision"` - // Factory run identifier. + // Workflow run identifier. RunID string `json:"runId"` } -func (*FactoryRunUpdatedData) sessionEventData() {} -func (*FactoryRunUpdatedData) Type() SessionEventType { return SessionEventTypeFactoryRunUpdated } +func (*WorkflowRunUpdatedData) sessionEventData() {} +func (*WorkflowRunUpdatedData) Type() SessionEventType { return SessionEventTypeWorkflowRunUpdated } // Ephemeral progress update from a running hook process type HookProgressData struct { @@ -935,39 +938,39 @@ type HookProgressData struct { func (*HookProgressData) sessionEventData() {} func (*HookProgressData) Type() SessionEventType { return SessionEventTypeHookProgress } -// Ephemeral signal that a factory run attempt began executing. -// Experimental: FactoryRunStartedData is part of an experimental API and may change or be removed. -type FactoryRunStartedData struct { +// Ephemeral signal that a workflow run attempt began executing. +// Experimental: WorkflowRunStartedData is part of an experimental API and may change or be removed. +type WorkflowRunStartedData struct { // Attempt number this start committed; a resumed run increments it. Attempt int64 `json:"attempt"` - // Name of the factory this run executes. Low cardinality by construction. - FactoryName string `json:"factoryName"` - // Identifier of the factory run that started. + // Identifier of the workflow run that started. RunID string `json:"runId"` + // Name of the workflow this run executes. Low cardinality by construction. + WorkflowName string `json:"workflowName"` } -func (*FactoryRunStartedData) sessionEventData() {} -func (*FactoryRunStartedData) Type() SessionEventType { return SessionEventTypeFactoryRunStarted } +func (*WorkflowRunStartedData) sessionEventData() {} +func (*WorkflowRunStartedData) Type() SessionEventType { return SessionEventTypeWorkflowRunStarted } -// Ephemeral signal that a factory run reached a terminal status. -// Experimental: FactoryRunSettledData is part of an experimental API and may change or be removed. -type FactoryRunSettledData struct { +// Ephemeral signal that a workflow run reached a terminal status. +// Experimental: WorkflowRunSettledData is part of an experimental API and may change or be removed. +type WorkflowRunSettledData struct { // AI credits this run consumed, in nano-AIU. ConsumedNanoAiu int64 `json:"consumedNanoAiu"` // Subagents this run consumed against its limits. ConsumedSubagents int64 `json:"consumedSubagents"` // Active milliseconds accumulated across every attempt of this run. ElapsedMs int64 `json:"elapsedMs"` - // Typed failure class recorded on the run, when it failed with one (e.g. `factory_limit_reached`). + // Typed failure class recorded on the run, when it failed with one (e.g. `workflow_limit_reached`). FailureType *string `json:"failureType,omitempty"` - // Identifier of the factory run that settled. + // Identifier of the workflow run that settled. RunID string `json:"runId"` // Terminal status the run committed. - Status FactoryRunSettledStatus `json:"status"` + Status WorkflowRunSettledStatus `json:"status"` } -func (*FactoryRunSettledData) sessionEventData() {} -func (*FactoryRunSettledData) Type() SessionEventType { return SessionEventTypeFactoryRunSettled } +func (*WorkflowRunSettledData) sessionEventData() {} +func (*WorkflowRunSettledData) Type() SessionEventType { return SessionEventTypeWorkflowRunSettled } // Error details for timeline display including message and optional diagnostic information type SessionErrorData struct { @@ -1398,35 +1401,7 @@ type ModelCallFinishedData struct { func (*ModelCallFinishedData) sessionEventData() {} func (*ModelCallFinishedData) Type() SessionEventType { return SessionEventTypeModelCallFinished } -// Freezes a blinded contextual authorization proposal whose verbatim human span was deterministically bound to the immediately preceding blocked permission request. The event carries no action fields; replay re-derives the exact action from the earlier permission request and mints a one-shot message grant only when the binding and span still verify. -// Experimental: PermissionContextualAuthorizationData is part of an experimental API and may change or be removed. -type PermissionContextualAuthorizationData struct { - // Whether the contextual human span granted or denied authority. - // Experimental: Polarity is part of an experimental API and may change or be removed. - Polarity PermissionMessageAuthorizationPolarity `json:"polarity"` - // Deterministic identity of the contextual message grant. - // Experimental: RecordID is part of an experimental API and may change or be removed. - RecordID string `json:"recordId"` - // Original blocked permission request selected by deterministic event ordering, never by the extraction model. - // Experimental: RequestID is part of an experimental API and may change or be removed. - RequestID string `json:"requestId"` - // End byte offset of the contextual decision span within the turn. - // Experimental: SpanEnd is part of an experimental API and may change or be removed. - SpanEnd int64 `json:"spanEnd"` - // Start byte offset of the contextual decision span within the turn. - // Experimental: SpanStart is part of an experimental API and may change or be removed. - SpanStart int64 `json:"spanStart"` - // Human turn containing the contextual decision. - // Experimental: TurnIndex is part of an experimental API and may change or be removed. - TurnIndex int64 `json:"turnIndex"` -} - -func (*PermissionContextualAuthorizationData) sessionEventData() {} -func (*PermissionContextualAuthorizationData) Type() SessionEventType { - return SessionEventTypePermissionContextualAuthorization -} - -// Freezes one blinded, verbatim-verified authorization claim the runtime minted from a human user message, so a resumed session re-establishes the same grant deterministically instead of re-running the extraction model. This mints no authority on its own: it records what a blinded proposer pointed at and the trusted discriminator the runtime established, and deterministic establishment runs on replay. Persisted so recorded authority survives compaction and process resume. +// Historical decode-only claim from the retired Assisted Permissions authorization extractor. Current runtimes preserve the payload but do not establish authority from it. // Experimental: PermissionMessageAuthorizationData is part of an experimental API and may change or be removed. type PermissionMessageAuthorizationData struct { // The kind of effect authorized, as an action-class identifier. @@ -1463,6 +1438,101 @@ func (*PermissionMessageAuthorizationData) Type() SessionEventType { return SessionEventTypePermissionMessageAuthorization } +// Historical decode-only contextual authorization claim. Current runtimes preserve the payload but do not establish authority from it. +// Experimental: PermissionContextualAuthorizationData is part of an experimental API and may change or be removed. +type PermissionContextualAuthorizationData struct { + // Whether the contextual human span granted or denied authority. + // Experimental: Polarity is part of an experimental API and may change or be removed. + Polarity PermissionMessageAuthorizationPolarity `json:"polarity"` + // Deterministic identity of the contextual message grant. + // Experimental: RecordID is part of an experimental API and may change or be removed. + RecordID string `json:"recordId"` + // Original blocked permission request selected by deterministic event ordering, never by the extraction model. + // Experimental: RequestID is part of an experimental API and may change or be removed. + RequestID string `json:"requestId"` + // End byte offset of the contextual decision span within the turn. + // Experimental: SpanEnd is part of an experimental API and may change or be removed. + SpanEnd int64 `json:"spanEnd"` + // Start byte offset of the contextual decision span within the turn. + // Experimental: SpanStart is part of an experimental API and may change or be removed. + SpanStart int64 `json:"spanStart"` + // Human turn containing the contextual decision. + // Experimental: TurnIndex is part of an experimental API and may change or be removed. + TurnIndex int64 `json:"turnIndex"` +} + +func (*PermissionContextualAuthorizationData) sessionEventData() {} +func (*PermissionContextualAuthorizationData) Type() SessionEventType { + return SessionEventTypePermissionContextualAuthorization +} + +// Historical decode-only contextual-assent marker. Current runtimes do not project it into the conversation or permission flow. +// Experimental: PermissionAssentDetectedData is part of an experimental API and may change or be removed. +type PermissionAssentDetectedData struct { + // Permission request the likely assent may refer to. The runtime derives this from the preceding durable blocker; the human message and extraction model do not choose it. + // Experimental: RequestID is part of an experimental API and may change or be removed. + RequestID string `json:"requestId"` + // Human turn whose text triggered the deterministic assent recognizer. + // Experimental: TurnIndex is part of an experimental API and may change or be removed. + TurnIndex int64 `json:"turnIndex"` +} + +func (*PermissionAssentDetectedData) sessionEventData() {} +func (*PermissionAssentDetectedData) Type() SessionEventType { + return SessionEventTypePermissionAssentDetected +} + +// Historical decode-only degradation marker from the retired extractor. Current runtimes ignore it for permission decisions. +// Experimental: PermissionMessageAuthorizationDegradedData is part of an experimental API and may change or be removed. +type PermissionMessageAuthorizationDegradedData struct { + // The human turn that could not be represented safely. + // Experimental: TurnIndex is part of an experimental API and may change or be removed. + TurnIndex int64 `json:"turnIndex"` +} + +func (*PermissionMessageAuthorizationDegradedData) sessionEventData() {} +func (*PermissionMessageAuthorizationDegradedData) Type() SessionEventType { + return SessionEventTypePermissionMessageAuthorizationDegraded +} + +// Historical decode-only extractor progress marker. Current runtimes do not run or resume extraction from it. +// Experimental: PermissionMessageAuthorizationReadData is part of an experimental API and may change or be removed. +type PermissionMessageAuthorizationReadData struct { + // Whether this read activates ongoing message-backed extraction. False for a contextual-assent-only pass while auto-approval is off, so unrelated future messages remain outside extraction. + // Experimental: ActivatesExtraction is part of an experimental API and may change or be removed. + ActivatesExtraction *bool `json:"activatesExtraction,omitempty"` + // The human turn that was read by the proposer. + // Experimental: TurnIndex is part of an experimental API and may change or be removed. + TurnIndex int64 `json:"turnIndex"` +} + +func (*PermissionMessageAuthorizationReadData) sessionEventData() {} +func (*PermissionMessageAuthorizationReadData) Type() SessionEventType { + return SessionEventTypePermissionMessageAuthorizationRead +} + +// Historical decode-only receipt from the retired Assisted Permissions authorization extractor. Current runtimes ignore it for permission decisions. +// Experimental: PermissionCarriedForwardData is part of an experimental API and may change or be removed. +type PermissionCarriedForwardData struct { + // Always `authorization_carry_forward`. Stated explicitly so a consumer reading this event cannot mistake it for a human, host-policy, or assisted-approval decision. + // Experimental: DecisionSource is part of an experimental API and may change or be removed. + DecisionSource PermissionDecisionSource `json:"decisionSource"` + // Identity of the prior authorization record that contained the proposal. + // Experimental: RecordID is part of an experimental API and may change or be removed. + RecordID string `json:"recordId"` + // Authorization edge minted for this admission. Not a prompt id: no prompt was raised, so no client should expect a request with this id. + // Experimental: RequestID is part of an experimental API and may change or be removed. + RequestID string `json:"requestId"` + // Tool call this admission authorizes. Its execution receipts the prior grant, which is how a single-effect approval is spent rather than carried forward again. + // Experimental: ToolCallID is part of an experimental API and may change or be removed. + ToolCallID string `json:"toolCallId"` +} + +func (*PermissionCarriedForwardData) sessionEventData() {} +func (*PermissionCarriedForwardData) Type() SessionEventType { + return SessionEventTypePermissionCarriedForward +} + // Hook invocation completion details including output, success status, and error information type HookEndData struct { // Error details when the hook failed @@ -2305,28 +2375,6 @@ type CommandQueuedData struct { func (*CommandQueuedData) sessionEventData() {} func (*CommandQueuedData) Type() SessionEventType { return SessionEventTypeCommandQueued } -// Records that a live authorization record from an earlier human decision in this session contained a permission proposal, so it ran without another prompt. This mints no authority: it accounts for one more effect against the prior grant, which is what lets a replayed session agree with the live one about how much of that grant is left. -// Experimental: PermissionCarriedForwardData is part of an experimental API and may change or be removed. -type PermissionCarriedForwardData struct { - // Always `authorization_carry_forward`. Stated explicitly so a consumer reading this event cannot mistake it for a human, host-policy, or assisted-approval decision. - // Experimental: DecisionSource is part of an experimental API and may change or be removed. - DecisionSource PermissionDecisionSource `json:"decisionSource"` - // Identity of the prior authorization record that contained the proposal. - // Experimental: RecordID is part of an experimental API and may change or be removed. - RecordID string `json:"recordId"` - // Authorization edge minted for this admission. Not a prompt id: no prompt was raised, so no client should expect a request with this id. - // Experimental: RequestID is part of an experimental API and may change or be removed. - RequestID string `json:"requestId"` - // Tool call this admission authorizes. Its execution receipts the prior grant, which is how a single-effect approval is spent rather than carried forward again. - // Experimental: ToolCallID is part of an experimental API and may change or be removed. - ToolCallID string `json:"toolCallId"` -} - -func (*PermissionCarriedForwardData) sessionEventData() {} -func (*PermissionCarriedForwardData) Type() SessionEventType { - return SessionEventTypePermissionCarriedForward -} - // Records that a mode transition notice reached the model so cache-stable mode tools can remain offered across resume. type SessionModeNoticeDeliveredData struct { // Model-visible transition notice persisted for a mid-turn delivery @@ -2340,51 +2388,6 @@ func (*SessionModeNoticeDeliveredData) Type() SessionEventType { return SessionEventTypeSessionModeNoticeDelivered } -// Records that deterministic text recognition found likely assent in the human turn immediately following a root Autopilot permission request that was blocked because no interactive response was available. This event grants no authority; its model-facing projection only suggests retrying the unchanged operation. -// Experimental: PermissionAssentDetectedData is part of an experimental API and may change or be removed. -type PermissionAssentDetectedData struct { - // Permission request the likely assent may refer to. The runtime derives this from the preceding durable blocker; the human message and extraction model do not choose it. - // Experimental: RequestID is part of an experimental API and may change or be removed. - RequestID string `json:"requestId"` - // Human turn whose text triggered the deterministic assent recognizer. - // Experimental: TurnIndex is part of an experimental API and may change or be removed. - TurnIndex int64 `json:"turnIndex"` -} - -func (*PermissionAssentDetectedData) sessionEventData() {} -func (*PermissionAssentDetectedData) Type() SessionEventType { - return SessionEventTypePermissionAssentDetected -} - -// Records that message-backed authorization could not safely represent one human turn before compaction. The runtime may compact the original message after this marker is durable, but message-derived carry-forward and assisted auto-approval remain disabled for the rest of the session so subsequent commands continue through the ordinary permission prompt. -// Experimental: PermissionMessageAuthorizationDegradedData is part of an experimental API and may change or be removed. -type PermissionMessageAuthorizationDegradedData struct { - // The human turn that could not be represented safely. - // Experimental: TurnIndex is part of an experimental API and may change or be removed. - TurnIndex int64 `json:"turnIndex"` -} - -func (*PermissionMessageAuthorizationDegradedData) sessionEventData() {} -func (*PermissionMessageAuthorizationDegradedData) Type() SessionEventType { - return SessionEventTypePermissionMessageAuthorizationDegraded -} - -// Records that one human turn has been read by the blinded authorization proposer, whether or not it minted anything, so a resumed session does not re-run the extraction model on a turn the live session already read. Also records whether that pass activates ongoing extraction; contextual-assent-only passes do not, so unrelated future messages remain outside extraction. -// Experimental: PermissionMessageAuthorizationReadData is part of an experimental API and may change or be removed. -type PermissionMessageAuthorizationReadData struct { - // Whether this read activates ongoing message-backed extraction. False for a contextual-assent-only pass while auto-approval is off, so unrelated future messages remain outside extraction. - // Experimental: ActivatesExtraction is part of an experimental API and may change or be removed. - ActivatesExtraction *bool `json:"activatesExtraction,omitempty"` - // The human turn that was read by the proposer. - // Experimental: TurnIndex is part of an experimental API and may change or be removed. - TurnIndex int64 `json:"turnIndex"` -} - -func (*PermissionMessageAuthorizationReadData) sessionEventData() {} -func (*PermissionMessageAuthorizationReadData) Type() SessionEventType { - return SessionEventTypePermissionMessageAuthorizationRead -} - // Registered command dispatch request routed to the owning client type CommandExecuteData struct { // Raw argument string after the command name @@ -2938,7 +2941,7 @@ type SubagentStartedData struct { AgentType *string `json:"agentType,omitempty"` // Whether the sub-agent runs synchronously or in the background. ExecutionMode *string `json:"executionMode,omitempty"` - // Root id of the factory run that spawned this sub-agent, when it was spawned by one. + // Legacy root id of the workflow run that spawned this sub-agent. New consumers should use workflowRunId. FactoryRunID *string `json:"factoryRunId,omitempty"` // Model the sub-agent will run with, when known at start. Model *string `json:"model,omitempty"` @@ -2948,10 +2951,12 @@ type SubagentStartedData struct { ParentID *string `json:"parentId,omitempty"` // Whether this sub-agent can be resumed. Currently always false. Resumable *bool `json:"resumable,omitempty"` - // Where the model input for this sub-agent came from. Present when the task planner resolved the launch (the task tool and factory agents); absent for sub-agents created through other runtime paths. + // Where the model input for this sub-agent came from. Present when the task planner resolved the launch (the task tool and workflow agents); absent for sub-agents created through other runtime paths. TaskModelSource *SubagentTaskModelSource `json:"taskModelSource,omitempty"` // Tool call ID of the parent tool invocation that spawned this sub-agent ToolCallID string `json:"toolCallId"` + // Root id of the workflow run that spawned this sub-agent, when it was spawned by one. + WorkflowRunID *string `json:"workflowRunId,omitempty"` } func (*SubagentStartedData) sessionEventData() {} @@ -3678,14 +3683,6 @@ type ExtensionsLoadedExtension struct { Status ExtensionsLoadedExtensionStatus `json:"status"` } -// A declared phase shown in a factory permission prompt. -type FactoryPermissionPhase struct { - // Optional phase detail - Detail *string `json:"detail,omitempty"` - // Phase title - Title string `json:"title"` -} - // Experimental attribution linking an ordinary event to the HydraFusion turn, phase, and concrete source that produced it. // Experimental: FusionAttribution is part of an experimental API and may change or be removed. type FusionAttribution struct { @@ -4061,50 +4058,6 @@ func (PermissionPromptRequestExtensionPermissionAccess) Kind() PermissionPromptR return PermissionPromptRequestKindExtensionPermissionAccess } -// Factory run or authoring permission prompt -type PermissionPromptRequestFactory struct { - // Canonical key used for scoped factory approvals - ApprovalKey string `json:"approvalKey"` - // Assisted-approval judge information for this request; present only in assisted mode. - // Experimental: AssistedApproval is part of an experimental API and may change or be removed. - AssistedApproval *PermissionAssistedApproval `json:"assistedApproval,omitempty"` - // Whether this factory is eligible for persistent approval - CanPersistApproval bool `json:"canPersistApproval"` - // Factory-declared AI-credit limit before any run/resume caller override is applied. - DeclaredMaxAiCredits *float64 `json:"declaredMaxAiCredits,omitempty"` - // Factory-declared concurrent-subagent limit before any run/resume caller override is applied. - DeclaredMaxConcurrentSubagents *int64 `json:"declaredMaxConcurrentSubagents,omitempty"` - // Factory-declared total-subagent limit before any run/resume caller override is applied. - DeclaredMaxTotalSubagents *int64 `json:"declaredMaxTotalSubagents,omitempty"` - // Factory-declared active-time limit in seconds before any run/resume caller override is applied. - DeclaredTimeoutSeconds *float64 `json:"declaredTimeoutSeconds,omitempty"` - // Factory description - Description string `json:"description"` - // Whether managed policy requires a human response and forbids host auto-approval - ManagedApprovalRequired *bool `json:"managedApprovalRequired,omitempty"` - // Effective AI-credit limit; omitted means unlimited - MaxAiCredits *float64 `json:"maxAiCredits,omitempty"` - // Effective concurrent-subagent limit; omitted means unlimited - MaxConcurrentSubagents *int64 `json:"maxConcurrentSubagents,omitempty"` - // Effective total-subagent limit; omitted means unlimited - MaxTotalSubagents *int64 `json:"maxTotalSubagents,omitempty"` - // Factory name - Name string `json:"name"` - // Factory operation, either run or author - Operation FactoryPermissionOperation `json:"operation"` - // Declared factory phases - Phases []FactoryPermissionPhase `json:"phases"` - // Effective active-time limit in seconds; omitted means unlimited - TimeoutSeconds *float64 `json:"timeoutSeconds,omitempty"` - // Tool call ID that triggered this permission request - ToolCallID *string `json:"toolCallId,omitempty"` -} - -func (PermissionPromptRequestFactory) permissionPromptRequest() {} -func (PermissionPromptRequestFactory) Kind() PermissionPromptRequestKind { - return PermissionPromptRequestKindFactory -} - // Hook confirmation permission prompt type PermissionPromptRequestHook struct { // Assisted-approval judge information for this request; present only in assisted mode. @@ -4245,6 +4198,50 @@ func (PermissionPromptRequestURL) Kind() PermissionPromptRequestKind { return PermissionPromptRequestKindURL } +// Workflow run or authoring permission prompt +type PermissionPromptRequestWorkflow struct { + // Canonical key used for scoped workflow approvals + ApprovalKey string `json:"approvalKey"` + // Assisted-approval judge information for this request; present only in assisted mode. + // Experimental: AssistedApproval is part of an experimental API and may change or be removed. + AssistedApproval *PermissionAssistedApproval `json:"assistedApproval,omitempty"` + // Whether this workflow is eligible for persistent approval + CanPersistApproval bool `json:"canPersistApproval"` + // Workflow-declared AI-credit limit before any run/resume caller override is applied. + DeclaredMaxAiCredits *float64 `json:"declaredMaxAiCredits,omitempty"` + // Workflow-declared concurrent-subagent limit before any run/resume caller override is applied. + DeclaredMaxConcurrentSubagents *int64 `json:"declaredMaxConcurrentSubagents,omitempty"` + // Workflow-declared total-subagent limit before any run/resume caller override is applied. + DeclaredMaxTotalSubagents *int64 `json:"declaredMaxTotalSubagents,omitempty"` + // Workflow-declared active-time limit in seconds before any run/resume caller override is applied. + DeclaredTimeoutSeconds *float64 `json:"declaredTimeoutSeconds,omitempty"` + // Workflow description + Description string `json:"description"` + // Whether managed policy requires a human response and forbids host auto-approval + ManagedApprovalRequired *bool `json:"managedApprovalRequired,omitempty"` + // Effective AI-credit limit; omitted means unlimited + MaxAiCredits *float64 `json:"maxAiCredits,omitempty"` + // Effective concurrent-subagent limit; omitted means unlimited + MaxConcurrentSubagents *int64 `json:"maxConcurrentSubagents,omitempty"` + // Effective total-subagent limit; omitted means unlimited + MaxTotalSubagents *int64 `json:"maxTotalSubagents,omitempty"` + // Workflow name + Name string `json:"name"` + // Workflow operation, either run or author + Operation WorkflowPermissionOperation `json:"operation"` + // Declared workflow phases + Phases []WorkflowPermissionPhase `json:"phases"` + // Effective active-time limit in seconds; omitted means unlimited + TimeoutSeconds *float64 `json:"timeoutSeconds,omitempty"` + // Tool call ID that triggered this permission request + ToolCallID *string `json:"toolCallId,omitempty"` +} + +func (PermissionPromptRequestWorkflow) permissionPromptRequest() {} +func (PermissionPromptRequestWorkflow) Kind() PermissionPromptRequestKind { + return PermissionPromptRequestKindWorkflow +} + // File write permission prompt type PermissionPromptRequestWrite struct { // Assisted-approval judge information for this request; present only in assisted mode. @@ -4363,47 +4360,6 @@ func (PermissionRequestExtensionPermissionAccess) Kind() PermissionRequestKind { return PermissionRequestKindExtensionPermissionAccess } -// Factory run or authoring permission request -type PermissionRequestFactory struct { - // Canonical key used for scoped factory approvals - ApprovalKey string `json:"approvalKey"` - // Whether this factory is eligible for persistent approval - CanPersistApproval bool `json:"canPersistApproval"` - // Factory-declared AI-credit limit before any run/resume caller override is applied. - DeclaredMaxAiCredits *float64 `json:"declaredMaxAiCredits,omitempty"` - // Factory-declared concurrent-subagent limit before any run/resume caller override is applied. - DeclaredMaxConcurrentSubagents *int64 `json:"declaredMaxConcurrentSubagents,omitempty"` - // Factory-declared total-subagent limit before any run/resume caller override is applied. - DeclaredMaxTotalSubagents *int64 `json:"declaredMaxTotalSubagents,omitempty"` - // Factory-declared active-time limit in seconds before any run/resume caller override is applied. - DeclaredTimeoutSeconds *float64 `json:"declaredTimeoutSeconds,omitempty"` - // Factory description - Description string `json:"description"` - // When true, managed policy requires an explicit user decision and automatic approval must be bypassed. - ManagedApprovalRequired *bool `json:"managedApprovalRequired,omitempty"` - // Effective AI-credit limit; omitted means unlimited - MaxAiCredits *float64 `json:"maxAiCredits,omitempty"` - // Effective concurrent-subagent limit; omitted means unlimited - MaxConcurrentSubagents *int64 `json:"maxConcurrentSubagents,omitempty"` - // Effective total-subagent limit; omitted means unlimited - MaxTotalSubagents *int64 `json:"maxTotalSubagents,omitempty"` - // Factory name - Name string `json:"name"` - // Factory operation, either run or author - Operation FactoryPermissionOperation `json:"operation"` - // Declared factory phases - Phases []FactoryPermissionPhase `json:"phases"` - // Effective active-time limit in seconds; omitted means unlimited - TimeoutSeconds *float64 `json:"timeoutSeconds,omitempty"` - // Tool call ID that triggered this permission request - ToolCallID *string `json:"toolCallId,omitempty"` -} - -func (PermissionRequestFactory) permissionRequest() {} -func (PermissionRequestFactory) Kind() PermissionRequestKind { - return PermissionRequestKindFactory -} - // Hook confirmation permission request type PermissionRequestHook struct { // Optional message from the hook explaining why confirmation is needed @@ -4571,6 +4527,47 @@ func (PermissionRequestURL) Kind() PermissionRequestKind { return PermissionRequestKindURL } +// Workflow run or authoring permission request +type PermissionRequestWorkflow struct { + // Canonical key used for scoped workflow approvals + ApprovalKey string `json:"approvalKey"` + // Whether this workflow is eligible for persistent approval + CanPersistApproval bool `json:"canPersistApproval"` + // Workflow-declared AI-credit limit before any run/resume caller override is applied. + DeclaredMaxAiCredits *float64 `json:"declaredMaxAiCredits,omitempty"` + // Workflow-declared concurrent-subagent limit before any run/resume caller override is applied. + DeclaredMaxConcurrentSubagents *int64 `json:"declaredMaxConcurrentSubagents,omitempty"` + // Workflow-declared total-subagent limit before any run/resume caller override is applied. + DeclaredMaxTotalSubagents *int64 `json:"declaredMaxTotalSubagents,omitempty"` + // Workflow-declared active-time limit in seconds before any run/resume caller override is applied. + DeclaredTimeoutSeconds *float64 `json:"declaredTimeoutSeconds,omitempty"` + // Workflow description + Description string `json:"description"` + // Whether managed policy requires a human response and forbids host auto-approval + ManagedApprovalRequired *bool `json:"managedApprovalRequired,omitempty"` + // Effective AI-credit limit; omitted means unlimited + MaxAiCredits *float64 `json:"maxAiCredits,omitempty"` + // Effective concurrent-subagent limit; omitted means unlimited + MaxConcurrentSubagents *int64 `json:"maxConcurrentSubagents,omitempty"` + // Effective total-subagent limit; omitted means unlimited + MaxTotalSubagents *int64 `json:"maxTotalSubagents,omitempty"` + // Workflow name + Name string `json:"name"` + // Workflow operation, either run or author + Operation WorkflowPermissionOperation `json:"operation"` + // Declared workflow phases + Phases []WorkflowPermissionPhase `json:"phases"` + // Effective active-time limit in seconds; omitted means unlimited + TimeoutSeconds *float64 `json:"timeoutSeconds,omitempty"` + // Tool call ID that triggered this permission request + ToolCallID *string `json:"toolCallId,omitempty"` +} + +func (PermissionRequestWorkflow) permissionRequest() {} +func (PermissionRequestWorkflow) Kind() PermissionRequestKind { + return PermissionRequestKindWorkflow +} + // File write permission request type PermissionRequestWrite struct { // Whether the UI can offer session-wide approval for file write operations @@ -5017,37 +5014,6 @@ func (SystemNotificationAgentIdle) Type() SystemNotificationType { return SystemNotificationTypeAgentIdle } -// System notification metadata for a factory execution attempt that reached a terminal state. -type SystemNotificationFactoryCompleted struct { - // Execution attempt that reached this terminal state. - Attempt int64 `json:"attempt"` - // Consumed AI usage in nano-AIU. - ConsumedNanoAiu int64 `json:"consumedNanoAiu"` - // Subagents consumed by the run across all attempts. - ConsumedSubagents int64 `json:"consumedSubagents"` - // Accumulated active execution time in milliseconds. - ElapsedMs int64 `json:"elapsedMs"` - // Persisted factory name. - FactoryName string `json:"factoryName"` - // Machine-readable terminal failure details, when present. - Failure any `json:"failure,omitempty"` - // Pause initiator metadata when this attempt settled as paused. - PauseInfo SystemNotificationFactoryPauseInfo `json:"pauseInfo,omitempty"` - // Bounded prompt-safe preview of the completed result. - ResultPreview *string `json:"resultPreview,omitempty"` - // Actionable run_factory resume guidance for a resource-limit failure. - RetryGuidance *string `json:"retryGuidance,omitempty"` - // Factory run identifier. - RunID string `json:"runId"` - // Terminal status reached by this execution attempt. - Status SystemNotificationFactoryCompletedStatus `json:"status"` -} - -func (SystemNotificationFactoryCompleted) systemNotification() {} -func (SystemNotificationFactoryCompleted) Type() SystemNotificationType { - return SystemNotificationTypeFactoryCompleted -} - // System notification metadata for an instruction file discovered during tool access, including source, trigger file, and tool. type SystemNotificationInstructionDiscovered struct { // Human-readable label for the timeline (e.g., 'AGENTS.md from packages/billing/') @@ -5121,38 +5087,69 @@ func (SystemNotificationUnclassified) Type() SystemNotificationType { return SystemNotificationTypeUnclassified } -// Durable metadata describing who initiated a factory pause. -type SystemNotificationFactoryPauseInfo interface { - systemNotificationFactoryPauseInfo() - Type() SystemNotificationFactoryPauseInfoType +// System notification metadata for a workflow execution attempt that reached a terminal state. +type SystemNotificationWorkflowCompleted struct { + // Execution attempt that reached this terminal state. + Attempt int64 `json:"attempt"` + // Consumed AI usage in nano-AIU. + ConsumedNanoAiu int64 `json:"consumedNanoAiu"` + // Subagents consumed by the run across all attempts. + ConsumedSubagents int64 `json:"consumedSubagents"` + // Accumulated active execution time in milliseconds. + ElapsedMs int64 `json:"elapsedMs"` + // Machine-readable terminal failure details, when present. + Failure any `json:"failure,omitempty"` + // Pause initiator metadata when this attempt settled as paused. + PauseInfo SystemNotificationWorkflowPauseInfo `json:"pauseInfo,omitempty"` + // Bounded prompt-safe preview of the completed result. + ResultPreview *string `json:"resultPreview,omitempty"` + // Actionable run_dynamic_workflow resume guidance for a resource-limit failure. + RetryGuidance *string `json:"retryGuidance,omitempty"` + // Workflow run identifier. + RunID string `json:"runId"` + // Terminal status reached by this execution attempt. + Status SystemNotificationWorkflowCompletedStatus `json:"status"` + // Persisted workflow name. + WorkflowName string `json:"workflowName"` +} + +func (SystemNotificationWorkflowCompleted) systemNotification() {} +func (SystemNotificationWorkflowCompleted) Type() SystemNotificationType { + return SystemNotificationTypeWorkflowCompleted } -type RawSystemNotificationFactoryPauseInfo struct { - Discriminator SystemNotificationFactoryPauseInfoType +// Durable metadata describing who initiated a workflow pause. +type SystemNotificationWorkflowPauseInfo interface { + systemNotificationWorkflowPauseInfo() + Type() SystemNotificationWorkflowPauseInfoType +} + +type RawSystemNotificationWorkflowPauseInfo struct { + Discriminator SystemNotificationWorkflowPauseInfoType Raw json.RawMessage } -func (RawSystemNotificationFactoryPauseInfo) systemNotificationFactoryPauseInfo() {} -func (r RawSystemNotificationFactoryPauseInfo) Type() SystemNotificationFactoryPauseInfoType { +func (RawSystemNotificationWorkflowPauseInfo) systemNotificationWorkflowPauseInfo() {} +func (r RawSystemNotificationWorkflowPauseInfo) Type() SystemNotificationWorkflowPauseInfoType { return r.Discriminator } -type SystemNotificationFactoryPauseInfoCheckpoint struct { +type SystemNotificationWorkflowPauseInfoCheckpoint struct { // Stable author-defined checkpoint key that initiated the pause. Key string `json:"key"` } -func (SystemNotificationFactoryPauseInfoCheckpoint) systemNotificationFactoryPauseInfo() {} -func (SystemNotificationFactoryPauseInfoCheckpoint) Type() SystemNotificationFactoryPauseInfoType { - return SystemNotificationFactoryPauseInfoTypeCheckpoint +func (SystemNotificationWorkflowPauseInfoCheckpoint) systemNotificationWorkflowPauseInfo() {} +func (SystemNotificationWorkflowPauseInfoCheckpoint) Type() SystemNotificationWorkflowPauseInfoType { + return SystemNotificationWorkflowPauseInfoTypeCheckpoint } -type SystemNotificationFactoryPauseInfoUser struct { +type SystemNotificationWorkflowPauseInfoUser struct { } -func (SystemNotificationFactoryPauseInfoUser) systemNotificationFactoryPauseInfo() {} -func (SystemNotificationFactoryPauseInfoUser) Type() SystemNotificationFactoryPauseInfoType { - return SystemNotificationFactoryPauseInfoTypeUser +func (SystemNotificationWorkflowPauseInfoUser) systemNotificationWorkflowPauseInfo() {} +func (SystemNotificationWorkflowPauseInfoUser) Type() SystemNotificationWorkflowPauseInfoType { + return SystemNotificationWorkflowPauseInfoTypeUser } // A content block within a tool result, which may be text, terminal output, image, audio, or a resource @@ -5479,6 +5476,14 @@ type UsageCheckpointModelCacheState struct { ModelID string `json:"modelId"` } +// A declared phase shown in a workflow permission prompt. +type WorkflowPermissionPhase struct { + // Optional phase detail + Detail *string `json:"detail,omitempty"` + // Phase title + Title string `json:"title"` +} + // Working directory and git context at session start type WorkingDirectoryContext struct { // Base commit of current git branch at session start time @@ -5820,32 +5825,6 @@ const ( ExtensionsLoadedExtensionStatusStarting ExtensionsLoadedExtensionStatus = "starting" ) -// Operation gated by a factory permission request. -type FactoryPermissionOperation string - -const ( - // Authoring a factory, which writes JavaScript into a session-scoped extension and loads it. - FactoryPermissionOperationAuthor FactoryPermissionOperation = "author" - // Running a registered factory, which spends subagents, active time, and AI credits under the approved limits. - FactoryPermissionOperationRun FactoryPermissionOperation = "run" -) - -// Terminal status a factory run committed. A settled run is never `pending` or `running`, so those two members of the run-status domain are deliberately absent. -type FactoryRunSettledStatus string - -const ( - // The run was cancelled by its caller or by session disposal. - FactoryRunSettledStatusCancelled FactoryRunSettledStatus = "cancelled" - // The factory body resolved and its result was committed. - FactoryRunSettledStatusCompleted FactoryRunSettledStatus = "completed" - // The run failed, with `failureType` carrying the class when it has one. - FactoryRunSettledStatusError FactoryRunSettledStatus = "error" - // The run was stopped by a limit, an approval refusal or another policy decision. - FactoryRunSettledStatusHalted FactoryRunSettledStatus = "halted" - // The attempt paused intentionally while preserving resumable run state. - FactoryRunSettledStatusPaused FactoryRunSettledStatus = "paused" -) - // Conversation scope in which a HydraFusion phase executes. // Experimental: FusionConversationScope is part of an experimental API and may change or be removed. type FusionConversationScope string @@ -6225,14 +6204,14 @@ const ( PermissionApprovalEvaluationReasonCodeUnreviewableScriptInvocation PermissionApprovalEvaluationReasonCode = "unreviewable-script-invocation" ) -// Which direction a message-backed authorization claim moves authority in. +// Direction stored in a historical extractor claim. Current runtimes do not apply it. // Experimental: PermissionMessageAuthorizationPolarity is part of an experimental API and may change or be removed. type PermissionMessageAuthorizationPolarity string const ( - // The human's words refused an effect. + // Historical claim recorded as a denial. PermissionMessageAuthorizationPolarityDenial PermissionMessageAuthorizationPolarity = "denial" - // The human's words authorized an effect. + // Historical claim recorded as a grant. PermissionMessageAuthorizationPolarityGrant PermissionMessageAuthorizationPolarity = "grant" ) @@ -6245,13 +6224,13 @@ const ( PermissionPromptRequestKindExtensionEnvAccess PermissionPromptRequestKind = "extension-env-access" PermissionPromptRequestKindExtensionManagement PermissionPromptRequestKind = "extension-management" PermissionPromptRequestKindExtensionPermissionAccess PermissionPromptRequestKind = "extension-permission-access" - PermissionPromptRequestKindFactory PermissionPromptRequestKind = "factory" PermissionPromptRequestKindHook PermissionPromptRequestKind = "hook" PermissionPromptRequestKindMCP PermissionPromptRequestKind = "mcp" PermissionPromptRequestKindMemory PermissionPromptRequestKind = "memory" PermissionPromptRequestKindPath PermissionPromptRequestKind = "path" PermissionPromptRequestKindRead PermissionPromptRequestKind = "read" PermissionPromptRequestKindURL PermissionPromptRequestKind = "url" + PermissionPromptRequestKindWorkflow PermissionPromptRequestKind = "workflow" PermissionPromptRequestKindWrite PermissionPromptRequestKind = "write" ) @@ -6284,13 +6263,13 @@ const ( PermissionRequestKindExtensionEnvAccess PermissionRequestKind = "extension-env-access" PermissionRequestKindExtensionManagement PermissionRequestKind = "extension-management" PermissionRequestKindExtensionPermissionAccess PermissionRequestKind = "extension-permission-access" - PermissionRequestKindFactory PermissionRequestKind = "factory" PermissionRequestKindHook PermissionRequestKind = "hook" PermissionRequestKindMCP PermissionRequestKind = "mcp" PermissionRequestKindMemory PermissionRequestKind = "memory" PermissionRequestKindRead PermissionRequestKind = "read" PermissionRequestKindShell PermissionRequestKind = "shell" PermissionRequestKindURL PermissionRequestKind = "url" + PermissionRequestKindWorkflow PermissionRequestKind = "workflow" PermissionRequestKindWrite PermissionRequestKind = "write" ) @@ -6472,42 +6451,42 @@ const ( SystemNotificationAgentCompletedStatusFailed SystemNotificationAgentCompletedStatus = "failed" ) -// Terminal status reached by a factory execution attempt. -type SystemNotificationFactoryCompletedStatus string - -const ( - // The factory was cancelled. - SystemNotificationFactoryCompletedStatusCancelled SystemNotificationFactoryCompletedStatus = "cancelled" - // The factory completed successfully. - SystemNotificationFactoryCompletedStatusCompleted SystemNotificationFactoryCompletedStatus = "completed" - // The factory failed. - SystemNotificationFactoryCompletedStatusError SystemNotificationFactoryCompletedStatus = "error" - // The factory was halted. - SystemNotificationFactoryCompletedStatusHalted SystemNotificationFactoryCompletedStatus = "halted" - // The factory attempt paused intentionally. - SystemNotificationFactoryCompletedStatusPaused SystemNotificationFactoryCompletedStatus = "paused" -) - -// Type discriminator for SystemNotificationFactoryPauseInfo. -type SystemNotificationFactoryPauseInfoType string - -const ( - SystemNotificationFactoryPauseInfoTypeCheckpoint SystemNotificationFactoryPauseInfoType = "checkpoint" - SystemNotificationFactoryPauseInfoTypeUser SystemNotificationFactoryPauseInfoType = "user" -) - // Type discriminator for SystemNotification. type SystemNotificationType string const ( SystemNotificationTypeAgentCompleted SystemNotificationType = "agent_completed" SystemNotificationTypeAgentIdle SystemNotificationType = "agent_idle" - SystemNotificationTypeFactoryCompleted SystemNotificationType = "factory_completed" SystemNotificationTypeInstructionDiscovered SystemNotificationType = "instruction_discovered" SystemNotificationTypeNewInboxMessage SystemNotificationType = "new_inbox_message" SystemNotificationTypeShellCompleted SystemNotificationType = "shell_completed" SystemNotificationTypeShellDetachedCompleted SystemNotificationType = "shell_detached_completed" SystemNotificationTypeUnclassified SystemNotificationType = "unclassified" + SystemNotificationTypeWorkflowCompleted SystemNotificationType = "workflow_completed" +) + +// Terminal status reached by a workflow execution attempt. +type SystemNotificationWorkflowCompletedStatus string + +const ( + // The workflow was cancelled. + SystemNotificationWorkflowCompletedStatusCancelled SystemNotificationWorkflowCompletedStatus = "cancelled" + // The workflow completed successfully. + SystemNotificationWorkflowCompletedStatusCompleted SystemNotificationWorkflowCompletedStatus = "completed" + // The workflow failed. + SystemNotificationWorkflowCompletedStatusError SystemNotificationWorkflowCompletedStatus = "error" + // The workflow was halted. + SystemNotificationWorkflowCompletedStatusHalted SystemNotificationWorkflowCompletedStatus = "halted" + // The workflow attempt paused intentionally. + SystemNotificationWorkflowCompletedStatusPaused SystemNotificationWorkflowCompletedStatus = "paused" +) + +// Type discriminator for SystemNotificationWorkflowPauseInfo. +type SystemNotificationWorkflowPauseInfoType string + +const ( + SystemNotificationWorkflowPauseInfoTypeCheckpoint SystemNotificationWorkflowPauseInfoType = "checkpoint" + SystemNotificationWorkflowPauseInfoTypeUser SystemNotificationWorkflowPauseInfoType = "user" ) // Theme variant this icon is intended for @@ -6596,6 +6575,32 @@ const ( UserMessageDeliverySteering UserMessageDelivery = "steering" ) +// Operation gated by a workflow permission request. +type WorkflowPermissionOperation string + +const ( + // Authoring a workflow, which writes JavaScript into a session-scoped extension and loads it. + WorkflowPermissionOperationAuthor WorkflowPermissionOperation = "author" + // Running a registered workflow, which spends subagents, active time, and AI credits under the approved limits. + WorkflowPermissionOperationRun WorkflowPermissionOperation = "run" +) + +// Terminal status a workflow run committed. A settled run is never `pending` or `running`, so those two members of the run-status domain are deliberately absent. +type WorkflowRunSettledStatus string + +const ( + // The run was cancelled by its caller or by session disposal. + WorkflowRunSettledStatusCancelled WorkflowRunSettledStatus = "cancelled" + // The workflow body resolved and its result was committed. + WorkflowRunSettledStatusCompleted WorkflowRunSettledStatus = "completed" + // The run failed, with `failureType` carrying the class when it has one. + WorkflowRunSettledStatusError WorkflowRunSettledStatus = "error" + // The run was stopped by a limit, an approval refusal or another policy decision. + WorkflowRunSettledStatusHalted WorkflowRunSettledStatus = "halted" + // The attempt paused intentionally while preserving resumable run state. + WorkflowRunSettledStatusPaused WorkflowRunSettledStatus = "paused" +) + // Hosting platform type of the repository (github or ado) type WorkingDirectoryContextHostType string diff --git a/go/zsession_events.go b/go/zsession_events.go index a1aab5837f..9926470e3c 100644 --- a/go/zsession_events.go +++ b/go/zsession_events.go @@ -122,12 +122,6 @@ type ( ExtensionsLoadedExtensionStatus = rpc.ExtensionsLoadedExtensionStatus ExternalToolCompletedData = rpc.ExternalToolCompletedData ExternalToolRequestedData = rpc.ExternalToolRequestedData - FactoryPermissionOperation = rpc.FactoryPermissionOperation - FactoryPermissionPhase = rpc.FactoryPermissionPhase - FactoryRunSettledData = rpc.FactoryRunSettledData - FactoryRunSettledStatus = rpc.FactoryRunSettledStatus - FactoryRunStartedData = rpc.FactoryRunStartedData - FactoryRunUpdatedData = rpc.FactoryRunUpdatedData FusionAttribution = rpc.FusionAttribution FusionConversationScope = rpc.FusionConversationScope FusionFollowUpAction = rpc.FusionFollowUpAction @@ -221,7 +215,6 @@ type ( PermissionPromptRequestExtensionEnvAccess = rpc.PermissionPromptRequestExtensionEnvAccess PermissionPromptRequestExtensionManagement = rpc.PermissionPromptRequestExtensionManagement PermissionPromptRequestExtensionPermissionAccess = rpc.PermissionPromptRequestExtensionPermissionAccess - PermissionPromptRequestFactory = rpc.PermissionPromptRequestFactory PermissionPromptRequestHook = rpc.PermissionPromptRequestHook PermissionPromptRequestKind = rpc.PermissionPromptRequestKind PermissionPromptRequestMCP = rpc.PermissionPromptRequestMCP @@ -230,6 +223,7 @@ type ( PermissionPromptRequestPathAccessKind = rpc.PermissionPromptRequestPathAccessKind PermissionPromptRequestRead = rpc.PermissionPromptRequestRead PermissionPromptRequestURL = rpc.PermissionPromptRequestURL + PermissionPromptRequestWorkflow = rpc.PermissionPromptRequestWorkflow PermissionPromptRequestWrite = rpc.PermissionPromptRequestWrite PermissionRecommendation = rpc.PermissionRecommendation PermissionRecoveryAttempt = rpc.PermissionRecoveryAttempt @@ -247,7 +241,6 @@ type ( PermissionRequestExtensionEnvAccess = rpc.PermissionRequestExtensionEnvAccess PermissionRequestExtensionManagement = rpc.PermissionRequestExtensionManagement PermissionRequestExtensionPermissionAccess = rpc.PermissionRequestExtensionPermissionAccess - PermissionRequestFactory = rpc.PermissionRequestFactory PermissionRequestHook = rpc.PermissionRequestHook PermissionRequestKind = rpc.PermissionRequestKind PermissionRequestMCP = rpc.PermissionRequestMCP @@ -261,6 +254,7 @@ type ( PermissionRequestShellCommandSegment = rpc.PermissionRequestShellCommandSegment PermissionRequestShellPossibleURL = rpc.PermissionRequestShellPossibleURL PermissionRequestURL = rpc.PermissionRequestURL + PermissionRequestWorkflow = rpc.PermissionRequestWorkflow PermissionRequestWrite = rpc.PermissionRequestWrite PermissionResult = rpc.PermissionResult PermissionResultKind = rpc.PermissionResultKind @@ -279,7 +273,7 @@ type ( RawPersistedBinaryResult = rpc.RawPersistedBinaryResult RawSessionEventData = rpc.RawSessionEventData RawSystemNotification = rpc.RawSystemNotification - RawSystemNotificationFactoryPauseInfo = rpc.RawSystemNotificationFactoryPauseInfo + RawSystemNotificationWorkflowPauseInfo = rpc.RawSystemNotificationWorkflowPauseInfo RawToolExecutionCompleteContent = rpc.RawToolExecutionCompleteContent ReasoningSummary = rpc.ReasoningSummary RecommendedAutoTier = rpc.RecommendedAutoTier @@ -392,18 +386,18 @@ type ( SystemNotificationAgentCompletedStatus = rpc.SystemNotificationAgentCompletedStatus SystemNotificationAgentIdle = rpc.SystemNotificationAgentIdle SystemNotificationData = rpc.SystemNotificationData - SystemNotificationFactoryCompleted = rpc.SystemNotificationFactoryCompleted - SystemNotificationFactoryCompletedStatus = rpc.SystemNotificationFactoryCompletedStatus - SystemNotificationFactoryPauseInfo = rpc.SystemNotificationFactoryPauseInfo - SystemNotificationFactoryPauseInfoCheckpoint = rpc.SystemNotificationFactoryPauseInfoCheckpoint - SystemNotificationFactoryPauseInfoType = rpc.SystemNotificationFactoryPauseInfoType - SystemNotificationFactoryPauseInfoUser = rpc.SystemNotificationFactoryPauseInfoUser SystemNotificationInstructionDiscovered = rpc.SystemNotificationInstructionDiscovered SystemNotificationNewInboxMessage = rpc.SystemNotificationNewInboxMessage SystemNotificationShellCompleted = rpc.SystemNotificationShellCompleted SystemNotificationShellDetachedCompleted = rpc.SystemNotificationShellDetachedCompleted SystemNotificationType = rpc.SystemNotificationType SystemNotificationUnclassified = rpc.SystemNotificationUnclassified + SystemNotificationWorkflowCompleted = rpc.SystemNotificationWorkflowCompleted + SystemNotificationWorkflowCompletedStatus = rpc.SystemNotificationWorkflowCompletedStatus + SystemNotificationWorkflowPauseInfo = rpc.SystemNotificationWorkflowPauseInfo + SystemNotificationWorkflowPauseInfoCheckpoint = rpc.SystemNotificationWorkflowPauseInfoCheckpoint + SystemNotificationWorkflowPauseInfoType = rpc.SystemNotificationWorkflowPauseInfoType + SystemNotificationWorkflowPauseInfoUser = rpc.SystemNotificationWorkflowPauseInfoUser TaskBlocker = rpc.TaskBlocker TaskBlockerKind = rpc.TaskBlockerKind TaskCompleteData = rpc.TaskCompleteData @@ -460,13 +454,19 @@ type ( UserToolSessionApprovalExtensionEnvAccess = rpc.UserToolSessionApprovalExtensionEnvAccess UserToolSessionApprovalExtensionManagement = rpc.UserToolSessionApprovalExtensionManagement UserToolSessionApprovalExtensionPermissionAccess = rpc.UserToolSessionApprovalExtensionPermissionAccess - UserToolSessionApprovalFactory = rpc.UserToolSessionApprovalFactory UserToolSessionApprovalKind = rpc.UserToolSessionApprovalKind UserToolSessionApprovalMCP = rpc.UserToolSessionApprovalMCP UserToolSessionApprovalMemory = rpc.UserToolSessionApprovalMemory UserToolSessionApprovalRead = rpc.UserToolSessionApprovalRead + UserToolSessionApprovalWorkflow = rpc.UserToolSessionApprovalWorkflow UserToolSessionApprovalWrite = rpc.UserToolSessionApprovalWrite Verbosity = rpc.Verbosity + WorkflowPermissionOperation = rpc.WorkflowPermissionOperation + WorkflowPermissionPhase = rpc.WorkflowPermissionPhase + WorkflowRunSettledData = rpc.WorkflowRunSettledData + WorkflowRunSettledStatus = rpc.WorkflowRunSettledStatus + WorkflowRunStartedData = rpc.WorkflowRunStartedData + WorkflowRunUpdatedData = rpc.WorkflowRunUpdatedData WorkingDirectoryContext = rpc.WorkingDirectoryContext WorkingDirectoryContextHostType = rpc.WorkingDirectoryContextHostType WorkspaceFileChangedOperation = rpc.WorkspaceFileChangedOperation @@ -583,13 +583,6 @@ const ( ExtensionsLoadedExtensionStatusFailed = rpc.ExtensionsLoadedExtensionStatusFailed ExtensionsLoadedExtensionStatusRunning = rpc.ExtensionsLoadedExtensionStatusRunning ExtensionsLoadedExtensionStatusStarting = rpc.ExtensionsLoadedExtensionStatusStarting - FactoryPermissionOperationAuthor = rpc.FactoryPermissionOperationAuthor - FactoryPermissionOperationRun = rpc.FactoryPermissionOperationRun - FactoryRunSettledStatusCancelled = rpc.FactoryRunSettledStatusCancelled - FactoryRunSettledStatusCompleted = rpc.FactoryRunSettledStatusCompleted - FactoryRunSettledStatusError = rpc.FactoryRunSettledStatusError - FactoryRunSettledStatusHalted = rpc.FactoryRunSettledStatusHalted - FactoryRunSettledStatusPaused = rpc.FactoryRunSettledStatusPaused FusionConversationScopeReview = rpc.FusionConversationScopeReview FusionConversationScopeRoot = rpc.FusionConversationScopeRoot FusionFollowUpActionReroute = rpc.FusionFollowUpActionReroute @@ -680,6 +673,7 @@ const ( ModelCallFinishedOutcomeSuccess = rpc.ModelCallFinishedOutcomeSuccess ModelChangeSourceAgent = rpc.ModelChangeSourceAgent ModelChangeSourceAutomatic = rpc.ModelChangeSourceAutomatic + ModelChangeSourceAutoTierRecommendation = rpc.ModelChangeSourceAutoTierRecommendation ModelChangeSourceChangeboardingShortcut = rpc.ModelChangeSourceChangeboardingShortcut ModelChangeSourceConfigCommand = rpc.ModelChangeSourceConfigCommand ModelChangeSourceManagedSettings = rpc.ModelChangeSourceManagedSettings @@ -743,13 +737,13 @@ const ( PermissionPromptRequestKindExtensionEnvAccess = rpc.PermissionPromptRequestKindExtensionEnvAccess PermissionPromptRequestKindExtensionManagement = rpc.PermissionPromptRequestKindExtensionManagement PermissionPromptRequestKindExtensionPermissionAccess = rpc.PermissionPromptRequestKindExtensionPermissionAccess - PermissionPromptRequestKindFactory = rpc.PermissionPromptRequestKindFactory PermissionPromptRequestKindHook = rpc.PermissionPromptRequestKindHook PermissionPromptRequestKindMCP = rpc.PermissionPromptRequestKindMCP PermissionPromptRequestKindMemory = rpc.PermissionPromptRequestKindMemory PermissionPromptRequestKindPath = rpc.PermissionPromptRequestKindPath PermissionPromptRequestKindRead = rpc.PermissionPromptRequestKindRead PermissionPromptRequestKindURL = rpc.PermissionPromptRequestKindURL + PermissionPromptRequestKindWorkflow = rpc.PermissionPromptRequestKindWorkflow PermissionPromptRequestKindWrite = rpc.PermissionPromptRequestKindWrite PermissionPromptRequestPathAccessKindRead = rpc.PermissionPromptRequestPathAccessKindRead PermissionPromptRequestPathAccessKindShell = rpc.PermissionPromptRequestPathAccessKindShell @@ -788,13 +782,13 @@ const ( PermissionRequestKindExtensionEnvAccess = rpc.PermissionRequestKindExtensionEnvAccess PermissionRequestKindExtensionManagement = rpc.PermissionRequestKindExtensionManagement PermissionRequestKindExtensionPermissionAccess = rpc.PermissionRequestKindExtensionPermissionAccess - PermissionRequestKindFactory = rpc.PermissionRequestKindFactory PermissionRequestKindHook = rpc.PermissionRequestKindHook PermissionRequestKindMCP = rpc.PermissionRequestKindMCP PermissionRequestKindMemory = rpc.PermissionRequestKindMemory PermissionRequestKindRead = rpc.PermissionRequestKindRead PermissionRequestKindShell = rpc.PermissionRequestKindShell PermissionRequestKindURL = rpc.PermissionRequestKindURL + PermissionRequestKindWorkflow = rpc.PermissionRequestKindWorkflow PermissionRequestKindWrite = rpc.PermissionRequestKindWrite PermissionRequestMemoryActionStore = rpc.PermissionRequestMemoryActionStore PermissionRequestMemoryActionVote = rpc.PermissionRequestMemoryActionVote @@ -864,9 +858,6 @@ const ( SessionEventTypeExitPlanModeRequested = rpc.SessionEventTypeExitPlanModeRequested SessionEventTypeExternalToolCompleted = rpc.SessionEventTypeExternalToolCompleted SessionEventTypeExternalToolRequested = rpc.SessionEventTypeExternalToolRequested - SessionEventTypeFactoryRunSettled = rpc.SessionEventTypeFactoryRunSettled - SessionEventTypeFactoryRunStarted = rpc.SessionEventTypeFactoryRunStarted - SessionEventTypeFactoryRunUpdated = rpc.SessionEventTypeFactoryRunUpdated SessionEventTypeHookEnd = rpc.SessionEventTypeHookEnd SessionEventTypeHookProgress = rpc.SessionEventTypeHookProgress SessionEventTypeHookStart = rpc.SessionEventTypeHookStart @@ -980,6 +971,9 @@ const ( SessionEventTypeUserInputCompleted = rpc.SessionEventTypeUserInputCompleted SessionEventTypeUserInputRequested = rpc.SessionEventTypeUserInputRequested SessionEventTypeUserMessage = rpc.SessionEventTypeUserMessage + SessionEventTypeWorkflowRunSettled = rpc.SessionEventTypeWorkflowRunSettled + SessionEventTypeWorkflowRunStarted = rpc.SessionEventTypeWorkflowRunStarted + SessionEventTypeWorkflowRunUpdated = rpc.SessionEventTypeWorkflowRunUpdated SessionLimitsExhaustedResponseActionAdd = rpc.SessionLimitsExhaustedResponseActionAdd SessionLimitsExhaustedResponseActionCancel = rpc.SessionLimitsExhaustedResponseActionCancel SessionLimitsExhaustedResponseActionSet = rpc.SessionLimitsExhaustedResponseActionSet @@ -1015,21 +1009,21 @@ const ( SystemMessageRoleSystem = rpc.SystemMessageRoleSystem SystemNotificationAgentCompletedStatusCompleted = rpc.SystemNotificationAgentCompletedStatusCompleted SystemNotificationAgentCompletedStatusFailed = rpc.SystemNotificationAgentCompletedStatusFailed - SystemNotificationFactoryCompletedStatusCancelled = rpc.SystemNotificationFactoryCompletedStatusCancelled - SystemNotificationFactoryCompletedStatusCompleted = rpc.SystemNotificationFactoryCompletedStatusCompleted - SystemNotificationFactoryCompletedStatusError = rpc.SystemNotificationFactoryCompletedStatusError - SystemNotificationFactoryCompletedStatusHalted = rpc.SystemNotificationFactoryCompletedStatusHalted - SystemNotificationFactoryCompletedStatusPaused = rpc.SystemNotificationFactoryCompletedStatusPaused - SystemNotificationFactoryPauseInfoTypeCheckpoint = rpc.SystemNotificationFactoryPauseInfoTypeCheckpoint - SystemNotificationFactoryPauseInfoTypeUser = rpc.SystemNotificationFactoryPauseInfoTypeUser SystemNotificationTypeAgentCompleted = rpc.SystemNotificationTypeAgentCompleted SystemNotificationTypeAgentIdle = rpc.SystemNotificationTypeAgentIdle - SystemNotificationTypeFactoryCompleted = rpc.SystemNotificationTypeFactoryCompleted SystemNotificationTypeInstructionDiscovered = rpc.SystemNotificationTypeInstructionDiscovered SystemNotificationTypeNewInboxMessage = rpc.SystemNotificationTypeNewInboxMessage SystemNotificationTypeShellCompleted = rpc.SystemNotificationTypeShellCompleted SystemNotificationTypeShellDetachedCompleted = rpc.SystemNotificationTypeShellDetachedCompleted SystemNotificationTypeUnclassified = rpc.SystemNotificationTypeUnclassified + SystemNotificationTypeWorkflowCompleted = rpc.SystemNotificationTypeWorkflowCompleted + SystemNotificationWorkflowCompletedStatusCancelled = rpc.SystemNotificationWorkflowCompletedStatusCancelled + SystemNotificationWorkflowCompletedStatusCompleted = rpc.SystemNotificationWorkflowCompletedStatusCompleted + SystemNotificationWorkflowCompletedStatusError = rpc.SystemNotificationWorkflowCompletedStatusError + SystemNotificationWorkflowCompletedStatusHalted = rpc.SystemNotificationWorkflowCompletedStatusHalted + SystemNotificationWorkflowCompletedStatusPaused = rpc.SystemNotificationWorkflowCompletedStatusPaused + SystemNotificationWorkflowPauseInfoTypeCheckpoint = rpc.SystemNotificationWorkflowPauseInfoTypeCheckpoint + SystemNotificationWorkflowPauseInfoTypeUser = rpc.SystemNotificationWorkflowPauseInfoTypeUser TaskBlockerKindPermissionRecovery = rpc.TaskBlockerKindPermissionRecovery TaskCompletionOutcomeBlocked = rpc.TaskCompletionOutcomeBlocked TaskCompletionOutcomeCompleted = rpc.TaskCompletionOutcomeCompleted @@ -1064,14 +1058,21 @@ const ( UserToolSessionApprovalKindExtensionEnvAccess = rpc.UserToolSessionApprovalKindExtensionEnvAccess UserToolSessionApprovalKindExtensionManagement = rpc.UserToolSessionApprovalKindExtensionManagement UserToolSessionApprovalKindExtensionPermissionAccess = rpc.UserToolSessionApprovalKindExtensionPermissionAccess - UserToolSessionApprovalKindFactory = rpc.UserToolSessionApprovalKindFactory UserToolSessionApprovalKindMCP = rpc.UserToolSessionApprovalKindMCP UserToolSessionApprovalKindMemory = rpc.UserToolSessionApprovalKindMemory UserToolSessionApprovalKindRead = rpc.UserToolSessionApprovalKindRead + UserToolSessionApprovalKindWorkflow = rpc.UserToolSessionApprovalKindWorkflow UserToolSessionApprovalKindWrite = rpc.UserToolSessionApprovalKindWrite VerbosityHigh = rpc.VerbosityHigh VerbosityLow = rpc.VerbosityLow VerbosityMedium = rpc.VerbosityMedium + WorkflowPermissionOperationAuthor = rpc.WorkflowPermissionOperationAuthor + WorkflowPermissionOperationRun = rpc.WorkflowPermissionOperationRun + WorkflowRunSettledStatusCancelled = rpc.WorkflowRunSettledStatusCancelled + WorkflowRunSettledStatusCompleted = rpc.WorkflowRunSettledStatusCompleted + WorkflowRunSettledStatusError = rpc.WorkflowRunSettledStatusError + WorkflowRunSettledStatusHalted = rpc.WorkflowRunSettledStatusHalted + WorkflowRunSettledStatusPaused = rpc.WorkflowRunSettledStatusPaused WorkingDirectoryContextHostTypeADO = rpc.WorkingDirectoryContextHostTypeADO WorkingDirectoryContextHostTypeGitHub = rpc.WorkingDirectoryContextHostTypeGitHub WorkspaceFileChangedOperationCreate = rpc.WorkspaceFileChangedOperationCreate diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/ModelChangeSource.java b/java/sdk/src/generated/java/com/github/copilot/generated/ModelChangeSource.java index 6279057df9..7ee778b7fe 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/ModelChangeSource.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/ModelChangeSource.java @@ -39,7 +39,9 @@ public enum ModelChangeSource { /** The {@code changeboarding_shortcut} variant. */ CHANGEBOARDING_SHORTCUT("changeboarding_shortcut"), /** The {@code sdk} variant. */ - SDK("sdk"); + SDK("sdk"), + /** The {@code auto_tier_recommendation} variant. */ + AUTO_TIER_RECOMMENDATION("auto_tier_recommendation"); private final String value; ModelChangeSource(String value) { this.value = value; } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionAssentDetectedEvent.java b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionAssentDetectedEvent.java index 6e8d6aecb6..0f3453c45a 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionAssentDetectedEvent.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionAssentDetectedEvent.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Session event "permission.assentDetected". Records that deterministic text recognition found likely assent in the human turn immediately following a root Autopilot permission request that was blocked because no interactive response was available. This event grants no authority; its model-facing projection only suggests retrying the unchanged operation. + * Session event "permission.assentDetected". Historical decode-only contextual-assent marker. Current runtimes do not project it into the conversation or permission flow. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionCarriedForwardEvent.java b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionCarriedForwardEvent.java index 27a5d0df91..a89b59660d 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionCarriedForwardEvent.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionCarriedForwardEvent.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Session event "permission.carriedForward". Records that a live authorization record from an earlier human decision in this session contained a permission proposal, so it ran without another prompt. This mints no authority: it accounts for one more effect against the prior grant, which is what lets a replayed session agree with the live one about how much of that grant is left. + * Session event "permission.carriedForward". Historical decode-only receipt from the retired Assisted Permissions authorization extractor. Current runtimes ignore it for permission decisions. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionContextualAuthorizationEvent.java b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionContextualAuthorizationEvent.java index 2bee51662f..0712d39db8 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionContextualAuthorizationEvent.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionContextualAuthorizationEvent.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Session event "permission.contextualAuthorization". Freezes a blinded contextual authorization proposal whose verbatim human span was deterministically bound to the immediately preceding blocked permission request. The event carries no action fields; replay re-derives the exact action from the earlier permission request and mints a one-shot message grant only when the binding and span still verify. + * Session event "permission.contextualAuthorization". Historical decode-only contextual authorization claim. Current runtimes preserve the payload but do not establish authority from it. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationDegradedEvent.java b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationDegradedEvent.java index dc37375dcf..8efdf509a6 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationDegradedEvent.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationDegradedEvent.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Session event "permission.messageAuthorizationDegraded". Records that message-backed authorization could not safely represent one human turn before compaction. The runtime may compact the original message after this marker is durable, but message-derived carry-forward and assisted auto-approval remain disabled for the rest of the session so subsequent commands continue through the ordinary permission prompt. + * Session event "permission.messageAuthorizationDegraded". Historical decode-only degradation marker from the retired extractor. Current runtimes ignore it for permission decisions. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationEvent.java b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationEvent.java index c87dce05cb..3a6c5aa6f0 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationEvent.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationEvent.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Session event "permission.messageAuthorization". Freezes one blinded, verbatim-verified authorization claim the runtime minted from a human user message, so a resumed session re-establishes the same grant deterministically instead of re-running the extraction model. This mints no authority on its own: it records what a blinded proposer pointed at and the trusted discriminator the runtime established, and deterministic establishment runs on replay. Persisted so recorded authority survives compaction and process resume. + * Session event "permission.messageAuthorization". Historical decode-only claim from the retired Assisted Permissions authorization extractor. Current runtimes preserve the payload but do not establish authority from it. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationPolarity.java b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationPolarity.java index e142238e7b..59183322fa 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationPolarity.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationPolarity.java @@ -11,7 +11,7 @@ import javax.annotation.processing.Generated; /** - * Which direction a message-backed authorization claim moves authority in. + * Direction stored in a historical extractor claim. Current runtimes do not apply it. * * @apiNote This type is experimental and may change in a future version. * diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationReadEvent.java b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationReadEvent.java index afa6ea4735..7a372823c6 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationReadEvent.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/PermissionMessageAuthorizationReadEvent.java @@ -13,7 +13,7 @@ import javax.annotation.processing.Generated; /** - * Session event "permission.messageAuthorizationRead". Records that one human turn has been read by the blinded authorization proposer, whether or not it minted anything, so a resumed session does not re-run the extraction model on a turn the live session already read. Also records whether that pass activates ongoing extraction; contextual-assent-only passes do not, so unrelated future messages remain outside extraction. + * Session event "permission.messageAuthorizationRead". Historical decode-only extractor progress marker. Current runtimes do not run or resume extraction from it. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/SessionCompactionCompleteEvent.java b/java/sdk/src/generated/java/com/github/copilot/generated/SessionCompactionCompleteEvent.java index 6b21976b0c..046317ee26 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/SessionCompactionCompleteEvent.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/SessionCompactionCompleteEvent.java @@ -54,7 +54,9 @@ public record SessionCompactionCompleteEventData( @JsonProperty("summaryContent") String summaryContent, /** Reasoning baseline on the replacement summary, preserved when replay skips the compacted history */ @JsonProperty("responsesReasoning") ResponsesReasoning responsesReasoning, - /** Authoritative active-factory reminder appended to the compacted context */ + /** Authoritative active-workflow reminder appended to the compacted context */ + @JsonProperty("activeWorkflowSummary") String activeWorkflowSummary, + /** Legacy active-workflow reminder retained for replay compatibility */ @JsonProperty("activeFactorySummary") String activeFactorySummary, /** Canonical model identifier used for model-specific behavior when replaying compaction */ @JsonProperty("behaviorModelId") String behaviorModelId, diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/SessionEvent.java b/java/sdk/src/generated/java/com/github/copilot/generated/SessionEvent.java index b8419f2ab0..864072a110 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/SessionEvent.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/SessionEvent.java @@ -153,9 +153,9 @@ @JsonSubTypes.Type(value = ExitPlanModeCompletedEvent.class, name = "exit_plan_mode.completed"), @JsonSubTypes.Type(value = SessionToolsUpdatedEvent.class, name = "session.tools_updated"), @JsonSubTypes.Type(value = SessionBackgroundTasksChangedEvent.class, name = "session.background_tasks_changed"), - @JsonSubTypes.Type(value = FactoryRunUpdatedEvent.class, name = "factory.run_updated"), - @JsonSubTypes.Type(value = FactoryRunStartedEvent.class, name = "factory.run_started"), - @JsonSubTypes.Type(value = FactoryRunSettledEvent.class, name = "factory.run_settled"), + @JsonSubTypes.Type(value = WorkflowRunUpdatedEvent.class, name = "workflow.run_updated"), + @JsonSubTypes.Type(value = WorkflowRunStartedEvent.class, name = "workflow.run_started"), + @JsonSubTypes.Type(value = WorkflowRunSettledEvent.class, name = "workflow.run_settled"), @JsonSubTypes.Type(value = SessionSkillsLoadedEvent.class, name = "session.skills_loaded"), @JsonSubTypes.Type(value = SessionCustomAgentsUpdatedEvent.class, name = "session.custom_agents_updated"), @JsonSubTypes.Type(value = SessionMcpServersLoadedEvent.class, name = "session.mcp_servers_loaded"), @@ -305,9 +305,9 @@ public abstract sealed class SessionEvent permits ExitPlanModeCompletedEvent, SessionToolsUpdatedEvent, SessionBackgroundTasksChangedEvent, - FactoryRunUpdatedEvent, - FactoryRunStartedEvent, - FactoryRunSettledEvent, + WorkflowRunUpdatedEvent, + WorkflowRunStartedEvent, + WorkflowRunSettledEvent, SessionSkillsLoadedEvent, SessionCustomAgentsUpdatedEvent, SessionMcpServersLoadedEvent, diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/SubagentStartedEvent.java b/java/sdk/src/generated/java/com/github/copilot/generated/SubagentStartedEvent.java index 7d8f5afe9e..8c8cde1c90 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/SubagentStartedEvent.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/SubagentStartedEvent.java @@ -44,12 +44,14 @@ public record SubagentStartedEventData( @JsonProperty("agentDescription") String agentDescription, /** Model the sub-agent will run with, when known at start. */ @JsonProperty("model") String model, - /** Where the model input for this sub-agent came from. Present when the task planner resolved the launch (the task tool and factory agents); absent for sub-agents created through other runtime paths. */ + /** Where the model input for this sub-agent came from. Present when the task planner resolved the launch (the task tool and workflow agents); absent for sub-agents created through other runtime paths. */ @JsonProperty("taskModelSource") SubagentTaskModelSource taskModelSource, /** Authority or runtime mechanism responsible for sub-agent model selection, when known at start. */ @JsonProperty("modelSelectionSource") SubagentModelSelectionSource modelSelectionSource, - /** Root id of the factory run that spawned this sub-agent, when it was spawned by one. */ + /** Legacy root id of the workflow run that spawned this sub-agent. New consumers should use workflowRunId. */ @JsonProperty("factoryRunId") String factoryRunId, + /** Root id of the workflow run that spawned this sub-agent, when it was spawned by one. */ + @JsonProperty("workflowRunId") String workflowRunId, /** Task-registry ID of the spawning sub-agent. Absent when the root session spawned this child. */ @JsonProperty("parentId") String parentId, /** Whether this sub-agent can be resumed. Currently always false. */ diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/FactoryRunSettledEvent.java b/java/sdk/src/generated/java/com/github/copilot/generated/WorkflowRunSettledEvent.java similarity index 68% rename from java/sdk/src/generated/java/com/github/copilot/generated/FactoryRunSettledEvent.java rename to java/sdk/src/generated/java/com/github/copilot/generated/WorkflowRunSettledEvent.java index 58ffa9cb3c..7cfef0df02 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/FactoryRunSettledEvent.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/WorkflowRunSettledEvent.java @@ -13,38 +13,38 @@ import javax.annotation.processing.Generated; /** - * Session event "factory.run_settled". Ephemeral signal that a factory run reached a terminal status. + * Session event "workflow.run_settled". Ephemeral signal that a workflow run reached a terminal status. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) @javax.annotation.processing.Generated("copilot-sdk-codegen") -public final class FactoryRunSettledEvent extends SessionEvent { +public final class WorkflowRunSettledEvent extends SessionEvent { @Override - public String getType() { return "factory.run_settled"; } + public String getType() { return "workflow.run_settled"; } @JsonProperty("data") - private FactoryRunSettledEventData data; + private WorkflowRunSettledEventData data; - public FactoryRunSettledEventData getData() { return data; } - public void setData(FactoryRunSettledEventData data) { this.data = data; } + public WorkflowRunSettledEventData getData() { return data; } + public void setData(WorkflowRunSettledEventData data) { this.data = data; } - /** Data payload for {@link FactoryRunSettledEvent}. */ + /** Data payload for {@link WorkflowRunSettledEvent}. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) - public record FactoryRunSettledEventData( - /** Identifier of the factory run that settled. */ + public record WorkflowRunSettledEventData( + /** Identifier of the workflow run that settled. */ @JsonProperty("runId") String runId, /** Terminal status the run committed. */ - @JsonProperty("status") FactoryRunSettledStatus status, + @JsonProperty("status") WorkflowRunSettledStatus status, /** Subagents this run consumed against its limits. */ @JsonProperty("consumedSubagents") Long consumedSubagents, /** AI credits this run consumed, in nano-AIU. */ @JsonProperty("consumedNanoAiu") Long consumedNanoAiu, /** Active milliseconds accumulated across every attempt of this run. */ @JsonProperty("elapsedMs") Long elapsedMs, - /** Typed failure class recorded on the run, when it failed with one (e.g. `factory_limit_reached`). */ + /** Typed failure class recorded on the run, when it failed with one (e.g. `workflow_limit_reached`). */ @JsonProperty("failureType") String failureType ) { } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/FactoryRunSettledStatus.java b/java/sdk/src/generated/java/com/github/copilot/generated/WorkflowRunSettledStatus.java similarity index 68% rename from java/sdk/src/generated/java/com/github/copilot/generated/FactoryRunSettledStatus.java rename to java/sdk/src/generated/java/com/github/copilot/generated/WorkflowRunSettledStatus.java index 828ddc9ee3..05dee5d53a 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/FactoryRunSettledStatus.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/WorkflowRunSettledStatus.java @@ -10,12 +10,12 @@ import javax.annotation.processing.Generated; /** - * Terminal status a factory run committed. A settled run is never `pending` or `running`, so those two members of the run-status domain are deliberately absent. + * Terminal status a workflow run committed. A settled run is never `pending` or `running`, so those two members of the run-status domain are deliberately absent. * * @since 1.0.0 */ @javax.annotation.processing.Generated("copilot-sdk-codegen") -public enum FactoryRunSettledStatus { +public enum WorkflowRunSettledStatus { /** The {@code completed} variant. */ COMPLETED("completed"), /** The {@code halted} variant. */ @@ -28,14 +28,14 @@ public enum FactoryRunSettledStatus { ERROR("error"); private final String value; - FactoryRunSettledStatus(String value) { this.value = value; } + WorkflowRunSettledStatus(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator - public static FactoryRunSettledStatus fromValue(String value) { - for (FactoryRunSettledStatus v : values()) { + public static WorkflowRunSettledStatus fromValue(String value) { + for (WorkflowRunSettledStatus v : values()) { if (v.value.equals(value)) return v; } - throw new IllegalArgumentException("Unknown FactoryRunSettledStatus value: " + value); + throw new IllegalArgumentException("Unknown WorkflowRunSettledStatus value: " + value); } } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/FactoryRunStartedEvent.java b/java/sdk/src/generated/java/com/github/copilot/generated/WorkflowRunStartedEvent.java similarity index 59% rename from java/sdk/src/generated/java/com/github/copilot/generated/FactoryRunStartedEvent.java rename to java/sdk/src/generated/java/com/github/copilot/generated/WorkflowRunStartedEvent.java index 691c7185d4..656b51f596 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/FactoryRunStartedEvent.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/WorkflowRunStartedEvent.java @@ -13,31 +13,31 @@ import javax.annotation.processing.Generated; /** - * Session event "factory.run_started". Ephemeral signal that a factory run attempt began executing. + * Session event "workflow.run_started". Ephemeral signal that a workflow run attempt began executing. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) @javax.annotation.processing.Generated("copilot-sdk-codegen") -public final class FactoryRunStartedEvent extends SessionEvent { +public final class WorkflowRunStartedEvent extends SessionEvent { @Override - public String getType() { return "factory.run_started"; } + public String getType() { return "workflow.run_started"; } @JsonProperty("data") - private FactoryRunStartedEventData data; + private WorkflowRunStartedEventData data; - public FactoryRunStartedEventData getData() { return data; } - public void setData(FactoryRunStartedEventData data) { this.data = data; } + public WorkflowRunStartedEventData getData() { return data; } + public void setData(WorkflowRunStartedEventData data) { this.data = data; } - /** Data payload for {@link FactoryRunStartedEvent}. */ + /** Data payload for {@link WorkflowRunStartedEvent}. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) - public record FactoryRunStartedEventData( - /** Identifier of the factory run that started. */ + public record WorkflowRunStartedEventData( + /** Identifier of the workflow run that started. */ @JsonProperty("runId") String runId, - /** Name of the factory this run executes. Low cardinality by construction. */ - @JsonProperty("factoryName") String factoryName, + /** Name of the workflow this run executes. Low cardinality by construction. */ + @JsonProperty("workflowName") String workflowName, /** Attempt number this start committed; a resumed run increments it. */ @JsonProperty("attempt") Long attempt ) { diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/FactoryRunUpdatedEvent.java b/java/sdk/src/generated/java/com/github/copilot/generated/WorkflowRunUpdatedEvent.java similarity index 65% rename from java/sdk/src/generated/java/com/github/copilot/generated/FactoryRunUpdatedEvent.java rename to java/sdk/src/generated/java/com/github/copilot/generated/WorkflowRunUpdatedEvent.java index 33b542058b..6a51db49f6 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/FactoryRunUpdatedEvent.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/WorkflowRunUpdatedEvent.java @@ -13,28 +13,28 @@ import javax.annotation.processing.Generated; /** - * Session event "factory.run_updated". Ephemeral invalidation signal for a changed factory run. + * Session event "workflow.run_updated". Ephemeral invalidation signal for a changed workflow run. * @since 1.0.0 */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) @javax.annotation.processing.Generated("copilot-sdk-codegen") -public final class FactoryRunUpdatedEvent extends SessionEvent { +public final class WorkflowRunUpdatedEvent extends SessionEvent { @Override - public String getType() { return "factory.run_updated"; } + public String getType() { return "workflow.run_updated"; } @JsonProperty("data") - private FactoryRunUpdatedEventData data; + private WorkflowRunUpdatedEventData data; - public FactoryRunUpdatedEventData getData() { return data; } - public void setData(FactoryRunUpdatedEventData data) { this.data = data; } + public WorkflowRunUpdatedEventData getData() { return data; } + public void setData(WorkflowRunUpdatedEventData data) { this.data = data; } - /** Data payload for {@link FactoryRunUpdatedEvent}. */ + /** Data payload for {@link WorkflowRunUpdatedEvent}. */ @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) - public record FactoryRunUpdatedEventData( - /** Factory run identifier. */ + public record WorkflowRunUpdatedEventData( + /** Workflow run identifier. */ @JsonProperty("runId") String runId, /** Monotonic revision now available for the run. */ @JsonProperty("revision") Long revision diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AccountKind.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AccountKind.java new file mode 100644 index 0000000000..e635762661 --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AccountKind.java @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * The provider kind stamped on a signed-in account. + * + * @apiNote This type is experimental and may change in a future version. + * + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public enum AccountKind { + /** The {@code githubDotCom} variant. */ + GITHUBDOTCOM("githubDotCom"), + /** The {@code proxima} variant. */ + PROXIMA("proxima"), + /** The {@code entraEmu} variant. */ + ENTRAEMU("entraEmu"), + /** The {@code entra} variant. */ + ENTRA("entra"), + /** The {@code loki} variant. */ + LOKI("loki"); + + private final String value; + AccountKind(String value) { this.value = value; } + @com.fasterxml.jackson.annotation.JsonValue + public String getValue() { return value; } + @com.fasterxml.jackson.annotation.JsonCreator + public static AccountKind fromValue(String value) { + for (AccountKind v : values()) { + if (v.value.equals(value)) return v; + } + throw new IllegalArgumentException("Unknown AccountKind value: " + value); + } +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryAgentOptions.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AccountStatus.java similarity index 53% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryAgentOptions.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/AccountStatus.java index 35470e7199..cb0868ce74 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryAgentOptions.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AccountStatus.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Options for one factory-scoped subagent call. + * One signed-in account in the roster forest. * * @apiNote This type is experimental and may change in a future version. * @@ -24,18 +24,18 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryAgentOptions( - /** Optional label distinguishing otherwise identical memoized agent calls. */ - @JsonProperty("label") String label, - /** Optional JSON Schema for structured agent output. */ - @JsonProperty("schema") Object schema, - /** Optional model identifier for the subagent. */ - @JsonProperty("model") String model, - /** Optional reasoning effort override for the subagent. */ - @JsonProperty("reasoningEffort") String reasoningEffort, - /** Optional context tier override for the subagent. */ - @JsonProperty("contextTier") ContextTier contextTier, - /** Optional built-in or custom agent name whose definition configures the subagent. */ - @JsonProperty("agent") String agent +public record AccountStatus( + /** Authentication host URL. */ + @JsonProperty("host") String host, + /** Authenticated login/username. */ + @JsonProperty("login") String login, + /** The provider kind of this account. */ + @JsonProperty("kind") AccountKind kind, + /** Opaque id of the account this one was derived from (e.g. an EMU account's base Entra identity); absent for a root account. Matches the base identity account's selectionId, forming the derivation edge. */ + @JsonProperty("derivedFrom") String derivedFrom, + /** Whether this is the active account. */ + @JsonProperty("active") Boolean active, + /** Opaque selection id used to switch to, or log out, this account. */ + @JsonProperty("selectionId") String selectionId ) { } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthEnumerateValue.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthEnumerateValue.java new file mode 100644 index 0000000000..f84ccee737 --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthEnumerateValue.java @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * The enumerated collection, keyed by the same selector as the query. + * + * @apiNote This type is experimental and may change in a future version. + * + * @since 1.0.0 + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "kind", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = AuthEnumerateValueAccounts.class, name = "accounts"), + @JsonSubTypes.Type(value = AuthEnumerateValueProviders.class, name = "providers") +}) +@CopilotExperimental +@JsonIgnoreProperties(ignoreUnknown = true) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public abstract class AuthEnumerateValue { + + /** + * Returns the discriminator value for this variant. + * + * @return the kind discriminator + */ + public abstract String getKind(); +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeFromToolResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthEnumerateValueAccounts.java similarity index 57% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeFromToolResult.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthEnumerateValueAccounts.java index d4566384c5..11afc36f14 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeFromToolResult.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthEnumerateValueAccounts.java @@ -10,23 +10,29 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; +import java.util.List; import javax.annotation.processing.Generated; /** - * Resolved persisted factory identity and resumed run envelope. + * Variant {@code accounts} of {@link AuthEnumerateValue}. * - * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryResumeFromToolResult( - /** Persisted factory name resolved for the resumed run. */ - @JsonProperty("factoryName") String factoryName, - /** Terminal resumed run envelope. */ - @JsonProperty("run") FactoryRunResult run -) { +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AuthEnumerateValueAccounts extends AuthEnumerateValue { + + @JsonProperty("kind") + private final String kind = "accounts"; + + @Override + public String getKind() { return kind; } + + /** The signed-in account forest; empty when not logged in. */ + @JsonProperty("items") + private List items; + + public List getItems() { return items; } + public void setItems(List items) { this.items = items; } } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthEnumerateValueProviders.java similarity index 57% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeResult.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthEnumerateValueProviders.java index b4cfcae116..965684e8ed 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeResult.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthEnumerateValueProviders.java @@ -10,23 +10,29 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; +import java.util.List; import javax.annotation.processing.Generated; /** - * Resolved persisted factory identity and resumed run envelope. + * Variant {@code providers} of {@link AuthEnumerateValue}. * - * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryResumeResult( - /** Persisted factory name resolved for the resumed run. */ - @JsonProperty("factoryName") String factoryName, - /** Terminal resumed run envelope. */ - @JsonProperty("run") FactoryRunResult run -) { +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AuthEnumerateValueProviders extends AuthEnumerateValue { + + @JsonProperty("kind") + private final String kind = "providers"; + + @Override + public String getKind() { return kind; } + + /** The providers offered for interactive login. */ + @JsonProperty("items") + private List items; + + public List getItems() { return items; } + public void setItems(List items) { this.items = items; } } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryToolRunOptions.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginResultDto.java similarity index 71% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryToolRunOptions.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginResultDto.java index e2444c7053..cbcffb6e54 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryToolRunOptions.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginResultDto.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Options for an internal tool-originated factory invocation. + * Terminal result of an interactive login flow. * * @apiNote This type is experimental and may change in a future version. * @@ -24,10 +24,12 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryToolRunOptions( - /** Per-invocation resource ceiling overrides. */ - @JsonProperty("limits") FactoryRunLimits limits, - /** Run identifier whose journal and progress should seed this resumed run. */ - @JsonProperty("resumeFromRunId") String resumeFromRunId +public record AuthLoginResultDto( + /** Terminal disposition of the login. */ + @JsonProperty("status") AuthLoginResultStatus status, + /** Host that was signed in, when completed. */ + @JsonProperty("host") String host, + /** Login that was signed in, when completed. */ + @JsonProperty("login") String login ) { } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseStatus.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginResultStatus.java similarity index 63% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseStatus.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginResultStatus.java index 8432507176..9e36ad0027 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseStatus.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginResultStatus.java @@ -11,7 +11,7 @@ import javax.annotation.processing.Generated; /** - * Derived lifecycle state of a factory phase. + * Terminal disposition of a login persistence attempt. * * @apiNote This type is experimental and may change in a future version. * @@ -19,25 +19,23 @@ */ @CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") -public enum FactoryPhaseStatus { - /** The {@code pending} variant. */ - PENDING("pending"), - /** The {@code active} variant. */ - ACTIVE("active"), +public enum AuthLoginResultStatus { /** The {@code completed} variant. */ COMPLETED("completed"), - /** The {@code skipped} variant. */ - SKIPPED("skipped"); + /** The {@code needs-plaintext-consent} variant. */ + NEEDS_PLAINTEXT_CONSENT("needs-plaintext-consent"), + /** The {@code declined} variant. */ + DECLINED("declined"); private final String value; - FactoryPhaseStatus(String value) { this.value = value; } + AuthLoginResultStatus(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator - public static FactoryPhaseStatus fromValue(String value) { - for (FactoryPhaseStatus v : values()) { + public static AuthLoginResultStatus fromValue(String value) { + for (AuthLoginResultStatus v : values()) { if (v.value.equals(value)) return v; } - throw new IllegalArgumentException("Unknown FactoryPhaseStatus value: " + value); + throw new IllegalArgumentException("Unknown AuthLoginResultStatus value: " + value); } } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStep.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStep.java new file mode 100644 index 0000000000..f13d72f1b9 --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStep.java @@ -0,0 +1,43 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * One step in an interactive login flow. The consumer acts on the step and calls advance to proceed. Browser-open is encoded as two distinct steps by design: `open-url` is CONSUMER-driven (the provider surfaces the authorize URL and the consumer opens it — github.com/GHEC web), while `needs-interaction` is PROVIDER-driven (the provider opens the browser or broker UI itself and does not surface a URL — Entra). + * + * @apiNote This type is experimental and may change in a future version. + * + * @since 1.0.0 + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "kind", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = AuthLoginStepOpenUrl.class, name = "open-url"), + @JsonSubTypes.Type(value = AuthLoginStepInputRequired.class, name = "input-required"), + @JsonSubTypes.Type(value = AuthLoginStepAwaiting.class, name = "awaiting"), + @JsonSubTypes.Type(value = AuthLoginStepNeedsInteraction.class, name = "needs-interaction"), + @JsonSubTypes.Type(value = AuthLoginStepCompleted.class, name = "completed"), + @JsonSubTypes.Type(value = AuthLoginStepError.class, name = "error") +}) +@CopilotExperimental +@JsonIgnoreProperties(ignoreUnknown = true) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public abstract class AuthLoginStep { + + /** + * Returns the discriminator value for this variant. + * + * @return the kind discriminator + */ + public abstract String getKind(); +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryCurrentPhase.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepAwaiting.java similarity index 77% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryCurrentPhase.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepAwaiting.java index c15631835d..10d61f66a0 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryCurrentPhase.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepAwaiting.java @@ -14,20 +14,21 @@ import javax.annotation.processing.Generated; /** - * Current factory phase identity. + * Variant {@code awaiting} of {@link AuthLoginStep}. * * @apiNote This type is experimental and may change in a future version. * * @since 1.0.0 */ @CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryCurrentPhase( - /** Current phase identifier. */ - @JsonProperty("id") String id, - /** Zero-based declared phase ordinal, or null for an undeclared phase. */ - @JsonProperty("ordinal") Long ordinal -) { +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AuthLoginStepAwaiting extends AuthLoginStep { + + @JsonProperty("kind") + private final String kind = "awaiting"; + + @Override + public String getKind() { return kind; } } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepCompleted.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepCompleted.java new file mode 100644 index 0000000000..b1fb524643 --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepCompleted.java @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Variant {@code completed} of {@link AuthLoginStep}. + * + * @apiNote This type is experimental and may change in a future version. + * + * @since 1.0.0 + */ +@CopilotExperimental +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AuthLoginStepCompleted extends AuthLoginStep { + + @JsonProperty("kind") + private final String kind = "completed"; + + @Override + public String getKind() { return kind; } + + /** The terminal login result. */ + @JsonProperty("result") + private AuthLoginResultDto result; + + public AuthLoginResultDto getResult() { return result; } + public void setResult(AuthLoginResultDto result) { this.result = result; } +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepError.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepError.java new file mode 100644 index 0000000000..1d6d425122 --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepError.java @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Variant {@code error} of {@link AuthLoginStep}. + * + * @apiNote This type is experimental and may change in a future version. + * + * @since 1.0.0 + */ +@CopilotExperimental +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AuthLoginStepError extends AuthLoginStep { + + @JsonProperty("kind") + private final String kind = "error"; + + @Override + public String getKind() { return kind; } + + /** Human-readable failure message. */ + @JsonProperty("message") + private String message; + + public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepInputRequired.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepInputRequired.java new file mode 100644 index 0000000000..f2fe79429b --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepInputRequired.java @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Variant {@code input-required} of {@link AuthLoginStep}. + * + * @apiNote This type is experimental and may change in a future version. + * + * @since 1.0.0 + */ +@CopilotExperimental +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AuthLoginStepInputRequired extends AuthLoginStep { + + @JsonProperty("kind") + private final String kind = "input-required"; + + @Override + public String getKind() { return kind; } + + /** Prompt for the value the provider needs; the consumer supplies it as advance input (e.g. a GitHub Enterprise Cloud host, *.ghe.com). */ + @JsonProperty("prompt") + private String prompt; + + public String getPrompt() { return prompt; } + public void setPrompt(String prompt) { this.prompt = prompt; } +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryLogLine.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepNeedsInteraction.java similarity index 74% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryLogLine.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepNeedsInteraction.java index 1f7afdd583..27902574e1 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryLogLine.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepNeedsInteraction.java @@ -14,22 +14,21 @@ import javax.annotation.processing.Generated; /** - * One ordered factory progress line. + * Variant {@code needs-interaction} of {@link AuthLoginStep}. * * @apiNote This type is experimental and may change in a future version. * * @since 1.0.0 */ @CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryLogLine( - /** Monotonic sequence number within the factory run. */ - @JsonProperty("seq") Long seq, - /** Progress line kind. */ - @JsonProperty("kind") FactoryLogLineKind kind, - /** Progress text. */ - @JsonProperty("text") String text -) { +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AuthLoginStepNeedsInteraction extends AuthLoginStep { + + @JsonProperty("kind") + private final String kind = "needs-interaction"; + + @Override + public String getKind() { return kind; } } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepOpenUrl.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepOpenUrl.java new file mode 100644 index 0000000000..977ee8caf0 --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthLoginStepOpenUrl.java @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Variant {@code open-url} of {@link AuthLoginStep}. + * + * @apiNote This type is experimental and may change in a future version. + * + * @since 1.0.0 + */ +@CopilotExperimental +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AuthLoginStepOpenUrl extends AuthLoginStep { + + @JsonProperty("kind") + private final String kind = "open-url"; + + @Override + public String getKind() { return kind; } + + /** Authorize URL the consumer should open in a browser (consumer-driven browser-open). */ + @JsonProperty("url") + private String url; + + public String getUrl() { return url; } + public void setUrl(String url) { this.url = url; } +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValue.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValue.java new file mode 100644 index 0000000000..4e19659e4b --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValue.java @@ -0,0 +1,40 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * The read result, keyed by the same selector as the query. + * + * @apiNote This type is experimental and may change in a future version. + * + * @since 1.0.0 + */ +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "kind", visible = true) +@JsonSubTypes({ + @JsonSubTypes.Type(value = AuthReadValueActiveAccount.class, name = "activeAccount"), + @JsonSubTypes.Type(value = AuthReadValueStatus.class, name = "status"), + @JsonSubTypes.Type(value = AuthReadValueLastErrors.class, name = "lastErrors") +}) +@CopilotExperimental +@JsonIgnoreProperties(ignoreUnknown = true) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public abstract class AuthReadValue { + + /** + * Returns the discriminator value for this variant. + * + * @return the kind discriminator + */ + public abstract String getKind(); +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValueActiveAccount.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValueActiveAccount.java new file mode 100644 index 0000000000..8ee2fb9416 --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValueActiveAccount.java @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Variant {@code activeAccount} of {@link AuthReadValue}. + * + * @apiNote This type is experimental and may change in a future version. + * + * @since 1.0.0 + */ +@CopilotExperimental +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AuthReadValueActiveAccount extends AuthReadValue { + + @JsonProperty("kind") + private final String kind = "activeAccount"; + + @Override + public String getKind() { return kind; } + + /** The active account, or absent when not logged in. */ + @JsonProperty("account") + private AccountStatus account; + + public AccountStatus getAccount() { return account; } + public void setAccount(AccountStatus account) { this.account = account; } +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryDeclaredLimits.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValueLastErrors.java similarity index 61% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryDeclaredLimits.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValueLastErrors.java index 7e2e4e6b5b..d7a84eae33 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryDeclaredLimits.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValueLastErrors.java @@ -11,27 +11,32 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.github.copilot.CopilotExperimental; +import java.util.List; import javax.annotation.processing.Generated; /** - * Declared or approved factory resource ceilings. + * Variant {@code lastErrors} of {@link AuthReadValue}. * * @apiNote This type is experimental and may change in a future version. * * @since 1.0.0 */ @CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryDeclaredLimits( - /** Maximum concurrently active subagents. */ - @JsonProperty("maxConcurrentSubagents") Long maxConcurrentSubagents, - /** Maximum total subagents spawned by the run. */ - @JsonProperty("maxTotalSubagents") Long maxTotalSubagents, - /** Maximum accumulated active execution time in seconds. */ - @JsonProperty("timeoutSeconds") Double timeoutSeconds, - /** Maximum AI credits consumed by subagents and descendants. */ - @JsonProperty("maxAiCredits") Double maxAiCredits -) { +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AuthReadValueLastErrors extends AuthReadValue { + + @JsonProperty("kind") + private final String kind = "lastErrors"; + + @Override + public String getKind() { return kind; } + + /** Validation errors from the most recent authentication attempt. */ + @JsonProperty("errors") + private List errors; + + public List getErrors() { return errors; } + public void setErrors(List errors) { this.errors = errors; } } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValueStatus.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValueStatus.java new file mode 100644 index 0000000000..01b03f041a --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthReadValueStatus.java @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Variant {@code status} of {@link AuthReadValue}. + * + * @apiNote This type is experimental and may change in a future version. + * + * @since 1.0.0 + */ +@CopilotExperimental +@JsonIgnoreProperties(ignoreUnknown = true) +@JsonInclude(JsonInclude.Include.NON_NULL) +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class AuthReadValueStatus extends AuthReadValue { + + @JsonProperty("kind") + private final String kind = "status"; + + @Override + public String getKind() { return kind; } + + /** The neutral authentication status summary. */ + @JsonProperty("status") + private AuthStatusDto status; + + public AuthStatusDto getStatus() { return status; } + public void setStatus(AuthStatusDto status) { this.status = status; } +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthStatusDto.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthStatusDto.java new file mode 100644 index 0000000000..35a4113c80 --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/AuthStatusDto.java @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Neutral authentication status summary. + * + * @apiNote This type is experimental and may change in a future version. + * + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record AuthStatusDto( + /** Whether the session has resolved authentication. */ + @JsonProperty("isAuthenticated") Boolean isAuthenticated, + /** Active account login, if authenticated. */ + @JsonProperty("activeLogin") String activeLogin, + /** Active account host, if authenticated. */ + @JsonProperty("activeHost") String activeHost, + /** Copilot plan tier of the active account, if known. */ + @JsonProperty("copilotPlan") String copilotPlan, + /** Number of signed-in accounts in the roster. */ + @JsonProperty("accountCount") Long accountCount +) { +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryAgentSummary.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryAgentSummary.java deleted file mode 100644 index d063fc9c6b..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryAgentSummary.java +++ /dev/null @@ -1,57 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Prompt-safe durable identity and live status for a direct factory agent. - * - * @apiNote This type is experimental and may change in a future version. - * - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryAgentSummary( - /** Stable direct-agent identifier. */ - @JsonProperty("agentId") String agentId, - /** Tool-call identifier that launched the agent. */ - @JsonProperty("toolCallId") String toolCallId, - /** Owning factory run identifier. */ - @JsonProperty("runId") String runId, - /** Phase identifier active when the agent was launched, or null. */ - @JsonProperty("phaseId") String phaseId, - /** Friendly, non-unique name intended for display */ - @JsonProperty("label") String label, - /** Friendly, non-unique name intended for display */ - @JsonProperty("displayName") String displayName, - /** Registered agent type. */ - @JsonProperty("agentType") String agentType, - /** Current durable or live agent status. */ - @JsonProperty("status") String status, - /** Model requested when the agent was launched. */ - @JsonProperty("requestedModel") String requestedModel, - /** Concrete model resolved for the agent. */ - @JsonProperty("resolvedModel") String resolvedModel, - /** Epoch milliseconds when the agent started. */ - @JsonProperty("startedAt") Long startedAt, - /** Epoch milliseconds when the agent completed. */ - @JsonProperty("completedAt") Long completedAt, - /** Accumulated active agent time in milliseconds. */ - @JsonProperty("activeMs") Long activeMs, - /** Prompt-safe live activity text. */ - @JsonProperty("activity") String activity -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryExecuteParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryExecuteParams.java deleted file mode 100644 index 6834dd4b12..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryExecuteParams.java +++ /dev/null @@ -1,38 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Parameters sent to the owning extension to execute a factory closure. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryExecuteParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId, - /** Registered factory name. */ - @JsonProperty("name") String name, - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** Opaque token identifying this factory execution attempt. */ - @JsonProperty("executionToken") String executionToken, - /** Factory input value. */ - @JsonProperty("args") Object args -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryLogLineKind.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryLogLineKind.java deleted file mode 100644 index 1064f1691d..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryLogLineKind.java +++ /dev/null @@ -1,35 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import javax.annotation.processing.Generated; - -/** - * Kind of factory progress line. - * - * @since 1.0.0 - */ -@javax.annotation.processing.Generated("copilot-sdk-codegen") -public enum FactoryLogLineKind { - /** The {@code log} variant. */ - LOG("log"), - /** The {@code phase} variant. */ - PHASE("phase"); - - private final String value; - FactoryLogLineKind(String value) { this.value = value; } - @com.fasterxml.jackson.annotation.JsonValue - public String getValue() { return value; } - @com.fasterxml.jackson.annotation.JsonCreator - public static FactoryLogLineKind fromValue(String value) { - for (FactoryLogLineKind v : values()) { - if (v.value.equals(value)) return v; - } - throw new IllegalArgumentException("Unknown FactoryLogLineKind value: " + value); - } -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseObservation.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseObservation.java deleted file mode 100644 index 167766885c..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryPhaseObservation.java +++ /dev/null @@ -1,55 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Durable lifecycle and timing for one factory phase. - * - * @apiNote This type is experimental and may change in a future version. - * - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryPhaseObservation( - /** Phase identifier. */ - @JsonProperty("id") String id, - /** Zero-based declared phase ordinal, or null for an undeclared phase. */ - @JsonProperty("ordinal") Long ordinal, - /** Human-readable phase title. */ - @JsonProperty("title") String title, - /** Optional human-readable phase detail. */ - @JsonProperty("detail") String detail, - /** Derived lifecycle state of the phase. */ - @JsonProperty("status") FactoryPhaseStatus status, - /** Most recent run attempt that entered this phase, or `0` if the phase has never been entered. */ - @JsonProperty("lastEnteredRunAttempt") Long lastEnteredRunAttempt, - /** Number of times execution entered this phase. */ - @JsonProperty("entryCount") Long entryCount, - /** Epoch milliseconds when this phase first started; for a skipped phase, the synthetic skip timestamp (equal to `completedAt`). */ - @JsonProperty("startedAt") Long startedAt, - /** Epoch milliseconds when this phase completed; for a skipped phase, the synthetic skip timestamp (equal to `startedAt`). */ - @JsonProperty("completedAt") Long completedAt, - /** Completed active time accumulated by this phase in milliseconds. */ - @JsonProperty("accumulatedActiveMs") Long accumulatedActiveMs, - /** Current live active time for this phase in milliseconds. */ - @JsonProperty("currentActiveMs") Long currentActiveMs, - /** Total direct agents associated with this phase. */ - @JsonProperty("totalAgentCount") Long totalAgentCount, - /** Direct agents in this phase that are currently live. */ - @JsonProperty("liveAgentCount") Long liveAgentCount -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressLine.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressLine.java deleted file mode 100644 index c9ed149610..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressLine.java +++ /dev/null @@ -1,41 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * One durable factory progress record. - * - * @apiNote This type is experimental and may change in a future version. - * - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryProgressLine( - /** Global monotonic sequence number within the run. */ - @JsonProperty("seq") Long seq, - /** Resume attempt that emitted this record. */ - @JsonProperty("attempt") Long attempt, - /** Phase active when the record was emitted, or null before any phase. */ - @JsonProperty("phaseId") String phaseId, - /** Epoch milliseconds when the record was persisted. */ - @JsonProperty("recordedAt") Long recordedAt, - /** Progress record kind. */ - @JsonProperty("kind") FactoryLogLineKind kind, - /** Prompt-safe progress text. */ - @JsonProperty("text") String text -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressPage.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressPage.java deleted file mode 100644 index 935140612e..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryProgressPage.java +++ /dev/null @@ -1,42 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import java.util.List; -import javax.annotation.processing.Generated; - -/** - * A bidirectional page of factory progress. - * - * @apiNote This type is experimental and may change in a future version. - * - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryProgressPage( - /** Progress records in sequence order. */ - @JsonProperty("records") List records, - /** Oldest sequence number in this page, or null when empty. */ - @JsonProperty("oldestSeq") Long oldestSeq, - /** Newest sequence number in this page, or null when empty. */ - @JsonProperty("newestSeq") Long newestSeq, - /** Whether progress records older than this page exist. */ - @JsonProperty("hasMoreOlder") Boolean hasMoreOlder, - /** Whether progress records newer than this page exist. */ - @JsonProperty("hasMoreNewer") Boolean hasMoreNewer, - /** Run revision reflected by this page. */ - @JsonProperty("revision") Long revision -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunLimits.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunLimits.java deleted file mode 100644 index 300e4977b3..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunLimits.java +++ /dev/null @@ -1,37 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Wire-only per-invocation factory resource ceiling overrides. - * - * @apiNote This type is experimental and may change in a future version. - * - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryRunLimits( - /** Maximum number of factory subagents that may run concurrently. */ - @JsonProperty("maxConcurrentSubagents") Long maxConcurrentSubagents, - /** Maximum total number of factory subagents that may be admitted. */ - @JsonProperty("maxTotalSubagents") Long maxTotalSubagents, - /** Maximum accumulated active-execution time in seconds. Active execution includes the entire extension body, subprocess waits, queued-agent waits, and sleeps; time between resumed attempts is not counted. */ - @JsonProperty("timeoutSeconds") Double timeoutSeconds, - /** Maximum AI credits consumed by factory subagents and their descendants. The post-paid ceiling is soft: parallel turns can settle beyond it before the run stops. */ - @JsonProperty("maxAiCredits") Double maxAiCredits -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunResult.java deleted file mode 100644 index 436f969f61..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunResult.java +++ /dev/null @@ -1,43 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import javax.annotation.processing.Generated; - -/** - * Complete current or terminal factory run envelope. - * - * @since 1.0.0 - */ -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryRunResult( - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. */ - @JsonProperty("attempt") Long attempt, - /** Current or terminal factory run status. */ - @JsonProperty("status") FactoryRunStatus status, - /** Completed factory result. */ - @JsonProperty("result") Object result, - /** Error message for an errored run. */ - @JsonProperty("error") String error, - /** Machine-readable failure details for a halted or errored run. */ - @JsonProperty("failure") Object failure, - /** Reason for a halted or cancelled run. */ - @JsonProperty("reason") String reason, - /** Partial journal and progress snapshot for a halted, cancelled, or errored run. */ - @JsonProperty("snapshot") Object snapshot, - /** Structured pause initiator metadata for a paused attempt. */ - @JsonProperty("pauseInfo") Object pauseInfo -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunStatus.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunStatus.java deleted file mode 100644 index d5c87e7304..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunStatus.java +++ /dev/null @@ -1,45 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import javax.annotation.processing.Generated; - -/** - * Current or terminal state of a factory run. - * - * @since 1.0.0 - */ -@javax.annotation.processing.Generated("copilot-sdk-codegen") -public enum FactoryRunStatus { - /** The {@code pending} variant. */ - PENDING("pending"), - /** The {@code running} variant. */ - RUNNING("running"), - /** The {@code completed} variant. */ - COMPLETED("completed"), - /** The {@code halted} variant. */ - HALTED("halted"), - /** The {@code paused} variant. */ - PAUSED("paused"), - /** The {@code cancelled} variant. */ - CANCELLED("cancelled"), - /** The {@code error} variant. */ - ERROR("error"); - - private final String value; - FactoryRunStatus(String value) { this.value = value; } - @com.fasterxml.jackson.annotation.JsonValue - public String getValue() { return value; } - @com.fasterxml.jackson.annotation.JsonCreator - public static FactoryRunStatus fromValue(String value) { - for (FactoryRunStatus v : values()) { - if (v.value.equals(value)) return v; - } - throw new IllegalArgumentException("Unknown FactoryRunStatus value: " + value); - } -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunSummary.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunSummary.java deleted file mode 100644 index 56d1f91763..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunSummary.java +++ /dev/null @@ -1,69 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Durable factory run summary with read-time live overlays. - * - * @apiNote This type is experimental and may change in a future version. - * - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryRunSummary( - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** Registered factory name. */ - @JsonProperty("factoryName") String factoryName, - /** Human-readable factory description. */ - @JsonProperty("description") String description, - /** Current factory run status. */ - @JsonProperty("status") FactoryRunStatus status, - /** Monotonic durable run revision. */ - @JsonProperty("revision") Long revision, - /** Epoch milliseconds when the run was created. */ - @JsonProperty("createdAt") Long createdAt, - /** Epoch milliseconds when execution first started, or null before start. */ - @JsonProperty("startedAt") Long startedAt, - /** Epoch milliseconds when the durable run was last updated. */ - @JsonProperty("updatedAt") Long updatedAt, - /** Epoch milliseconds when the run completed, or null while nonterminal. */ - @JsonProperty("completedAt") Long completedAt, - /** Current phase identity, or null before any phase is entered. */ - @JsonProperty("currentPhase") FactoryCurrentPhase currentPhase, - /** Number of phases declared by the factory. */ - @JsonProperty("declaredPhaseCount") Long declaredPhaseCount, - /** Number of direct factory agents currently live. */ - @JsonProperty("liveAgentCount") Long liveAgentCount, - /** Total direct factory agents spawned across all attempts. */ - @JsonProperty("totalSpawnedAgentCount") Long totalSpawnedAgentCount, - /** Durable resource consumption. */ - @JsonProperty("consumed") FactoryRunConsumed consumed, - /** Resource ceilings declared by the factory. */ - @JsonProperty("declaredLimits") FactoryDeclaredLimits declaredLimits, - /** Approved effective resource ceilings, or null until approved. */ - @JsonProperty("approved") FactoryDeclaredLimits approved, - /** Epoch milliseconds when this live-overlay snapshot was observed. */ - @JsonProperty("observedAt") Long observedAt, - /** Epoch milliseconds when the current active segment started, or null while inactive. */ - @JsonProperty("activeSegmentStartedAt") Long activeSegmentStartedAt, - /** Terminal run outcome, or null while nonterminal. */ - @JsonProperty("terminal") FactoryRunTerminal terminal, - /** Whether the durable run state currently passes runtime resume eligibility checks. */ - @JsonProperty("canResume") Boolean canResume -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunTerminal.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunTerminal.java deleted file mode 100644 index 0b0db7d9b7..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunTerminal.java +++ /dev/null @@ -1,39 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Prompt-safe terminal factory outcome. - * - * @apiNote This type is experimental and may change in a future version. - * - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryRunTerminal( - /** Human-readable terminal reason. */ - @JsonProperty("reason") String reason, - /** Machine-readable terminal failure. */ - @JsonProperty("failure") Object failure, - /** Human-readable terminal error. */ - @JsonProperty("error") String error, - /** Prompt-safe preview of the completed result. */ - @JsonProperty("resultPreview") String resultPreview, - /** Pause initiator metadata, or null when the run did not pause. */ - @JsonProperty("pauseInfo") Object pauseInfo -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryPauseCheckpointAction.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/LoginProviderKind.java similarity index 52% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryPauseCheckpointAction.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/LoginProviderKind.java index a07aa8a677..75517e5892 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryPauseCheckpointAction.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/LoginProviderKind.java @@ -7,29 +7,35 @@ package com.github.copilot.generated.rpc; +import com.github.copilot.CopilotExperimental; import javax.annotation.processing.Generated; /** - * Action the runtime selected for a durable factory pause checkpoint. + * A provider a consumer may interactively sign in with. + * + * @apiNote This type is experimental and may change in a future version. * * @since 1.0.0 */ +@CopilotExperimental @javax.annotation.processing.Generated("copilot-sdk-codegen") -public enum FactoryPauseCheckpointAction { - /** The {@code continue} variant. */ - CONTINUE("continue"), - /** The {@code pause} variant. */ - PAUSE("pause"); +public enum LoginProviderKind { + /** The {@code githubDotCom} variant. */ + GITHUBDOTCOM("githubDotCom"), + /** The {@code proxima} variant. */ + PROXIMA("proxima"), + /** The {@code entra} variant. */ + ENTRA("entra"); private final String value; - FactoryPauseCheckpointAction(String value) { this.value = value; } + LoginProviderKind(String value) { this.value = value; } @com.fasterxml.jackson.annotation.JsonValue public String getValue() { return value; } @com.fasterxml.jackson.annotation.JsonCreator - public static FactoryPauseCheckpointAction fromValue(String value) { - for (FactoryPauseCheckpointAction v : values()) { + public static LoginProviderKind fromValue(String value) { + for (LoginProviderKind v : values()) { if (v.value.equals(value)) return v; } - throw new IllegalArgumentException("Unknown FactoryPauseCheckpointAction value: " + value); + throw new IllegalArgumentException("Unknown LoginProviderKind value: " + value); } } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/ModelChangeSource.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/ModelChangeSource.java index 6f0687414c..c7505885fa 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/ModelChangeSource.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/ModelChangeSource.java @@ -39,7 +39,9 @@ public enum ModelChangeSource { /** The {@code changeboarding_shortcut} variant. */ CHANGEBOARDING_SHORTCUT("changeboarding_shortcut"), /** The {@code sdk} variant. */ - SDK("sdk"); + SDK("sdk"), + /** The {@code auto_tier_recommendation} variant. */ + AUTO_TIER_RECOMMENDATION("auto_tier_recommendation"); private final String value; ModelChangeSource(String value) { this.value = value; } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunConsumed.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/ProviderDescriptor.java similarity index 67% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunConsumed.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/ProviderDescriptor.java index 5ffc43435d..f56810a7f9 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryRunConsumed.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/ProviderDescriptor.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Durable factory resource consumption. + * A provider offered for interactive login. * * @apiNote This type is experimental and may change in a future version. * @@ -24,12 +24,12 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryRunConsumed( - /** Accumulated active execution time in milliseconds. */ - @JsonProperty("activeMs") Long activeMs, - /** Total subagents spawned by the run. */ - @JsonProperty("subagents") Long subagents, - /** AI usage consumed by the run in nano-AIU. */ - @JsonProperty("nanoAiu") Long nanoAiu +public record ProviderDescriptor( + /** The neutral provider kind. */ + @JsonProperty("kind") LoginProviderKind kind, + /** Human-readable menu label, owned by the runtime so every consumer renders identical text. */ + @JsonProperty("label") String label, + /** Whether this provider is currently available to sign in with. */ + @JsonProperty("available") Boolean available ) { } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/RunOptions.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/RunOptions.java deleted file mode 100644 index ae535af8cf..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/RunOptions.java +++ /dev/null @@ -1,37 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Options controlling factory invocation. - * - * @apiNote This type is experimental and may change in a future version. - * - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record RunOptions( - /** Per-invocation resource ceiling overrides. */ - @JsonProperty("limits") FactoryRunLimits limits, - /** Whether to notify the originating session when the factory completes. */ - @JsonProperty("notifyOnComplete") Boolean notifyOnComplete, - /** Whether to emit factory phase names to the session transcript. */ - @JsonProperty("logPhaseNames") Boolean logPhaseNames, - /** Run identifier whose journal and progress should seed this resumed run. */ - @JsonProperty("resumeFromRunId") String resumeFromRunId -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsApi.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsApi.java new file mode 100644 index 0000000000..76b3fdc7e0 --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsApi.java @@ -0,0 +1,85 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.github.copilot.CopilotExperimental; +import java.util.concurrent.CompletableFuture; +import javax.annotation.processing.Generated; + +/** + * API methods for the {@code accounts} namespace. + * + * @since 1.0.0 + */ +@javax.annotation.processing.Generated("copilot-sdk-codegen") +public final class SessionAccountsApi { + + private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; + + private final RpcCaller caller; + private final String sessionId; + + /** API methods for the {@code accounts.login} sub-namespace. */ + public final SessionAccountsLoginApi login; + + /** @param caller the RPC transport function */ + SessionAccountsApi(RpcCaller caller, String sessionId) { + this.caller = caller; + this.sessionId = sessionId; + this.login = new SessionAccountsLoginApi(caller, sessionId); + } + + /** + * Enumerate request carrying the typed collection query. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture enumerate(SessionAccountsEnumerateParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.accounts.enumerate", _p, AuthEnumerateValue.class); + } + + /** + * Read request carrying the typed datum query. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture get(SessionAccountsGetParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.accounts.get", _p, AuthReadValue.class); + } + + /** + * Mutation request carrying the typed write command. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture set(SessionAccountsSetParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.accounts.set", _p, SessionAccountsSetResult.class); + } + +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsEnumerateParams.java similarity index 83% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseParams.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsEnumerateParams.java index 00a1b4d660..480ba804b5 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseParams.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsEnumerateParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Parameters for pausing a running factory. + * Enumerate request carrying the typed collection query. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,10 +23,10 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryPauseParams( +public record SessionAccountsEnumerateParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId, - /** Factory run identifier. */ - @JsonProperty("runId") String runId + /** Which typed accounts collection to enumerate. */ + @JsonProperty("query") Object query ) { } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsGetParams.java similarity index 85% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunParams.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsGetParams.java index f98e1f0d74..d75a1bc76a 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunParams.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsGetParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Parameters for retrieving a factory run. + * Read request carrying the typed datum query. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,10 +23,10 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryGetRunParams( +public record SessionAccountsGetParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId, - /** Factory run identifier. */ - @JsonProperty("runId") String runId + /** Which typed accounts datum to read. */ + @JsonProperty("query") Object query ) { } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryAbortParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginAdvanceParams.java similarity index 73% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryAbortParams.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginAdvanceParams.java index 178c135cdd..e4a8e34b3a 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryAbortParams.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginAdvanceParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Parameters for cooperatively aborting a factory body. + * Advance an in-flight login flow, optionally fulfilling an input-required step. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,12 +23,12 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryAbortParams( +public record SessionAccountsLoginAdvanceParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId, - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** Opaque token identifying the execution attempt to abort. */ - @JsonProperty("executionToken") String executionToken + /** Opaque flow id from begin. */ + @JsonProperty("flowId") String flowId, + /** Neutral input fulfilling a preceding input-required step (e.g. a GHEC host); ignored otherwise. */ + @JsonProperty("input") String input ) { } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalApi.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginApi.java similarity index 56% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalApi.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginApi.java index e5bfb4e66a..5537a0dad2 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalApi.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginApi.java @@ -12,12 +12,12 @@ import javax.annotation.processing.Generated; /** - * API methods for the {@code factory.journal} namespace. + * API methods for the {@code accounts.login} namespace. * * @since 1.0.0 */ @javax.annotation.processing.Generated("copilot-sdk-codegen") -public final class SessionFactoryJournalApi { +public final class SessionAccountsLoginApi { private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; @@ -25,13 +25,13 @@ public final class SessionFactoryJournalApi { private final String sessionId; /** @param caller the RPC transport function */ - SessionFactoryJournalApi(RpcCaller caller, String sessionId) { + SessionAccountsLoginApi(RpcCaller caller, String sessionId) { this.caller = caller; this.sessionId = sessionId; } /** - * Parameters for reading a factory journal entry. + * Begin an interactive login flow for a provider kind. Dispatch is kind-only. *

* Note: the {@code sessionId} field in the params record is overridden * by the session-scoped wrapper; any value provided is ignored. @@ -40,14 +40,14 @@ public final class SessionFactoryJournalApi { * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture get(SessionFactoryJournalGetParams params) { + public CompletableFuture begin(SessionAccountsLoginBeginParams params) { com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.journal.get", _p, SessionFactoryJournalGetResult.class); + return caller.invoke("session.accounts.login.begin", _p, SessionAccountsLoginBeginResult.class); } /** - * Parameters for storing a factory journal entry. + * Advance an in-flight login flow, optionally fulfilling an input-required step. *

* Note: the {@code sessionId} field in the params record is overridden * by the session-scoped wrapper; any value provided is ignored. @@ -56,10 +56,26 @@ public CompletableFuture get(SessionFactoryJourn * @since 1.0.0 */ @CopilotExperimental - public CompletableFuture put(SessionFactoryJournalPutParams params) { + public CompletableFuture advance(SessionAccountsLoginAdvanceParams params) { com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.journal.put", _p, Void.class); + return caller.invoke("session.accounts.login.advance", _p, AuthLoginStep.class); + } + + /** + * Cancel an in-flight login flow. + *

+ * Note: the {@code sessionId} field in the params record is overridden + * by the session-scoped wrapper; any value provided is ignored. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ + @CopilotExperimental + public CompletableFuture cancel(SessionAccountsLoginCancelParams params) { + com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); + _p.put("sessionId", this.sessionId); + return caller.invoke("session.accounts.login.cancel", _p, Void.class); } } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginBeginParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginBeginParams.java new file mode 100644 index 0000000000..2f2fdc473e --- /dev/null +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginBeginParams.java @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + *--------------------------------------------------------------------------------------------*/ + +// AUTO-GENERATED FILE - DO NOT EDIT +// Generated from: api.schema.json + +package com.github.copilot.generated.rpc; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.github.copilot.CopilotExperimental; +import javax.annotation.processing.Generated; + +/** + * Begin an interactive login flow for a provider kind. Dispatch is kind-only. + * + * @apiNote This method is experimental and may change in a future version. + * @since 1.0.0 + */ +@CopilotExperimental +@javax.annotation.processing.Generated("copilot-sdk-codegen") +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonIgnoreProperties(ignoreUnknown = true) +public record SessionAccountsLoginBeginParams( + /** Target session identifier */ + @JsonProperty("sessionId") String sessionId, + /** The provider kind to sign in with. */ + @JsonProperty("kind") LoginProviderKind kind +) { +} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryExecuteResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginBeginResult.java similarity index 76% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryExecuteResult.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginBeginResult.java index b47b9fb073..451890e8c0 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/FactoryExecuteResult.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginBeginResult.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Result returned by an extension factory closure. + * A started login flow: its opaque id and first step. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,8 +23,10 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record FactoryExecuteResult( - /** Factory result value. */ - @JsonProperty("result") Object result +public record SessionAccountsLoginBeginResult( + /** Opaque flow id used to advance or cancel this login. */ + @JsonProperty("flowId") String flowId, + /** The first step of the flow. */ + @JsonProperty("step") Object step ) { } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryCancelParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginCancelParams.java similarity index 85% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryCancelParams.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginCancelParams.java index 8ed7e4aa37..4426b02941 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryCancelParams.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsLoginCancelParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Parameters for cancelling a factory run. + * Cancel an in-flight login flow. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,10 +23,10 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryCancelParams( +public record SessionAccountsLoginCancelParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId, - /** Factory run identifier. */ - @JsonProperty("runId") String runId + /** Opaque flow id from begin. */ + @JsonProperty("flowId") String flowId ) { } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsSetParams.java similarity index 83% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailParams.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsSetParams.java index b4563d4b35..b7c16327d4 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailParams.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsSetParams.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Parameters for retrieving a factory run. + * Mutation request carrying the typed write command. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,10 +23,10 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryGetRunDetailParams( +public record SessionAccountsSetParams( /** Target session identifier */ @JsonProperty("sessionId") String sessionId, - /** Factory run identifier. */ - @JsonProperty("runId") String runId + /** The non-interactive mutation command to apply. */ + @JsonProperty("command") Object command ) { } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryAgentResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsSetResult.java similarity index 76% rename from java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryAgentResult.java rename to java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsSetResult.java index dcd31fd34a..7c6c42c029 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryAgentResult.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionAccountsSetResult.java @@ -14,7 +14,7 @@ import javax.annotation.processing.Generated; /** - * Result of one factory-scoped subagent call. + * Result of a non-interactive accounts mutation. * * @apiNote This method is experimental and may change in a future version. * @since 1.0.0 @@ -23,8 +23,10 @@ @javax.annotation.processing.Generated("copilot-sdk-codegen") @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryAgentResult( - /** Agent result, omitted when the agent produced no result. */ - @JsonProperty("result") Object result +public record SessionAccountsSetResult( + /** Whether the mutation was applied. */ + @JsonProperty("ok") Boolean ok, + /** For a logout, whether other signed-in accounts remain. */ + @JsonProperty("moreUsers") Boolean moreUsers ) { } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryAgentParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryAgentParams.java deleted file mode 100644 index 6ab02c27eb..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryAgentParams.java +++ /dev/null @@ -1,38 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Parameters for one factory-scoped subagent call. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryAgentParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId, - /** Factory run identifier that owns the subagent. */ - @JsonProperty("factoryRunId") String factoryRunId, - /** Opaque token identifying the current factory execution attempt. */ - @JsonProperty("executionToken") String executionToken, - /** Prompt to send to the subagent. */ - @JsonProperty("prompt") String prompt, - /** Subagent execution options. */ - @JsonProperty("opts") FactoryAgentOptions opts -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryApi.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryApi.java deleted file mode 100644 index 12fa3cf6fd..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryApi.java +++ /dev/null @@ -1,245 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.github.copilot.CopilotExperimental; -import java.util.concurrent.CompletableFuture; -import javax.annotation.processing.Generated; - -/** - * API methods for the {@code factory} namespace. - * - * @since 1.0.0 - */ -@javax.annotation.processing.Generated("copilot-sdk-codegen") -public final class SessionFactoryApi { - - private static final com.fasterxml.jackson.databind.ObjectMapper MAPPER = RpcMapper.INSTANCE; - - private final RpcCaller caller; - private final String sessionId; - - /** API methods for the {@code factory.journal} sub-namespace. */ - public final SessionFactoryJournalApi journal; - - /** @param caller the RPC transport function */ - SessionFactoryApi(RpcCaller caller, String sessionId) { - this.caller = caller; - this.sessionId = sessionId; - this.journal = new SessionFactoryJournalApi(caller, sessionId); - } - - /** - * Parameters for invoking a registered factory. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture run(SessionFactoryRunParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.run", _p, SessionFactoryRunResult.class); - } - - /** - * Parameters for resuming a factory run from its persisted identity. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture resume(SessionFactoryResumeParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.resume", _p, SessionFactoryResumeResult.class); - } - - /** - * Internal parameters for invoking a registered factory from a tool. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture runFromTool(SessionFactoryRunFromToolParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.runFromTool", _p, SessionFactoryRunFromToolResult.class); - } - - /** - * Internal parameters for resuming a factory run from a tool. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture resumeFromTool(SessionFactoryResumeFromToolParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.resumeFromTool", _p, SessionFactoryResumeFromToolResult.class); - } - - /** - * Parameters for retrieving a factory run. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture getRun(SessionFactoryGetRunParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.getRun", _p, SessionFactoryGetRunResult.class); - } - - /** - * Parameters for paging factory runs. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture listRuns(SessionFactoryListRunsParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.listRuns", _p, SessionFactoryListRunsResult.class); - } - - /** - * Parameters for retrieving a factory run. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture getRunDetail(SessionFactoryGetRunDetailParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.getRunDetail", _p, SessionFactoryGetRunDetailResult.class); - } - - /** - * Parameters for paging factory progress. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture getRunProgress(SessionFactoryGetRunProgressParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.getRunProgress", _p, SessionFactoryGetRunProgressResult.class); - } - - /** - * Parameters for cancelling a factory run. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture cancel(SessionFactoryCancelParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.cancel", _p, SessionFactoryCancelResult.class); - } - - /** - * Parameters for pausing a running factory. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture pause(SessionFactoryPauseParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.pause", _p, SessionFactoryPauseResult.class); - } - - /** - * Parameters for an owned durable pause checkpoint. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture pauseAtCheckpoint(SessionFactoryPauseAtCheckpointParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.pauseAtCheckpoint", _p, SessionFactoryPauseAtCheckpointResult.class); - } - - /** - * Parameters for recording factory progress. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture log(SessionFactoryLogParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.log", _p, Void.class); - } - - /** - * Parameters for one factory-scoped subagent call. - *

- * Note: the {@code sessionId} field in the params record is overridden - * by the session-scoped wrapper; any value provided is ignored. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ - @CopilotExperimental - public CompletableFuture agent(SessionFactoryAgentParams params) { - com.fasterxml.jackson.databind.node.ObjectNode _p = MAPPER.valueToTree(params); - _p.put("sessionId", this.sessionId); - return caller.invoke("session.factory.agent", _p, SessionFactoryAgentResult.class); - } - -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryCancelResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryCancelResult.java deleted file mode 100644 index 42e1b38811..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryCancelResult.java +++ /dev/null @@ -1,46 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Complete current or terminal factory run envelope. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryCancelResult( - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. */ - @JsonProperty("attempt") Long attempt, - /** Current or terminal factory run status. */ - @JsonProperty("status") FactoryRunStatus status, - /** Completed factory result. */ - @JsonProperty("result") Object result, - /** Error message for an errored run. */ - @JsonProperty("error") String error, - /** Machine-readable failure details for a halted or errored run. */ - @JsonProperty("failure") Object failure, - /** Reason for a halted or cancelled run. */ - @JsonProperty("reason") String reason, - /** Partial journal and progress snapshot for a halted, cancelled, or errored run. */ - @JsonProperty("snapshot") Object snapshot, - /** Structured pause initiator metadata for a paused attempt. */ - @JsonProperty("pauseInfo") Object pauseInfo -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailResult.java deleted file mode 100644 index 0a3fb7f83a..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunDetailResult.java +++ /dev/null @@ -1,75 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import java.util.List; -import javax.annotation.processing.Generated; - -/** - * Full factory run observability detail. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryGetRunDetailResult( - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** Registered factory name. */ - @JsonProperty("factoryName") String factoryName, - /** Human-readable factory description. */ - @JsonProperty("description") String description, - /** Current factory run status. */ - @JsonProperty("status") FactoryRunStatus status, - /** Monotonic durable run revision. */ - @JsonProperty("revision") Long revision, - /** Epoch milliseconds when the run was created. */ - @JsonProperty("createdAt") Long createdAt, - /** Epoch milliseconds when execution first started, or null before start. */ - @JsonProperty("startedAt") Long startedAt, - /** Epoch milliseconds when the durable run was last updated. */ - @JsonProperty("updatedAt") Long updatedAt, - /** Epoch milliseconds when the run completed, or null while nonterminal. */ - @JsonProperty("completedAt") Long completedAt, - /** Current phase identity, or null before any phase is entered. */ - @JsonProperty("currentPhase") FactoryCurrentPhase currentPhase, - /** Number of phases declared by the factory. */ - @JsonProperty("declaredPhaseCount") Long declaredPhaseCount, - /** Number of direct factory agents currently live. */ - @JsonProperty("liveAgentCount") Long liveAgentCount, - /** Total direct factory agents spawned across all attempts. */ - @JsonProperty("totalSpawnedAgentCount") Long totalSpawnedAgentCount, - /** Durable resource consumption. */ - @JsonProperty("consumed") FactoryRunConsumed consumed, - /** Resource ceilings declared by the factory. */ - @JsonProperty("declaredLimits") FactoryDeclaredLimits declaredLimits, - /** Approved effective resource ceilings, or null until approved. */ - @JsonProperty("approved") FactoryDeclaredLimits approved, - /** Epoch milliseconds when this live-overlay snapshot was observed. */ - @JsonProperty("observedAt") Long observedAt, - /** Epoch milliseconds when the current active segment started, or null while inactive. */ - @JsonProperty("activeSegmentStartedAt") Long activeSegmentStartedAt, - /** Terminal run outcome, or null while nonterminal. */ - @JsonProperty("terminal") FactoryRunTerminal terminal, - /** Whether the durable run state currently passes runtime resume eligibility checks. */ - @JsonProperty("canResume") Boolean canResume, - /** Lifecycle and timing observations for each factory phase. */ - @JsonProperty("phases") List phases, - /** Durable identities and live statuses for direct factory agents. */ - @JsonProperty("agents") List agents, - /** Bidirectional page of durable factory progress. */ - @JsonProperty("progress") FactoryProgressPage progress -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressParams.java deleted file mode 100644 index 8445943cba..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressParams.java +++ /dev/null @@ -1,40 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Parameters for paging factory progress. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryGetRunProgressParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId, - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** Optional phase identifier used to scope records and cursors. */ - @JsonProperty("phaseId") String phaseId, - /** Exclusive forward cursor. */ - @JsonProperty("afterSeq") Long afterSeq, - /** Exclusive backward cursor. */ - @JsonProperty("beforeSeq") Long beforeSeq, - /** Maximum records to return. Defaults to 200 and is capped at 500. */ - @JsonProperty("limit") Long limit -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressResult.java deleted file mode 100644 index 2a4cb78cb2..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunProgressResult.java +++ /dev/null @@ -1,41 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import java.util.List; -import javax.annotation.processing.Generated; - -/** - * A bidirectional page of factory progress. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryGetRunProgressResult( - /** Progress records in sequence order. */ - @JsonProperty("records") List records, - /** Oldest sequence number in this page, or null when empty. */ - @JsonProperty("oldestSeq") Long oldestSeq, - /** Newest sequence number in this page, or null when empty. */ - @JsonProperty("newestSeq") Long newestSeq, - /** Whether progress records older than this page exist. */ - @JsonProperty("hasMoreOlder") Boolean hasMoreOlder, - /** Whether progress records newer than this page exist. */ - @JsonProperty("hasMoreNewer") Boolean hasMoreNewer, - /** Run revision reflected by this page. */ - @JsonProperty("revision") Long revision -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunResult.java deleted file mode 100644 index 9c141b28d4..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryGetRunResult.java +++ /dev/null @@ -1,46 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Complete current or terminal factory run envelope. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryGetRunResult( - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. */ - @JsonProperty("attempt") Long attempt, - /** Current or terminal factory run status. */ - @JsonProperty("status") FactoryRunStatus status, - /** Completed factory result. */ - @JsonProperty("result") Object result, - /** Error message for an errored run. */ - @JsonProperty("error") String error, - /** Machine-readable failure details for a halted or errored run. */ - @JsonProperty("failure") Object failure, - /** Reason for a halted or cancelled run. */ - @JsonProperty("reason") String reason, - /** Partial journal and progress snapshot for a halted, cancelled, or errored run. */ - @JsonProperty("snapshot") Object snapshot, - /** Structured pause initiator metadata for a paused attempt. */ - @JsonProperty("pauseInfo") Object pauseInfo -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalGetParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalGetParams.java deleted file mode 100644 index 251ca946cb..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalGetParams.java +++ /dev/null @@ -1,36 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Parameters for reading a factory journal entry. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryJournalGetParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId, - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** Opaque token identifying the current factory execution attempt. */ - @JsonProperty("executionToken") String executionToken, - /** Namespaced journal key. */ - @JsonProperty("key") String key -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalGetResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalGetResult.java deleted file mode 100644 index 4b97e10296..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalGetResult.java +++ /dev/null @@ -1,32 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Result of reading a factory journal entry. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryJournalGetResult( - /** Whether the journal contained the requested key. */ - @JsonProperty("hit") Boolean hit, - /** Cached JSON result. The hit field distinguishes a cached JSON null from a miss. */ - @JsonProperty("resultJson") Object resultJson -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalPutParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalPutParams.java deleted file mode 100644 index 06467b2657..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryJournalPutParams.java +++ /dev/null @@ -1,38 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Parameters for storing a factory journal entry. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryJournalPutParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId, - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** Opaque token identifying the current factory execution attempt. */ - @JsonProperty("executionToken") String executionToken, - /** Namespaced journal key. */ - @JsonProperty("key") String key, - /** JSON result to memoize. */ - @JsonProperty("resultJson") Object resultJson -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsParams.java deleted file mode 100644 index 41de4ae4a6..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsParams.java +++ /dev/null @@ -1,36 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Parameters for paging factory runs. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryListRunsParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId, - /** Exclusive forward cursor. */ - @JsonProperty("afterSeq") Long afterSeq, - /** Exclusive backward cursor. */ - @JsonProperty("beforeSeq") Long beforeSeq, - /** Maximum terminal runs to return. Defaults to 200 and is capped at 500. */ - @JsonProperty("limit") Long limit -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsResult.java deleted file mode 100644 index d081003e47..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryListRunsResult.java +++ /dev/null @@ -1,39 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import java.util.List; -import javax.annotation.processing.Generated; - -/** - * A page of factory runs in durable creation order. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryListRunsResult( - /** Factory run summaries in durable creation order. */ - @JsonProperty("runs") List runs, - /** Oldest terminal-run cursor in this page, or null when the terminal window is empty. */ - @JsonProperty("oldestSeq") Long oldestSeq, - /** Newest terminal-run cursor in this page, or null when the terminal window is empty. */ - @JsonProperty("newestSeq") Long newestSeq, - /** Whether terminal runs newer than this page exist. */ - @JsonProperty("hasMoreNewer") Boolean hasMoreNewer, - /** Number of terminal runs older than this page. */ - @JsonProperty("omittedOlder") Long omittedOlder -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryLogParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryLogParams.java deleted file mode 100644 index b4f52617f1..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryLogParams.java +++ /dev/null @@ -1,37 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import java.util.List; -import javax.annotation.processing.Generated; - -/** - * Parameters for recording factory progress. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryLogParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId, - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** Opaque token identifying the current factory execution attempt. */ - @JsonProperty("executionToken") String executionToken, - /** Ordered progress lines to append. */ - @JsonProperty("lines") List lines -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseAtCheckpointParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseAtCheckpointParams.java deleted file mode 100644 index a54c089e20..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseAtCheckpointParams.java +++ /dev/null @@ -1,36 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Parameters for an owned durable pause checkpoint. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryPauseAtCheckpointParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId, - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** Opaque token identifying the execution attempt that reached the checkpoint. */ - @JsonProperty("executionToken") String executionToken, - /** Stable author-defined checkpoint key. */ - @JsonProperty("key") String key -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseAtCheckpointResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseAtCheckpointResult.java deleted file mode 100644 index 4775fa0c6b..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseAtCheckpointResult.java +++ /dev/null @@ -1,30 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Result for the {@code session.factory.pauseAtCheckpoint} RPC method. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryPauseAtCheckpointResult( - /** Whether this execution attempt must pause or may continue. */ - @JsonProperty("action") FactoryPauseCheckpointAction action -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseResult.java deleted file mode 100644 index aa93afbea2..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryPauseResult.java +++ /dev/null @@ -1,46 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Complete current or terminal factory run envelope. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryPauseResult( - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. */ - @JsonProperty("attempt") Long attempt, - /** Current or terminal factory run status. */ - @JsonProperty("status") FactoryRunStatus status, - /** Completed factory result. */ - @JsonProperty("result") Object result, - /** Error message for an errored run. */ - @JsonProperty("error") String error, - /** Machine-readable failure details for a halted or errored run. */ - @JsonProperty("failure") Object failure, - /** Reason for a halted or cancelled run. */ - @JsonProperty("reason") String reason, - /** Partial journal and progress snapshot for a halted, cancelled, or errored run. */ - @JsonProperty("snapshot") Object snapshot, - /** Structured pause initiator metadata for a paused attempt. */ - @JsonProperty("pauseInfo") Object pauseInfo -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeFromToolParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeFromToolParams.java deleted file mode 100644 index 3a54179329..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeFromToolParams.java +++ /dev/null @@ -1,36 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Internal parameters for resuming a factory run from a tool. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryResumeFromToolParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId, - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** Optional per-invocation resource ceiling overrides. */ - @JsonProperty("limits") FactoryRunLimits limits, - /** Opaque identifier of the originating tool call. */ - @JsonProperty("toolCallId") String toolCallId -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeParams.java deleted file mode 100644 index edb39e0811..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryResumeParams.java +++ /dev/null @@ -1,38 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Parameters for resuming a factory run from its persisted identity. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryResumeParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId, - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** Optional per-invocation resource ceiling overrides. */ - @JsonProperty("limits") FactoryRunLimits limits, - /** Whether to notify the originating session when the factory completes. */ - @JsonProperty("notifyOnComplete") Boolean notifyOnComplete, - /** Whether to emit factory phase names to the session transcript. */ - @JsonProperty("logPhaseNames") Boolean logPhaseNames -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunFromToolParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunFromToolParams.java deleted file mode 100644 index dab8ae120d..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunFromToolParams.java +++ /dev/null @@ -1,38 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Internal parameters for invoking a registered factory from a tool. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryRunFromToolParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId, - /** Registered factory name. */ - @JsonProperty("name") String name, - /** Factory input value. */ - @JsonProperty("args") Object args, - /** Tool-originated factory invocation options. */ - @JsonProperty("options") FactoryToolRunOptions options, - /** Opaque identifier of the originating tool call. */ - @JsonProperty("toolCallId") String toolCallId -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunFromToolResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunFromToolResult.java deleted file mode 100644 index b76daece8d..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunFromToolResult.java +++ /dev/null @@ -1,46 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Complete current or terminal factory run envelope. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryRunFromToolResult( - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. */ - @JsonProperty("attempt") Long attempt, - /** Current or terminal factory run status. */ - @JsonProperty("status") FactoryRunStatus status, - /** Completed factory result. */ - @JsonProperty("result") Object result, - /** Error message for an errored run. */ - @JsonProperty("error") String error, - /** Machine-readable failure details for a halted or errored run. */ - @JsonProperty("failure") Object failure, - /** Reason for a halted or cancelled run. */ - @JsonProperty("reason") String reason, - /** Partial journal and progress snapshot for a halted, cancelled, or errored run. */ - @JsonProperty("snapshot") Object snapshot, - /** Structured pause initiator metadata for a paused attempt. */ - @JsonProperty("pauseInfo") Object pauseInfo -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunParams.java deleted file mode 100644 index fd60b9643e..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunParams.java +++ /dev/null @@ -1,36 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Parameters for invoking a registered factory. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryRunParams( - /** Target session identifier */ - @JsonProperty("sessionId") String sessionId, - /** Registered factory name. */ - @JsonProperty("name") String name, - /** Factory input value. */ - @JsonProperty("args") Object args, - /** Factory invocation options. */ - @JsonProperty("options") RunOptions options -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunResult.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunResult.java deleted file mode 100644 index 4a7cc978e4..0000000000 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionFactoryRunResult.java +++ /dev/null @@ -1,46 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -// AUTO-GENERATED FILE - DO NOT EDIT -// Generated from: api.schema.json - -package com.github.copilot.generated.rpc; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.github.copilot.CopilotExperimental; -import javax.annotation.processing.Generated; - -/** - * Complete current or terminal factory run envelope. - * - * @apiNote This method is experimental and may change in a future version. - * @since 1.0.0 - */ -@CopilotExperimental -@javax.annotation.processing.Generated("copilot-sdk-codegen") -@JsonInclude(JsonInclude.Include.NON_NULL) -@JsonIgnoreProperties(ignoreUnknown = true) -public record SessionFactoryRunResult( - /** Factory run identifier. */ - @JsonProperty("runId") String runId, - /** One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. */ - @JsonProperty("attempt") Long attempt, - /** Current or terminal factory run status. */ - @JsonProperty("status") FactoryRunStatus status, - /** Completed factory result. */ - @JsonProperty("result") Object result, - /** Error message for an errored run. */ - @JsonProperty("error") String error, - /** Machine-readable failure details for a halted or errored run. */ - @JsonProperty("failure") Object failure, - /** Reason for a halted or cancelled run. */ - @JsonProperty("reason") String reason, - /** Partial journal and progress snapshot for a halted, cancelled, or errored run. */ - @JsonProperty("snapshot") Object snapshot, - /** Structured pause initiator metadata for a paused attempt. */ - @JsonProperty("pauseInfo") Object pauseInfo -) { -} diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionModelApplyStartupOverlayParams.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionModelApplyStartupOverlayParams.java index d24ac9e7c2..73ae210e78 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionModelApplyStartupOverlayParams.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionModelApplyStartupOverlayParams.java @@ -45,6 +45,10 @@ public record SessionModelApplyStartupOverlayParams( /** Model explicitly selected by the CLI, when provided. */ @JsonProperty("cliModel") String cliModel, /** Whether the overlay is being applied while resuming a deferred session. */ - @JsonProperty("deferredResume") Boolean deferredResume + @JsonProperty("deferredResume") Boolean deferredResume, + /** Reasoning effort paired with the effective organization-managed model. Applies only when that concrete managed model is selected; it is ignored for Auto and for CLI, resume, or user overrides. */ + @JsonProperty("managedReasoningEffort") String managedReasoningEffort, + /** Context tier paired with the effective organization-managed model. Applies only when that concrete managed model is selected; it is ignored for Auto and for CLI, resume, or user overrides. */ + @JsonProperty("managedContextTier") String managedContextTier ) { } diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionRpc.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionRpc.java index 5f3f359551..bb3bb0680b 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionRpc.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SessionRpc.java @@ -33,12 +33,12 @@ public final class SessionRpc { public final SessionSandboxApi sandbox; /** API methods for the {@code gitHubAuth} namespace. */ public final SessionGitHubAuthApi gitHubAuth; + /** API methods for the {@code accounts} namespace. */ + public final SessionAccountsApi accounts; /** API methods for the {@code debug} namespace. */ public final SessionDebugApi debug; /** API methods for the {@code canvas} namespace. */ public final SessionCanvasApi canvas; - /** API methods for the {@code factory} namespace. */ - public final SessionFactoryApi factory; /** API methods for the {@code workflow} namespace. */ public final SessionWorkflowApi workflow; /** API methods for the {@code model} namespace. */ @@ -131,9 +131,9 @@ public SessionRpc(RpcCaller caller, String sessionId) { this.sessionId = sessionId; this.sandbox = new SessionSandboxApi(caller, sessionId); this.gitHubAuth = new SessionGitHubAuthApi(caller, sessionId); + this.accounts = new SessionAccountsApi(caller, sessionId); this.debug = new SessionDebugApi(caller, sessionId); this.canvas = new SessionCanvasApi(caller, sessionId); - this.factory = new SessionFactoryApi(caller, sessionId); this.workflow = new SessionWorkflowApi(caller, sessionId); this.model = new SessionModelApi(caller, sessionId); this.mode = new SessionModeApi(caller, sessionId); diff --git a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInvocationResultSetModel.java b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInvocationResultSetModel.java index 95e4d8544c..4502ccb34b 100644 --- a/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInvocationResultSetModel.java +++ b/java/sdk/src/generated/java/com/github/copilot/generated/rpc/SlashCommandInvocationResultSetModel.java @@ -33,6 +33,10 @@ public final class SlashCommandInvocationResultSetModel extends SlashCommandInvo @JsonProperty("model") private String model; + /** Auto routing profile selected by the command, when the model is Auto. */ + @JsonProperty("autoTier") + private AutoTier autoTier; + /** Settings scope modified by the command. */ @JsonProperty("scope") private String scope; @@ -60,6 +64,9 @@ public final class SlashCommandInvocationResultSetModel extends SlashCommandInvo public String getModel() { return model; } public void setModel(String model) { this.model = model; } + public AutoTier getAutoTier() { return autoTier; } + public void setAutoTier(AutoTier autoTier) { this.autoTier = autoTier; } + public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } diff --git a/java/sdk/src/test/java/com/github/copilot/RpcSurfaceParityE2ETest.java b/java/sdk/src/test/java/com/github/copilot/RpcSurfaceParityE2ETest.java index 43f07d2315..68339000a9 100644 --- a/java/sdk/src/test/java/com/github/copilot/RpcSurfaceParityE2ETest.java +++ b/java/sdk/src/test/java/com/github/copilot/RpcSurfaceParityE2ETest.java @@ -41,8 +41,8 @@ class RpcSurfaceParityE2ETest { private static final ObjectMapper MAPPER = new ObjectMapper(); private static final long TIMEOUT_SECONDS = 30; - private static final int EXPECTED_RPC_METHOD_COUNT = 420; - private static final String EXPECTED_RPC_SIGNATURE_SHA256 = "b060cc39689fb59c658ddc1d073e23c3fc16f08abf719e9102a7f54b26a99166"; + private static final int EXPECTED_RPC_METHOD_COUNT = 411; + private static final String EXPECTED_RPC_SIGNATURE_SHA256 = "6404e16283b5504806589a1bd2b594865dfe4f1d6447f1872b1195688609fd84"; private static final Map EXPECTED_METHODS_BY_DECLARING_TYPE = Map.ofEntries( Map.entry("RpcCaller", 2), Map.entry("ServerAccountApi", 6), Map.entry("ServerAgentRegistryApi", 1), Map.entry("ServerAgentsApi", 2), Map.entry("ServerCatalogApi", 2), Map.entry("ServerCommandsApi", 1), @@ -53,15 +53,15 @@ class RpcSurfaceParityE2ETest { Map.entry("ServerPluginsMarketplacesApi", 6), Map.entry("ServerRpc", 3), Map.entry("ServerRuntimeApi", 1), Map.entry("ServerSandboxApi", 1), Map.entry("ServerSecretsApi", 1), Map.entry("ServerSessionFsApi", 1), Map.entry("ServerSessionsApi", 34), Map.entry("ServerSkillsApi", 2), Map.entry("ServerSkillsConfigApi", 2), - Map.entry("ServerToolsApi", 1), Map.entry("ServerUserSettingsApi", 3), Map.entry("SessionAgentApi", 7), + Map.entry("ServerToolsApi", 1), Map.entry("ServerUserSettingsApi", 3), Map.entry("SessionAccountsApi", 3), + Map.entry("SessionAccountsLoginApi", 3), Map.entry("SessionAgentApi", 7), Map.entry("SessionAutopilotObjectiveApi", 1), Map.entry("SessionCanvasActionApi", 1), Map.entry("SessionCanvasApi", 4), Map.entry("SessionCanvasProviderApi", 2), Map.entry("SessionCommandsApi", 8), Map.entry("SessionCompletionsApi", 2), Map.entry("SessionConnectorsApi", 11), Map.entry("SessionContentExclusionApi", 1), Map.entry("SessionCustomizationsApi", 1), Map.entry("SessionDebugApi", 1), - Map.entry("SessionEventLogApi", 4), Map.entry("SessionExtensionsApi", 5), - Map.entry("SessionFactoryApi", 13), Map.entry("SessionFactoryJournalApi", 2), - Map.entry("SessionFleetApi", 1), Map.entry("SessionGitHubAuthApi", 10), Map.entry("SessionHistoryApi", 10), + Map.entry("SessionEventLogApi", 4), Map.entry("SessionExtensionsApi", 5), Map.entry("SessionFleetApi", 1), + Map.entry("SessionGitHubAuthApi", 10), Map.entry("SessionHistoryApi", 10), Map.entry("SessionInstructionsApi", 2), Map.entry("SessionLimitPredictionApi", 2), Map.entry("SessionManagedSettingsApi", 1), Map.entry("SessionLspApi", 1), Map.entry("SessionMcpApi", 18), Map.entry("SessionDiagnosticsApi", 2), Map.entry("SessionMcpAppsApi", 6), @@ -321,13 +321,13 @@ void remainingGeneratedMethodsUseExactEntryPoints() { rpc.eventLog.releaseInterest(params(SessionEventLogReleaseInterestParams.class, "{}")); rpc.eventLog.tail(); rpc.extensions.sendAttachmentsToMessage(params(SessionExtensionsSendAttachmentsToMessageParams.class, "{}")); - rpc.factory.cancel(params(SessionFactoryCancelParams.class, "{}")); - rpc.factory.getRunDetail(params(SessionFactoryGetRunDetailParams.class, "{}")); - rpc.factory.getRunProgress(params(SessionFactoryGetRunProgressParams.class, "{}")); - rpc.factory.listRuns(params(SessionFactoryListRunsParams.class, "{}")); - rpc.factory.pauseAtCheckpoint(params(SessionFactoryPauseAtCheckpointParams.class, "{}")); - rpc.factory.resumeFromTool(params(SessionFactoryResumeFromToolParams.class, "{}")); - rpc.factory.runFromTool(params(SessionFactoryRunFromToolParams.class, "{}")); + rpc.workflow.cancel(params(SessionWorkflowCancelParams.class, "{}")); + rpc.workflow.getRunDetail(params(SessionWorkflowGetRunDetailParams.class, "{}")); + rpc.workflow.getRunProgress(params(SessionWorkflowGetRunProgressParams.class, "{}")); + rpc.workflow.listRuns(params(SessionWorkflowListRunsParams.class, "{}")); + rpc.workflow.pauseAtCheckpoint(params(SessionWorkflowPauseAtCheckpointParams.class, "{}")); + rpc.workflow.resumeFromTool(params(SessionWorkflowResumeFromToolParams.class, "{}")); + rpc.workflow.runFromTool(params(SessionWorkflowRunFromToolParams.class, "{}")); rpc.gitHubAuth.getAllAuthAvailable(); rpc.gitHubAuth.getCurrentAuthInfo(); rpc.gitHubAuth.lastAuthErrors(); @@ -631,7 +631,7 @@ void sessionControlRpcsSerializeRequestsAndProjectUnionsAndState() throws Except } @Test - void factoryAndMcpRpcsSerializeRequestsAndProjectStateTransitions() throws Exception { + void workflowAndMcpRpcsSerializeRequestsAndProjectStateTransitions() throws Exception { try (var runtime = new RpcSurfaceTestCli(RpcSurfaceParityE2ETest::handle); var client = createClient(runtime)) { client.start().get(TIMEOUT_SECONDS, TimeUnit.SECONDS); try (var session = client @@ -639,49 +639,49 @@ void factoryAndMcpRpcsSerializeRequestsAndProjectStateTransitions() throws Excep .get(TIMEOUT_SECONDS, TimeUnit.SECONDS)) { var rpc = session.getRpc(); - var run = rpc.factory.run(params(SessionFactoryRunParams.class, """ - {"name":"rpc-factory","args":{"input":42}, + var run = rpc.workflow.run(params(SessionWorkflowRunParams.class, """ + {"name":"rpc-workflow","args":{"input":42}, "options":{"limits":{"maxAiCredits":2.5,"maxConcurrentSubagents":2, "maxTotalSubagents":4,"timeoutSeconds":30}, "logPhaseNames":true,"notifyOnComplete":false}} """)).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - assertEquals("factory-run-1", run.runId()); - assertEquals(FactoryRunStatus.RUNNING, run.status()); + assertEquals("workflow-run-1", run.runId()); + assertEquals(WorkflowRunStatus.RUNNING, run.status()); assertEquals(1L, run.attempt()); - var resumed = rpc.factory.resume(params(SessionFactoryResumeParams.class, """ - {"runId":"factory-run-1","limits":{"maxTotalSubagents":8}, + var resumed = rpc.workflow.resume(params(SessionWorkflowResumeParams.class, """ + {"runId":"workflow-run-1","limits":{"maxTotalSubagents":8}, "notifyOnComplete":true,"logPhaseNames":false} """)).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - assertEquals("rpc-factory", resumed.factoryName()); + assertEquals("rpc-workflow", resumed.workflowName()); assertEquals(2L, resumed.run().attempt()); - assertEquals(FactoryRunStatus.RUNNING, - rpc.factory.getRun(new SessionFactoryGetRunParams(null, "factory-run-1")) + assertEquals(WorkflowRunStatus.RUNNING, + rpc.workflow.getRun(new SessionWorkflowGetRunParams(null, "workflow-run-1")) .get(TIMEOUT_SECONDS, TimeUnit.SECONDS).status()); - assertEquals(FactoryRunStatus.PAUSED, - rpc.factory.pause(new SessionFactoryPauseParams(null, "factory-run-1")) + assertEquals(WorkflowRunStatus.PAUSED, + rpc.workflow.pause(new SessionWorkflowPauseParams(null, "workflow-run-1")) .get(TIMEOUT_SECONDS, TimeUnit.SECONDS).status()); - rpc.factory.log(params(SessionFactoryLogParams.class, """ - {"runId":"factory-run-1","executionToken":"execution-token-1", - "lines":[{"kind":"log","seq":7,"text":"Factory progress"}]} + rpc.workflow.log(params(SessionWorkflowLogParams.class, """ + {"runId":"workflow-run-1","executionToken":"execution-token-1", + "lines":[{"kind":"log","seq":7,"text":"Workflow progress"}]} """)).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); - var agent = rpc.factory.agent(params(SessionFactoryAgentParams.class, """ - {"runId":"factory-run-1","executionToken":"execution-token-1", + var agent = rpc.workflow.agent(params(SessionWorkflowAgentParams.class, """ + {"runId":"workflow-run-1","executionToken":"execution-token-1", "prompt":"Complete the RPC task.", "options":{"agent":"explore","label":"rpc-agent","model":"model-a", "reasoningEffort":"high"}} """)).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); assertEquals("agent-result", ((Map) agent.result()).get("answer")); - var journal = rpc.factory.journal.get( - new SessionFactoryJournalGetParams(null, "factory-run-1", "execution-token-1", "checkpoint")) + var journal = rpc.workflow.journal.get( + new SessionWorkflowJournalGetParams(null, "workflow-run-1", "execution-token-1", "checkpoint")) .get(TIMEOUT_SECONDS, TimeUnit.SECONDS); assertTrue(journal.hit()); assertEquals(7, ((Map) journal.resultJson()).get("checkpoint")); - rpc.factory.journal.put(params(SessionFactoryJournalPutParams.class, """ - {"runId":"factory-run-1","executionToken":"execution-token-1", + rpc.workflow.journal.put(params(SessionWorkflowJournalPutParams.class, """ + {"runId":"workflow-run-1","executionToken":"execution-token-1", "key":"checkpoint","resultJson":{"checkpoint":8}} """)).get(TIMEOUT_SECONDS, TimeUnit.SECONDS); @@ -713,14 +713,14 @@ void factoryAndMcpRpcsSerializeRequestsAndProjectStateTransitions() throws Excep assertEquals("resource-content", content.text()); assertEquals("assistant", content.meta().get("audience")); - assertCalledOnce(runtime, "session.factory.run", "session.factory.resume", "session.factory.getRun", - "session.factory.pause", "session.factory.log", "session.factory.agent", - "session.factory.journal.get", "session.factory.journal.put", + assertCalledOnce(runtime, "session.workflow.run", "session.workflow.resume", "session.workflow.getRun", + "session.workflow.pause", "session.workflow.log", "session.workflow.agent", + "session.workflow.journal.get", "session.workflow.journal.put", "session.mcp.moveLoadingToBackground", "session.mcp.startServer", "session.mcp.oauth.authenticationStateChanged", "session.mcp.oauth.respond", "session.mcp.resources.list", "session.mcp.resources.listTemplates", "session.mcp.resources.read"); - assertEquals(42, parameters(runtime, "session.factory.run").path("args").path("input").asInt()); + assertEquals(42, parameters(runtime, "session.workflow.run").path("args").path("input").asInt()); assertEquals("resource-cursor", parameters(runtime, "session.mcp.resources.list").path("cursor").asText()); } @@ -909,22 +909,22 @@ private static JsonNode handle(JsonNode request) { case "session.log" -> json(""" {"eventId":"11111111-2222-3333-4444-555555555555"} """); - case "session.factory.run", "session.factory.getRun" -> json(""" - {"runId":"factory-run-1","status":"running","attempt":1, + case "session.workflow.run", "session.workflow.getRun" -> json(""" + {"runId":"workflow-run-1","status":"running","attempt":1, "result":{"value":"running"},"snapshot":{"step":1}} """); - case "session.factory.resume" -> json(""" - {"factoryName":"rpc-factory","run":{"runId":"factory-run-1","status":"running", + case "session.workflow.resume" -> json(""" + {"workflowName":"rpc-workflow","run":{"runId":"workflow-run-1","status":"running", "attempt":2,"snapshot":{"step":3}}} """); - case "session.factory.pause" -> json(""" - {"runId":"factory-run-1","status":"paused","attempt":1, + case "session.workflow.pause" -> json(""" + {"runId":"workflow-run-1","status":"paused","attempt":1, "reason":"caller requested pause","snapshot":{"step":2}} """); - case "session.factory.agent" -> json(""" + case "session.workflow.agent" -> json(""" {"result":{"answer":"agent-result"}} """); - case "session.factory.journal.get" -> json(""" + case "session.workflow.journal.get" -> json(""" {"hit":true,"resultJson":{"checkpoint":7}} """); case "session.mcp.moveLoadingToBackground" -> json(""" diff --git a/nodejs/docs/extensions.md b/nodejs/docs/extensions.md index 15577bfdd0..5a50d9db3f 100644 --- a/nodejs/docs/extensions.md +++ b/nodejs/docs/extensions.md @@ -78,5 +78,4 @@ An approved extension can pass a granted value to anything it starts, so ask onl - `examples.md` — Practical code examples for tools, hooks, events, and complete extensions - `workflows.md` — Authoring, running, resuming, and observing Dynamic Workflows -- `factories.md`: Authoring, running, resuming, and observing Agent Factories - `agent-author.md` — Step-by-step workflow for agents authoring extensions programmatically diff --git a/nodejs/docs/factories.md b/nodejs/docs/factories.md deleted file mode 100644 index f07230a839..0000000000 --- a/nodejs/docs/factories.md +++ /dev/null @@ -1,296 +0,0 @@ -# Agent Factories - -Agent Factories are extension-authored, session-scoped workflows that coordinate subagents and durable steps. The API is experimental. - -## Define and register a factory - -Use `defineFactory` and pass the returned handle to `joinSession`: - -```js -import { defineFactory, joinSession } from "@github/copilot-sdk/extension"; - -const reviewChanged = defineFactory({ - meta: { - name: "review-changed", - description: - "Review changed files and verify the findings. " + - "args: { files: string[] } — the paths to review.", - phases: [{ title: "Review" }, { title: "Verify" }], - argsSchema: { - type: "object", - required: ["files"], - properties: { - files: { type: "array", items: { type: "string" } }, - }, - }, - }, - run: async (ctx) => { - ctx.phase("Review"); - const reviews = await ctx.parallel( - ctx.args.files.map( - (file) => () => ctx.agent(`Review ${file}`, { label: `Review ${file}` }) - ) - ); - - ctx.phase("Verify"); - const report = await ctx.step("report", () => ({ reviews })); - ctx.log(`Completed factory run ${ctx.runId}`); - return report; - }, -}); - -const session = await joinSession({ factories: [reviewChanged] }); -``` - -Factory metadata contains a stable `name`, a human-readable `description`, declared `phases`, an optional `argsSchema`, and optional `limits`. Phase entries contain a `title` and optional `detail`. - -## Declaring an argument shape - -A factory that reads `ctx.args` should declare `meta.argsSchema`, as the example above does. When the model invokes the factory through the `run_factory` tool, the CLI validates `args` against the declaration **before** the run starts. - -Declaring one turns an expensive failure into a cheap one. With a schema, a malformed call is rejected up front — the model gets a correction hint and retries, and no run row, permission prompt, or credit spend happens. Without one, nothing validates: the run starts, takes a user approval, spends credits, and then dies inside the factory body with a confusing error. Agents can read the declared shape with `factories_manage` using `operation: "inspect"`. - -Enforcement covers structure — types, required properties, and enum or const values. Finer constraints such as `minLength`, `pattern`, or `additionalProperties` are recorded in the declaration but not enforced. The accepted vocabulary is the `FactoryJsonSchema` subset also used for subagent structured output: `type`, `required`, `enum`, `const`, recursive `properties`/`items`, and `anyOf`/`oneOf`/`allOf`. A `type` is one of `null`, `boolean`, `integer`, `number`, `string`, `array`, or `object`, or a non-empty array of those such as `["object", "null"]`. A declaration outside that subset is rejected at registration. - -`argsSchema` is optional and backward compatible. A factory that omits it behaves exactly as before, so **the `description` is then the only thing telling an agent what arguments to supply** — state the expected shape there. - -Validation covers the model's `run_factory` path only. An extension calling `session.factory.run(...)` directly is not validated against `argsSchema`; those arguments are typed through `defineFactory` instead, and that typing does not reach the model. So a factory that reads `ctx.args` should still validate it rather than assume a shape — the declared subset does not enforce every constraint, and it does not run at all on the SDK path. - -`defineFactory` accepts a `run(context)` function returning `Promise`, where `TResult` is `JsonValue | void`. Objects, arrays, strings, numbers, booleans, and `null` are valid results. Returning `undefined` completes the factory with no result. Other non-JSON values are rejected. - -## Factory context - -The `run()` context provides: - -* `ctx.runId`: Stable ID reused across resumed attempts. -* `ctx.args`: Invocation arguments, forwarded verbatim. When the caller omits `args`, this is `{}` rather than `undefined`. -* `ctx.agent(prompt, options?)`: Runs one factory-owned subagent. Options are exactly `label`, `schema`, `model`, `agent`, `reasoningEffort`, and `contextTier`. See [Subagent calls](#subagent-calls). -* `ctx.parallel(thunks)`: Runs thunks concurrently and awaits all of them (a barrier). A thunk that throws becomes `null` in the result array, so one failed item does not lose the rest. Cancellation and hard runtime failures (`ResponseError`, `ConnectionError`) are the exception — those propagate and reject the whole call, because they mean the run itself is in trouble rather than one item having failed. Handle them at run level; do not assume every failure arrives as a `null`. Rejects above 4096 items. -* `ctx.pipeline(items, ...stages)`: Flows each item through every stage without a barrier between stages, so one item can be in a later stage while another is still in an earlier one. Each stage is called as `(previous, item, index)`, where `previous` is the prior stage's result and `item` is the original input. A stage that throws drops that item to `null` and skips its remaining stages, with the same exception for cancellation and hard runtime failures. Rejects above 4096 items. -* `ctx.phase(title)`: Starts a named progress phase. This sets a single run-global value, so calling it from inside concurrent `parallel`/`pipeline` stages races. Call it at run-level transitions and distinguish concurrent work by `label` instead. -* `ctx.log(message)`: Appends a progress line. When a factory bounds its own coverage (top-N, sampling), log what was dropped. -* `ctx.step(key, producer, options?)`: Journals the producer's JSON result under a stable key so a resume replays it without re-running the producer. A journaled (default) producer must return a JSON-serializable value; `undefined` or a non-JSON value is rejected. Pass `{ volatile: true }` to bypass the journal and run the producer every time. - - The key is the *sole* identity: neither the producer body nor its inputs contribute to it. A resume replays the cached value for a matching key even if the producer has since changed, so version the key (`"scan-v2"`) whenever its inputs or meaning change. Journaled producers are best-effort at-least-once and may run again across crashes or concurrent same-key callers, so keep side effects idempotent. -* `ctx.pause(key)`: Pauses at a durable, one-shot checkpoint. The first attempt records the checkpoint, pauses, and throws `AbortError` after cooperative cancellation. When the run resumes, the factory starts again and the same checkpoint returns so execution can continue. Call it only from the main factory flow, not inside `ctx.parallel()` or `ctx.pipeline()`. -* `ctx.session`: The session returned by `joinSession`. It refuses calls that start, resume, or pause a factory run. Call `extensions_manage` with `operation: "guide"` to read more about the session APIs. -* `ctx.signal`: Cooperative cancellation signal for extension work and subprocesses. -* `ctx.factory(...)`: Always rejects because nested factories are not supported. - -Factory-owned subagents are intentionally hidden from `read_agent` and `write_agent`. Use the factory observability APIs instead. - -### Subagent calls - -`ctx.agent(prompt, options?)` spawns one factory-scoped subagent and awaits it. Without a schema it resolves to the subagent's final text. With `options.schema` it resolves to the parsed JSON value. - -**Identical calls are memoized into one subagent.** Each call is journaled by its canonical prompt and options, including `label`. Two calls with the same prompt and the same options return one shared result — even when issued concurrently. To spawn N *independent* subagents, give each a unique `label` or vary the prompt: - -```js -// One subagent, awaited five times — almost certainly not what you want. -await ctx.parallel([1, 2, 3, 4, 5].map(() => () => ctx.agent("Find a bug"))); - -// Five independent subagents. -await ctx.parallel( - [1, 2, 3, 4, 5].map((i) => () => ctx.agent("Find a bug", { label: `finder:${i}` })) -); -``` - -**An ordinary failure resolves to `null` — it does not throw.** A subagent that errors, returns nothing, or (with a schema) produces output that still fails to parse or match after its one retry resolves `null`. Always guard the result before using it, including a bare `await ctx.agent(...)`: - -```js -const finding = await ctx.agent(prompt, { label: "inspector" }); -if (!finding) return { finding: null }; -``` - -Cancellation and hard runtime failures — a reached limit, a durable-state failure — reject instead, aborting the run. When filtering results, prefer `v => v !== null` over `Boolean`, which also discards a valid `false`, `0`, or `""`. - -**`schema` is a structural subset of JSON Schema, not a validator.** Honored: `type`, `required`, `enum`, `const`, recursive `properties`/`items`, and `anyOf`/`oneOf`/`allOf` — where `oneOf` is treated as `anyOf`, meaning at least one branch matches rather than exactly one. Ignored and *not* enforced: `additionalProperties`, `pattern`, `minLength`/`maxLength`, `format`, numeric ranges, and boolean schemas. Do not rely on an ignored keyword to constrain a result. A schema call retries once on a parse or match failure, so it may spawn twice, and both spawns count toward `maxTotalSubagents`. - -### Choosing between pipeline and parallel - -Prefer `pipeline` for multi-stage work. It has no barrier between stages, so each item advances as soon as its own prior stage finishes. - -Reach for a barrier — `parallel` between stages — only when a stage genuinely needs every prior result at once: deduplicating or merging across the full set, an early exit based on the total, or a prompt that compares one result against the others. Needing to map, filter, or flatten is not a reason to use a barrier; do that inside a pipeline stage. Barrier latency is real: if the slowest of N subagents takes three times the fastest, a barrier wastes the rest of the pool's time. - -See [factory-patterns.md](./factory-patterns.md) for composable orchestration patterns built on these primitives. - -## Resource limits - -Limits may be declared in `meta.limits` and overridden per invocation. Every limit is optional and must be positive when present; an omitted limit leaves that dimension unbounded, except that an omitted `maxConcurrentSubagents` falls back to `maxTotalSubagents`, so a declared total cap also bounds concurrency. - -Set a ceiling only from real knowledge of what the factory costs, or because the user named one. A guessed ceiling does not make a run safer: it stops a healthy run partway with `factory_limit_reached`, after that run has already spent credits. An agent authoring or invoking a factory on the user's behalf has no basis for estimating a number, so it should leave `limits` unset and bound the work with the factory's own counters instead. Omitting limits does not remove oversight of a model-initiated run: `run_factory` requests permission first, and that prompt shows the effective limits. SDK-initiated `run` and `resume` do not request permission, so an SDK caller that wants a ceiling sets it deliberately, from the cost it already knows. - -```js -// Only when the cost profile is known, or the user asked for this ceiling. -limits: { maxTotalSubagents: 10 }, -``` - -- `maxConcurrentSubagents`: Positive integer concurrent-subagent cap. Additional subagents wait in a queue. Queueing applies backpressure and does not fail the run. -- `maxTotalSubagents`: Positive integer cumulative admission cap. An attempted subagent beyond the cap ends the attempt with failure kind `maxTotalSubagents`. -- `timeoutSeconds`: Positive finite number of seconds, including positive fractions, capped at `2_147_483.647`. It measures accumulated active-execution time across attempts, including the extension body, subprocess waits, queued-agent waits, and sleeps. Time between attempts is excluded. The timeout is soft because already-running work may take time to stop. Its failure kind is `timeoutSeconds`. -- `maxAiCredits`: Positive finite AI-credit budget for the whole run's factory subagent subtree, including descendants. AI credits are GitHub Copilot's universal usage metric. This is a soft, post-paid ceiling, so completed or parallel turns can settle above it before the run stops. Accounting is fail-closed: an accounting failure stops a budgeted run rather than allowing untracked use. Its failure kind is `maxAiCredits`. - -`maxTotalSubagents`, `timeoutSeconds`, and `maxAiCredits` use reject-and-retry semantics. A rejected attempt ends with run status `error` and `failure.type` set to `factory_limit_reached`. The failed run keeps its ID, arguments, journal, and accounting. Resume the run with a raised limit when additional work is approved. Previously consumed resources still count. - -## Run and resume - -Run by registered name or handle: - -```ts -const run = await session.factory.run("review-changed", { - args: { files: ["src/a.ts"] }, - limits: { maxAiCredits: 3 }, - notifyOnComplete: true, - logPhaseNames: true, -}); - -if (run.status === "completed") { - console.log(run.result); -} else { - console.error(`run ${run.runId} ended as ${run.status}`, run.failure ?? run.error); -} -``` - -The name overload is: - -```ts -session.factory.run( - name: string, - options?: { - args?: JsonValue; - limits?: FactoryLimitOverrides; - notifyOnComplete?: boolean; - logPhaseNames?: boolean; - }, -): Promise; -``` - -Resume by run ID without resending the name or arguments: - -```ts -const run = await session.factory.resume(runId, { - limits: { maxAiCredits: 6 }, - notifyOnComplete: true, - logPhaseNames: true, -}); -``` - -The signature is: - -```ts -session.factory.resume( - runId: string, - options?: { - limits?: FactoryLimitOverrides; - notifyOnComplete?: boolean; - logPhaseNames?: boolean; - }, -): Promise; -``` - -Set `notifyOnComplete` to `true` for factories that are likely to be invoked by an agent, so the originating session is notified when the factory completes. Set it to `false` for factories intended to be invoked programmatically, where the caller awaits the result directly. Set `logPhaseNames` to emit factory phase names to the session transcript. Both options apply to new and resumed runs. - -Both resolve with the run envelope (`FactoryRunResult`) for **every** outcome—`completed`, `error`, `halted`, `paused`, and `cancelled` alike. Inspect `status` and read `result` only when the run completed; a limit breach carries a typed `failure`. A `paused` envelope means that the current attempt settled, not that the durable run is permanently finished. Resume the same run ID to start another attempt with its journal and accounting intact. SDK-initiated `run` and `resume` do not request permission, so they have no declined outcome. The model's `run_factory` tool requests permission before the durable row exists; declining it creates no run row. An SDK-initiated run is refused only when the session already has its maximum number of active top-level runs. Pre-execution resume failures throw `FactoryResumeError`, whose `code` is one of `not_found`, `non_resumable`, `already_active`, `factory_already_running`, `factory_limits_invalid`, `factory_session_disposed`, `factory_storage_unavailable`, or `factory_storage_corrupt`. - -An agent that no longer has a prior run's ID in context can recover it with `factories_manage` and `operation: "runs"`, which lists the session's factory runs with their IDs and statuses. This matters for resume: a run that reached a limit keeps its journal, so resuming it replays completed work for free, while restarting it from scratch pays for that work twice. - -Pause a running attempt from outside its factory body: - -```ts -const paused = await session.factory.pause(runId); -``` - -Inside a factory body, use a durable checkpoint instead: - -```ts -await ctx.step("prepare", prepareInput); -await ctx.pause("review-ready"); -await ctx.agent("Review the prepared input"); -``` - -The first attempt pauses at `"review-ready"` and ends through cooperative cancellation. On resume, the factory starts from the beginning, reuses the journaled step, returns from the checkpoint, and continues. - -The agent-facing `run_factory` tool has exactly two input branches: - -```ts -{ name: string; args?: JsonValue; limits?: FactoryLimitOverrides } -{ resumeFromRunId: string; limits?: FactoryLimitOverrides } -``` - -## Authoring a factory from inside a session - -The agent-facing `factories_manage` tool writes a factory into a session-scoped extension at runtime with `operation: "author"`. The rules above all apply, plus one constraint that does not affect an extension author. - -**The `run` body is self-contained.** It is emitted verbatim into a generated module as a single async function expression. It closes over nothing: not the conversation that authored it, and not any authoring-time binding. Only its own locals, its `ctx` parameter, and standard Node and JavaScript globals are in scope, so every schema, constant, and helper must be defined *inside* the function. The generated module imports the SDK itself; the expression cannot add static `import` statements or use `require`. Load anything else with a dynamic `await import("...")` in the body. - -```js -async ({ args, agent, phase }) => { - // Defined inside — there is no outer scope to close over. - const VERDICT = { type: "object", properties: { real: { type: "boolean" } }, required: ["real"] }; - - phase("Inspect"); - const finding = await agent(`Name one likely bug in ${args.file ?? "the code"}.`, { - label: "inspector", - }); - if (!finding) return { finding: null, real: false }; - - phase("Verify"); - const verdict = await agent(`Is this a real bug? Claim: ${finding}`, { - label: "verifier", - schema: VERDICT, - }); - return { finding, real: verdict?.real === true }; -}; -``` - -Authoring registers the factory but does not run it. Invoke it afterwards with `run_factory`. Use `factories_manage` with `operation: "list"` to see the factories already registered in the session and `operation: "inspect"` to read one factory's description, phases, declared argument shape, and limits before running it. - -## Observe a run - -The calling session can inspect its own factory runs: - -```ts -const runs = await session.factory.listRuns(); -const runsPage = await session.factory.listRuns({ - afterSeq, - beforeSeq, - limit, -}); -const detail = await session.factory.getRunDetail(runId); -const progressPage = await session.factory.getRunProgress(runId, { - phaseId, - afterSeq, - beforeSeq, - limit, -}); -``` - -- `listRuns()` returns only the runs array from the newest default page of this session's durable factory runs. This overload preserves the original convenience API. -- `listRuns({ afterSeq, beforeSeq, limit })` returns the full page. Its `oldestSeq`, `newestSeq`, `hasMoreNewer`, and `omittedOlder` fields let callers continue paging without raw RPC calls. -- `getRunDetail(runId)` returns phases, prompt-safe agent summaries, and the latest progress page. -- `getRunProgress(runId, options?)` pages progress forward, backward, by phase, or from the latest tail. - -`getRun(runId)` reads the latest run envelope. `pause(runId)` pauses a running attempt and returns its `paused` envelope. `cancel(runId)` cancels a run and returns its terminal envelope. - -`waitForRun(runId, options?)` resolves with the current attempt's envelope once it settles into `completed`, `error`, `halted`, `paused`, or `cancelled`. It resolves immediately when the current attempt has already settled: - -```ts -const settled = await session.factory.waitForRun(runId); -if (settled.status === "completed") { - console.log(settled.result); -} -``` - -It watches `factory.run_updated` and re-reads the durable envelope on each invalidation, collapsing a burst of events into a single in-flight read. A low-frequency periodic re-read runs alongside the subscription, so a dropped or missing invalidation degrades into a slightly late resolution rather than an unbounded wait. Pass a `signal` to stop waiting: - -```ts -const controller = new AbortController(); -setTimeout(() => controller.abort(), 30_000); -const settled = await session.factory.waitForRun(runId, { signal: controller.signal }); -``` - -Aborting rejects the wait and has no effect on the run, which keeps executing—use `pause(runId)` or `cancel(runId)` to stop it. The resolved object is a snapshot of that settled attempt. If its status is `paused`, a later resume updates the durable envelope under the same run ID. Call `getRun(runId)` to read the latest envelope. `isFactoryRunTerminal(status)` exposes the same current-attempt settlement test for callers driving their own loop. - -Listen for the ephemeral `factory.run_updated` event. Its `{ runId, revision }` payload is an invalidation signal. Re-read the desired API when a newer monotonic revision arrives. - -Revisions cover durable lifecycle, accounting, phase, agent, and progress changes. Continuous read-time fields can change without a new revision. These include `observedAt`, active-time calculations, live counts, and a live agent's status or prompt-safe activity text. Factory prompts are never exposed by these APIs. A run is visible only through the session that owns it. diff --git a/nodejs/docs/factory-patterns.md b/nodejs/docs/factory-patterns.md deleted file mode 100644 index 8ae403d55a..0000000000 --- a/nodejs/docs/factory-patterns.md +++ /dev/null @@ -1,194 +0,0 @@ -# Agent Factory patterns - -Composable orchestration patterns built on the factory context. Read [factories.md](./factories.md) first for the API and its semantics. The API is experimental. - -Every snippet below assumes the surrounding `async (ctx) => { ... }` run body and destructures the hooks it uses. Three rules apply throughout, because breaking them fails silently: - -- **Give every independent subagent a unique `label`.** Identical prompt-and-options pairs memoize into a single shared subagent. -- **Guard every `agent()` result.** An ordinary failure resolves to `null` rather than throwing. -- **Filter with `v => v !== null`,** not `Boolean`, which also discards a valid `false`, `0`, or `""`. - -## Multi-stage review - -The default shape: fan out across dimensions, and let each dimension verify as soon as its own review lands. No barrier, so a slow dimension never holds up a fast one. - -```js -async ({ pipeline, parallel, agent, phase, log }) => { - const FINDINGS = { - type: "object", - properties: { - findings: { - type: "array", - items: { - type: "object", - properties: { title: { type: "string" } }, - required: ["title"], - }, - }, - }, - required: ["findings"], - }; - const VERDICT = { - type: "object", - properties: { isReal: { type: "boolean" } }, - required: ["isReal"], - }; - const DIMENSIONS = [ - { key: "bugs", prompt: "Review the diff for correctness bugs. Return JSON {findings:[{title}]}." }, - { key: "perf", prompt: "Review the diff for performance issues. Return JSON {findings:[{title}]}." }, - ]; - - phase("Review"); // Run-global: set it before the fan-out, never inside a stage. - const perDimension = await pipeline( - DIMENSIONS, - (d) => agent(d.prompt, { label: `review:${d.key}`, schema: FINDINGS }), - (review, d) => { - if (!review) { - log(`review:${d.key} produced nothing`); - return []; - } - return parallel( - (review.findings ?? []).map((f, i) => () => - agent(`Adversarially verify this finding is real: ${f.title}`, { - label: `verify:${d.key}:${i}`, - schema: VERDICT, - }).then((v) => (v && v.isReal ? f : null)) - ) - ); - } - ); - - return { confirmed: perDimension.flat().filter((v) => v !== null) }; -}; -``` - -## When a barrier is correct - -Deduplicating across every finding needs the whole set in hand, so the barrier earns its cost here. Dedup itself is plain JavaScript, done in the body between the two fan-outs. This excerpt reuses `FINDINGS`, `VERDICT`, and `DIMENSIONS` from the previous example — define them inside your own function. - -```js -const all = await parallel( - DIMENSIONS.map((d) => () => agent(d.prompt, { label: `find:${d.key}`, schema: FINDINGS })) -); -const findings = all.filter((v) => v !== null).flatMap((r) => r.findings ?? []); -const deduped = [...new Map(findings.map((f) => [f.title, f])).values()]; // Needs all of them. -const verified = await parallel( - deduped.map((f, i) => () => agent(`Verify: ${f.title}`, { label: `verify:${i}`, schema: VERDICT })) -); -``` - -## Loop until count - -Accumulate toward a target. Each iteration needs a unique identity — a unique label plus a prompt that excludes what has already been found — a bounded attempt count, and a null guard. - -```js -const BUG = { - type: "object", - properties: { title: { type: "string" } }, - required: ["title"], -}; - -const bugs = []; -let attempt = 0; -while (bugs.length < 10 && attempt < 30) { - const r = await agent( - `Find ONE distinct bug NOT already listed: ${JSON.stringify(bugs.map((b) => b.title))}. Return JSON {title}.`, - { label: `finder:${attempt}`, schema: BUG } - ); - attempt++; - if (r && r.title) bugs.push(r); - log(`${bugs.length}/10 found`); -} -``` - -## Loop until dry - -Keep spawning finders until some number of consecutive rounds surface nothing new. Deduplicate against everything *seen*, not just what was kept, or discarded findings resurface every round. - -```js -const BUGS = { - type: "object", - properties: { - bugs: { - type: "array", - items: { type: "object", properties: { title: { type: "string" } }, required: ["title"] }, - }, - }, - required: ["bugs"], -}; -const VERDICT = { - type: "object", - properties: { real: { type: "boolean" } }, - required: ["real"], -}; - -const seen = new Set(); -const confirmed = []; -const keyOf = (b) => b.title.toLowerCase(); -let dry = 0; -let round = 0; - -while (dry < 2 && round < 20) { - const found = ( - await parallel( - [0, 1, 2].map((i) => () => - agent(`Find bugs (finder ${i}, round ${round}). Return JSON {bugs:[{title}]}.`, { - label: `find:${round}:${i}`, - schema: BUGS, - }) - ) - ) - ) - .filter((v) => v !== null) - .flatMap((r) => r.bugs ?? []); - - const fresh = found.filter((b) => { - const k = keyOf(b); - if (seen.has(k)) return false; - seen.add(k); - return true; - }); - - if (!fresh.length) { - dry++; - round++; - continue; - } - dry = 0; - - const judged = await parallel( - fresh.map((b, i) => () => - parallel( - ["correctness", "security", "repro"].map((lens) => () => - agent(`Judge via ${lens}: is "${b.title}" real? Return JSON {real}.`, { - label: `judge:${round}:${i}:${lens}`, - schema: VERDICT, - }) - ) - ).then((vs) => ({ b, real: vs.filter((v) => v !== null).filter((v) => v.real).length >= 2 })) - ) - ); - - confirmed.push(...judged.filter((v) => v !== null && v.real).map((v) => v.b)); - round++; -} -``` - -## Quality patterns - -Compose these freely. - -- **Adversarial verify.** Spawn several independent skeptics per finding, each prompted to *refute* it and to default to refuted when uncertain. Keep only what a majority fails to refute. -- **Perspective-diverse verify.** Give each verifier a distinct lens — correctness, security, performance, does-it-reproduce — instead of several identical skeptics. The distinct prompts also stop them memoizing into one subagent. -- **Judge panel.** Generate several independent attempts from different angles, score them with parallel judges, then synthesize from the winner while grafting the best ideas from the runners-up. -- **Multi-modal sweep.** Run parallel searchers that each look a different way: by container, by content, by entity, by time. -- **Completeness critic.** End with an agent asking what is missing — an angle not run, a claim unverified, a source unread — and use its answer to seed the next round. -- **No silent caps.** When the factory bounds its own coverage with a top-N, a sampling step, or a no-retry rule, `log()` what was dropped. - -## Scaling - -Match the orchestration to what was asked. A quick check wants a couple of subagents and single-vote verification; a request to be thorough or comprehensive wants a larger finder pool, a three-to-five vote adversarial pass, and a synthesis stage. - -There is no in-script budget object. Scale with your own counters, as in the loop patterns above, and treat any declared limits as the safety ceiling rather than the control mechanism. Only `agent()` spawns are throttled, by `maxConcurrentSubagents` falling back to `maxTotalSubagents`; with neither declared there is no built-in concurrency cap, so bound a wide fan-out with the factory's own counters. Do not invent a ceiling to compensate, and see [Resource limits](./factories.md#resource-limits) for when declaring one is appropriate. `parallel` itself is `Promise.all`, so non-agent work in a thunk runs fully concurrently regardless. - -These patterns are not exhaustive. Compose novel harnesses — tournament brackets, self-repair loops, staged escalation — when the task calls for it. diff --git a/nodejs/docs/workflows.md b/nodejs/docs/workflows.md index 821778fcd8..872cbcb0fe 100644 --- a/nodejs/docs/workflows.md +++ b/nodejs/docs/workflows.md @@ -2,8 +2,6 @@ Dynamic Workflows are extension-authored, session-scoped workflows that coordinate subagents and durable steps. The API is experimental. -Use Dynamic Workflows for new extension-authored orchestration. Existing Agent Factory extensions remain supported during the transition, but one `joinSession` call must register either `workflows` or `factories`, never both. - ## Define and register a workflow Use `defineWorkflow` and pass the returned handle to `joinSession`: @@ -242,7 +240,7 @@ if (settled.status === "completed") { } ``` -It watches the runtime's `factory.run_updated` compatibility event and re-reads the durable envelope on each invalidation, collapsing a burst of events into a single in-flight read. A low-frequency periodic re-read runs alongside the subscription, so a dropped or missing invalidation degrades into a slightly late resolution rather than an unbounded wait. Pass a `signal` to stop waiting: +It watches `workflow.run_updated` and re-reads the durable envelope on each invalidation, collapsing a burst of events into a single in-flight read. A low-frequency periodic re-read runs alongside the subscription, so a dropped or missing invalidation degrades into a slightly late resolution rather than an unbounded wait. Pass a `signal` to stop waiting: ```ts const controller = new AbortController(); @@ -252,6 +250,6 @@ const settled = await session.workflow.waitForRun(runId, { signal: controller.si Aborting rejects the wait and has no effect on the run, which keeps executing—use `pause(runId)` or `cancel(runId)` to stop it. The resolved object is a snapshot of that settled attempt. If its status is `paused`, a later resume updates the durable envelope under the same run ID. Call `getRun(runId)` to read the latest envelope. `isWorkflowRunTerminal(status)` exposes the same current-attempt settlement test for callers driving their own loop. -Listen for the ephemeral `factory.run_updated` compatibility event. Its `{ runId, revision }` payload is an invalidation signal. Re-read the desired API when a newer monotonic revision arrives. +Listen for the ephemeral `workflow.run_updated` event. Its `{ runId, revision }` payload is an invalidation signal. Re-read the desired API when a newer monotonic revision arrives. Revisions cover durable lifecycle, accounting, phase, agent, and progress changes. Continuous read-time fields can change without a new revision. These include `observedAt`, active-time calculations, live counts, and a live agent's status or prompt-safe activity text. Workflow prompts are never exposed by these APIs. A run is visible only through the session that owns it. diff --git a/nodejs/package.json b/nodejs/package.json index f6187b73d8..b5ee4a1872 100644 --- a/nodejs/package.json +++ b/nodejs/package.json @@ -5,7 +5,7 @@ "url": "https://github.com/github/copilot-sdk.git" }, "version": "0.0.0-dev", - "copilotCliVersion": "1.0.89-3", + "copilotCliVersion": "1.0.89-4", "description": "TypeScript SDK for programmatic control of GitHub Copilot CLI via JSON-RPC", "main": "./dist/cjs/index.js", "types": "./dist/index.d.ts", diff --git a/nodejs/src/cliVersion.ts b/nodejs/src/cliVersion.ts index a2c01fa144..8f38c41ec6 100644 --- a/nodejs/src/cliVersion.ts +++ b/nodejs/src/cliVersion.ts @@ -1,3 +1,3 @@ -export const COPILOT_CLI_VERSION = "1.0.89-3"; +export const COPILOT_CLI_VERSION = "1.0.89-4"; export const COPILOT_CLI_USE_NPM_PACKAGE = false; diff --git a/nodejs/src/client.ts b/nodejs/src/client.ts index f4f911c273..c812598d73 100644 --- a/nodejs/src/client.ts +++ b/nodejs/src/client.ts @@ -93,11 +93,9 @@ import type { TypedSessionLifecycleHandler, } from "./types.js"; import { defaultJoinSessionPermissionHandler } from "./types.js"; -import type { FactoryHandle } from "./factory.js"; import type { WorkflowHandle } from "./workflow.js"; interface ExtensionOrchestrationContributions { - factories?: FactoryHandle[]; workflows?: WorkflowHandle[]; } @@ -1817,20 +1815,7 @@ export class CopilotClient { async resumeSessionForExtension( sessionId: string, config: ResumeSessionConfig, - factories?: FactoryHandle[], - extensionOptions?: ExtensionJoinOptions - ): Promise; - /** @internal */ - async resumeSessionForExtension( - sessionId: string, - config: ResumeSessionConfig, - contributions?: ExtensionOrchestrationContributions, - extensionOptions?: ExtensionJoinOptions - ): Promise; - async resumeSessionForExtension( - sessionId: string, - config: ResumeSessionConfig, - contributions: FactoryHandle[] | ExtensionOrchestrationContributions = {}, + contributions: ExtensionOrchestrationContributions = {}, extensionOptions?: ExtensionJoinOptions ): Promise { return this.resumeSessionInternal(sessionId, config, contributions, extensionOptions); @@ -1839,15 +1824,10 @@ export class CopilotClient { private async resumeSessionInternal( sessionId: string, config: ResumeSessionConfig, - contributions: FactoryHandle[] | ExtensionOrchestrationContributions = {}, + contributions: ExtensionOrchestrationContributions = {}, extensionOptions?: ExtensionJoinOptions ): Promise { - const { factories, workflows } = Array.isArray(contributions) - ? { factories: contributions, workflows: undefined } - : contributions; - if (factories !== undefined && workflows !== undefined) { - throw new Error("Session configuration cannot include both factories and workflows"); - } + const { workflows } = contributions; if (config.gitHubToken !== undefined && config.gitHubTokenProvider !== undefined) { throw new Error("gitHubToken and gitHubTokenProvider are mutually exclusive"); } @@ -1871,7 +1851,6 @@ export class CopilotClient { session.registerTools(config.tools); session.registerCanvases(config.canvases); session.registerCommands(config.commands); - session.registerFactories(factories); session.registerWorkflows(workflows); const { wireProvider: bearerWireProvider, @@ -1958,7 +1937,6 @@ export class CopilotClient { })), toolSearch: config.toolSearch, canvases: config.canvases?.map((canvas) => canvas.declaration), - factories: factories?.map((factory) => factory.meta), workflows: workflows?.map((workflow) => workflow.meta), requestCanvasRenderer: config.requestCanvasRenderer, requestExtensions: config.requestExtensions, diff --git a/nodejs/src/extension.ts b/nodejs/src/extension.ts index e1b9a7f72a..e7bb21e3b2 100644 --- a/nodejs/src/extension.ts +++ b/nodejs/src/extension.ts @@ -9,7 +9,6 @@ import { type PermissionHandler, type ResumeSessionConfig, } from "./types.js"; -import type { FactoryHandle } from "./factory.js"; import type { WorkflowHandle } from "./workflow.js"; export { @@ -23,28 +22,6 @@ export { type CanvasOptions, } from "./canvas.js"; -type JoinSessionContributionConfig = - | { - /** - * Factory handles to register when the extension joins the session. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ - factories?: FactoryHandle[]; - workflows?: never; - } - | { - factories?: never; - /** - * Workflow handles to register when the extension joins the session. - * - * @experimental Part of the experimental Dynamic Workflows surface and may - * change or be removed in future SDK or CLI releases. - */ - workflows?: WorkflowHandle[]; - }; - export type JoinSessionConfig = Omit< ResumeSessionConfig, "onPermissionRequest" | "extensionSdkPath" @@ -79,37 +56,16 @@ export type JoinSessionConfig = Omit< * ``` */ requestedEnvironmentVariables?: string[]; -} & JoinSessionContributionConfig; + /** + * Workflow handles to register when the extension joins the session. + * + * @experimental Part of the experimental Dynamic Workflows surface and may + * change or be removed in future SDK or CLI releases. + */ + workflows?: WorkflowHandle[]; +}; -export type { ExtensionInfo, FactoryLimits, FactoryMeta } from "./types.js"; -export { - defineFactory, - FactoryResumeError, - isFactoryRunTerminal, - type RunOptions, - type ResumeOptions, - type FactoryResumeErrorCode, - type SessionFactoryApi, - type FactoryAgentOptions, - type FactoryContext, - type FactoryDefinition, - type FactoryHandle, - type FactoryJsonSchema, - type JsonValue, - type FactoryPipelineStage, - type FactoryStepOptions, - type FactoryRunResult, - type FactoryRunStatus, - type FactoryRunSummary, - type FactoryListRunsOptions, - type FactoryRunsPage, - type FactoryRunDetail, - type FactoryProgressPage, - type FactoryProgressLine, - type FactoryPhaseObservation, - type FactoryPhaseStatus, - type FactoryAgentSummary, -} from "./factory.js"; +export type { ExtensionInfo } from "./types.js"; export { defineWorkflow, WorkflowResumeError, @@ -123,6 +79,7 @@ export { type WorkflowContext, type WorkflowDefinition, type WorkflowHandle, + type JsonValue, type WorkflowJsonSchema, type WorkflowLimits, type WorkflowMeta, @@ -170,7 +127,6 @@ export async function joinSession(config: JoinSessionConfig = {}): Promise = new Set([ - "completed", - "halted", - "paused", - "cancelled", - "error", -]); - -/** - * Whether a factory run status is terminal. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export function isFactoryRunTerminal(status: FactoryRunStatus): boolean { - return FACTORY_TERMINAL_STATUSES.has(status); -} - -declare const factoryHandleBrand: unique symbol; - -/** A value that can be represented losslessly on the SDK JSON wire. */ -export type JsonValue = - | null - | boolean - | number - | string - | JsonValue[] - | { [key: string]: JsonValue }; - -/** - * Conservative JSON shape language accepted by the Agent Factories surface, for - * both structured factory agent output and a factory's declared `argsSchema`. - * - * This is a best-effort structural guard — used to decide whether a subagent's - * structured output should be accepted or retried, and whether a caller's - * factory `args` match the declared shape — **not** a full JSON Schema - * validator. Only these keywords are honored: `type`, `required`, `enum`, - * `const`, recursive `properties`/`items`, and `anyOf`/`oneOf`/`allOf`. A `type` - * is one of `null`, `boolean`, `integer`, `number`, `string`, `array`, or - * `object`, or a non-empty array of those (for example `["object", "null"]`). - * - * Everything else is **ignored, not enforced**. In particular, string - * constraints (`pattern`, `minLength`, `maxLength`, `format`), numeric ranges - * (`minimum`, `maximum`), `additionalProperties`, and boolean (`true`/`false`) - * schemas do not reject non-conforming output. `oneOf` is treated like `anyOf` - * (at least one branch must match) rather than strict exactly-one. Author - * schemas within this subset; do not rely on unsupported constraints for - * correctness. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export type FactoryJsonSchema = { [key: string]: JsonValue }; - -/** - * Options for one factory-scoped subagent call. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export interface FactoryAgentOptions { - label?: string; - schema?: FactoryJsonSchema; - model?: string; - reasoningEffort?: string; - contextTier?: ContextTier; - agent?: string; -} - -export const FACTORY_AGENT_OPTION_KEYS = [ - "label", - "schema", - "model", - "reasoningEffort", - "contextTier", - "agent", -] as const; - -/** - * Options for a durable factory step. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export interface FactoryStepOptions { - /** Skip the journal and always invoke the producer. */ - volatile?: boolean; -} - -/** - * Per-invocation factory resource ceiling overrides. - * - * An omitted field preserves the existing/default ceiling, a number replaces - * it, and `null` explicitly makes that dimension unlimited. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export interface FactoryLimitOverrides { - maxConcurrentSubagents?: number | null; - maxTotalSubagents?: number | null; - maxAiCredits?: number | null; - timeoutSeconds?: number | null; -} - -/** - * One stage in a per-item factory pipeline. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export type FactoryPipelineStage = ( - previous: TInput, - item: unknown, - index: number -) => Promise | TResult; - -/** - * Context passed to an extension-authored factory body. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export interface FactoryContext { - /** Stable identifier for the current factory run. */ - readonly runId: string; - /** Spawn and await one factory-scoped subagent. */ - agent(prompt: string, options?: FactoryAgentOptions): Promise; - /** Memoize an arbitrary producer under a stable author-supplied key. */ - step( - key: string, - producer: () => Promise | JsonValue, - options?: FactoryStepOptions - ): Promise; - /** - * Pause this run at a durable, one-shot checkpoint. - * - * The first attempt to reach a key pauses and aborts cooperatively. A - * resumed attempt returns from the same key and continues. - */ - pause(key: string): Promise; - /** - * Run thunks concurrently and await all of them. - * - * A thunk that throws becomes `null` in the result array, so one failed - * item does not lose the rest. Cancellation and hard runtime failures - * (`ResponseError`, `ConnectionError`) are the exception: those propagate - * and reject the whole call, because they mean the run itself is in - * trouble rather than one item having failed. - */ - parallel( - thunks: Array<() => Promise | TResult> - ): Promise>; - /** - * Run each item through every stage without barriers between stages. - * - * A stage that throws drops that item to `null` and skips its remaining - * stages. As with {@link FactoryContext.parallel}, cancellation and hard - * runtime failures propagate instead of being recorded per item. - */ - pipeline(items: unknown[], ...stages: FactoryPipelineStage[]): Promise; - /** Start a named factory progress phase. */ - phase(title: string): void; - /** Emit a factory progress line. */ - log(message: string): void; - /** Reject because nested factories are not supported. */ - factory(name: string, args?: JsonValue): Promise; - /** Caller-supplied input, forwarded verbatim. */ - args: TArgs; - /** - * The session instance returned by `joinSession`. It refuses calls that - * start, resume, or pause a factory run. - */ - session: CopilotSession; - /** Cooperative cancellation signal for the current factory run. */ - signal: AbortSignal; -} - -/** - * Definition accepted by {@link defineFactory}. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export interface FactoryDefinition< - TArgs extends JsonValue = JsonValue, - TResult extends JsonValue | void = JsonValue | void, -> { - meta: FactoryMeta; - run(context: FactoryContext): Promise; -} - -/** - * A deeply immutable view of a value. - * - * `defineFactory` deep-freezes the metadata it stores, so the handle's view of - * it has to be readonly all the way down or `handle.meta.name = "..."` and - * `handle.meta.phases.push(...)` would compile and then throw at runtime. - */ -type DeepReadonly = T extends (infer U)[] - ? readonly DeepReadonly[] - : T extends object - ? { readonly [K in keyof T]: DeepReadonly } - : T; - -/** - * Opaque reusable reference to a defined factory. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export interface FactoryHandle< - TArgs extends JsonValue = JsonValue, - TResult extends JsonValue | void = JsonValue | void, -> { - readonly meta: DeepReadonly; - readonly [factoryHandleBrand]: { - readonly args: TArgs; - readonly result: TResult; - }; -} - -/** - * Options for invoking a factory. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export interface RunOptions { - /** Input surfaced as `context.args`. */ - args?: TArgs; - /** Optional per-invocation resource ceiling overrides. */ - limits?: FactoryLimitOverrides; - /** Whether to notify the originating session when the factory completes. */ - notifyOnComplete?: boolean; - /** Whether to emit factory phase names to the session transcript. */ - logPhaseNames?: boolean; - /** - * Prior run whose persisted identity, arguments, journal, and accounting should be resumed. - * - * @deprecated Use {@link SessionFactoryApi.resume} instead. - */ - resumeFromRunId?: string; -} - -/** - * Options for resuming a factory run by ID. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export interface ResumeOptions { - /** Optional per-invocation resource ceiling overrides. */ - limits?: FactoryLimitOverrides; - /** Whether to notify the originating session when the factory completes. */ - notifyOnComplete?: boolean; - /** Whether to emit factory phase names to the session transcript. */ - logPhaseNames?: boolean; -} - -/** - * Machine-readable pre-execution factory resume failure. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export type FactoryResumeErrorCode = - | "not_found" - | "non_resumable" - | "already_active" - | "factory_already_running" - | "factory_limits_invalid" - | "factory_session_disposed" - | "factory_storage_unavailable" - | "factory_storage_corrupt"; - -/** - * Friendly factory API exposed on a session. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export interface SessionFactoryApi { - /** - * Run a registered factory and resolve with its run envelope. - * - * The envelope is returned for every outcome, including `error`, `halted`, - * `paused`, and `cancelled` — inspect `status` and read `result` only when - * the run completed. `paused` settles the current attempt, but the same - * durable run can later resume under its existing run ID. SDK-initiated - * runs do not request permission, so they have no declined outcome. The - * model's `run_factory` tool requests permission before a durable row - * exists; declining it creates no run row. Failures that occur before a run - * exists (such as an unknown factory or attempting to start a run while the - * session is at its active top-level run limit) still reject. - */ - run(name: string, options?: RunOptions): Promise; - run( - factory: FactoryHandle, - options?: RunOptions - ): Promise; - /** - * Resume a run from its persisted factory name, arguments, journal, and accounting. - * - * Resolves with the run envelope like {@link SessionFactoryApi.run}. - * SDK-initiated resumes do not request permission. A pre-execution failure - * with a documented resume code rejects with {@link FactoryResumeError}. - */ - resume(runId: string, options?: ResumeOptions): Promise; - /** Read the latest durable envelope for a factory run. */ - getRun(runId: string): Promise; - /** - * Wait for the current attempt to settle and resolve with its envelope. - * - * Resolves as soon as the run reaches `completed`, `error`, `halted`, - * `paused`, or `cancelled`, and resolves immediately when the current - * attempt has already settled. A `paused` envelope is an attempt-level - * snapshot: resuming the same durable run can later change the envelope - * returned by {@link SessionFactoryApi.getRun}. - * - * This watches the run's `factory.run_updated` invalidation events and - * periodically re-reads the durable envelope so a missed event cannot - * leave the wait hanging. Pass a `signal` to stop waiting; aborting rejects - * and has no effect on the run itself, which keeps executing. Use - * {@link SessionFactoryApi.cancel} to actually stop it. - */ - waitForRun(runId: string, options?: { signal?: AbortSignal }): Promise; - /** - * List the newest default page of this session's durable factory runs. - * - * This backwards-compatible overload returns only the runs array. Pass - * paging options to receive the full page, including its cursors and - * truncation metadata. - */ - listRuns(): Promise; - /** - * Page this session's durable factory runs. - * - * `afterSeq` and `beforeSeq` are exclusive cursors. The result includes - * `oldestSeq`, `newestSeq`, `hasMoreNewer`, and `omittedOlder` so callers - * can continue paging without using the raw RPC client. - */ - listRuns(options: FactoryListRunsOptions): Promise; - /** Read durable phases, direct agents, and the latest progress tail for a run. */ - getRunDetail(runId: string): Promise; - /** Page durable progress forward, backward, or from the latest tail. */ - getRunProgress( - runId: string, - options?: Omit - ): Promise; - /** Pause a running factory attempt and return its `paused` envelope. */ - pause(runId: string): Promise; - /** Cancel a factory run and return its terminal envelope. */ - cancel(runId: string): Promise; -} - -/** - * Error thrown when a factory cannot be resumed before execution begins. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export class FactoryResumeError extends Error { - constructor( - public readonly code: FactoryResumeErrorCode, - message: string - ) { - super(message); - this.name = "FactoryResumeError"; - } -} - -interface StoredFactory { - meta: FactoryMeta; - run(context: FactoryContext): Promise; -} - -const factoryHandles = new WeakMap(); - -/** Maximum accepted factory timeout in seconds, derived from Node's maximum timer delay. */ -const MAX_FACTORY_TIMEOUT_SECONDS = 2_147_483.647; -const NANO_AIU_PER_AIU = 1_000_000_000; - -function deepFreeze(value: T): T { - if (value !== null && typeof value === "object" && !Object.isFrozen(value)) { - Object.freeze(value); - for (const nested of Object.values(value)) { - deepFreeze(nested); - } - } - return value; -} - -function validateLimits(meta: FactoryMeta): void { - const limits = meta.limits; - if (!limits) { - return; - } - - for (const field of ["maxConcurrentSubagents", "maxTotalSubagents"] as const) { - const value = limits[field]; - if (value !== undefined && (!Number.isInteger(value) || value <= 0)) { - throw new Error(`Factory limit "${field}" must be a positive integer`); - } - } - - if ( - limits.timeoutSeconds !== undefined && - (!Number.isFinite(limits.timeoutSeconds) || limits.timeoutSeconds <= 0) - ) { - throw new Error( - 'Factory limit "timeoutSeconds" must be a positive, finite number of seconds' - ); - } - if ( - limits.timeoutSeconds !== undefined && - limits.timeoutSeconds > MAX_FACTORY_TIMEOUT_SECONDS - ) { - throw new Error( - `Factory limit "timeoutSeconds" must not exceed ${MAX_FACTORY_TIMEOUT_SECONDS} seconds` - ); - } - - if (limits.maxAiCredits !== undefined) { - const maxNanoAiu = Math.round(limits.maxAiCredits * NANO_AIU_PER_AIU); - if ( - !Number.isFinite(limits.maxAiCredits) || - limits.maxAiCredits <= 0 || - !Number.isSafeInteger(maxNanoAiu) || - maxNanoAiu < 1 - ) { - throw new Error( - 'Factory limit "maxAiCredits" must be a positive, finite number that rounds to a safe positive integer nano-AIU ceiling' - ); - } - } -} - -function validatePhases(meta: FactoryMeta): void { - const titles = new Set(); - for (const phase of meta.phases) { - if (phase.title.trim().length === 0) { - throw new Error("Factory phase titles must not be empty"); - } - if (titles.has(phase.title)) { - throw new Error(`Factory phase title "${phase.title}" is declared more than once`); - } - titles.add(phase.title); - } -} - -/** - * Defines an extension-authored factory and returns an opaque registration handle. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export function defineFactory< - TArgs extends JsonValue = JsonValue, - TResult extends JsonValue | void = JsonValue | void, ->(definition: FactoryDefinition): FactoryHandle { - // Snapshot before validating so post-registration mutation of the caller's - // object cannot slip past the authoring-boundary checks. - const meta = deepFreeze(structuredClone(definition.meta)); - validateLimits(meta); - validatePhases(meta); - - const stored: StoredFactory = { - meta, - run: definition.run, - }; - const handle = Object.freeze({ meta }) as unknown as FactoryHandle; - - factoryHandles.set(handle, stored); - return handle; -} - -/** @internal */ -export function getFactoryDefinition(handle: FactoryHandle): StoredFactory { - const definition = factoryHandles.get(handle); - if (!definition) { - throw new Error("Invalid factory handle"); - } - return definition; -} diff --git a/nodejs/src/generated/rpc.ts b/nodejs/src/generated/rpc.ts index 16f5b1695a..c5852fa06e 100644 --- a/nodejs/src/generated/rpc.ts +++ b/nodejs/src/generated/rpc.ts @@ -33,6 +33,24 @@ export type AuthInfo = | UserAuthInfo | GhCliAuthInfo | ApiKeyAuthInfo; +/** + * The provider kind stamped on a signed-in account. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AccountKind". + */ +/** @experimental */ +export type AccountKind = + /** An OAuth github.com account. */ + | "githubDotCom" + /** A GitHub Enterprise Cloud account — a GitHub account on a non-github.com host, e.g. *.ghe.com. */ + | "proxima" + /** A GitHub (EMU) account derived from a base Entra identity. */ + | "entraEmu" + /** A base Microsoft Entra identity. */ + | "entra" + /** A Microsoft 365 Copilot (Loki) inference account derived from the same base Entra identity as an EMU account; its bearer is a Loki-scoped inference token consumed through the model-provider path, not the GitHub switcher. */ + | "loki"; /** * User to log out * @@ -43,6 +61,102 @@ export type AuthInfo = export type AccountLogoutRequest = { [k: string]: unknown | undefined; }; +/** + * Selects which accounts collection to enumerate. A no-arg selector is the empty-payload variant. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AuthEnumerateQuery". + */ +/** @experimental */ +export type AuthEnumerateQuery = + | { + /** + * Account-collection query variant discriminator. + */ + kind: "accounts"; + } + | { + /** + * Whether an interactive Entra broker is available on the host; gates Entra availability in the returned list. + */ + brokerAvailable?: boolean; + /** + * Account-collection query variant discriminator. + */ + kind: "providers"; + }; +/** + * Selects which typed accounts datum to read. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AuthReadQuery". + */ +/** @experimental */ +export type AuthReadQuery = + | { + /** + * Account read-datum query variant discriminator. + */ + kind: "activeAccount"; + } + | { + /** + * Account read-datum query variant discriminator. + */ + kind: "status"; + } + | { + /** + * Account read-datum query variant discriminator. + */ + kind: "lastErrors"; + }; +/** + * One non-interactive accounts mutation command (the selector is fused with its typed args). + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AuthWrite". + */ +/** @experimental */ +export type AuthWrite = + | { + /** + * Opaque selection id of the account to make active. + */ + selectionId: string; + /** + * Account mutation command variant discriminator. + */ + kind: "switchActive"; + } + | { + /** + * Opaque selection id of the account to log out; absent logs out the active account. + */ + selectionId?: string; + /** + * Account mutation command variant discriminator. + */ + kind: "logout"; + } + | { + /** + * Authentication host URL. + */ + host: string; + /** + * Login/username for the credential. + */ + login: string; + /** + * GitHub authentication token to install. + */ + token: string; + /** + * Account mutation command variant discriminator. + */ + kind: "setCredentials"; + }; /** * Resolved Anthropic adaptive-thinking capability for a model. * @@ -246,6 +360,48 @@ export type AgentRegistrySpawnValidationErrorField = | "model" /** The permissionMode parameter */ | "permissionMode"; +/** + * The enumerated collection, keyed by the same selector as the query. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AuthEnumerateValue". + */ +/** @experimental */ +export type AuthEnumerateValue = + | { + /** + * The signed-in account forest; empty when not logged in. + */ + items: AccountStatus[]; + /** + * Enumerated account-collection variant discriminator. + */ + kind: "accounts"; + } + | { + /** + * The providers offered for interactive login. + */ + items: ProviderDescriptor[]; + /** + * Enumerated account-collection variant discriminator. + */ + kind: "providers"; + }; +/** + * A provider a consumer may interactively sign in with. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "LoginProviderKind". + */ +/** @experimental */ +export type LoginProviderKind = + /** OAuth github.com sign-in via the browser (web loopback + PKCE). */ + | "githubDotCom" + /** A GitHub Enterprise Cloud account — a GitHub account on a non-github.com host, e.g. *.ghe.com; the host is supplied interactively through the neutral input-required step. */ + | "proxima" + /** Microsoft Entra sign-in that derives a GitHub (EMU) credential. */ + | "entra"; /** * Authentication type * @@ -270,6 +426,109 @@ export type AuthInfoType = | "token-provider" /** Authentication from a Copilot API token. */ | "copilot-api-token"; +/** + * One step in an interactive login flow. The consumer acts on the step and calls advance to proceed. Browser-open is encoded as two distinct steps by design: `open-url` is CONSUMER-driven (the provider surfaces the authorize URL and the consumer opens it — github.com/GHEC web), while `needs-interaction` is PROVIDER-driven (the provider opens the browser or broker UI itself and does not surface a URL — Entra). + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AuthLoginStep". + */ +/** @experimental */ +export type AuthLoginStep = + | { + /** + * Authorize URL the consumer should open in a browser (consumer-driven browser-open). + */ + url: string; + /** + * Login flow step variant discriminator. + */ + kind: "open-url"; + } + | { + /** + * Prompt for the value the provider needs; the consumer supplies it as advance input (e.g. a GitHub Enterprise Cloud host, *.ghe.com). + */ + prompt: string; + /** + * Login flow step variant discriminator. + */ + kind: "input-required"; + } + | { + /** + * Login flow step variant discriminator. + */ + kind: "awaiting"; + } + | { + /** + * Login flow step variant discriminator. + */ + kind: "needs-interaction"; + } + | { + result: AuthLoginResultDto; + /** + * Login flow step variant discriminator. + */ + kind: "completed"; + } + | { + /** + * Human-readable failure message. + */ + message: string; + /** + * Login flow step variant discriminator. + */ + kind: "error"; + }; +/** + * Terminal disposition of a login persistence attempt. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AuthLoginResultStatus". + */ +/** @experimental */ +export type AuthLoginResultStatus = + /** The credential was persisted and the account is signed in. */ + | "completed" + /** Persistence needs explicit consent to store the token in plaintext. */ + | "needs-plaintext-consent" + /** The user declined plaintext persistence. */ + | "declined"; +/** + * The read result, keyed by the same selector as the query. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AuthReadValue". + */ +/** @experimental */ +export type AuthReadValue = + | { + account?: AccountStatus; + /** + * Account read-datum variant discriminator. + */ + kind: "activeAccount"; + } + | { + status: AuthStatusDto; + /** + * Account read-datum variant discriminator. + */ + kind: "status"; + } + | { + /** + * Validation errors from the most recent authentication attempt. + */ + errors: AuthValidationError[]; + /** + * Account read-datum variant discriminator. + */ + kind: "lastErrors"; + }; /** * Validation errors from the most recent authentication attempt. * @@ -1634,296 +1893,86 @@ export type ExternalToolTextResultForLlmContentResourceDetails = | EmbeddedTextResourceContents | EmbeddedBlobResourceContents; /** - * Execution-critical factory storage operation. + * Content filtering mode to apply to all tools, or a map of tool name to content filtering mode. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryDurableOperation". + * via the `definition` "FilterMapping". */ /** @experimental */ -export type FactoryDurableOperation = - /** Creating the durable run and declared phases. */ - | "createRun" - /** Persisting the transition to running. */ - | "markRunStarted" - /** Persisting the terminal run envelope. */ - | "finishRun" - /** Persisting subagent admission accounting. */ - | "reserveAgent" - /** Rolling back an uncommitted subagent admission. */ - | "releaseAgent" - /** Persisting an idempotent model-usage charge. */ - | "chargeCredit" - /** Persisting active execution time. */ - | "addElapsed" - /** Reading the authoritative AI-credit total. */ - | "reconcileCreditTotal" - /** Reading a journal entry without treating storage failure as a cache miss. */ - | "journalGet" - /** Persisting a journal entry before reporting success. */ - | "journalPut" - /** Renewing the durable owner lease that proves this process still owns the run. */ - | "refreshLease"; +export type FilterMapping = + | { + [k: string]: ContentFilterMode; + } + | ContentFilterMode; /** - * Current or terminal state of a factory run. + * Why the runtime is requesting a GitHub credential. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunStatus". + * via the `definition` "GitHubTokenAcquireReason". */ /** @experimental */ -export type FactoryRunStatus = - /** The run was minted and is awaiting approval. */ - | "pending" - /** The run is executing. */ - | "running" - /** The run completed successfully. */ - | "completed" - /** The run was interrupted while resource budget remained. */ - | "halted" - /** The current attempt stopped intentionally and the run may be resumed. */ - | "paused" - /** The run was cancelled before completion. */ - | "cancelled" - /** The factory body failed or reached a cumulative resource ceiling. */ - | "error"; +export type GitHubTokenAcquireReason = + /** The runtime is acquiring the registration's first credential. */ + | "initial" + /** The runtime is replacing a credential that is approaching expiry. */ + | "refresh"; /** - * Machine-readable factory run failure. + * SDK host response to a GitHub credential request. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunFailure". + * via the `definition` "GitHubTokenAcquireResult". */ /** @experimental */ -export type FactoryRunFailure = +export type GitHubTokenAcquireResult = | { - kind: FactoryRunFailureKind; /** - * Approved effective ceiling that was reached. + * GitHub access token acquired by the SDK host. */ - value: number; + accessToken: string; /** - * Suggested larger ceiling when the runtime can derive one safely. + * OAuth token type. Defaults to bearer when omitted. */ - suggestedValue?: number; + tokenType?: string; /** - * Factory run identifier. + * Remaining token lifetime in seconds when callback execution completes. It must exceed the one-hour preflight refresh threshold. */ - runId: string; + expiresIn: number; /** - * Factory failure variant discriminator. + * GitHub credential response variant discriminator. */ - type: "factory_limit_reached"; + kind: "token"; } | { /** - * Factory run identifier whose changed limits were declined. - */ - runId: string; - /** - * Human-readable reason the resume did not proceed. - */ - reason: string; - /** - * Factory failure variant discriminator. + * GitHub credential response variant discriminator. */ - type: "factory_resume_declined"; - } + kind: "cancelled"; + }; +/** + * Optional compaction parameters. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "HistoryCompactRequest". + */ +/** @experimental */ +export type HistoryCompactRequest = | { - /** - * Stable failure code. - */ - code: string; - operation: FactoryDurableOperation; - /** - * Factory run identifier. - */ - runId: string; - /** - * Factory failure variant discriminator. - */ - type: "factory_durable_failure"; + [k: string]: unknown | undefined; } | { /** - * Factory run identifier. + * Optional user-provided instructions to focus the compaction summary */ - runId: string; + customInstructions?: string; /** - * Confirmed usage in nano-AIU, representing the floor of what the run spent. + * What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). */ - drainedNanoAiu: number; + trigger?: /** User-requested compaction, e.g. the /compact command or a direct history.compact call. */ + | "manual" + /** Compaction requested while switching to a model with a smaller context window. */ + | "model_switch"; /** - * Factory failure variant discriminator. - */ - type: "factory_accounting_incomplete"; - } - | { - /** - * Factory run identifier. - */ - runId: string; - /** - * Factory failure variant discriminator. - */ - type: "factory_provider_disconnected"; - }; -/** - * Cumulative resource ceiling that stopped a factory run. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunFailureKind". - */ -/** @experimental */ -export type FactoryRunFailureKind = - /** The run admitted the approved maximum total number of subagents. */ - | "maxTotalSubagents" - /** The run reached the approved accumulated active-execution time in seconds. */ - | "timeoutSeconds" - /** The run's settled subagent model usage exceeded the approved AI-credit ceiling, or no headroom remained for another subagent. */ - | "maxAiCredits"; -/** - * Durable metadata describing who initiated a factory pause. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryPauseInfo". - */ -/** @experimental */ -export type FactoryPauseInfo = - | { - /** - * Factory pause initiator discriminator. - */ - type: "user"; - } - | { - /** - * Stable author-defined checkpoint key that initiated the pause. - */ - key: string; - /** - * Factory pause initiator discriminator. - */ - type: "checkpoint"; - }; -/** - * Kind of factory progress line. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryLogLineKind". - */ -/** @experimental */ -export type FactoryLogLineKind = - /** A narrator log line. */ - | "log" - /** A named factory phase marker. */ - | "phase"; -/** - * Action the runtime selected for a durable factory pause checkpoint. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryPauseCheckpointAction". - */ -/** @experimental */ -export type FactoryPauseCheckpointAction = - /** The checkpoint was committed by a prior paused attempt, so execution may continue. */ - | "continue" - /** This attempt claimed the checkpoint and must cooperatively stop. */ - | "pause"; -/** - * Derived lifecycle state of a factory phase. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryPhaseStatus". - */ -/** @experimental */ -export type FactoryPhaseStatus = - /** The phase has not been entered yet. */ - | "pending" - /** The phase is currently entered and accumulating active time. */ - | "active" - /** The phase was entered and has since been closed. */ - | "completed" - /** The phase was never entered because a later phase was entered or the run reached a terminal state. */ - | "skipped"; -/** - * Content filtering mode to apply to all tools, or a map of tool name to content filtering mode. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FilterMapping". - */ -/** @experimental */ -export type FilterMapping = - | { - [k: string]: ContentFilterMode; - } - | ContentFilterMode; -/** - * Why the runtime is requesting a GitHub credential. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "GitHubTokenAcquireReason". - */ -/** @experimental */ -export type GitHubTokenAcquireReason = - /** The runtime is acquiring the registration's first credential. */ - | "initial" - /** The runtime is replacing a credential that is approaching expiry. */ - | "refresh"; -/** - * SDK host response to a GitHub credential request. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "GitHubTokenAcquireResult". - */ -/** @experimental */ -export type GitHubTokenAcquireResult = - | { - /** - * GitHub access token acquired by the SDK host. - */ - accessToken: string; - /** - * OAuth token type. Defaults to bearer when omitted. - */ - tokenType?: string; - /** - * Remaining token lifetime in seconds when callback execution completes. It must exceed the one-hour preflight refresh threshold. - */ - expiresIn: number; - /** - * GitHub credential response variant discriminator. - */ - kind: "token"; - } - | { - /** - * GitHub credential response variant discriminator. - */ - kind: "cancelled"; - }; -/** - * Optional compaction parameters. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "HistoryCompactRequest". - */ -/** @experimental */ -export type HistoryCompactRequest = - | { - [k: string]: unknown | undefined; - } - | { - /** - * Optional user-provided instructions to focus the compaction summary - */ - customInstructions?: string; - /** - * What initiated this compaction request, recorded as the `trigger` on the persisted `session.compaction_start` / `session.compaction_complete` events. When absent, the compaction is persisted without trigger attribution (initiator unknown). - */ - trigger?: /** User-requested compaction, e.g. the /compact command or a direct history.compact call. */ - | "manual" - /** Compaction requested while switching to a model with a smaller context window. */ - | "model_switch"; - /** - * Context window token limit this compaction is targeting, recorded as the `tokenLimit` on the persisted `session.compaction_start` / `session.compaction_complete` events. Set it when the compaction targets a window other than the compacting model's own, e.g. switching to a model with a smaller context window: the compaction still runs on the current model, so the limit that motivated it would otherwise be lost. When absent, the events record the compacting model's own resolved limit. Attribution metadata only - it does not change how much the compaction removes. + * Context window token limit this compaction is targeting, recorded as the `tokenLimit` on the persisted `session.compaction_start` / `session.compaction_complete` events. Set it when the compaction targets a window other than the compacting model's own, e.g. switching to a model with a smaller context window: the compaction still runs on the current model, so the limit that motivated it would otherwise be lost. When absent, the events record the compacting model's own resolved limit. Attribution metadata only - it does not change how much the compaction removes. */ tokenLimit?: number; }; @@ -3138,7 +3187,7 @@ export type PermissionDecisionApproveForSessionApproval = | PermissionDecisionApproveForSessionApprovalMemory | PermissionDecisionApproveForSessionApprovalCustomTool | PermissionDecisionApproveForSessionApprovalExtensionManagement - | PermissionDecisionApproveForSessionApprovalFactory + | PermissionDecisionApproveForSessionApprovalWorkflow | PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess | PermissionDecisionApproveForSessionApprovalExtensionEnvAccess; /** @@ -3157,7 +3206,7 @@ export type PermissionDecisionApproveForLocationApproval = | PermissionDecisionApproveForLocationApprovalMemory | PermissionDecisionApproveForLocationApprovalCustomTool | PermissionDecisionApproveForLocationApprovalExtensionManagement - | PermissionDecisionApproveForLocationApprovalFactory + | PermissionDecisionApproveForLocationApprovalWorkflow | PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess | PermissionDecisionApproveForLocationApprovalExtensionEnvAccess; /** @@ -3222,7 +3271,7 @@ export type PermissionsLocationsAddToolApprovalDetails = | PermissionsLocationsAddToolApprovalDetailsMemory | PermissionsLocationsAddToolApprovalDetailsCustomTool | PermissionsLocationsAddToolApprovalDetailsExtensionManagement - | PermissionsLocationsAddToolApprovalDetailsFactory + | PermissionsLocationsAddToolApprovalDetailsWorkflow | PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess | PermissionsLocationsAddToolApprovalDetailsExtensionEnvAccess; /** @@ -3253,7 +3302,7 @@ export type PermissionModeSource = | "autopilot_confirmation" /** The mode was set at startup by the `defaultPermissionMode` user setting. */ | "user_setting" - /** The mode was set at startup by authenticated organization targeting. */ + /** Historical compatibility value for runtimes that selected Assisted mode through organization targeting. Current runtimes do not produce this source. */ | "organization_targeting" /** The mode was set through an RPC caller. */ | "rpc"; @@ -5713,6 +5762,66 @@ export interface AccountLogoutResult { */ hasMoreUsers: boolean; } +/** + * Enumerate request carrying the typed collection query. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AccountsEnumerateRequest". + */ +/** @experimental */ +export interface AccountsEnumerateRequest { + query: AuthEnumerateQuery; +} +/** + * Read request carrying the typed datum query. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AccountsGetRequest". + */ +/** @experimental */ +export interface AccountsGetRequest { + query: AuthReadQuery; +} +/** + * Mutation request carrying the typed write command. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AccountsSetRequest". + */ +/** @experimental */ +export interface AccountsSetRequest { + command: AuthWrite; +} +/** + * One signed-in account in the roster forest. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AccountStatus". + */ +/** @experimental */ +export interface AccountStatus { + /** + * Authentication host URL. + */ + host: string; + /** + * Authenticated login/username. + */ + login: string; + kind: AccountKind; + /** + * Opaque id of the account this one was derived from (e.g. an EMU account's base Entra identity); absent for a root account. Matches the base identity account's selectionId, forming the derivation edge. + */ + derivedFrom?: string; + /** + * Whether this is the active account. + */ + active: boolean; + /** + * Opaque selection id used to switch to, or log out, this account. + */ + selectionId: string; +} /** * Canonical directory where custom agents can be discovered or created, with scope, preference, and optional project path. * @@ -6136,6 +6245,24 @@ export interface AgentsGetDiscoveryPathsRequest { */ excludeHostAgents?: boolean; } +/** + * A provider offered for interactive login. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ProviderDescriptor". + */ +/** @experimental */ +export interface ProviderDescriptor { + kind: LoginProviderKind; + /** + * Human-readable menu label, owned by the runtime so every consumer renders identical text. + */ + label: string; + /** + * Whether this provider is currently available to sign in with. + */ + available: boolean; +} /** * Credential-free authentication identity safe to expose to hosts and user interfaces. * @@ -6164,96 +6291,214 @@ export interface AuthIdentity { copilotUser?: CopilotUserResponse; } /** - * Validation error from an authentication attempt. + * Advance an in-flight login flow, optionally fulfilling an input-required step. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "AuthValidationError". + * via the `definition` "AuthLoginAdvanceRequest". */ /** @experimental */ -export interface AuthValidationError { +export interface AuthLoginAdvanceRequest { /** - * Authentication validation error message + * Opaque flow id from begin. */ - message: string; + flowId: string; /** - * Optional message returned by GitHub + * Neutral input fulfilling a preceding input-required step (e.g. a GHEC host); ignored otherwise. */ - githubMessage?: string; + input?: string; } /** - * Current per-window credit limit and consumption for an autopilot objective. + * Begin an interactive login flow for a provider kind. Dispatch is kind-only. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "AutopilotObjectiveCreditLimit". + * via the `definition` "AuthLoginBeginRequest". */ /** @experimental */ -export interface AutopilotObjectiveCreditLimit { +export interface AuthLoginBeginRequest { + kind: LoginProviderKind; +} +/** + * A started login flow: its opaque id and first step. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AuthLoginBegun". + */ +/** @experimental */ +export interface AuthLoginBegun { /** - * Configured AI-credit cap, when one is set. + * Opaque flow id used to advance or cancel this login. */ - credits?: number; + flowId: string; + step: AuthLoginStep; +} +/** + * Terminal result of an interactive login flow. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AuthLoginResultDto". + */ +/** @experimental */ +export interface AuthLoginResultDto { + status: AuthLoginResultStatus; /** - * Window consumption in fractional AI credits, for display. + * Host that was signed in, when completed. */ - creditsUsed: number; + host?: string; /** - * Exact window consumption in non-negative integer nano-AIU, encoded as a decimal string. + * Login that was signed in, when completed. */ - creditsUsedNanoAiu: string; + login?: string; } /** - * Canonical runtime state for the session's current autopilot objective. + * Cancel an in-flight login flow. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "AutopilotObjectiveGetStateResult". + * via the `definition` "AuthLoginCancelRequest". */ /** @experimental */ -export interface AutopilotObjectiveGetStateResult { +export interface AuthLoginCancelRequest { /** - * Current objective state, or `null` when the session has no objective. + * Opaque flow id from begin. */ - state: AutopilotObjectiveState | null; + flowId: string; } /** - * Public, persistence-independent projection of an autopilot objective. + * Neutral authentication status summary. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "AutopilotObjectiveState". + * via the `definition` "AuthStatusDto". */ /** @experimental */ -export interface AutopilotObjectiveState { - /** - * Session-local objective identifier. - */ - id: number; +export interface AuthStatusDto { /** - * User-provided objective text. + * Whether the session has resolved authentication. */ - objective: string; - status: AutopilotObjectiveStatus; + isAuthenticated: boolean; /** - * Number of objective turns started. + * Active account login, if authenticated. */ - turnCount: number; + activeLogin?: string; /** - * Optional reason the objective is paused. + * Active account host, if authenticated. */ - pauseReason?: string; + activeHost?: string; /** - * Optional summary recorded when the objective completed. + * Copilot plan tier of the active account, if known. */ - completionSummary?: string; + copilotPlan?: string; /** - * Exact lifetime AI-credit consumption in non-negative integer nano-AIU, encoded as a decimal string. + * Number of signed-in accounts in the roster. */ - creditCountNanoAiu: string; - creditLimit?: AutopilotObjectiveCreditLimit; + accountCount: number; } /** - * The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata. + * Validation error from an authentication attempt. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "BuiltInModelCatalog". + * via the `definition` "AuthValidationError". + */ +/** @experimental */ +export interface AuthValidationError { + /** + * Authentication validation error message + */ + message: string; + /** + * Optional message returned by GitHub + */ + githubMessage?: string; +} +/** + * Result of a non-interactive accounts mutation. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AuthWriteResult". + */ +/** @experimental */ +export interface AuthWriteResult { + /** + * Whether the mutation was applied. + */ + ok: boolean; + /** + * For a logout, whether other signed-in accounts remain. + */ + moreUsers?: boolean; +} +/** + * Current per-window credit limit and consumption for an autopilot objective. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AutopilotObjectiveCreditLimit". + */ +/** @experimental */ +export interface AutopilotObjectiveCreditLimit { + /** + * Configured AI-credit cap, when one is set. + */ + credits?: number; + /** + * Window consumption in fractional AI credits, for display. + */ + creditsUsed: number; + /** + * Exact window consumption in non-negative integer nano-AIU, encoded as a decimal string. + */ + creditsUsedNanoAiu: string; +} +/** + * Canonical runtime state for the session's current autopilot objective. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AutopilotObjectiveGetStateResult". + */ +/** @experimental */ +export interface AutopilotObjectiveGetStateResult { + /** + * Current objective state, or `null` when the session has no objective. + */ + state: AutopilotObjectiveState | null; +} +/** + * Public, persistence-independent projection of an autopilot objective. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "AutopilotObjectiveState". + */ +/** @experimental */ +export interface AutopilotObjectiveState { + /** + * Session-local objective identifier. + */ + id: number; + /** + * User-provided objective text. + */ + objective: string; + status: AutopilotObjectiveStatus; + /** + * Number of objective turns started. + */ + turnCount: number; + /** + * Optional reason the objective is paused. + */ + pauseReason?: string; + /** + * Optional summary recorded when the objective completed. + */ + completionSummary?: string; + /** + * Exact lifetime AI-credit consumption in non-negative integer nano-AIU, encoded as a decimal string. + */ + creditCountNanoAiu: string; + creditLimit?: AutopilotObjectiveCreditLimit; +} +/** + * The running runtime's complete catalog of well-known built-in model IDs, including supported models and additional IDs with built-in metadata. + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "BuiltInModelCatalog". */ /** @experimental */ export interface BuiltInModelCatalog { @@ -9401,1201 +9646,181 @@ export interface ExternalToolTextResultForLlmContentText { * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema * via the `definition` "ExternalToolTextResultForLlmContentTerminal". - */ -/** @experimental */ -export interface ExternalToolTextResultForLlmContentTerminal { - /** - * Content block type discriminator - */ - type: "terminal"; - /** - * Terminal/shell output text - */ - text: string; - /** - * Process exit code, if the command has completed - */ - exitCode?: number; - /** - * Working directory where the command was executed - */ - cwd?: string; -} -/** - * Shell command exit metadata with optional output preview - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "ExternalToolTextResultForLlmContentShellExit". - */ -/** @experimental */ -export interface ExternalToolTextResultForLlmContentShellExit { - /** - * Content block type discriminator - */ - type: "shell_exit"; - /** - * Shell id, as assigned by Copilot runtime - */ - shellId: string; - /** - * Exit code from the completed shell command - */ - exitCode: number; - /** - * Working directory where the shell command was executed - */ - cwd?: string; - /** - * Output associated with this shell command, if available. May be partial, truncated, or a preview; not guaranteed to be full output. - */ - outputPreview?: string; - /** - * Whether outputPreview is known to be incomplete or truncated - */ - outputTruncated?: boolean; - /** - * Path reported in the shell session's filesystem namespace when shell output exceeded the configured large-output threshold. - */ - outputFilePath?: string; -} -/** - * Image content block with base64-encoded data - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "ExternalToolTextResultForLlmContentImage". - */ -/** @experimental */ -export interface ExternalToolTextResultForLlmContentImage { - /** - * Content block type discriminator - */ - type: "image"; - /** - * Base64-encoded image data - */ - data: string; - /** - * MIME type of the image (e.g., image/png, image/jpeg) - */ - mimeType: string; -} -/** - * Audio content block with base64-encoded data - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "ExternalToolTextResultForLlmContentAudio". - */ -/** @experimental */ -export interface ExternalToolTextResultForLlmContentAudio { - /** - * Content block type discriminator - */ - type: "audio"; - /** - * Base64-encoded audio data - */ - data: string; - /** - * MIME type of the audio (e.g., audio/wav, audio/mpeg) - */ - mimeType: string; -} -/** - * Resource link content block referencing an external resource - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "ExternalToolTextResultForLlmContentResourceLink". - */ -/** @experimental */ -export interface ExternalToolTextResultForLlmContentResourceLink { - /** - * Icons associated with this resource - */ - icons?: ExternalToolTextResultForLlmContentResourceLinkIcon[]; - /** - * Resource name identifier - */ - name: string; - /** - * Human-readable display title for the resource - */ - title?: string; - /** - * URI identifying the resource - */ - uri: string; - /** - * Human-readable description of the resource - */ - description?: string; - /** - * MIME type of the resource content - */ - mimeType?: string; - /** - * Size of the resource in bytes - */ - size?: number; - /** - * Content block type discriminator - */ - type: "resource_link"; -} -/** - * Icon image for a resource - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "ExternalToolTextResultForLlmContentResourceLinkIcon". - */ -/** @experimental */ -export interface ExternalToolTextResultForLlmContentResourceLinkIcon { - /** - * URL or path to the icon image - */ - src: string; - /** - * MIME type of the icon image - */ - mimeType?: string; - /** - * Available icon sizes (e.g., ['16x16', '32x32']) - */ - sizes?: string[]; - theme?: ExternalToolTextResultForLlmContentResourceLinkIconTheme; -} -/** - * Embedded resource content block with inline text or binary data - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "ExternalToolTextResultForLlmContentResource". - */ -/** @experimental */ -export interface ExternalToolTextResultForLlmContentResource { - /** - * Content block type discriminator - */ - type: "resource"; - resource: ExternalToolTextResultForLlmContentResourceDetails; -} -/** - * Parameters for cooperatively aborting a factory body. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryAbortRequest". - */ -/** @experimental */ -export interface FactoryAbortRequest { - /** - * Target session identifier - */ - sessionId: string; - /** - * Factory run identifier. - */ - runId: string; - /** - * Opaque token identifying the execution attempt to abort. - */ - executionToken: string; -} -/** - * Acknowledgement that a factory request was accepted. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryAckResult". - */ -/** @experimental */ -export interface FactoryAckResult {} -/** - * Options for one factory-scoped subagent call. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryAgentOptions". - */ -/** @experimental */ -export interface FactoryAgentOptions { - /** - * Optional label distinguishing otherwise identical memoized agent calls. - */ - label?: string; - /** - * Optional JSON Schema for structured agent output. - */ - schema?: JsonValue; - /** - * Optional model identifier for the subagent. - */ - model?: string; - /** - * Optional reasoning effort override for the subagent. - */ - reasoningEffort?: string; - contextTier?: ContextTier; - /** - * Optional built-in or custom agent name whose definition configures the subagent. - */ - agent?: string; -} -/** - * Parameters for one factory-scoped subagent call. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryAgentRequest". - */ -/** @experimental */ -export interface FactoryAgentRequest { - /** - * Factory run identifier that owns the subagent. - */ - factoryRunId: string; - /** - * Opaque token identifying the current factory execution attempt. - */ - executionToken: string; - /** - * Prompt to send to the subagent. - */ - prompt: string; - opts: FactoryAgentOptions; -} -/** - * Result of one factory-scoped subagent call. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryAgentResult". - */ -/** @experimental */ -export interface FactoryAgentResult { - /** - * Agent result, omitted when the agent produced no result. - */ - result?: JsonValue; -} -/** - * Prompt-safe durable identity and live status for a direct factory agent. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryAgentSummary". - */ -/** @experimental */ -export interface FactoryAgentSummary { - /** - * Stable direct-agent identifier. - */ - agentId: string; - /** - * Tool-call identifier that launched the agent. - */ - toolCallId: string; - /** - * Owning factory run identifier. - */ - runId: string; - /** - * Phase identifier active when the agent was launched, or null. - */ - phaseId: string | null; - /** - * Friendly, non-unique name intended for display - */ - label: string; - /** - * Friendly, non-unique name intended for display - */ - displayName?: string; - /** - * Registered agent type. - */ - agentType: string; - /** - * Current durable or live agent status. - */ - status: string; - /** - * Model requested when the agent was launched. - */ - requestedModel?: string; - /** - * Concrete model resolved for the agent. - */ - resolvedModel?: string; - /** - * Epoch milliseconds when the agent started. - */ - startedAt?: number; - /** - * Epoch milliseconds when the agent completed. - */ - completedAt?: number; - /** - * Accumulated active agent time in milliseconds. - */ - activeMs: number; - /** - * Prompt-safe live activity text. - */ - activity?: string; -} -/** - * Parameters for cancelling a factory run. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryCancelRequest". - */ -/** @experimental */ -export interface FactoryCancelRequest { - /** - * Factory run identifier. - */ - runId: string; -} -/** - * Current factory phase identity. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryCurrentPhase". - */ -/** @experimental */ -export interface FactoryCurrentPhase { - /** - * Current phase identifier. - */ - id: string; - /** - * Zero-based declared phase ordinal, or null for an undeclared phase. - */ - ordinal: number | null; -} -/** - * Declared or approved factory resource ceilings. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryDeclaredLimits". - */ -/** @experimental */ -export interface FactoryDeclaredLimits { - /** - * Maximum concurrently active subagents. - */ - maxConcurrentSubagents?: number; - /** - * Maximum total subagents spawned by the run. - */ - maxTotalSubagents?: number; - /** - * Maximum accumulated active execution time in seconds. - */ - timeoutSeconds?: number; - /** - * Maximum AI credits consumed by subagents and descendants. - */ - maxAiCredits?: number; -} -/** - * Parameters sent to the owning extension to execute a factory closure. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryExecuteRequest". - */ -/** @experimental */ -export interface FactoryExecuteRequest { - /** - * Target session identifier - */ - sessionId: string; - /** - * Registered factory name. - */ - name: string; - /** - * Factory run identifier. - */ - runId: string; - /** - * Opaque token identifying this factory execution attempt. - */ - executionToken: string; - /** - * Factory input value. - */ - args: JsonValue; -} -/** - * Result returned by an extension factory closure. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryExecuteResult". - */ -/** @experimental */ -export interface FactoryExecuteResult { - /** - * Factory result value. - */ - result?: JsonValue; -} -/** - * Parameters for paging factory progress. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryGetRunProgressRequest". - */ -/** @experimental */ -export interface FactoryGetRunProgressRequest { - /** - * Factory run identifier. - */ - runId: string; - /** - * Optional phase identifier used to scope records and cursors. - */ - phaseId?: string; - /** - * Exclusive forward cursor. - */ - afterSeq?: number; - /** - * Exclusive backward cursor. - */ - beforeSeq?: number; - /** - * Maximum records to return. Defaults to 200 and is capped at 500. - */ - limit?: number; -} -/** - * Parameters for retrieving a factory run. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryGetRunRequest". - */ -/** @experimental */ -export interface FactoryGetRunRequest { - /** - * Factory run identifier. - */ - runId: string; -} -/** - * Parameters for reading a factory journal entry. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryJournalGetRequest". - */ -/** @experimental */ -export interface FactoryJournalGetRequest { - /** - * Factory run identifier. - */ - runId: string; - /** - * Opaque token identifying the current factory execution attempt. - */ - executionToken: string; - /** - * Namespaced journal key. - */ - key: string; -} -/** - * Result of reading a factory journal entry. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryJournalGetResult". - */ -/** @experimental */ -export interface FactoryJournalGetResult { - /** - * Whether the journal contained the requested key. - */ - hit: boolean; - /** - * Cached JSON result. The hit field distinguishes a cached JSON null from a miss. - */ - resultJson?: JsonValue; -} -/** - * Parameters for storing a factory journal entry. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryJournalPutRequest". - */ -/** @experimental */ -export interface FactoryJournalPutRequest { - /** - * Factory run identifier. - */ - runId: string; - /** - * Opaque token identifying the current factory execution attempt. - */ - executionToken: string; - /** - * Namespaced journal key. - */ - key: string; - /** - * JSON result to memoize. - */ - resultJson: JsonValue; -} -/** - * Parameters for paging factory runs. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryListRunsRequest". - */ -/** @experimental */ -export interface FactoryListRunsRequest { - /** - * Exclusive forward cursor. - */ - afterSeq?: number; - /** - * Exclusive backward cursor. - */ - beforeSeq?: number; - /** - * Maximum terminal runs to return. Defaults to 200 and is capped at 500. - */ - limit?: number; -} -/** - * A page of factory runs in durable creation order. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryListRunsResult". - */ -/** @experimental */ -export interface FactoryListRunsResult { - /** - * Factory run summaries in durable creation order. - */ - runs: FactoryRunSummary[]; - /** - * Oldest terminal-run cursor in this page, or null when the terminal window is empty. - */ - oldestSeq?: number | null; - /** - * Newest terminal-run cursor in this page, or null when the terminal window is empty. - */ - newestSeq?: number | null; - /** - * Whether terminal runs newer than this page exist. - */ - hasMoreNewer?: boolean; - /** - * Number of terminal runs older than this page. - */ - omittedOlder?: number; -} -/** - * Durable factory run summary with read-time live overlays. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunSummary". - */ -/** @experimental */ -export interface FactoryRunSummary { - /** - * Factory run identifier. - */ - runId: string; - /** - * Registered factory name. - */ - factoryName: string; - /** - * Human-readable factory description. - */ - description: string; - status: FactoryRunStatus; - /** - * Monotonic durable run revision. - */ - revision: number; - /** - * Epoch milliseconds when the run was created. - */ - createdAt: number; - /** - * Epoch milliseconds when execution first started, or null before start. - */ - startedAt: number | null; - /** - * Epoch milliseconds when the durable run was last updated. - */ - updatedAt: number; - /** - * Epoch milliseconds when the run completed, or null while nonterminal. - */ - completedAt: number | null; - /** - * Current phase identity, or null before any phase is entered. - */ - currentPhase: FactoryCurrentPhase | null; - /** - * Number of phases declared by the factory. - */ - declaredPhaseCount: number; - /** - * Number of direct factory agents currently live. - */ - liveAgentCount: number; - /** - * Total direct factory agents spawned across all attempts. - */ - totalSpawnedAgentCount: number; - consumed: FactoryRunConsumed; - declaredLimits: FactoryDeclaredLimits; - /** - * Approved effective resource ceilings, or null until approved. - */ - approved: FactoryDeclaredLimits | null; - /** - * Epoch milliseconds when this live-overlay snapshot was observed. - */ - observedAt: number; - /** - * Epoch milliseconds when the current active segment started, or null while inactive. - */ - activeSegmentStartedAt: number | null; - /** - * Terminal run outcome, or null while nonterminal. - */ - terminal: FactoryRunTerminal | null; - /** - * Whether the durable run state currently passes runtime resume eligibility checks. - */ - canResume: boolean; -} -/** - * Durable factory resource consumption. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunConsumed". - */ -/** @experimental */ -export interface FactoryRunConsumed { - /** - * Accumulated active execution time in milliseconds. - */ - activeMs: number; - /** - * Total subagents spawned by the run. - */ - subagents: number; - /** - * AI usage consumed by the run in nano-AIU. - */ - nanoAiu: number; -} -/** - * Prompt-safe terminal factory outcome. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunTerminal". - */ -/** @experimental */ -export interface FactoryRunTerminal { - /** - * Human-readable terminal reason. - */ - reason?: string; - failure?: FactoryRunFailure; - /** - * Human-readable terminal error. - */ - error?: string; - /** - * Prompt-safe preview of the completed result. - */ - resultPreview?: string; - /** - * Pause initiator metadata, or null when the run did not pause. - */ - pauseInfo: FactoryPauseInfo | null; -} -/** - * One ordered factory progress line. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryLogLine". - */ -/** @experimental */ -export interface FactoryLogLine { - /** - * Monotonic sequence number within the factory run. - */ - seq: number; - kind: FactoryLogLineKind; - /** - * Progress text. - */ - text: string; -} -/** - * Parameters for recording factory progress. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryLogRequest". - */ -/** @experimental */ -export interface FactoryLogRequest { - /** - * Factory run identifier. - */ - runId: string; - /** - * Opaque token identifying the current factory execution attempt. - */ - executionToken: string; - /** - * Ordered progress lines to append. - */ - lines: FactoryLogLine[]; -} -/** - * Parameters for an owned durable pause checkpoint. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryPauseCheckpointRequest". - */ -/** @experimental */ -export interface FactoryPauseCheckpointRequest { - /** - * Factory run identifier. - */ - runId: string; - /** - * Opaque token identifying the execution attempt that reached the checkpoint. - */ - executionToken: string; - /** - * Stable author-defined checkpoint key. - */ - key: string; -} - -/** @experimental */ -export interface FactoryPauseCheckpointResult { - action: FactoryPauseCheckpointAction; -} -/** - * Parameters for pausing a running factory. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryPauseRequest". - */ -/** @experimental */ -export interface FactoryPauseRequest { - /** - * Factory run identifier. - */ - runId: string; -} -/** - * Durable lifecycle and timing for one factory phase. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryPhaseObservation". - */ -/** @experimental */ -export interface FactoryPhaseObservation { - /** - * Phase identifier. - */ - id: string; - /** - * Zero-based declared phase ordinal, or null for an undeclared phase. - */ - ordinal: number | null; - /** - * Human-readable phase title. - */ - title: string; - /** - * Optional human-readable phase detail. - */ - detail?: string; - status: FactoryPhaseStatus; - /** - * Most recent run attempt that entered this phase, or `0` if the phase has never been entered. - */ - lastEnteredRunAttempt: number; - /** - * Number of times execution entered this phase. - */ - entryCount: number; - /** - * Epoch milliseconds when this phase first started; for a skipped phase, the synthetic skip timestamp (equal to `completedAt`). - */ - startedAt?: number; - /** - * Epoch milliseconds when this phase completed; for a skipped phase, the synthetic skip timestamp (equal to `startedAt`). - */ - completedAt?: number; - /** - * Completed active time accumulated by this phase in milliseconds. - */ - accumulatedActiveMs: number; - /** - * Current live active time for this phase in milliseconds. - */ - currentActiveMs: number; - /** - * Total direct agents associated with this phase. - */ - totalAgentCount: number; - /** - * Direct agents in this phase that are currently live. - */ - liveAgentCount: number; -} -/** - * One durable factory progress record. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryProgressLine". - */ -/** @experimental */ -export interface FactoryProgressLine { - /** - * Global monotonic sequence number within the run. - */ - seq: number; - /** - * Resume attempt that emitted this record. - */ - attempt: number; - /** - * Phase active when the record was emitted, or null before any phase. - */ - phaseId: string | null; - /** - * Epoch milliseconds when the record was persisted. - */ - recordedAt: number; - kind: FactoryLogLineKind; - /** - * Prompt-safe progress text. - */ - text: string; -} -/** - * A bidirectional page of factory progress. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryProgressPage". - */ -/** @experimental */ -export interface FactoryProgressPage { - /** - * Progress records in sequence order. - */ - records: FactoryProgressLine[]; - /** - * Oldest sequence number in this page, or null when empty. - */ - oldestSeq: number | null; - /** - * Newest sequence number in this page, or null when empty. - */ - newestSeq: number | null; - /** - * Whether progress records older than this page exist. - */ - hasMoreOlder: boolean; - /** - * Whether progress records newer than this page exist. - */ - hasMoreNewer: boolean; - /** - * Run revision reflected by this page. - */ - revision: number; -} -/** - * Parameters for resuming a factory run from its persisted identity. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryResumeRequest". - */ -/** @experimental */ -export interface FactoryResumeRequest { - /** - * Factory run identifier. - */ - runId: string; - limits?: FactoryRunLimits; - /** - * Whether to notify the originating session when the factory completes. - */ - notifyOnComplete?: boolean; - /** - * Whether to emit factory phase names to the session transcript. - */ - logPhaseNames?: boolean; -} -/** - * Wire-only per-invocation factory resource ceiling overrides. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunLimits". - */ -/** @experimental */ -export interface FactoryRunLimits { - /** - * Maximum number of factory subagents that may run concurrently. - */ - maxConcurrentSubagents?: number | null; - /** - * Maximum total number of factory subagents that may be admitted. - */ - maxTotalSubagents?: number | null; - /** - * Maximum accumulated active-execution time in seconds. Active execution includes the entire extension body, subprocess waits, queued-agent waits, and sleeps; time between resumed attempts is not counted. - */ - timeoutSeconds?: number | null; - /** - * Maximum AI credits consumed by factory subagents and their descendants. The post-paid ceiling is soft: parallel turns can settle beyond it before the run stops. - */ - maxAiCredits?: number | null; -} -/** - * Resolved persisted factory identity and resumed run envelope. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryResumeResult". - */ -/** @experimental */ -export interface FactoryResumeResult { - /** - * Persisted factory name resolved for the resumed run. - */ - factoryName: string; - run: FactoryRunResult; -} -/** - * Complete current or terminal factory run envelope. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunResult". - */ -/** @experimental */ -export interface FactoryRunResult { - /** - * Factory run identifier. - */ - runId: string; - /** - * One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. - */ - attempt?: number; - status: FactoryRunStatus; - /** - * Completed factory result. - */ - result?: JsonValue; - /** - * Error message for an errored run. - */ - error?: string; - failure?: FactoryRunFailure; - /** - * Reason for a halted or cancelled run. - */ - reason?: string; - /** - * Partial journal and progress snapshot for a halted, cancelled, or errored run. - */ - snapshot?: JsonValue; - pauseInfo?: FactoryPauseInfo; -} -/** - * Full factory run observability detail. - * - * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunDetail". - */ -/** @experimental */ -export interface FactoryRunDetail { - /** - * Factory run identifier. - */ - runId: string; - /** - * Registered factory name. - */ - factoryName: string; - /** - * Human-readable factory description. - */ - description: string; - status: FactoryRunStatus; - /** - * Monotonic durable run revision. - */ - revision: number; - /** - * Epoch milliseconds when the run was created. - */ - createdAt: number; - /** - * Epoch milliseconds when execution first started, or null before start. - */ - startedAt: number | null; - /** - * Epoch milliseconds when the durable run was last updated. - */ - updatedAt: number; - /** - * Epoch milliseconds when the run completed, or null while nonterminal. - */ - completedAt: number | null; + */ +/** @experimental */ +export interface ExternalToolTextResultForLlmContentTerminal { /** - * Current phase identity, or null before any phase is entered. + * Content block type discriminator */ - currentPhase: FactoryCurrentPhase | null; + type: "terminal"; /** - * Number of phases declared by the factory. + * Terminal/shell output text */ - declaredPhaseCount: number; + text: string; /** - * Number of direct factory agents currently live. + * Process exit code, if the command has completed */ - liveAgentCount: number; + exitCode?: number; /** - * Total direct factory agents spawned across all attempts. + * Working directory where the command was executed */ - totalSpawnedAgentCount: number; - consumed: FactoryRunConsumed; - declaredLimits: FactoryDeclaredLimits; + cwd?: string; +} +/** + * Shell command exit metadata with optional output preview + * + * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema + * via the `definition` "ExternalToolTextResultForLlmContentShellExit". + */ +/** @experimental */ +export interface ExternalToolTextResultForLlmContentShellExit { /** - * Approved effective resource ceilings, or null until approved. + * Content block type discriminator */ - approved: FactoryDeclaredLimits | null; + type: "shell_exit"; /** - * Epoch milliseconds when this live-overlay snapshot was observed. + * Shell id, as assigned by Copilot runtime */ - observedAt: number; + shellId: string; /** - * Epoch milliseconds when the current active segment started, or null while inactive. + * Exit code from the completed shell command */ - activeSegmentStartedAt: number | null; + exitCode: number; /** - * Terminal run outcome, or null while nonterminal. + * Working directory where the shell command was executed */ - terminal: FactoryRunTerminal | null; + cwd?: string; /** - * Whether the durable run state currently passes runtime resume eligibility checks. + * Output associated with this shell command, if available. May be partial, truncated, or a preview; not guaranteed to be full output. */ - canResume: boolean; + outputPreview?: string; /** - * Lifecycle and timing observations for each factory phase. + * Whether outputPreview is known to be incomplete or truncated */ - phases: FactoryPhaseObservation[]; + outputTruncated?: boolean; /** - * Durable identities and live statuses for direct factory agents. + * Path reported in the shell session's filesystem namespace when shell output exceeded the configured large-output threshold. */ - agents: FactoryAgentSummary[]; - progress: FactoryProgressPage; + outputFilePath?: string; } /** - * Parameters for invoking a registered factory. + * Image content block with base64-encoded data * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryRunRequest". + * via the `definition` "ExternalToolTextResultForLlmContentImage". */ /** @experimental */ -export interface FactoryRunRequest { +export interface ExternalToolTextResultForLlmContentImage { /** - * Registered factory name. + * Content block type discriminator */ - name: string; + type: "image"; /** - * Factory input value. + * Base64-encoded image data */ - args: JsonValue; - options?: RunOptions; + data: string; + /** + * MIME type of the image (e.g., image/png, image/jpeg) + */ + mimeType: string; } /** - * Options controlling factory invocation. + * Audio content block with base64-encoded data * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "RunOptions". + * via the `definition` "ExternalToolTextResultForLlmContentAudio". */ /** @experimental */ -export interface RunOptions { - limits?: FactoryRunLimits; +export interface ExternalToolTextResultForLlmContentAudio { /** - * Whether to notify the originating session when the factory completes. + * Content block type discriminator */ - notifyOnComplete?: boolean; + type: "audio"; /** - * Whether to emit factory phase names to the session transcript. + * Base64-encoded audio data */ - logPhaseNames?: boolean; + data: string; /** - * Run identifier whose journal and progress should seed this resumed run. + * MIME type of the audio (e.g., audio/wav, audio/mpeg) */ - resumeFromRunId?: string; + mimeType: string; } /** - * Internal parameters for resuming a factory run from a tool. + * Resource link content block referencing an external resource * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryToolResumeRequest". + * via the `definition` "ExternalToolTextResultForLlmContentResourceLink". */ /** @experimental */ -/** @internal */ -export interface FactoryToolResumeRequest { +export interface ExternalToolTextResultForLlmContentResourceLink { /** - * Factory run identifier. + * Icons associated with this resource */ - runId: string; - limits?: FactoryRunLimits; + icons?: ExternalToolTextResultForLlmContentResourceLinkIcon[]; /** - * Opaque identifier of the originating tool call. + * Resource name identifier */ - toolCallId?: string; + name: string; + /** + * Human-readable display title for the resource + */ + title?: string; + /** + * URI identifying the resource + */ + uri: string; + /** + * Human-readable description of the resource + */ + description?: string; + /** + * MIME type of the resource content + */ + mimeType?: string; + /** + * Size of the resource in bytes + */ + size?: number; + /** + * Content block type discriminator + */ + type: "resource_link"; } /** - * Options for an internal tool-originated factory invocation. + * Icon image for a resource * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryToolRunOptions". + * via the `definition` "ExternalToolTextResultForLlmContentResourceLinkIcon". */ /** @experimental */ -/** @internal */ -export interface FactoryToolRunOptions { - limits?: FactoryRunLimits; +export interface ExternalToolTextResultForLlmContentResourceLinkIcon { /** - * Run identifier whose journal and progress should seed this resumed run. + * URL or path to the icon image */ - resumeFromRunId?: string; + src: string; + /** + * MIME type of the icon image + */ + mimeType?: string; + /** + * Available icon sizes (e.g., ['16x16', '32x32']) + */ + sizes?: string[]; + theme?: ExternalToolTextResultForLlmContentResourceLinkIconTheme; } /** - * Internal parameters for invoking a registered factory from a tool. + * Embedded resource content block with inline text or binary data * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "FactoryToolRunRequest". + * via the `definition` "ExternalToolTextResultForLlmContentResource". */ /** @experimental */ -/** @internal */ -export interface FactoryToolRunRequest { - /** - * Registered factory name. - */ - name: string; - /** - * Factory input value. - */ - args: JsonValue; - options?: FactoryToolRunOptions; +export interface ExternalToolTextResultForLlmContentResource { /** - * Opaque identifier of the originating tool call. + * Content block type discriminator */ - toolCallId?: string; + type: "resource"; + resource: ExternalToolTextResultForLlmContentResourceDetails; } /** * Parameters for starting fleet orchestration: an optional user prompt combined with the fleet instructions, plus the send options forwarded to the resulting turn. @@ -14870,6 +14095,14 @@ export interface ModelApplyStartupOverlayRequest { * Whether the overlay is being applied while resuming a deferred session. */ deferredResume?: boolean; + /** + * Reasoning effort paired with the effective organization-managed model. Applies only when that concrete managed model is selected; it is ignored for Auto and for CLI, resume, or user overrides. + */ + managedReasoningEffort?: string; + /** + * Context tier paired with the effective organization-managed model. Applies only when that concrete managed model is selected; it is ignored for Auto and for CLI, resume, or user overrides. + */ + managedContextTier?: string; } /** * Optional capability overrides (vision, tool_calls, reasoning, etc.). @@ -15676,19 +14909,19 @@ export interface PermissionDecisionApproveForSessionApprovalExtensionManagement operation?: string; } /** - * Session-scoped factory approval, optionally narrowed by approval key. + * Session-scoped workflow approval, optionally narrowed by approval key. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "PermissionDecisionApproveForSessionApprovalFactory". + * via the `definition` "PermissionDecisionApproveForSessionApprovalWorkflow". */ /** @experimental */ -export interface PermissionDecisionApproveForSessionApprovalFactory { +export interface PermissionDecisionApproveForSessionApprovalWorkflow { /** - * Approval covering factory operations. + * Approval covering workflow operations. */ - kind: "factory"; + kind: "workflow"; /** - * Optional factory operation name or canonical approval key; when omitted, the approval covers all factory operations. + * Optional workflow operation name or canonical approval key; when omitted, the approval covers all workflow operations. */ approvalKey?: string; } @@ -15879,19 +15112,19 @@ export interface PermissionDecisionApproveForLocationApprovalExtensionManagement operation?: string; } /** - * Location-scoped factory approval, optionally narrowed by approval key. + * Location-scoped workflow approval, optionally narrowed by approval key. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "PermissionDecisionApproveForLocationApprovalFactory". + * via the `definition` "PermissionDecisionApproveForLocationApprovalWorkflow". */ /** @experimental */ -export interface PermissionDecisionApproveForLocationApprovalFactory { +export interface PermissionDecisionApproveForLocationApprovalWorkflow { /** - * Approval covering factory operations. + * Approval covering workflow operations. */ - kind: "factory"; + kind: "workflow"; /** - * Optional factory operation name or canonical approval key; when omitted, the approval covers all factory operations. + * Optional workflow operation name or canonical approval key; when omitted, the approval covers all workflow operations. */ approvalKey?: string; } @@ -16308,19 +15541,19 @@ export interface PermissionsLocationsAddToolApprovalDetailsExtensionManagement { operation?: string; } /** - * Location-persisted factory approval, optionally narrowed by approval key. + * Location-persisted workflow approval, optionally narrowed by approval key. * * This interface was referenced by `_RpcSchemaRoot`'s JSON-Schema - * via the `definition` "PermissionsLocationsAddToolApprovalDetailsFactory". + * via the `definition` "PermissionsLocationsAddToolApprovalDetailsWorkflow". */ /** @experimental */ -export interface PermissionsLocationsAddToolApprovalDetailsFactory { +export interface PermissionsLocationsAddToolApprovalDetailsWorkflow { /** - * Approval covering factory operations. + * Approval covering workflow operations. */ - kind: "factory"; + kind: "workflow"; /** - * Optional factory operation name or canonical approval key; when omitted, the approval covers all factory operations. + * Optional workflow operation name or canonical approval key; when omitted, the approval covers all workflow operations. */ approvalKey?: string; } @@ -23445,6 +22678,7 @@ export interface SlashCommandSetModelResult { * Model selected by the command. */ model: string; + autoTier?: AutoTier; /** * Settings scope modified by the command. */ @@ -27078,11 +26312,6 @@ export interface WorkspacesWriteAutopilotObjectiveResult { operation: string; } -/** @experimental */ -export interface SessionFactoryPauseAtCheckpointResult { - action: FactoryPauseCheckpointAction; -} - /** @experimental */ export interface SessionWorkflowPauseAtCheckpointResult { action: WorkflowPauseCheckpointAction; @@ -28199,6 +27428,64 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin connection.sendRequest("session.gitHubAuth.setCredentials", { sessionId, ...params }), }, /** @experimental */ + accounts: { + /** + * Enumerate a typed accounts collection: the signed-in accounts, or the providers offered for interactive login. + * + * @param params Enumerate request carrying the typed collection query. + * + * @returns The enumerated collection, keyed by the same selector as the query. + */ + enumerate: async (params: AccountsEnumerateRequest): Promise => + connection.sendRequest("session.accounts.enumerate", { sessionId, ...params }), + /** + * Read one typed accounts datum: the active account, a neutral status summary, or the last authentication errors. + * + * @param params Read request carrying the typed datum query. + * + * @returns The read result, keyed by the same selector as the query. + */ + get: async (params: AccountsGetRequest): Promise => + connection.sendRequest("session.accounts.get", { sessionId, ...params }), + /** + * Apply one non-interactive accounts mutation: switch the active account, log an account out, or set credentials from a token. + * + * @param params Mutation request carrying the typed write command. + * + * @returns Result of a non-interactive accounts mutation. + */ + set: async (params: AccountsSetRequest): Promise => + connection.sendRequest("session.accounts.set", { sessionId, ...params }), + /** @experimental */ + login: { + /** + * Begin an interactive login flow for a provider kind (dispatch is kind-only) and return its opaque flow id and first step. + * + * @param params Begin an interactive login flow for a provider kind. Dispatch is kind-only. + * + * @returns A started login flow: its opaque id and first step. + */ + begin: async (params: AuthLoginBeginRequest): Promise => + connection.sendRequest("session.accounts.login.begin", { sessionId, ...params }), + /** + * Advance an in-flight login flow, optionally fulfilling an input-required step, and return the next step. + * + * @param params Advance an in-flight login flow, optionally fulfilling an input-required step. + * + * @returns One step in an interactive login flow. The consumer acts on the step and calls advance to proceed. Browser-open is encoded as two distinct steps by design: `open-url` is CONSUMER-driven (the provider surfaces the authorize URL and the consumer opens it — github.com/GHEC web), while `needs-interaction` is PROVIDER-driven (the provider opens the browser or broker UI itself and does not surface a URL — Entra). + */ + advance: async (params: AuthLoginAdvanceRequest): Promise => + connection.sendRequest("session.accounts.login.advance", { sessionId, ...params }), + /** + * Cancel an in-flight login flow and release its resources. + * + * @param params Cancel an in-flight login flow. + */ + cancel: async (params: AuthLoginCancelRequest): Promise => + connection.sendRequest("session.accounts.login.cancel", { sessionId, ...params }), + }, + }, + /** @experimental */ debug: { /** * Collects a session debug log bundle into a local archive or staging directory. Logs are redacted by default; redaction can be configured per caller-provided diagnostic entry. The runtime includes session-owned logs by default and accepts caller-provided diagnostic entries so host applications can add their own files without changing this API shape. @@ -28256,120 +27543,6 @@ export function createSessionRpc(connection: MessageConnection, sessionId: strin }, }, /** @experimental */ - factory: { - /** - * Runs a registered factory by name at the top level. - * - * @param params Parameters for invoking a registered factory. - * - * @returns Complete current or terminal factory run envelope. - */ - run: async (params: FactoryRunRequest): Promise => - connection.sendRequest("session.factory.run", { sessionId, ...params }), - /** - * Resumes a factory run using its persisted name, arguments, journal, and accounting. - * - * @param params Parameters for resuming a factory run from its persisted identity. - * - * @returns Resolved persisted factory identity and resumed run envelope. - */ - resume: async (params: FactoryResumeRequest): Promise => - connection.sendRequest("session.factory.resume", { sessionId, ...params }), - /** - * Gets the current or settled envelope for a factory run. - * - * @param params Parameters for retrieving a factory run. - * - * @returns Complete current or terminal factory run envelope. - */ - getRun: async (params: FactoryGetRunRequest): Promise => - connection.sendRequest("session.factory.getRun", { sessionId, ...params }), - /** - * Lists durable factory runs for this session in creation order. - * - * @param params Parameters for paging factory runs. - * - * @returns A page of factory runs in durable creation order. - */ - listRuns: async (params: FactoryListRunsRequest): Promise => - connection.sendRequest("session.factory.listRuns", { sessionId, ...params }), - /** - * Gets durable and live observability detail for one factory run. - * - * @param params Parameters for retrieving a factory run. - * - * @returns Full factory run observability detail. - */ - getRunDetail: async (params: FactoryGetRunRequest): Promise => - connection.sendRequest("session.factory.getRunDetail", { sessionId, ...params }), - /** - * Pages durable progress for one factory run. - * - * @param params Parameters for paging factory progress. - * - * @returns A bidirectional page of factory progress. - */ - getRunProgress: async (params: FactoryGetRunProgressRequest): Promise => - connection.sendRequest("session.factory.getRunProgress", { sessionId, ...params }), - /** - * Requests cancellation of a factory run and returns its run envelope. - * - * @param params Parameters for cancelling a factory run. - * - * @returns Complete current or terminal factory run envelope. - */ - cancel: async (params: FactoryCancelRequest): Promise => - connection.sendRequest("session.factory.cancel", { sessionId, ...params }), - /** - * Pauses a running factory and returns its settled run envelope. - * - * @param params Parameters for pausing a running factory. - * - * @returns Complete current or terminal factory run envelope. - */ - pause: async (params: FactoryPauseRequest): Promise => - connection.sendRequest("session.factory.pause", { sessionId, ...params }), - /** - * Records a batch of ordered factory progress lines. - * - * @param params Parameters for recording factory progress. - * - * @returns Acknowledgement that a factory request was accepted. - */ - log: async (params: FactoryLogRequest): Promise => - connection.sendRequest("session.factory.log", { sessionId, ...params }), - /** - * Runs one factory-scoped subagent and returns its result. - * - * @param params Parameters for one factory-scoped subagent call. - * - * @returns Result of one factory-scoped subagent call. - */ - agent: async (params: FactoryAgentRequest): Promise => - connection.sendRequest("session.factory.agent", { sessionId, ...params }), - /** @experimental */ - journal: { - /** - * Reads a memoized factory journal entry. - * - * @param params Parameters for reading a factory journal entry. - * - * @returns Result of reading a factory journal entry. - */ - get: async (params: FactoryJournalGetRequest): Promise => - connection.sendRequest("session.factory.journal.get", { sessionId, ...params }), - /** - * Stores a memoized factory journal entry. - * - * @param params Parameters for storing a factory journal entry. - * - * @returns Acknowledgement that a factory request was accepted. - */ - put: async (params: FactoryJournalPutRequest): Promise => - connection.sendRequest("session.factory.journal.put", { sessionId, ...params }), - }, - }, - /** @experimental */ workflow: { /** * Runs a registered dynamic workflow by name at the top level. @@ -30590,34 +29763,6 @@ export function createInternalSessionRpc(connection: MessageConnection, sessionI }, }, /** @experimental */ - factory: { - /** - * Internal tool-originated factory invocation. - * - * @param params Internal parameters for invoking a registered factory from a tool. - * - * @returns Complete current or terminal factory run envelope. - */ - runFromTool: async (params: FactoryToolRunRequest): Promise => - connection.sendRequest("session.factory.runFromTool", { sessionId, ...params }), - /** - * Internal tool-originated factory resume. - * - * @param params Internal parameters for resuming a factory run from a tool. - * - * @returns Resolved persisted factory identity and resumed run envelope. - */ - resumeFromTool: async (params: FactoryToolResumeRequest): Promise => - connection.sendRequest("session.factory.resumeFromTool", { sessionId, ...params }), - /** - * Atomically pauses an owned factory attempt at a durable checkpoint. - * - * @param params Parameters for an owned durable pause checkpoint. - */ - pauseAtCheckpoint: async (params: FactoryPauseCheckpointRequest): Promise => - connection.sendRequest("session.factory.pauseAtCheckpoint", { sessionId, ...params }), - }, - /** @experimental */ workflow: { /** * Internal tool-originated dynamic workflow invocation. @@ -30881,27 +30026,6 @@ export interface ProviderTokenHandler { getToken(params: ProviderTokenAcquireRequest): Promise; } -/** Handler for `factory` client session API methods. */ -/** @experimental */ -export interface FactoryHandler { - /** - * Asks the owning extension connection to execute a registered factory closure. - * - * @param params Parameters sent to the owning extension to execute a factory closure. - * - * @returns Result returned by an extension factory closure. - */ - execute(params: FactoryExecuteRequest): Promise; - /** - * Asks the owning extension connection to abort a running factory cooperatively. - * - * @param params Parameters for cooperatively aborting a factory body. - * - * @returns Acknowledgement that a factory request was accepted. - */ - abort(params: FactoryAbortRequest): Promise; -} - /** Handler for `workflow` client session API methods. */ /** @experimental */ export interface WorkflowHandler { @@ -31075,7 +30199,6 @@ export interface CanvasHandler { /** All client session API handler groups. */ export interface ClientSessionApiHandlers { providerToken?: ProviderTokenHandler; - factory?: FactoryHandler; workflow?: WorkflowHandler; tasks?: TasksHandler; sessionFs?: SessionFsHandler; @@ -31097,16 +30220,6 @@ export function registerClientSessionApiHandlers( if (!handler) throw new Error(`No providerToken handler registered for session: ${params.sessionId}`); return handler.getToken(params); }); - connection.onRequest("factory.execute", async (params: FactoryExecuteRequest) => { - const handler = getHandlers(params.sessionId).factory; - if (!handler) throw new Error(`No factory handler registered for session: ${params.sessionId}`); - return handler.execute(params); - }); - connection.onRequest("factory.abort", async (params: FactoryAbortRequest) => { - const handler = getHandlers(params.sessionId).factory; - if (!handler) throw new Error(`No factory handler registered for session: ${params.sessionId}`); - return handler.abort(params); - }); connection.onRequest("workflow.execute", async (params: WorkflowExecuteRequest) => { const handler = getHandlers(params.sessionId).workflow; if (!handler) throw new Error(`No workflow handler registered for session: ${params.sessionId}`); diff --git a/nodejs/src/generated/session-events.ts b/nodejs/src/generated/session-events.ts index 3b484f9e8c..7343ee9ae7 100644 --- a/nodejs/src/generated/session-events.ts +++ b/nodejs/src/generated/session-events.ts @@ -130,9 +130,9 @@ export type SessionEvent = | ExitPlanModeCompletedEvent | ToolsUpdatedEvent | BackgroundTasksChangedEvent - | FactoryRunUpdatedEvent - | FactoryRunStartedEvent - | FactoryRunSettledEvent + | WorkflowRunUpdatedEvent + | WorkflowRunStartedEvent + | WorkflowRunSettledEvent | SkillsLoadedEvent | CustomAgentsUpdatedEvent | McpServersLoadedEvent @@ -443,7 +443,9 @@ export type ModelChangeSource = /** The user selected the promoted model from the changeboarding card or its keyboard shortcut. */ | "changeboarding_shortcut" /** An SDK or RPC caller selected the model. */ - | "sdk"; + | "sdk" + /** The user accepted a CAPI-issued Auto tier recommendation. */ + | "auto_tier_recommendation"; /** * Why the session no longer has an explicitly selected model. */ @@ -1069,7 +1071,7 @@ export type SystemNotification = | SystemNotificationShellCompleted | SystemNotificationShellDetachedCompleted | SystemNotificationInstructionDiscovered - | SystemNotificationFactoryCompleted + | SystemNotificationWorkflowCompleted | SystemNotificationUnclassified; /** * Whether the agent completed successfully or failed @@ -1080,12 +1082,12 @@ export type SystemNotificationAgentCompletedStatus = /** The agent failed. */ | "failed"; /** - * Durable metadata describing who initiated a factory pause. + * Durable metadata describing who initiated a workflow pause. */ -export type SystemNotificationFactoryPauseInfo = +export type SystemNotificationWorkflowPauseInfo = | { /** - * Factory pause initiator discriminator. + * Workflow pause initiator discriminator. */ type: "user"; } @@ -1095,23 +1097,23 @@ export type SystemNotificationFactoryPauseInfo = */ key: string; /** - * Factory pause initiator discriminator. + * Workflow pause initiator discriminator. */ type: "checkpoint"; }; /** - * Terminal status reached by a factory execution attempt. + * Terminal status reached by a workflow execution attempt. */ -export type SystemNotificationFactoryCompletedStatus = - /** The factory completed successfully. */ +export type SystemNotificationWorkflowCompletedStatus = + /** The workflow completed successfully. */ | "completed" - /** The factory was halted. */ + /** The workflow was halted. */ | "halted" - /** The factory attempt paused intentionally. */ + /** The workflow attempt paused intentionally. */ | "paused" - /** The factory was cancelled. */ + /** The workflow was cancelled. */ | "cancelled" - /** The factory failed. */ + /** The workflow failed. */ | "error"; /** * Details of the permission being requested @@ -1126,7 +1128,7 @@ export type PermissionRequest = | PermissionRequestCustomTool | PermissionRequestHook | PermissionRequestExtensionManagement - | PermissionRequestFactory + | PermissionRequestWorkflow | PermissionRequestExtensionPermissionAccess | PermissionRequestExtensionEnvAccess; /** @@ -1189,12 +1191,12 @@ export type PermissionRequestMemoryScope = /** Store the memory for the current user. */ | "user"; /** - * Operation gated by a factory permission request. + * Operation gated by a workflow permission request. */ -export type FactoryPermissionOperation = - /** Running a registered factory, which spends subagents, active time, and AI credits under the approved limits. */ +export type WorkflowPermissionOperation = + /** Running a registered workflow, which spends subagents, active time, and AI credits under the approved limits. */ | "run" - /** Authoring a factory, which writes JavaScript into a session-scoped extension and loads it. */ + /** Authoring a workflow, which writes JavaScript into a session-scoped extension and loads it. */ | "author"; /** * Derived user-facing permission prompt details for UI consumers @@ -1210,7 +1212,7 @@ export type PermissionPromptRequest = | PermissionPromptRequestPath | PermissionPromptRequestHook | PermissionPromptRequestExtensionManagement - | PermissionPromptRequestFactory + | PermissionPromptRequestWorkflow | PermissionPromptRequestExtensionPermissionAccess | PermissionPromptRequestExtensionEnvAccess; /** @@ -1235,7 +1237,7 @@ export type PermissionDecisionSource = | "host_policy" /** The host denied the request because no interactive user response was available. */ | "unattended_fallback" - /** A live authorization record from an earlier human decision in this session contained the proposal, so it ran without another prompt. This is not a new human decision and never mints authority of its own. */ + /** Historical compatibility value for sessions created while authorization carry-forward was executable. Current runtimes do not produce this source. */ | "authorization_carry_forward"; /** * The result of the permission request @@ -1261,17 +1263,17 @@ export type UserToolSessionApproval = | UserToolSessionApprovalMemory | UserToolSessionApprovalCustomTool | UserToolSessionApprovalExtensionManagement - | UserToolSessionApprovalFactory + | UserToolSessionApprovalWorkflow | UserToolSessionApprovalExtensionPermissionAccess | UserToolSessionApprovalExtensionEnvAccess; /** - * Which direction a message-backed authorization claim moves authority in. + * Direction stored in a historical extractor claim. Current runtimes do not apply it. */ /** @experimental */ export type PermissionMessageAuthorizationPolarity = - /** The human's words authorized an effect. */ + /** Historical claim recorded as a grant. */ | "grant" - /** The human's words refused an effect. */ + /** Historical claim recorded as a denial. */ | "denial"; /** * Elicitation mode; "form" for structured input, "url" for browser-based. Defaults to "form" when absent. @@ -1439,10 +1441,10 @@ export type ExitPlanModeAction = /** Exit plan mode and continue with parallel autonomous workers. */ | "autopilot_fleet"; /** - * Terminal status a factory run committed. A settled run is never `pending` or `running`, so those two members of the run-status domain are deliberately absent. + * Terminal status a workflow run committed. A settled run is never `pending` or `running`, so those two members of the run-status domain are deliberately absent. */ -export type FactoryRunSettledStatus = - /** The factory body resolved and its result was committed. */ +export type WorkflowRunSettledStatus = + /** The workflow body resolved and its result was committed. */ | "completed" /** The run was stopped by a limit, an approval refusal or another policy decision. */ | "halted" @@ -3464,11 +3466,17 @@ export interface CompactionCompleteEvent { */ export interface CompactionCompleteData { /** - * Authoritative active-factory reminder appended to the compacted context + * Legacy active-workflow reminder retained for replay compatibility * * @internal */ activeFactorySummary?: string; + /** + * Authoritative active-workflow reminder appended to the compacted context + * + * @internal + */ + activeWorkflowSummary?: string; /** * Canonical model identifier used for model-specific behavior when replaying compaction */ @@ -7662,7 +7670,7 @@ export interface SubagentStartedData { */ executionMode?: string; /** - * Root id of the factory run that spawned this sub-agent, when it was spawned by one. + * Legacy root id of the workflow run that spawned this sub-agent. New consumers should use workflowRunId. */ factoryRunId?: string; /** @@ -7683,6 +7691,10 @@ export interface SubagentStartedData { * Tool call ID of the parent tool invocation that spawned this sub-agent */ toolCallId: string; + /** + * Root id of the workflow run that spawned this sub-agent, when it was spawned by one. + */ + workflowRunId?: string; } /** * Session event "subagent.configured". Resolved runtime configuration for a configured sub-agent @@ -8500,9 +8512,9 @@ export interface SystemNotificationInstructionDiscovered { type: "instruction_discovered"; } /** - * System notification metadata for a factory execution attempt that reached a terminal state. + * System notification metadata for a workflow execution attempt that reached a terminal state. */ -export interface SystemNotificationFactoryCompleted { +export interface SystemNotificationWorkflowCompleted { /** * Execution attempt that reached this terminal state. */ @@ -8519,32 +8531,32 @@ export interface SystemNotificationFactoryCompleted { * Accumulated active execution time in milliseconds. */ elapsedMs: number; - /** - * Persisted factory name. - */ - factoryName: string; /** * Machine-readable terminal failure details, when present. */ failure?: JsonValue; - pauseInfo?: SystemNotificationFactoryPauseInfo; + pauseInfo?: SystemNotificationWorkflowPauseInfo; /** * Bounded prompt-safe preview of the completed result. */ resultPreview?: string; /** - * Actionable run_factory resume guidance for a resource-limit failure. + * Actionable run_dynamic_workflow resume guidance for a resource-limit failure. */ retryGuidance?: string; /** - * Factory run identifier. + * Workflow run identifier. */ runId: string; - status: SystemNotificationFactoryCompletedStatus; + status: SystemNotificationWorkflowCompletedStatus; /** - * Type discriminator. Always "factory_completed". + * Type discriminator. Always "workflow_completed". */ - type: "factory_completed"; + type: "workflow_completed"; + /** + * Persisted workflow name. + */ + workflowName: string; } /** * System notification metadata from an external host that does not match a runtime-owned notification kind. @@ -9121,41 +9133,45 @@ export interface PermissionRequestExtensionManagement { toolCallId?: string; } /** - * Factory run or authoring permission request + * Workflow run or authoring permission request */ -export interface PermissionRequestFactory { +export interface PermissionRequestWorkflow { /** - * Canonical key used for scoped factory approvals + * Canonical key used for scoped workflow approvals */ approvalKey: string; /** - * Whether this factory is eligible for persistent approval + * Whether this workflow is eligible for persistent approval */ canPersistApproval: boolean; /** - * Factory-declared AI-credit limit before any run/resume caller override is applied. + * Workflow-declared AI-credit limit before any run/resume caller override is applied. */ declaredMaxAiCredits?: number; /** - * Factory-declared concurrent-subagent limit before any run/resume caller override is applied. + * Workflow-declared concurrent-subagent limit before any run/resume caller override is applied. */ declaredMaxConcurrentSubagents?: number; /** - * Factory-declared total-subagent limit before any run/resume caller override is applied. + * Workflow-declared total-subagent limit before any run/resume caller override is applied. */ declaredMaxTotalSubagents?: number; /** - * Factory-declared active-time limit in seconds before any run/resume caller override is applied. + * Workflow-declared active-time limit in seconds before any run/resume caller override is applied. */ declaredTimeoutSeconds?: number; /** - * Factory description + * Workflow description */ description: string; /** * Permission kind discriminator */ - kind: "factory"; + kind: "workflow"; + /** + * Whether managed policy requires a human response and forbids host auto-approval + */ + managedApprovalRequired?: boolean; /** * Effective AI-credit limit; omitted means unlimited */ @@ -9169,14 +9185,14 @@ export interface PermissionRequestFactory { */ maxTotalSubagents?: number; /** - * Factory name + * Workflow name */ name: string; - operation: FactoryPermissionOperation; + operation: WorkflowPermissionOperation; /** - * Declared factory phases + * Declared workflow phases */ - phases: FactoryPermissionPhase[]; + phases: WorkflowPermissionPhase[]; /** * Effective active-time limit in seconds; omitted means unlimited */ @@ -9187,9 +9203,9 @@ export interface PermissionRequestFactory { toolCallId?: string; } /** - * A declared phase shown in a factory permission prompt. + * A declared phase shown in a workflow permission prompt. */ -export interface FactoryPermissionPhase { +export interface WorkflowPermissionPhase { /** * Optional phase detail */ @@ -9623,11 +9639,11 @@ export interface PermissionPromptRequestExtensionManagement { toolCallId?: string; } /** - * Factory run or authoring permission prompt + * Workflow run or authoring permission prompt */ -export interface PermissionPromptRequestFactory { +export interface PermissionPromptRequestWorkflow { /** - * Canonical key used for scoped factory approvals + * Canonical key used for scoped workflow approvals */ approvalKey: string; /** @@ -9637,33 +9653,33 @@ export interface PermissionPromptRequestFactory { */ assistedApproval?: PermissionAssistedApproval; /** - * Whether this factory is eligible for persistent approval + * Whether this workflow is eligible for persistent approval */ canPersistApproval: boolean; /** - * Factory-declared AI-credit limit before any run/resume caller override is applied. + * Workflow-declared AI-credit limit before any run/resume caller override is applied. */ declaredMaxAiCredits?: number; /** - * Factory-declared concurrent-subagent limit before any run/resume caller override is applied. + * Workflow-declared concurrent-subagent limit before any run/resume caller override is applied. */ declaredMaxConcurrentSubagents?: number; /** - * Factory-declared total-subagent limit before any run/resume caller override is applied. + * Workflow-declared total-subagent limit before any run/resume caller override is applied. */ declaredMaxTotalSubagents?: number; /** - * Factory-declared active-time limit in seconds before any run/resume caller override is applied. + * Workflow-declared active-time limit in seconds before any run/resume caller override is applied. */ declaredTimeoutSeconds?: number; /** - * Factory description + * Workflow description */ description: string; /** * Prompt kind discriminator */ - kind: "factory"; + kind: "workflow"; /** * Whether managed policy requires a human response and forbids host auto-approval */ @@ -9681,14 +9697,14 @@ export interface PermissionPromptRequestFactory { */ maxTotalSubagents?: number; /** - * Factory name + * Workflow name */ name: string; - operation: FactoryPermissionOperation; + operation: WorkflowPermissionOperation; /** - * Declared factory phases + * Declared workflow phases */ - phases: FactoryPermissionPhase[]; + phases: WorkflowPermissionPhase[]; /** * Effective active-time limit in seconds; omitted means unlimited */ @@ -9920,17 +9936,17 @@ export interface UserToolSessionApprovalExtensionManagement { operation?: string; } /** - * Session-scoped factory approval, optionally narrowed by approval key. + * Session-scoped workflow approval, optionally narrowed by approval key. */ -export interface UserToolSessionApprovalFactory { +export interface UserToolSessionApprovalWorkflow { /** - * Optional factory operation name or canonical approval key + * Optional workflow operation name or canonical approval key */ approvalKey?: string; /** - * Factory approval kind + * Workflow approval kind */ - kind: "factory"; + kind: "workflow"; } /** * Session-scoped tool-approval rule for an extension's permission-gated capability access, keyed by extension name. @@ -10082,7 +10098,7 @@ export interface PermissionDeniedByPermissionRequestHook { message?: string; } /** - * Session event "permission.carriedForward". Records that a live authorization record from an earlier human decision in this session contained a permission proposal, so it ran without another prompt. This mints no authority: it accounts for one more effect against the prior grant, which is what lets a replayed session agree with the live one about how much of that grant is left. + * Session event "permission.carriedForward". Historical decode-only receipt from the retired Assisted Permissions authorization extractor. Current runtimes ignore it for permission decisions. */ /** @experimental */ export interface PermissionCarriedForwardEvent { @@ -10113,7 +10129,7 @@ export interface PermissionCarriedForwardEvent { type: "permission.carriedForward"; } /** - * Records that a live authorization record from an earlier human decision in this session contained a permission proposal, so it ran without another prompt. This mints no authority: it accounts for one more effect against the prior grant, which is what lets a replayed session agree with the live one about how much of that grant is left. + * Historical decode-only receipt from the retired Assisted Permissions authorization extractor. Current runtimes ignore it for permission decisions. */ /** @experimental */ export interface PermissionCarriedForwardData { @@ -10143,7 +10159,7 @@ export interface PermissionCarriedForwardData { toolCallId: string; } /** - * Session event "permission.messageAuthorization". Freezes one blinded, verbatim-verified authorization claim the runtime minted from a human user message, so a resumed session re-establishes the same grant deterministically instead of re-running the extraction model. This mints no authority on its own: it records what a blinded proposer pointed at and the trusted discriminator the runtime established, and deterministic establishment runs on replay. Persisted so recorded authority survives compaction and process resume. + * Session event "permission.messageAuthorization". Historical decode-only claim from the retired Assisted Permissions authorization extractor. Current runtimes preserve the payload but do not establish authority from it. */ /** @experimental */ export interface PermissionMessageAuthorizationEvent { @@ -10174,7 +10190,7 @@ export interface PermissionMessageAuthorizationEvent { type: "permission.messageAuthorization"; } /** - * Freezes one blinded, verbatim-verified authorization claim the runtime minted from a human user message, so a resumed session re-establishes the same grant deterministically instead of re-running the extraction model. This mints no authority on its own: it records what a blinded proposer pointed at and the trusted discriminator the runtime established, and deterministic establishment runs on replay. Persisted so recorded authority survives compaction and process resume. + * Historical decode-only claim from the retired Assisted Permissions authorization extractor. Current runtimes preserve the payload but do not establish authority from it. */ /** @experimental */ export interface PermissionMessageAuthorizationData { @@ -10234,7 +10250,7 @@ export interface PermissionMessageAuthorizationData { world?: JsonValue; } /** - * Session event "permission.messageAuthorizationRead". Records that one human turn has been read by the blinded authorization proposer, whether or not it minted anything, so a resumed session does not re-run the extraction model on a turn the live session already read. Also records whether that pass activates ongoing extraction; contextual-assent-only passes do not, so unrelated future messages remain outside extraction. + * Session event "permission.messageAuthorizationRead". Historical decode-only extractor progress marker. Current runtimes do not run or resume extraction from it. */ /** @experimental */ export interface PermissionMessageAuthorizationReadEvent { @@ -10265,7 +10281,7 @@ export interface PermissionMessageAuthorizationReadEvent { type: "permission.messageAuthorizationRead"; } /** - * Records that one human turn has been read by the blinded authorization proposer, whether or not it minted anything, so a resumed session does not re-run the extraction model on a turn the live session already read. Also records whether that pass activates ongoing extraction; contextual-assent-only passes do not, so unrelated future messages remain outside extraction. + * Historical decode-only extractor progress marker. Current runtimes do not run or resume extraction from it. */ /** @experimental */ export interface PermissionMessageAuthorizationReadData { @@ -10283,7 +10299,7 @@ export interface PermissionMessageAuthorizationReadData { turnIndex: number; } /** - * Session event "permission.messageAuthorizationDegraded". Records that message-backed authorization could not safely represent one human turn before compaction. The runtime may compact the original message after this marker is durable, but message-derived carry-forward and assisted auto-approval remain disabled for the rest of the session so subsequent commands continue through the ordinary permission prompt. + * Session event "permission.messageAuthorizationDegraded". Historical decode-only degradation marker from the retired extractor. Current runtimes ignore it for permission decisions. */ /** @experimental */ export interface PermissionMessageAuthorizationDegradedEvent { @@ -10314,7 +10330,7 @@ export interface PermissionMessageAuthorizationDegradedEvent { type: "permission.messageAuthorizationDegraded"; } /** - * Records that message-backed authorization could not safely represent one human turn before compaction. The runtime may compact the original message after this marker is durable, but message-derived carry-forward and assisted auto-approval remain disabled for the rest of the session so subsequent commands continue through the ordinary permission prompt. + * Historical decode-only degradation marker from the retired extractor. Current runtimes ignore it for permission decisions. */ /** @experimental */ export interface PermissionMessageAuthorizationDegradedData { @@ -10326,7 +10342,7 @@ export interface PermissionMessageAuthorizationDegradedData { turnIndex: number; } /** - * Session event "permission.assentDetected". Records that deterministic text recognition found likely assent in the human turn immediately following a root Autopilot permission request that was blocked because no interactive response was available. This event grants no authority; its model-facing projection only suggests retrying the unchanged operation. + * Session event "permission.assentDetected". Historical decode-only contextual-assent marker. Current runtimes do not project it into the conversation or permission flow. */ /** @experimental */ export interface PermissionAssentDetectedEvent { @@ -10357,7 +10373,7 @@ export interface PermissionAssentDetectedEvent { type: "permission.assentDetected"; } /** - * Records that deterministic text recognition found likely assent in the human turn immediately following a root Autopilot permission request that was blocked because no interactive response was available. This event grants no authority; its model-facing projection only suggests retrying the unchanged operation. + * Historical decode-only contextual-assent marker. Current runtimes do not project it into the conversation or permission flow. */ /** @experimental */ export interface PermissionAssentDetectedData { @@ -10375,7 +10391,7 @@ export interface PermissionAssentDetectedData { turnIndex: number; } /** - * Session event "permission.contextualAuthorization". Freezes a blinded contextual authorization proposal whose verbatim human span was deterministically bound to the immediately preceding blocked permission request. The event carries no action fields; replay re-derives the exact action from the earlier permission request and mints a one-shot message grant only when the binding and span still verify. + * Session event "permission.contextualAuthorization". Historical decode-only contextual authorization claim. Current runtimes preserve the payload but do not establish authority from it. */ /** @experimental */ export interface PermissionContextualAuthorizationEvent { @@ -10406,7 +10422,7 @@ export interface PermissionContextualAuthorizationEvent { type: "permission.contextualAuthorization"; } /** - * Freezes a blinded contextual authorization proposal whose verbatim human span was deterministically bound to the immediately preceding blocked permission request. The event carries no action fields; replay re-derives the exact action from the earlier permission request and mints a one-shot message grant only when the binding and span still verify. + * Historical decode-only contextual authorization claim. Current runtimes preserve the payload but do not establish authority from it. */ /** @experimental */ export interface PermissionContextualAuthorizationData { @@ -12064,15 +12080,15 @@ export interface BackgroundTasksChangedEvent { */ export interface BackgroundTasksChangedData {} /** - * Session event "factory.run_updated". Ephemeral invalidation signal for a changed factory run. + * Session event "workflow.run_updated". Ephemeral invalidation signal for a changed workflow run. */ /** @experimental */ -export interface FactoryRunUpdatedEvent { +export interface WorkflowRunUpdatedEvent { /** * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; - data: FactoryRunUpdatedData; + data: WorkflowRunUpdatedData; /** * Always true for events that are transient and not persisted to the session event log on disk. */ @@ -12090,34 +12106,34 @@ export interface FactoryRunUpdatedEvent { */ timestamp: string; /** - * Type discriminator. Always "factory.run_updated". + * Type discriminator. Always "workflow.run_updated". */ - type: "factory.run_updated"; + type: "workflow.run_updated"; } /** - * Ephemeral invalidation signal for a changed factory run. + * Ephemeral invalidation signal for a changed workflow run. */ /** @experimental */ -export interface FactoryRunUpdatedData { +export interface WorkflowRunUpdatedData { /** * Monotonic revision now available for the run. */ revision: number; /** - * Factory run identifier. + * Workflow run identifier. */ runId: string; } /** - * Session event "factory.run_started". Ephemeral signal that a factory run attempt began executing. + * Session event "workflow.run_started". Ephemeral signal that a workflow run attempt began executing. */ /** @experimental */ -export interface FactoryRunStartedEvent { +export interface WorkflowRunStartedEvent { /** * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; - data: FactoryRunStartedData; + data: WorkflowRunStartedData; /** * Always true for events that are transient and not persisted to the session event log on disk. */ @@ -12135,38 +12151,38 @@ export interface FactoryRunStartedEvent { */ timestamp: string; /** - * Type discriminator. Always "factory.run_started". + * Type discriminator. Always "workflow.run_started". */ - type: "factory.run_started"; + type: "workflow.run_started"; } /** - * Ephemeral signal that a factory run attempt began executing. + * Ephemeral signal that a workflow run attempt began executing. */ /** @experimental */ -export interface FactoryRunStartedData { +export interface WorkflowRunStartedData { /** * Attempt number this start committed; a resumed run increments it. */ attempt: number; /** - * Name of the factory this run executes. Low cardinality by construction. + * Identifier of the workflow run that started. */ - factoryName: string; + runId: string; /** - * Identifier of the factory run that started. + * Name of the workflow this run executes. Low cardinality by construction. */ - runId: string; + workflowName: string; } /** - * Session event "factory.run_settled". Ephemeral signal that a factory run reached a terminal status. + * Session event "workflow.run_settled". Ephemeral signal that a workflow run reached a terminal status. */ /** @experimental */ -export interface FactoryRunSettledEvent { +export interface WorkflowRunSettledEvent { /** * Sub-agent instance identifier. Absent for events from the root/main agent and session-level events. */ agentId?: string; - data: FactoryRunSettledData; + data: WorkflowRunSettledData; /** * Always true for events that are transient and not persisted to the session event log on disk. */ @@ -12184,15 +12200,15 @@ export interface FactoryRunSettledEvent { */ timestamp: string; /** - * Type discriminator. Always "factory.run_settled". + * Type discriminator. Always "workflow.run_settled". */ - type: "factory.run_settled"; + type: "workflow.run_settled"; } /** - * Ephemeral signal that a factory run reached a terminal status. + * Ephemeral signal that a workflow run reached a terminal status. */ /** @experimental */ -export interface FactoryRunSettledData { +export interface WorkflowRunSettledData { /** * AI credits this run consumed, in nano-AIU. */ @@ -12206,14 +12222,14 @@ export interface FactoryRunSettledData { */ elapsedMs: number; /** - * Typed failure class recorded on the run, when it failed with one (e.g. `factory_limit_reached`). + * Typed failure class recorded on the run, when it failed with one (e.g. `workflow_limit_reached`). */ failureType?: string; /** - * Identifier of the factory run that settled. + * Identifier of the workflow run that settled. */ runId: string; - status: FactoryRunSettledStatus; + status: WorkflowRunSettledStatus; } /** * Session event "session.skills_loaded". Payload of `session.skills_loaded` listing resolved skill metadata. diff --git a/nodejs/src/index.ts b/nodejs/src/index.ts index c46742d853..c5d2b4e852 100644 --- a/nodejs/src/index.ts +++ b/nodejs/src/index.ts @@ -12,7 +12,6 @@ export { CopilotClient } from "./client.js"; export { DisableBypassPermissionsModes, RuntimeConnection } from "./types.js"; export { BuiltInTools, ToolSet } from "./toolSet.js"; export { CopilotSession, type AssistantMessageEvent } from "./session.js"; -export { defineFactory, FactoryResumeError, isFactoryRunTerminal } from "./factory.js"; export { defineWorkflow, WorkflowResumeError, isWorkflowRunTerminal } from "./workflow.js"; export { Canvas, @@ -48,7 +47,7 @@ export { // `PermissionRequest` (re-exported below from `./types.js`), // `PermissionRequestedData`/`PermissionRequestedEvent` (also re-exported below // from `./types.js`), `AssistantMessageEvent` (re-exported above from -// `./session.js`), and `JsonValue` (re-exported below from `./factory.js`). +// `./session.js`), and `JsonValue` (re-exported below from `./workflow.js`). // Per the ECMAScript module spec, the explicit named re-exports // shadow the names arriving via `export type *`, so the hand-authored public API // surface for those six identifiers is preserved unchanged. @@ -127,8 +126,6 @@ export type { LargeToolOutputConfig, MemoryConfiguration, UiInputOptions, - FactoryLimits, - FactoryMeta, MCPStdioServerConfig, MCPHTTPServerConfig, MCPServerConfig, @@ -222,32 +219,7 @@ export type { ZodSchema, } from "./types.js"; export type { - RunOptions, - ResumeOptions, - FactoryLimitOverrides, - FactoryResumeErrorCode, - SessionFactoryApi, - FactoryAgentOptions, - FactoryContext, - FactoryDefinition, - FactoryHandle, - FactoryJsonSchema, JsonValue, - FactoryPipelineStage, - FactoryStepOptions, - FactoryRunResult, - FactoryRunStatus, - FactoryRunSummary, - FactoryListRunsOptions, - FactoryRunsPage, - FactoryRunDetail, - FactoryProgressPage, - FactoryProgressLine, - FactoryPhaseObservation, - FactoryPhaseStatus, - FactoryAgentSummary, -} from "./factory.js"; -export type { WorkflowRunOptions, WorkflowResumeOptions, WorkflowLimitOverrides, diff --git a/nodejs/src/session.ts b/nodejs/src/session.ts index 43b2128625..39e023a7bc 100644 --- a/nodejs/src/session.ts +++ b/nodejs/src/session.ts @@ -16,8 +16,6 @@ import type { CanvasActionInvokeResult, CurrentToolMetadata, McpOauthPendingRequestResponse, - FactoryLogLine, - FactoryRunResult as WireFactoryRunResult, WorkflowLogLine, WorkflowRunResult as WireWorkflowRunResult, ModelSwitchAutoTierResult, @@ -71,22 +69,6 @@ import type { UserInputRequest, UserInputResponse, } from "./types.js"; -import { - FACTORY_AGENT_OPTION_KEYS, - getFactoryDefinition, - FactoryResumeError, - isFactoryRunTerminal, - type FactoryResumeErrorCode, - type FactoryListRunsOptions, - type FactoryRunResult, - type FactoryAgentOptions, - type RunOptions, - type SessionFactoryApi, - type FactoryContext, - type FactoryHandle, - type JsonValue, - type FactoryStepOptions, -} from "./factory.js"; import { WORKFLOW_AGENT_OPTION_KEYS, getWorkflowDefinition, @@ -100,33 +82,10 @@ import { type SessionWorkflowApi, type WorkflowContext, type WorkflowHandle, + type JsonValue, type WorkflowStepOptions, } from "./workflow.js"; -function isFactoryResumeErrorCode(value: unknown): value is FactoryResumeErrorCode { - return ( - value === "not_found" || - value === "non_resumable" || - value === "already_active" || - value === "factory_already_running" || - value === "factory_limits_invalid" || - value === "factory_session_disposed" || - value === "factory_storage_unavailable" || - value === "factory_storage_corrupt" - ); -} - -function copyDefinedFactoryAgentOption( - source: FactoryAgentOptions, - target: FactoryAgentOptions, - key: TKey -): void { - const value = source[key]; - if (value !== undefined) { - target[key] = value; - } -} - function isWorkflowResumeErrorCode(value: unknown): value is WorkflowResumeErrorCode { return ( value === "not_found" || @@ -152,21 +111,6 @@ function copyDefinedWorkflowAgentOption } } -type FactoryExecutionContext = { - active: boolean; - helperScope?: "parallel" | "pipeline"; -}; - -const factoryExecutionStore = new AsyncLocalStorage(); - -function throwIfFactoryExecutionIsActive(): void { - if (factoryExecutionStore.getStore()?.active) { - throw new Error( - "factory.run, factory.resume, and factory.pause are not allowed while a factory body is running on this call path." - ); - } -} - type WorkflowExecutionContext = { active: boolean; helperScope?: "parallel" | "pipeline"; @@ -190,14 +134,6 @@ function runInWorkflowHelperScope( return workflowExecutionStore.run({ active: current?.active ?? false, helperScope }, callback); } -function runInFactoryHelperScope( - helperScope: "parallel" | "pipeline", - callback: () => Promise | TResult -): Promise | TResult { - const current = factoryExecutionStore.getStore(); - return factoryExecutionStore.run({ active: current?.active ?? false, helperScope }, callback); -} - /** * Convert a raw hook input received over the wire into its public-facing shape. * This deserializes the numeric Unix-ms `timestamp` field on BaseHookInput @@ -243,7 +179,7 @@ function isOpenCanvasInstance(value: unknown): value is OpenCanvasInstance { const FACTORY_LOG_FLUSH_DELAY_MS = 10; const MAX_FACTORY_FANOUT_ITEMS = 4096; -function assertFactoryFanoutSize(kind: "parallel" | "pipeline", size: number): void { +function assertWorkflowFanoutSize(kind: "parallel" | "pipeline", size: number): void { if (size > MAX_FACTORY_FANOUT_ITEMS) { throw new Error( `${kind}() accepts at most ${MAX_FACTORY_FANOUT_ITEMS} items; got ${size}.` @@ -251,74 +187,6 @@ function assertFactoryFanoutSize(kind: "parallel" | "pipeline", size: number): v } } -async function runFactoryParallel( - thunks: Array<() => Promise | TResult> -): Promise> { - if (!Array.isArray(thunks)) { - throw new Error( - "parallel() expects an array of functions, not promises. Wrap each call: () => agent(...)" - ); - } - assertFactoryFanoutSize("parallel", thunks.length); - if (thunks.some((thunk) => typeof thunk !== "function")) { - throw new Error( - "parallel() expects an array of functions, not promises. Wrap each call: () => agent(...)" - ); - } - return Promise.all( - thunks.map((thunk) => - Promise.resolve() - .then(() => runInFactoryHelperScope("parallel", thunk)) - .catch((error) => { - // Cancellation and hard runtime failures must propagate out - // of the combinator rather than be mapped to a successful - // `null`; otherwise an aborted run, or one that hit a - // resource ceiling or durable-state failure, could be - // reported as completed. An ordinary subagent failure never - // rejects — it already resolves `null`. - if (isFactoryFatalError(error)) { - throw error; - } - return null; - }) - ) - ); -} - -async function runFactoryPipeline( - items: unknown[], - ...stages: Array< - (previous: unknown, item: unknown, index: number) => Promise | unknown - > -): Promise { - if (!Array.isArray(items)) { - throw new Error("pipeline(items, ...stages): items must be an array"); - } - assertFactoryFanoutSize("pipeline", items.length); - return Promise.all( - items.map(async (item, index) => { - let previous = item; - for (const stage of stages) { - try { - previous = await runInFactoryHelperScope("pipeline", () => - stage(previous, item, index) - ); - } catch (error) { - // Propagate cancellation and hard runtime failures instead - // of mapping them to `null`, so an aborted stage — or one - // that hit a resource ceiling or durable-state failure — - // does not let the run report success. - if (isFactoryFatalError(error)) { - throw error; - } - return null; - } - } - return previous; - }) - ); -} - async function runWorkflowParallel( thunks: Array<() => Promise | TResult> ): Promise> { @@ -327,7 +195,7 @@ async function runWorkflowParallel( "parallel() expects an array of functions, not promises. Wrap each call: () => agent(...)" ); } - assertFactoryFanoutSize("parallel", thunks.length); + assertWorkflowFanoutSize("parallel", thunks.length); if (thunks.some((thunk) => typeof thunk !== "function")) { throw new Error( "parallel() expects an array of functions, not promises. Wrap each call: () => agent(...)" @@ -338,7 +206,7 @@ async function runWorkflowParallel( Promise.resolve() .then(() => runInWorkflowHelperScope("parallel", thunk)) .catch((error) => { - if (isFactoryFatalError(error)) { + if (isWorkflowFatalError(error)) { throw error; } return null; @@ -356,7 +224,7 @@ async function runWorkflowPipeline( if (!Array.isArray(items)) { throw new Error("pipeline(items, ...stages): items must be an array"); } - assertFactoryFanoutSize("pipeline", items.length); + assertWorkflowFanoutSize("pipeline", items.length); return Promise.all( items.map(async (item, index) => { let previous = item; @@ -366,7 +234,7 @@ async function runWorkflowPipeline( stage(previous, item, index) ); } catch (error) { - if (isFactoryFatalError(error)) { + if (isWorkflowFatalError(error)) { throw error; } return null; @@ -377,89 +245,6 @@ async function runWorkflowPipeline( ); } -class FactoryProgressBuffer { - private nextSeq = 0; - private pending: FactoryLogLine[] = []; - private flushTimer?: ReturnType; - private flushTail: Promise = Promise.resolve(); - private flushError: unknown; - private flushFailed = false; - private closed = false; - - constructor(private readonly send: (lines: FactoryLogLine[]) => Promise) {} - - enqueue(kind: FactoryLogLine["kind"], text: string): void { - if (this.closed) { - throw new Error("Cannot log after the factory run has settled"); - } - - this.pending.push({ seq: this.nextSeq++, kind, text }); - this.scheduleFlush(); - } - - async flush(): Promise { - this.clearFlushTimer(); - const lines = this.pending.splice(0); - if (lines.length > 0) { - this.flushTail = this.flushTail.then(async () => { - try { - await this.send(lines); - } catch (error) { - if (!this.flushFailed) { - this.flushFailed = true; - this.flushError = error; - } - } - }); - } - await this.flushTail; - if (this.flushFailed) { - throw this.flushError; - } - } - - async close(): Promise { - this.closed = true; - this.clearFlushTimer(); - const lines = this.pending.splice(0); - await this.flushTail; - if (this.flushFailed) { - console.warn( - "Ignoring a background factory progress flush failure after the factory body settled", - this.flushError - ); - } - if (lines.length > 0) { - try { - await this.send(lines); - } catch (error) { - console.warn( - "Failed to flush final factory progress after the factory body settled", - error - ); - } - } - } - - private scheduleFlush(): void { - if (this.flushTimer !== undefined) { - return; - } - this.flushTimer = setTimeout(() => { - this.flushTimer = undefined; - void this.flush().catch(() => {}); - }, FACTORY_LOG_FLUSH_DELAY_MS); - this.flushTimer.unref?.(); - } - - private clearFlushTimer(): void { - if (this.flushTimer !== undefined) { - clearTimeout(this.flushTimer); - this.flushTimer = undefined; - } - } -} - class WorkflowProgressBuffer { private nextSeq = 0; private pending: WorkflowLogLine[] = []; @@ -542,7 +327,7 @@ class WorkflowProgressBuffer { } } -async function awaitFactoryOperation( +async function awaitWorkflowOperation( operation: () => Promise, signal: AbortSignal ): Promise { @@ -553,32 +338,19 @@ async function awaitFactoryOperation( rejectAbort = reject; }); const onAbort = () => - rejectAbort?.(signal.reason ?? new DOMException("Factory run was aborted", "AbortError")); + rejectAbort?.(signal.reason ?? new DOMException("Workflow run was aborted", "AbortError")); // Register before the abort check and before dispatching, so an abort can // neither be missed by a not-yet-attached listener nor start work on an // already-cancelled run. signal.addEventListener("abort", onAbort, { once: true }); try { - throwIfFactoryAborted(signal); + throwIfWorkflowAborted(signal); return await Promise.race([operation(), abortPromise]); } finally { signal.removeEventListener("abort", onAbort); } } -async function awaitWorkflowOperation( - operation: () => Promise, - signal: AbortSignal -): Promise { - return awaitFactoryOperation(operation, signal); -} - -function throwIfFactoryAborted(signal: AbortSignal): void { - if (signal.aborted) { - throw signal.reason ?? new DOMException("Factory run was aborted", "AbortError"); - } -} - function throwIfWorkflowAborted(signal: AbortSignal): void { if (signal.aborted) { throw signal.reason ?? new DOMException("Workflow run was aborted", "AbortError"); @@ -586,11 +358,11 @@ function throwIfWorkflowAborted(signal: AbortSignal): void { } /** - * Whether an error represents factory run cancellation (an `AbortError`-shaped - * rejection from {@link awaitFactoryOperation}). Cancellation must bubble out of + * Whether an error represents workflow run cancellation (an `AbortError`-shaped + * rejection from {@link awaitWorkflowOperation}). Cancellation must bubble out of * `parallel`/`pipeline` rather than being flattened into a `null` result. */ -function isFactoryAbortError(error: unknown): boolean { +function isWorkflowAbortError(error: unknown): boolean { return ( typeof error === "object" && error !== null && @@ -600,7 +372,7 @@ function isFactoryAbortError(error: unknown): boolean { } /** - * Errors a factory combinator must never swallow into a `null` item. + * Errors a workflow combinator must never swallow into a `null` item. * * Cooperative cancellation aborts the run, and a rejected RPC is a hard * runtime failure — a reached limit, a durable-state failure, or a dropped @@ -608,9 +380,9 @@ function isFactoryAbortError(error: unknown): boolean { * successfully-`null` item. An ordinary subagent failure does not reject; the * runtime already resolves it as `null`. */ -function isFactoryFatalError(error: unknown): boolean { +function isWorkflowFatalError(error: unknown): boolean { return ( - isFactoryAbortError(error) || + isWorkflowAbortError(error) || error instanceof ResponseError || error instanceof ConnectionError ); @@ -661,8 +433,6 @@ export class CopilotSession { private canvases: Map = new Map(); private bearerTokenProviders: Map = new Map(); private commandHandlers: Map = new Map(); - private factories = new Map>(); - private factoryAbortControllers = new Map>(); private workflows = new Map>(); private workflowAbortControllers = new Map>(); private permissionHandler?: PermissionHandler; @@ -688,81 +458,11 @@ export class CopilotSession { clientSessionApis: ClientSessionApiHandlers = {}; /** - * Friendly factory API for running registered factories by name or handle. + * Friendly workflow API for running registered workflows by name or handle. * - * @experimental Part of the experimental Agent Factories surface and may + * @experimental Part of the experimental Dynamic Workflows surface and may * change or be removed in future SDK or CLI releases. */ - readonly factory: SessionFactoryApi = { - run: (async ( - nameOrHandle: string | FactoryHandle, - options?: RunOptions - ): Promise => { - throwIfFactoryExecutionIsActive(); - const name = - typeof nameOrHandle === "string" - ? nameOrHandle - : getFactoryDefinition(nameOrHandle).meta.name; - if (options?.resumeFromRunId !== undefined) { - return this.factory.resume(options.resumeFromRunId, { - limits: options.limits, - notifyOnComplete: options.notifyOnComplete, - logPhaseNames: options.logPhaseNames, - }); - } - const envelope = await this.rpc.factory.run({ - name, - args: options?.args === undefined ? {} : options.args, - options: { - limits: options?.limits, - notifyOnComplete: options?.notifyOnComplete, - logPhaseNames: options?.logPhaseNames, - }, - }); - - return this.settleFactoryRun(envelope); - }) as SessionFactoryApi["run"], - resume: (async (runId: string, options?: Parameters[1]) => { - throwIfFactoryExecutionIsActive(); - let response; - try { - response = await this.rpc.factory.resume({ - runId, - limits: options?.limits, - notifyOnComplete: options?.notifyOnComplete, - logPhaseNames: options?.logPhaseNames, - }); - } catch (error) { - if ( - error instanceof ResponseError && - typeof error.data === "object" && - error.data !== null - ) { - const code = (error.data as { code?: unknown }).code; - if (isFactoryResumeErrorCode(code)) { - throw new FactoryResumeError(code, error.message); - } - } - throw error; - } - return this.settleFactoryRun(response.run); - }) as SessionFactoryApi["resume"], - getRun: async (runId) => this.rpc.factory.getRun({ runId }), - waitForRun: (runId, options) => this.waitForFactoryRun(runId, options?.signal), - listRuns: (async (options?: FactoryListRunsOptions) => { - const page = await this.rpc.factory.listRuns(options ?? {}); - return options === undefined ? page.runs : page; - }) as SessionFactoryApi["listRuns"], - getRunDetail: (runId) => this.rpc.factory.getRunDetail({ runId }), - getRunProgress: (runId, options = {}) => - this.rpc.factory.getRunProgress({ runId, ...options }), - pause: async (runId) => { - throwIfFactoryExecutionIsActive(); - return this.rpc.factory.pause({ runId }); - }, - cancel: async (runId) => this.rpc.factory.cancel({ runId }), - }; - readonly workflow: SessionWorkflowApi = { run: (async ( nameOrHandle: string | WorkflowHandle, @@ -826,104 +526,6 @@ export class CopilotSession { cancel: async (runId) => this.rpc.workflow.cancel({ runId }), }; - /** - * Resolve a start/resume envelope into the terminal envelope callers expect. - * - * The CLI may answer `session.factory.run` and `session.factory.resume` - * before the run settles, so a non-terminal envelope is followed by a wait - * on the run's terminal state. - */ - private settleFactoryRun(envelope: WireFactoryRunResult): Promise { - if (isFactoryRunTerminal(envelope.status)) { - return Promise.resolve(envelope); - } - return this.waitForFactoryRun(envelope.runId); - } - - /** - * Resolve when a factory run reaches a terminal status. - * - * The subscription is installed *before* the first read so a transition - * landing between the two cannot be missed, and re-reads are serialized so - * overlapping invalidation events cannot interleave — the run's revision - * advances once per operation, so a burst of events is common and must - * collapse into a single in-flight read. A bounded periodic re-read keeps a - * dropped invalidation from leaving the wait pending forever. - */ - private waitForFactoryRun(runId: string, signal?: AbortSignal): Promise { - const abortError = (): unknown => - signal?.reason ?? new DOMException("Factory run wait was aborted", "AbortError"); - if (signal?.aborted === true) { - return Promise.reject(abortError()); - } - - return new Promise((resolve, reject) => { - let settled = false; - let reading = false; - let rereadRequested = false; - let pollHandle: ReturnType | undefined; - let unsubscribe: (() => void) | undefined; - let onAbort: (() => void) | undefined; - - const finish = (complete: () => void): void => { - if (settled) { - return; - } - settled = true; - if (pollHandle !== undefined) { - clearInterval(pollHandle); - } - unsubscribe?.(); - if (onAbort !== undefined) { - signal?.removeEventListener("abort", onAbort); - } - complete(); - }; - - const read = async (): Promise => { - if (settled) { - return; - } - if (reading) { - rereadRequested = true; - return; - } - reading = true; - try { - do { - rereadRequested = false; - const envelope = await this.rpc.factory.getRun({ runId }); - if (isFactoryRunTerminal(envelope.status)) { - finish(() => resolve(envelope)); - return; - } - } while (rereadRequested && !settled); - } catch (error) { - finish(() => reject(error)); - } finally { - reading = false; - } - }; - - if (signal !== undefined) { - onAbort = (): void => finish(() => reject(abortError())); - signal.addEventListener("abort", onAbort, { once: true }); - } - - unsubscribe = this.on("factory.run_updated", (event) => { - if (event.data.runId === runId) { - void read(); - } - }); - - pollHandle = setInterval(() => void read(), 5_000); - // The re-read is a safety net, not work the process owes anyone: an - // outstanding wait must never keep Node alive on its own. - pollHandle.unref?.(); - void read(); - }); - } - private settleWorkflowRun(envelope: WireWorkflowRunResult): Promise { if (isWorkflowRunTerminal(envelope.status)) { return Promise.resolve(envelope); @@ -1001,7 +603,7 @@ export class CopilotSession { signal.addEventListener("abort", onAbort, { once: true }); } - unsubscribe = this.on("factory.run_updated", (event) => { + unsubscribe = this.on("workflow.run_updated", (event) => { if (event.data.runId === runId) { void read(); } @@ -1403,13 +1005,6 @@ export class CopilotSession { this.autoModeSwitchHandler = undefined; this.commandHandlers.clear(); this.canvases.clear(); - this.factories.clear(); - for (const controllersForRun of this.factoryAbortControllers.values()) { - for (const controller of controllersForRun.values()) { - controller.abort(); - } - } - this.factoryAbortControllers.clear(); this.workflows.clear(); for (const controllersForRun of this.workflowAbortControllers.values()) { for (const controller of controllersForRun.values()) { @@ -2000,213 +1595,6 @@ export class CopilotSession { }; } - /** - * Registers factory closures and reverse-RPC handlers for this session. - * - * @param factories - Factory handles declared by the joining extension. - * @internal Called by the SDK when an extension joins a session. - */ - registerFactories(factories?: FactoryHandle[]): void { - this.factories.clear(); - if (!factories || factories.length === 0) { - delete this.clientSessionApis.factory; - return; - } - - for (const handle of factories) { - const definition = getFactoryDefinition(handle); - if (this.factories.has(definition.meta.name)) { - throw new Error( - `Duplicate factory name "${definition.meta.name}". Factory names must be unique within a joinSession call.` - ); - } - this.factories.set(definition.meta.name, definition); - } - - const self = this; - this.clientSessionApis.factory = { - async execute(params) { - const definition = self.factories.get(params.name); - if (!definition) { - const message = `No factory registered with name "${params.name}"`; - throw new ResponseError(ErrorCodes.InvalidParams, message, { - code: "factory_not_found", - name: params.name, - }); - } - - const controller = new AbortController(); - // Keyed by execution token as well as run ID so overlapping - // attempts for one run stay individually addressable. - let controllersForRun = self.factoryAbortControllers.get(params.runId); - if (controllersForRun === undefined) { - controllersForRun = new Map(); - self.factoryAbortControllers.set(params.runId, controllersForRun); - } - controllersForRun.set(params.executionToken, controller); - const progress = new FactoryProgressBuffer(async (lines) => { - await self.rpc.factory.log({ - runId: params.runId, - executionToken: params.executionToken, - lines, - }); - }); - try { - const context: FactoryContext = { - runId: params.runId, - args: params.args, - session: self, - signal: controller.signal, - phase: (title: string) => { - throwIfFactoryAborted(controller.signal); - progress.enqueue("phase", title); - }, - log: (message: string) => { - throwIfFactoryAborted(controller.signal); - progress.enqueue("log", message); - }, - agent: async (prompt, options = {}) => { - await progress.flush(); - const opts: FactoryAgentOptions = {}; - for (const key of FACTORY_AGENT_OPTION_KEYS) { - copyDefinedFactoryAgentOption(options, opts, key); - } - const response = await awaitFactoryOperation( - () => - self.rpc.factory.agent({ - factoryRunId: params.runId, - executionToken: params.executionToken, - prompt, - opts, - }), - controller.signal - ); - return response.result ?? null; - }, - step: async ( - key: string, - producer: () => Promise | JsonValue, - options: FactoryStepOptions = {} - ): Promise => { - await progress.flush(); - if (options.volatile) { - // The flush above is an await point, so an abort can land - // between entering step() and running the producer. The - // journaled branch is covered by awaitFactoryOperation; - // this one has to check for itself, or a cancelled run - // would still start new extension work. - throwIfFactoryAborted(controller.signal); - return producer(); - } - const cached = await awaitFactoryOperation( - () => - self.rpc.factory.journal.get({ - runId: params.runId, - executionToken: params.executionToken, - key, - }), - controller.signal - ); - if (cached.hit) { - if (cached.resultJson === undefined) { - throw new Error( - `step("${key}") journal returned a hit without a result` - ); - } - assertFactoryStepResult(cached.resultJson, key); - return cached.resultJson; - } - - // Producers are best-effort at-least-once across crashes or - // concurrent callers, so authors must make side effects idempotent. - const result = await producer(); - assertFactoryStepResult(result, key); - await awaitFactoryOperation( - () => - self.rpc.factory.journal.put({ - runId: params.runId, - executionToken: params.executionToken, - key, - resultJson: result, - }), - controller.signal - ); - return result; - }, - pause: async (key: string): Promise => { - if (typeof key !== "string" || key.length === 0) { - throw new Error("Factory pause checkpoint key must not be empty"); - } - const helperScope = factoryExecutionStore.getStore()?.helperScope; - if (helperScope !== undefined) { - throw new Error( - `Factory pause checkpoints are not allowed inside ${helperScope}() branches` - ); - } - await progress.flush(); - const response = await awaitFactoryOperation( - () => - self.internalRpc.factory.pauseAtCheckpoint({ - runId: params.runId, - executionToken: params.executionToken, - key, - }), - controller.signal - ); - switch (response.action) { - case "continue": - return; - case "pause": - await awaitFactoryOperation( - () => new Promise(() => {}), - controller.signal - ); - } - }, - parallel: runFactoryParallel, - pipeline: runFactoryPipeline, - factory: async () => { - throw new Error("nested factories are not supported"); - }, - }; - const execution = { active: true }; - const result = await factoryExecutionStore.run(execution, async () => { - try { - return await definition.run(context); - } finally { - execution.active = false; - } - }); - if (result === undefined) { - return {}; - } - assertFactoryResult(result); - return { result }; - } finally { - try { - await progress.close(); - } finally { - const controllersForRun = self.factoryAbortControllers.get(params.runId); - if (controllersForRun?.get(params.executionToken) === controller) { - controllersForRun.delete(params.executionToken); - if (controllersForRun.size === 0) { - self.factoryAbortControllers.delete(params.runId); - } - } - } - } - }, - async abort(params) { - const controllersForRun = self.factoryAbortControllers.get(params.runId); - const controller = controllersForRun?.get(params.executionToken); - if (controller !== undefined) { - controller.abort(new DOMException("Factory run was aborted", "AbortError")); - } - return {}; - }, - }; - } - /** * Registers workflow closures and reverse-RPC handlers for this session. * @@ -3065,7 +2453,7 @@ function toCanvasRpcError(error: unknown): ResponseError { return new ResponseError(ErrorCodes.InternalError, message, { code, message }); } -type FactoryResultValidationCategory = +type WorkflowResultValidationCategory = | "unsupported_type" | "non_finite_number" | "negative_zero" @@ -3074,21 +2462,17 @@ type FactoryResultValidationCategory = | "unsupported_object"; interface StrictJsonValidationContext { - code: - | "factory_result_not_json" - | "factory_step_not_json" - | "workflow_result_not_json" - | "workflow_step_not_json"; + code: "workflow_result_not_json" | "workflow_step_not_json"; label: string; allowTopLevelUndefined: boolean; } function strictJsonValidationError( context: StrictJsonValidationContext, - category: FactoryResultValidationCategory, + category: WorkflowResultValidationCategory, message: string, path: string -): ResponseError<{ code: string; category: FactoryResultValidationCategory; path: string }> { +): ResponseError<{ code: string; category: WorkflowResultValidationCategory; path: string }> { return new ResponseError(ErrorCodes.InternalError, message, { code: context.code, category, @@ -3251,22 +2635,6 @@ function assertStrictJson( visit(value, "$", context.allowTopLevelUndefined); } -function assertFactoryResult(value: unknown): asserts value is JsonValue | undefined { - assertStrictJson(value, { - code: "factory_result_not_json", - label: "Factory result", - allowTopLevelUndefined: true, - }); -} - -function assertFactoryStepResult(value: unknown, key: string): asserts value is JsonValue { - assertStrictJson(value, { - code: "factory_step_not_json", - label: `Factory step "${key}" result`, - allowTopLevelUndefined: false, - }); -} - function assertWorkflowResult(value: unknown): asserts value is JsonValue | undefined { assertStrictJson(value, { code: "workflow_result_not_json", diff --git a/nodejs/src/types.ts b/nodejs/src/types.ts index 98e594356c..3fc64960bd 100644 --- a/nodejs/src/types.ts +++ b/nodejs/src/types.ts @@ -21,7 +21,7 @@ import type { SessionEvent as GeneratedSessionEvent, } from "./generated/session-events.js"; import type { CopilotSession } from "./session.js"; -import type { FactoryJsonSchema, JsonValue } from "./factory.js"; +import type { JsonValue } from "./workflow.js"; import type { ExtensionLaunchProviderHandler as GeneratedExtensionLaunchProvider, GitHubTokenAcquireRequest, @@ -2149,68 +2149,6 @@ export interface CanvasProviderIdentity { name?: string; } -/** - * Static resource ceilings declared by a factory before it runs. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export interface FactoryLimits { - /** Maximum number of factory subagents that may run concurrently. Must be positive when present. */ - maxConcurrentSubagents?: number; - /** Maximum total number of factory subagents that may be spawned. Must be positive when present. */ - maxTotalSubagents?: number; - /** Maximum AI credits consumed by factory subagents and descendants. This post-paid ceiling is soft. */ - maxAiCredits?: number; - /** - * Maximum accumulated active-execution time, in seconds. Active execution includes the entire extension body, - * subprocess waits, queued-agent waits, and sleeps. The limit is armed from the remaining headroom when a run - * resumes; time between attempts is not counted. Must be finite and positive when present. - */ - timeoutSeconds?: number; -} - -/** - * Registration metadata for an extension-authored factory. - * - * @experimental Part of the experimental Agent Factories surface and may - * change or be removed in future SDK or CLI releases. - */ -export interface FactoryMeta { - /** Stable factory name used for invocation. */ - name: string; - /** Human-readable factory description. */ - description: string; - /** Display metadata for the progress phases the factory may report. */ - phases: Array<{ title: string; detail?: string }>; - /** - * Optional declared shape of the arguments this factory expects as `ctx.args`. - * - * Declaring one is strongly recommended for any factory that reads `ctx.args`. - * When the model invokes the factory through the `run_factory` tool, the CLI - * validates `args` against this declaration **before** the run starts, so a - * malformed call is rejected with a correction hint and retried without ever - * creating a run row, prompting the user for permission, or spending credits. A - * factory that declares nothing is never validated: a malformed call starts, - * takes an approval, spends credits, and then fails inside the factory body. - * `factories_manage` with `operation: "inspect"` reports the declared shape so an - * agent can read it before invoking. - * - * This covers the model's `run_factory` path only. `session.factory.run(...)` is - * not validated against the declaration, so a factory should still check - * `ctx.args` rather than assume the declared shape held. - * - * Enforcement covers structure — types, required properties, and enum/const - * values. Finer constraints such as `minLength`, `pattern`, and - * `additionalProperties` are recorded in the declaration but not enforced. See - * {@link FactoryJsonSchema} for the accepted subset. A declaration outside that - * subset is rejected at registration. - */ - argsSchema?: FactoryJsonSchema; - /** Optional resource ceilings presented to the user before execution. */ - limits?: FactoryLimits; -} - /** * Provider-scoped options for the Copilot API (CAPI). * diff --git a/nodejs/src/workflow.ts b/nodejs/src/workflow.ts index 6065c710ec..f7c0abe2d1 100644 --- a/nodejs/src/workflow.ts +++ b/nodejs/src/workflow.ts @@ -14,9 +14,16 @@ import type { } from "./generated/rpc.js"; import type { ContextTier } from "./generated/session-events.js"; import type { CopilotSession } from "./session.js"; -import type { JsonValue } from "./factory.js"; export type { WorkflowRunResult }; +/** A value that can be represented losslessly on the SDK JSON wire. */ +export type JsonValue = + | null + | boolean + | number + | string + | JsonValue[] + | { [key: string]: JsonValue }; export type { WorkflowAgentSummary, WorkflowPhaseStatus, @@ -404,7 +411,7 @@ export interface SessionWorkflowApi { * snapshot: resuming the same durable run can later change the envelope * returned by {@link SessionWorkflowApi.getRun}. * - * This watches the runtime's `factory.run_updated` compatibility event and + * This watches the runtime's `workflow.run_updated` event and * periodically re-reads the durable envelope so a missed event cannot * leave the wait hanging. Pass a `signal` to stop waiting; aborting rejects * and has no effect on the run itself, which keeps executing. Use diff --git a/nodejs/test/e2e/fixtures/factory-extension.mjs b/nodejs/test/e2e/fixtures/factory-extension.mjs deleted file mode 100644 index b082599bc9..0000000000 --- a/nodejs/test/e2e/fixtures/factory-extension.mjs +++ /dev/null @@ -1,234 +0,0 @@ -import { closeSync, existsSync, fstatSync, openSync, writeFileSync, writeSync } from "node:fs"; -import { defineFactory, joinSession } from "@github/copilot-sdk/extension"; - -const marker = (name) => new URL(`./${name}`, import.meta.url); - -async function waitForMarker(name, timeoutMs) { - const deadline = Date.now() + timeoutMs; - while (!existsSync(marker(name))) { - if (Date.now() >= deadline) { - throw new Error(`Timed out waiting for ${name}`); - } - await new Promise((resolve) => setTimeout(resolve, 50)); - } -} - -function incrementMarker(name) { - const descriptor = openSync(marker(name), "a+"); - try { - writeSync(descriptor, "1"); - return fstatSync(descriptor).size; - } finally { - closeSync(descriptor); - } -} - -const argumentEcho = defineFactory({ - meta: { - name: "argument-echo", - description: "Return the invocation arguments verbatim.", - phases: [], - // Proves a declared shape survives the SDK boundary and registers against a - // real runtime. It does not exercise enforcement: `argsSchema` is checked by - // the model's `run_factory` tool, and these tests invoke `session.factory.run`, - // which does not validate. The declaration stays as wide as this factory's - // actual contract — it echoes any JsonValue, and is called with an array, an - // object, and nothing — so it cannot constrain the runs below. - argsSchema: { - type: ["object", "array", "string", "number", "integer", "boolean", "null"], - }, - }, - run: async ({ args }) => args, -}); - -const arrayResult = defineFactory({ - meta: { - name: "array-result", - description: "Return an array result.", - phases: [], - }, - run: async () => [1, "two", false], -}); - -const phased = defineFactory({ - meta: { - name: "phased", - description: "Record named phases and ordinary progress.", - phases: [{ title: "Collect" }, { title: "Summarize" }], - }, - run: async ({ phase, log }) => { - phase("Collect"); - log("Collected"); - phase("Summarize"); - log("Summarized"); - return "finished"; - }, -}); - -const forwardsSubagentOptions = defineFactory({ - meta: { - name: "forwards-subagent-options", - description: "Send every declared subagent option to the runtime.", - phases: [], - }, - run: async ({ agent }) => { - // Only the runtime's acceptance of the payload is under test. A refused - // request rejects quickly, because the runtime parses the options before - // it starts a subagent. A subagent that is merely slow to reach a model - // proves the payload was accepted, so waiting for it adds nothing and - // hangs wherever no model is reachable. - const call = agent("Confirm that this request is accepted.", { - agent: "reviewer", - reasoningEffort: "high", - contextTier: "long_context", - }); - // A rejection that lands after the race still needs a handler. - call.catch(() => {}); - let settleTimer; - const stillPending = new Promise((resolve) => { - settleTimer = setTimeout(() => resolve(undefined), 3000); - settleTimer.unref?.(); - }); - try { - await Promise.race([call, stillPending]); - return { didThrow: false }; - } catch { - return { didThrow: true }; - } finally { - clearTimeout(settleTimer); - } - }, -}); - -const startsFromContextSession = defineFactory({ - meta: { - name: "starts-from-context-session", - description: "Try to start a factory through the context session.", - phases: [], - }, - run: async ({ session }) => { - try { - await session.factory.run("argument-echo"); - return "unexpectedly started a factory"; - } catch (error) { - return error instanceof Error ? error.message : String(error); - } - }, -}); - -let session; - -const startsFromModuleSession = defineFactory({ - meta: { - name: "starts-from-module-session", - description: "Try to start a factory through the module session.", - phases: [], - }, - run: async () => { - try { - await session.factory.run("argument-echo"); - return "unexpectedly started a factory"; - } catch (error) { - return error instanceof Error ? error.message : String(error); - } - }, -}); - -const parked = defineFactory({ - meta: { - name: "parked", - description: "Wait for a test-controlled release marker.", - phases: [], - }, - run: async () => { - writeFileSync(marker("entered"), "entered"); - await waitForMarker("release", 30_000); - return "released"; - }, -}); - -const failsOnce = defineFactory({ - meta: { - name: "fails-once", - description: "Fails its first attempt and succeeds when resumed.", - phases: [], - }, - run: async () => { - if (!existsSync(marker("fails-once-attempted"))) { - writeFileSync(marker("fails-once-attempted"), "attempted"); - throw new Error("first attempt failed"); - } - return "resumed"; - }, -}); - -const externallyPaused = defineFactory({ - meta: { - name: "externally-paused", - description: "Wait until the calling session pauses this run.", - phases: [], - }, - run: async ({ signal }) => { - writeFileSync(marker("external-pause-entered"), "entered"); - await new Promise((_, reject) => { - const abort = () => reject(signal.reason ?? new Error("Factory aborted")); - if (signal.aborted) { - abort(); - return; - } - signal.addEventListener("abort", abort, { once: true }); - }); - return "unexpectedly completed"; - }, -}); - -const durablePauseCheckpoint = defineFactory({ - meta: { - name: "durable-pause-checkpoint", - description: "Pause once after journaled preparation, then complete after resume.", - phases: [], - }, - run: async ({ pause, step }) => { - const attempt = incrementMarker("checkpoint-attempts"); - const prepared = await step("prepare", () => incrementMarker("checkpoint-preparations")); - await pause("review-ready"); - return { attempt, prepared }; - }, -}); - -session = await joinSession({ - factories: [ - argumentEcho, - arrayResult, - phased, - forwardsSubagentOptions, - startsFromContextSession, - startsFromModuleSession, - parked, - failsOnce, - externallyPaused, - durablePauseCheckpoint, - ], -}); - -void waitForMarker("start-b", 30_000) - .then(async () => { - const result = await session.factory.run("argument-echo", { - args: { source: "module-watcher" }, - notifyOnComplete: false, - }); - writeFileSync(marker("b-result"), JSON.stringify({ status: "success", result })); - }) - .catch((error) => { - if (existsSync(marker("start-b"))) { - writeFileSync( - marker("b-result"), - JSON.stringify({ - status: "error", - error: error instanceof Error ? error.message : String(error), - }) - ); - } - }); - -writeFileSync(marker("ready"), "ready"); diff --git a/nodejs/test/e2e/fixtures/workflow-extension.mjs b/nodejs/test/e2e/fixtures/workflow-extension.mjs index e8e0820a4b..e6b35228bb 100644 --- a/nodejs/test/e2e/fixtures/workflow-extension.mjs +++ b/nodejs/test/e2e/fixtures/workflow-extension.mjs @@ -1,6 +1,28 @@ -import { writeFileSync } from "node:fs"; +import { closeSync, existsSync, fstatSync, openSync, writeFileSync, writeSync } from "node:fs"; import { defineWorkflow, joinSession } from "@github/copilot-sdk/extension"; +const marker = (name) => new URL(`./${name}`, import.meta.url); + +async function waitForMarker(name, timeoutMs) { + const deadline = Date.now() + timeoutMs; + while (!existsSync(marker(name))) { + if (Date.now() >= deadline) { + throw new Error(`Timed out waiting for ${name}`); + } + await new Promise((resolve) => setTimeout(resolve, 50)); + } +} + +function incrementMarker(name) { + const descriptor = openSync(marker(name), "a+"); + try { + writeSync(descriptor, "1"); + return fstatSync(descriptor).size; + } finally { + closeSync(descriptor); + } +} + const argumentEcho = defineWorkflow({ meta: { name: "argument-echo", @@ -13,12 +35,192 @@ const argumentEcho = defineWorkflow({ run: async ({ args }) => args, }); -const session = await joinSession({ - workflows: [argumentEcho], +const arrayResult = defineWorkflow({ + meta: { + name: "array-result", + description: "Return an array result.", + phases: [], + }, + run: async () => [1, "two", false], +}); + +const phased = defineWorkflow({ + meta: { + name: "phased", + description: "Record named phases and ordinary progress.", + phases: [{ title: "Collect" }, { title: "Summarize" }], + }, + run: async ({ phase, log }) => { + phase("Collect"); + log("Collected"); + phase("Summarize"); + log("Summarized"); + return "finished"; + }, +}); + +const forwardsSubagentOptions = defineWorkflow({ + meta: { + name: "forwards-subagent-options", + description: "Send every declared subagent option to the runtime.", + phases: [], + }, + run: async ({ agent }) => { + const call = agent("Confirm that this request is accepted.", { + agent: "reviewer", + reasoningEffort: "high", + contextTier: "long_context", + }); + call.catch(() => {}); + let settleTimer; + const stillPending = new Promise((resolve) => { + settleTimer = setTimeout(() => resolve(undefined), 3000); + settleTimer.unref?.(); + }); + try { + await Promise.race([call, stillPending]); + return { didThrow: false }; + } catch { + return { didThrow: true }; + } finally { + clearTimeout(settleTimer); + } + }, +}); + +const startsFromContextSession = defineWorkflow({ + meta: { + name: "starts-from-context-session", + description: "Try to start a workflow through the context session.", + phases: [], + }, + run: async ({ session }) => { + try { + await session.workflow.run("argument-echo"); + return "unexpectedly started a workflow"; + } catch (error) { + return error instanceof Error ? error.message : String(error); + } + }, +}); + +let session; + +const startsFromModuleSession = defineWorkflow({ + meta: { + name: "starts-from-module-session", + description: "Try to start a workflow through the module session.", + phases: [], + }, + run: async () => { + try { + await session.workflow.run("argument-echo"); + return "unexpectedly started a workflow"; + } catch (error) { + return error instanceof Error ? error.message : String(error); + } + }, +}); + +const parked = defineWorkflow({ + meta: { + name: "parked", + description: "Wait for a test-controlled release marker.", + phases: [], + }, + run: async () => { + writeFileSync(marker("entered"), "entered"); + await waitForMarker("release", 30_000); + return "released"; + }, +}); + +const failsOnce = defineWorkflow({ + meta: { + name: "fails-once", + description: "Fails its first attempt and succeeds when resumed.", + phases: [], + }, + run: async () => { + if (!existsSync(marker("fails-once-attempted"))) { + writeFileSync(marker("fails-once-attempted"), "attempted"); + throw new Error("first attempt failed"); + } + return "resumed"; + }, +}); + +const externallyPaused = defineWorkflow({ + meta: { + name: "externally-paused", + description: "Wait until the calling session pauses this run.", + phases: [], + }, + run: async ({ signal }) => { + writeFileSync(marker("external-pause-entered"), "entered"); + await new Promise((_, reject) => { + const abort = () => reject(signal.reason ?? new Error("Workflow aborted")); + if (signal.aborted) { + abort(); + return; + } + signal.addEventListener("abort", abort, { once: true }); + }); + return "unexpectedly completed"; + }, +}); + +const durablePauseCheckpoint = defineWorkflow({ + meta: { + name: "durable-pause-checkpoint", + description: "Pause once after journaled preparation, then complete after resume.", + phases: [], + }, + run: async ({ pause, step }) => { + const attempt = incrementMarker("checkpoint-attempts"); + const prepared = await step("prepare", () => incrementMarker("checkpoint-preparations")); + await pause("review-ready"); + return { attempt, prepared }; + }, +}); + +session = await joinSession({ + workflows: [ + argumentEcho, + arrayResult, + phased, + forwardsSubagentOptions, + startsFromContextSession, + startsFromModuleSession, + parked, + failsOnce, + externallyPaused, + durablePauseCheckpoint, + ], }); if (!session.workflow) { throw new Error("Workflow API was not registered"); } -writeFileSync(new URL("./ready", import.meta.url), "ready"); +void waitForMarker("start-b", 30_000) + .then(async () => { + const result = await session.workflow.run("argument-echo", { + args: { source: "module-watcher" }, + notifyOnComplete: false, + }); + writeFileSync(marker("b-result"), JSON.stringify({ status: "success", result })); + }) + .catch((error) => { + if (existsSync(marker("start-b"))) { + writeFileSync( + marker("b-result"), + JSON.stringify({ + status: "error", + error: error instanceof Error ? error.message : String(error), + }) + ); + } + }); + +writeFileSync(marker("ready"), "ready"); diff --git a/nodejs/test/e2e/harness/sdkTestContext.ts b/nodejs/test/e2e/harness/sdkTestContext.ts index 4bd25fe5c3..466e4b625e 100644 --- a/nodejs/test/e2e/harness/sdkTestContext.ts +++ b/nodejs/test/e2e/harness/sdkTestContext.ts @@ -120,7 +120,7 @@ export async function createSdkTestContext({ if (userConn) { // Caller supplied a RuntimeConnection — merge in the harness-managed // CLI path (and stay on the same transport variant). Strip `kind` - // before forwarding to the factory opts since the factories don't + // before forwarding to the workflow opts since the workflows don't // accept it in their argument shape. if (userConn.kind === "tcp") { const { kind: _k, ...tcp } = userConn; diff --git a/nodejs/test/e2e/rpc_surface_coverage.e2e.test.ts b/nodejs/test/e2e/rpc_surface_coverage.e2e.test.ts index 3f017f07cc..3109e1e737 100644 --- a/nodejs/test/e2e/rpc_surface_coverage.e2e.test.ts +++ b/nodejs/test/e2e/rpc_surface_coverage.e2e.test.ts @@ -313,7 +313,7 @@ describe("Generated RPC surface coverage", () => { ...collectRuntimeFunctions(session.rpc, "session"), ]); - expect(inventory).toHaveLength(355); + expect(inventory).toHaveLength(349); expect([...runtimeFunctions.keys()].sort()).toEqual( inventory.map((method) => `${method.scope}.${method.path}`) ); diff --git a/nodejs/test/e2e/factory.e2e.test.ts b/nodejs/test/e2e/workflow.e2e.test.ts similarity index 52% rename from nodejs/test/e2e/factory.e2e.test.ts rename to nodejs/test/e2e/workflow.e2e.test.ts index 5b5796e4e3..bb1240fd36 100644 --- a/nodejs/test/e2e/factory.e2e.test.ts +++ b/nodejs/test/e2e/workflow.e2e.test.ts @@ -22,7 +22,7 @@ const cliPath = process.env.COPILOT_CLI_PATH ?? (await getLegacyCliPathForTests( const cliDistDirectory = process.env.COPILOT_EXTENSION_SDK_PATH ? dirname(process.env.COPILOT_EXTENSION_SDK_PATH) : dirname(cliPath); -const factoryTestContext = await createSdkTestContext({ +const workflowTestContext = await createSdkTestContext({ copilotClientOptions: { connection: RuntimeConnection.forStdio({ path: cliPath }), env: { @@ -43,20 +43,20 @@ const factoryTestContext = await createSdkTestContext({ }, }); -async function setupFactoryExtension(workDir: string, onPermissionRequest = approveAll) { - const { copilotClient, openAiEndpoint } = factoryTestContext; - const extensionDir = join(workDir, ".github", "extensions", "factory-smoke"); +async function setupWorkflowExtension(workDir: string, onPermissionRequest = approveAll) { + const { copilotClient, openAiEndpoint } = workflowTestContext; + const extensionDir = join(workDir, ".github", "extensions", "workflow-smoke"); const readyFile = join(extensionDir, "ready"); await rm(join(workDir, ".github"), { recursive: true, force: true }); await mkdir(extensionDir, { recursive: true }); await copyFile( - join(__dirname, "fixtures", "factory-extension.mjs"), + join(__dirname, "fixtures", "workflow-extension.mjs"), join(extensionDir, "extension.mjs") ); execFileSync("git", ["init", "--quiet"], { cwd: workDir }); await openAiEndpoint.setCopilotUserByToken(DEFAULT_GITHUB_TOKEN, { - login: "factory-e2e-user", + login: "workflow-e2e-user", copilot_plan: "individual_pro", token_based_billing: true, is_mcp_enabled: true, @@ -64,7 +64,7 @@ async function setupFactoryExtension(workDir: string, onPermissionRequest = appr api: openAiEndpoint.url, telemetry: "https://localhost:1/telemetry", }, - analytics_tracking_id: "e2e-test-tracking-id", + analytics_tracking_id: "workflow-e2e-tracking-id", }); const session = await copilotClient.createSession({ @@ -77,48 +77,6 @@ async function setupFactoryExtension(workDir: string, onPermissionRequest = appr }), }); - await retry( - "wait for the factory extension to join the session", - async () => { - expect(existsSync(readyFile)).toBe(true); - }, - 300, - 100 - ); - - return session; -} - -async function setupWorkflowExtension(workDir: string) { - const { copilotClient, openAiEndpoint } = factoryTestContext; - const extensionDir = join(workDir, ".github", "extensions", "workflow-smoke"); - const readyFile = join(extensionDir, "ready"); - await rm(join(workDir, ".github"), { recursive: true, force: true }); - await mkdir(extensionDir, { recursive: true }); - await copyFile( - join(__dirname, "fixtures", "workflow-extension.mjs"), - join(extensionDir, "extension.mjs") - ); - execFileSync("git", ["init", "--quiet"], { cwd: workDir }); - - await openAiEndpoint.setCopilotUserByToken(DEFAULT_GITHUB_TOKEN, { - login: "workflow-e2e-user", - copilot_plan: "individual_pro", - token_based_billing: true, - is_mcp_enabled: true, - endpoints: { - api: openAiEndpoint.url, - telemetry: "https://localhost:1/telemetry", - }, - analytics_tracking_id: "workflow-e2e-tracking-id", - }); - - const session = await copilotClient.createSession({ - requestExtensions: true, - extensionSdkPath: resolve(__dirname, "..", "..", "dist"), - onPermissionRequest: approveAll, - }); - try { await retry( "wait for the workflow extension to join the session", @@ -135,23 +93,8 @@ async function setupWorkflowExtension(workDir: string) { } } -it("runs an extension-authored factory across the SDK process boundary", async () => { - const { workDir } = factoryTestContext; - await using session = await setupFactoryExtension(workDir); - - const result = await session.factory.run("argument-echo", { - args: { source: "sdk-e2e", count: 11 }, - notifyOnComplete: false, - }); - - expect(result).toMatchObject({ - status: "completed", - result: { source: "sdk-e2e", count: 11 }, - }); -}); - it("runs an extension-authored workflow across the SDK process boundary", async () => { - const { workDir } = factoryTestContext; + const { workDir } = workflowTestContext; await using session = await setupWorkflowExtension(workDir); const result = await session.workflow.run("argument-echo", { @@ -166,19 +109,11 @@ it("runs an extension-authored workflow across the SDK process boundary", async expect(result.result).toEqual({ source: "sdk-workflow-e2e", count: 12 }); }, 45_000); -// TODO(cli-1.0.81-2): the subagent request is rejected downstream under CLI 1.0.81-2, so the -// fixture reports didThrow: true. Re-enable once the runtime fix ships. -// -// The timeout is generous because the factory abandons its subagent once the runtime has -// accepted the request, so the run settles only after the runtime drains that work. it.skip("forwards every declared subagent option to the runtime", async () => { - if (!factoryTestContext) { - throw new Error("Factory E2E requires the stdio transport"); - } - const { workDir } = factoryTestContext; - await using session = await setupFactoryExtension(workDir); + const { workDir } = workflowTestContext; + await using session = await setupWorkflowExtension(workDir); - const result = await session.factory.run("forwards-subagent-options"); + const result = await session.workflow.run("forwards-subagent-options"); expect(result).toMatchObject({ status: "completed", @@ -186,44 +121,38 @@ it.skip("forwards every declared subagent option to the runtime", async () => { }); }, 60_000); -it("throws FactoryResumeError with not_found for an unknown run", async () => { - if (!factoryTestContext) { - throw new Error("Factory E2E requires the stdio transport"); - } - const { workDir } = factoryTestContext; - await using session = await setupFactoryExtension(workDir); +it("throws WorkflowResumeError with not_found for an unknown run", async () => { + const { workDir } = workflowTestContext; + await using session = await setupWorkflowExtension(workDir); - const error = await session.factory + const error = await session.workflow .resume("00000000-0000-0000-0000-000000000000") .catch((caught: unknown) => caught); expect(error).toMatchObject({ - name: "FactoryResumeError", + name: "WorkflowResumeError", code: "not_found", }); }); -it("throws FactoryResumeError with non_resumable for a completed run", async () => { - if (!factoryTestContext) { - throw new Error("Factory E2E requires the stdio transport"); - } - const { workDir } = factoryTestContext; - await using session = await setupFactoryExtension(workDir); +it("throws WorkflowResumeError with non_resumable for a completed run", async () => { + const { workDir } = workflowTestContext; + await using session = await setupWorkflowExtension(workDir); - const run = await session.factory.run("argument-echo", { notifyOnComplete: false }); - const error = await session.factory.resume(run.runId).catch((caught: unknown) => caught); + const run = await session.workflow.run("argument-echo", { notifyOnComplete: false }); + const error = await session.workflow.resume(run.runId).catch((caught: unknown) => caught); expect(error).toMatchObject({ - name: "FactoryResumeError", + name: "WorkflowResumeError", code: "non_resumable", }); }); -it("forwards factory runtime controls across the SDK process boundary", async () => { - const { workDir } = factoryTestContext; - await using session = await setupFactoryExtension(workDir); +it("forwards workflow runtime controls across the SDK process boundary", async () => { + const { workDir } = workflowTestContext; + await using session = await setupWorkflowExtension(workDir); - const suppressed = await session.factory.run("phased", { + const suppressed = await session.workflow.run("phased", { notifyOnComplete: false, logPhaseNames: false, }); @@ -232,7 +161,7 @@ it("forwards factory runtime controls across the SDK process boundary", async () status: "completed", result: "finished", }); - const progress = await session.factory.getRunProgress(suppressed.runId); + const progress = await session.workflow.getRunProgress(suppressed.runId); expect(progress.records).toEqual( expect.arrayContaining([ expect.objectContaining({ kind: "phase", text: "Collect" }), @@ -247,35 +176,35 @@ it("forwards factory runtime controls across the SDK process boundary", async () events.some( (event) => event.type === "system.notification" && - event.data.kind.type === "factory_completed" && + event.data.kind.type === "workflow_completed" && event.data.kind.runId === suppressed.runId ) ).toBe(false); expect( events.filter( - (event) => event.type === "session.info" && event.data.infoType === "factory_phase" + (event) => event.type === "session.info" && event.data.infoType === "workflow_phase" ) ).toEqual([]); }); -it("pages factory runs and returns cursor metadata", async () => { - const { workDir } = factoryTestContext; - await using session = await setupFactoryExtension(workDir); +it("pages workflow runs and returns cursor metadata", async () => { + const { workDir } = workflowTestContext; + await using session = await setupWorkflowExtension(workDir); - const first = await session.factory.run("argument-echo", { + const first = await session.workflow.run("argument-echo", { args: { ordinal: 1 }, notifyOnComplete: false, }); - const second = await session.factory.run("argument-echo", { + const second = await session.workflow.run("argument-echo", { args: { ordinal: 2 }, notifyOnComplete: false, }); - const third = await session.factory.run("argument-echo", { + const third = await session.workflow.run("argument-echo", { args: { ordinal: 3 }, notifyOnComplete: false, }); - const newest = await session.factory.listRuns({ limit: 1 }); + const newest = await session.workflow.listRuns({ limit: 1 }); expect(newest).toMatchObject({ runs: [expect.objectContaining({ runId: third.runId })], hasMoreNewer: false, @@ -284,7 +213,7 @@ it("pages factory runs and returns cursor metadata", async () => { expect(newest.oldestSeq).toBe(newest.newestSeq); expect(newest.oldestSeq).not.toBeNull(); - const older = await session.factory.listRuns({ + const older = await session.workflow.listRuns({ beforeSeq: newest.oldestSeq!, limit: 1, }); @@ -294,7 +223,7 @@ it("pages factory runs and returns cursor metadata", async () => { omittedOlder: 1, }); - const oldest = await session.factory.listRuns({ + const oldest = await session.workflow.listRuns({ beforeSeq: older.oldestSeq!, limit: 1, }); @@ -305,37 +234,31 @@ it("pages factory runs and returns cursor metadata", async () => { }); }); -it("runs a factory when its session denies every permission request", async () => { - if (!factoryTestContext) { - throw new Error("Factory E2E requires the stdio transport"); - } - const { workDir } = factoryTestContext; +it("runs a workflow when its session denies every permission request", async () => { + const { workDir } = workflowTestContext; const denyPermissions = vi.fn(() => ({ kind: "reject" as const })); - await using session = await setupFactoryExtension(workDir, denyPermissions); + await using session = await setupWorkflowExtension(workDir, denyPermissions); await expect( - session.factory.run("argument-echo", { notifyOnComplete: false }) + session.workflow.run("argument-echo", { notifyOnComplete: false }) ).resolves.toMatchObject({ status: "completed", }); expect(denyPermissions).not.toHaveBeenCalled(); }); -it("resumes a failed factory when its session denies every permission request", async () => { - if (!factoryTestContext) { - throw new Error("Factory E2E requires the stdio transport"); - } - const { workDir } = factoryTestContext; +it("resumes a failed workflow when its session denies every permission request", async () => { + const { workDir } = workflowTestContext; const denyPermissions = vi.fn(() => ({ kind: "reject" as const })); - await using session = await setupFactoryExtension(workDir, denyPermissions); + await using session = await setupWorkflowExtension(workDir, denyPermissions); - const failedRun = await session.factory.run("fails-once", { notifyOnComplete: false }); + const failedRun = await session.workflow.run("fails-once", { notifyOnComplete: false }); expect(failedRun).toMatchObject({ status: "error", }); await expect( - session.factory.resume(failedRun.runId, { + session.workflow.resume(failedRun.runId, { notifyOnComplete: false, logPhaseNames: false, }) @@ -346,19 +269,16 @@ it("resumes a failed factory when its session denies every permission request", expect(denyPermissions).not.toHaveBeenCalled(); }); -it("pauses a running factory through the session API", async () => { - if (!factoryTestContext) { - throw new Error("Factory E2E requires the stdio transport"); - } - const { workDir } = factoryTestContext; - const extensionDir = join(workDir, ".github", "extensions", "factory-smoke"); - await using session = await setupFactoryExtension(workDir); +it("pauses a running workflow through the session API", async () => { + const { workDir } = workflowTestContext; + const extensionDir = join(workDir, ".github", "extensions", "workflow-smoke"); + await using session = await setupWorkflowExtension(workDir); - const execution = session.factory.run("externally-paused", { + const execution = session.workflow.run("externally-paused", { notifyOnComplete: false, }); await retry( - "wait for the externally paused factory to enter its body", + "wait for the externally paused workflow to enter its body", async () => { expect(existsSync(join(extensionDir, "external-pause-entered"))).toBe(true); }, @@ -368,10 +288,10 @@ it("pauses a running factory through the session API", async () => { let runId: string | undefined; await retry( - "find the running factory before pausing it", + "find the running workflow before pausing it", async () => { - const running = (await session.factory.listRuns()).find( - (run) => run.factoryName === "externally-paused" && run.status === "running" + const running = (await session.workflow.listRuns()).find( + (run) => run.workflowName === "externally-paused" && run.status === "running" ); expect(running).toBeDefined(); runId = running?.runId; @@ -380,10 +300,10 @@ it("pauses a running factory through the session API", async () => { 100 ); if (!runId) { - throw new Error("Running factory did not expose a run ID"); + throw new Error("Running workflow did not expose a run ID"); } - await expect(session.factory.pause(runId)).resolves.toMatchObject({ + await expect(session.workflow.pause(runId)).resolves.toMatchObject({ runId, status: "paused", }); @@ -394,21 +314,18 @@ it("pauses a running factory through the session API", async () => { }); it("pauses once at a durable checkpoint and continues after resume", async () => { - if (!factoryTestContext) { - throw new Error("Factory E2E requires the stdio transport"); - } - const { workDir } = factoryTestContext; - const extensionDir = join(workDir, ".github", "extensions", "factory-smoke"); - await using session = await setupFactoryExtension(workDir); + const { workDir } = workflowTestContext; + const extensionDir = join(workDir, ".github", "extensions", "workflow-smoke"); + await using session = await setupWorkflowExtension(workDir); - const paused = await session.factory.run("durable-pause-checkpoint", { + const paused = await session.workflow.run("durable-pause-checkpoint", { notifyOnComplete: false, }); expect(paused).toMatchObject({ status: "paused" }); expect(readFileSync(join(extensionDir, "checkpoint-attempts"))).toHaveLength(1); expect(readFileSync(join(extensionDir, "checkpoint-preparations"))).toHaveLength(1); - const resumed = await session.factory.resume(paused.runId, { + const resumed = await session.workflow.resume(paused.runId, { notifyOnComplete: false, }); expect(resumed).toMatchObject({ @@ -420,53 +337,44 @@ it("pauses once at a durable checkpoint and continues after resume", async () => expect(readFileSync(join(extensionDir, "checkpoint-preparations"))).toHaveLength(1); }); -it("refuses a factory started through the context session from a factory body", async () => { - if (!factoryTestContext) { - throw new Error("Factory E2E requires the stdio transport"); - } - const { workDir } = factoryTestContext; - await using session = await setupFactoryExtension(workDir); +it("refuses a workflow started through the context session from a workflow body", async () => { + const { workDir } = workflowTestContext; + await using session = await setupWorkflowExtension(workDir); - const result = await session.factory.run("starts-from-context-session", { + const result = await session.workflow.run("starts-from-context-session", { notifyOnComplete: false, }); expect(result).toMatchObject({ status: "completed", - result: expect.stringContaining("factory.run, factory.resume, and factory.pause"), + result: expect.stringContaining("workflow.run, workflow.resume, and workflow.pause"), }); - expect((result as { result: string }).result).toContain("factory body"); + expect((result as { result: string }).result).toContain("workflow body"); }); -it("refuses a factory started through the module session from a factory body", async () => { - if (!factoryTestContext) { - throw new Error("Factory E2E requires the stdio transport"); - } - const { workDir } = factoryTestContext; - await using session = await setupFactoryExtension(workDir); +it("refuses a workflow started through the module session from a workflow body", async () => { + const { workDir } = workflowTestContext; + await using session = await setupWorkflowExtension(workDir); - const result = await session.factory.run("starts-from-module-session", { + const result = await session.workflow.run("starts-from-module-session", { notifyOnComplete: false, }); expect(result).toMatchObject({ status: "completed", - result: expect.stringContaining("factory.run, factory.resume, and factory.pause"), + result: expect.stringContaining("workflow.run, workflow.resume, and workflow.pause"), }); - expect((result as { result: string }).result).toContain("factory body"); + expect((result as { result: string }).result).toContain("workflow body"); }); -it("allows a module-level extension watcher to start a factory while another body is parked", async () => { - if (!factoryTestContext) { - throw new Error("Factory E2E requires the stdio transport"); - } - const { workDir } = factoryTestContext; - const extensionDir = join(workDir, ".github", "extensions", "factory-smoke"); - await using session = await setupFactoryExtension(workDir); +it("allows a module-level extension watcher to start a workflow while another body is parked", async () => { + const { workDir } = workflowTestContext; + const extensionDir = join(workDir, ".github", "extensions", "workflow-smoke"); + await using session = await setupWorkflowExtension(workDir); - const parked = session.factory.run("parked", { notifyOnComplete: false }); + const parked = session.workflow.run("parked", { notifyOnComplete: false }); await retry( - "wait for the parked factory to enter its body", + "wait for the parked workflow to enter its body", async () => { expect(existsSync(join(extensionDir, "entered"))).toBe(true); }, @@ -477,7 +385,7 @@ it("allows a module-level extension watcher to start a factory while another bod writeFileSync(join(extensionDir, "start-b"), "start"); const bResultFile = join(extensionDir, "b-result"); await retry( - "wait for the module-level watcher factory run to succeed", + "wait for the module-level watcher workflow run to succeed", async () => { expect(existsSync(bResultFile)).toBe(true); expect(JSON.parse(readFileSync(bResultFile, "utf8"))).toMatchObject({ @@ -499,14 +407,11 @@ it("allows a module-level extension watcher to start a factory while another bod }); }, 60_000); -it("returns an array result from an extension-authored factory", async () => { - if (!factoryTestContext) { - throw new Error("Factory E2E requires the stdio transport"); - } - const { workDir } = factoryTestContext; - await using session = await setupFactoryExtension(workDir); +it("returns an array result from an extension-authored workflow", async () => { + const { workDir } = workflowTestContext; + await using session = await setupWorkflowExtension(workDir); - const result = await session.factory.run("array-result", { notifyOnComplete: false }); + const result = await session.workflow.run("array-result", { notifyOnComplete: false }); expect(result).toMatchObject({ status: "completed", @@ -514,15 +419,12 @@ it("returns an array result from an extension-authored factory", async () => { }); }); -it("passes array factory arguments across the SDK process boundary", async () => { - if (!factoryTestContext) { - throw new Error("Factory E2E requires the stdio transport"); - } - const { workDir } = factoryTestContext; - await using session = await setupFactoryExtension(workDir); +it("passes array workflow arguments across the SDK process boundary", async () => { + const { workDir } = workflowTestContext; + await using session = await setupWorkflowExtension(workDir); const args = [1, "two", false]; - const result = await session.factory.run("argument-echo", { + const result = await session.workflow.run("argument-echo", { args, notifyOnComplete: false, }); diff --git a/nodejs/test/extension.test.ts b/nodejs/test/extension.test.ts index 91d9de1567..676f6dff2b 100644 --- a/nodejs/test/extension.test.ts +++ b/nodejs/test/extension.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { CopilotClient } from "../src/client.js"; import { approveAll } from "../src/index.js"; -import { createCanvas, defineFactory, defineWorkflow, joinSession } from "../src/extension.js"; +import { createCanvas, defineWorkflow, joinSession } from "../src/extension.js"; import { defaultJoinSessionPermissionHandler } from "../src/types.js"; describe("joinSession", () => { @@ -93,31 +93,10 @@ describe("joinSession", () => { await joinSession({ workflows: [workflow] }); expect(resumeForExtension.mock.calls[0]![2]).toEqual({ - factories: undefined, workflows: [workflow], }); }); - it("rejects mixed factory and workflow contributions", async () => { - process.env.SESSION_ID = "session-123"; - const factory = defineFactory({ - meta: { name: "legacy", description: "Legacy", phases: [] }, - run: async () => null, - }); - const workflow = defineWorkflow({ - meta: { name: "review", description: "Review", phases: [] }, - run: async () => null, - }); - - await expect( - joinSession({ - // @ts-expect-error Contribution generations are mutually exclusive. - factories: [factory], - workflows: [workflow], - }) - ).rejects.toThrow("cannot register both factories and workflows"); - }); - it("exports the canvas helper from the extension surface", () => { const canvas = createCanvas({ id: "counter", diff --git a/nodejs/test/factory.test.ts b/nodejs/test/factory.test.ts deleted file mode 100644 index 679cbf9131..0000000000 --- a/nodejs/test/factory.test.ts +++ /dev/null @@ -1,2772 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - *--------------------------------------------------------------------------------------------*/ - -import { readFileSync } from "node:fs"; -import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest"; -import { ResponseError } from "vscode-jsonrpc/node.js"; -import { CopilotClient } from "../src/client.js"; -import { joinSession } from "../src/extension.js"; -import { CopilotSession } from "../src/session.js"; -import { - defineFactory, - FactoryResumeError, - isFactoryRunTerminal, - type FactoryAgentOptions, - type FactoryContext, - type FactoryDefinition, - type FactoryJsonSchema, - type JsonValue, -} from "../src/factory.js"; - -/** Builds a `factory.run_updated` invalidation event for a run. */ -function runUpdatedEvent(runId: string, revision: number): Record { - return { - type: "factory.run_updated", - id: `event-${runId}-${revision}`, - parentId: null, - timestamp: new Date().toISOString(), - ephemeral: true, - data: { runId, revision }, - }; -} - -async function stopClient(client: CopilotClient): Promise { - await client.stop(); -} - -describe("factories", () => { - const originalSessionId = process.env.SESSION_ID; - - afterEach(() => { - if (originalSessionId === undefined) { - delete process.env.SESSION_ID; - } else { - process.env.SESSION_ID = originalSessionId; - } - vi.restoreAllMocks(); - }); - - it("defines a stable handle and accepts omitted limits", async () => { - const meta = { - name: "no-limits", - description: "A factory without resource limits", - phases: [], - }; - const run = vi.fn(async ({ args }: { args: unknown }) => args); - const handle = defineFactory({ meta, run }); - - expect(handle.meta).toEqual(meta); - expect(handle.meta).not.toBe(meta); - expect(Object.isFrozen(handle)).toBe(true); - expect(Object.isFrozen(handle.meta)).toBe(true); - - // The handle holds a snapshot, so mutating the caller's object after - // registration cannot desynchronize the advertised metadata. - meta.name = "mutated"; - (meta.phases as string[]).push("late"); - expect(handle.meta.name).toBe("no-limits"); - expect(handle.meta.phases).toEqual([]); - meta.name = "no-limits"; - meta.phases.length = 0; - - // The stored metadata is deep-frozen, so the handle's view of it must be - // readonly all the way down. Assert both halves: the mutation is a type - // error, and it also throws at runtime. - expect(() => { - // @ts-expect-error handle.meta is deeply readonly. - handle.meta.name = "mutated"; - }).toThrow(TypeError); - expect(() => { - // @ts-expect-error handle.meta.phases is a readonly array. - handle.meta.phases.push({ title: "late" }); - }).toThrow(TypeError); - - const session = new CopilotSession("session-1", {} as never); - session.registerFactories([handle]); - const result = await session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: meta.name, - runId: "run-1", - executionToken: "execution-token", - args: { value: 42 }, - }); - - expect(run).toHaveBeenCalledOnce(); - expect(result).toEqual({ result: { value: 42 } }); - }); - - it.each([ - [[{ title: "" }], "must not be empty"], - [[{ title: "Inspect" }, { title: "Inspect" }], "declared more than once"], - ])("rejects invalid declared phase titles", (phases, message) => { - expect(() => - defineFactory({ - meta: { - name: "invalid-phases", - description: "Invalid phase metadata", - phases, - }, - run: async () => {}, - }) - ).toThrow(message); - }); - - it("returns an absent execute result for a void factory", async () => { - const factory = defineFactory({ - meta: { - name: "void-result", - description: "Returns no result", - phases: [], - }, - run: async () => {}, - }); - const session = new CopilotSession("session-void-result", {} as never); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "void-result", - runId: "run-void-result", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({}); - }); - - it.each([42, "factory-result", [1, "two", false]])( - "returns non-object JSON factory result %j", - async (factoryResult) => { - const factory = defineFactory({ - meta: { - name: "json-result", - description: "Returns any JSON value", - phases: [], - }, - run: async () => factoryResult, - }); - const session = new CopilotSession("session-json-result", {} as never); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "json-result", - runId: "run-json-result", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ result: factoryResult }); - } - ); - - it.each([ - ["function", { nested: () => undefined }, "$.nested"], - ["symbol", [Symbol("invalid")], "$[0]"], - ["BigInt", { nested: 1n }, "$.nested"], - ])("rejects a %s anywhere in a factory result", async (_label, factoryResult, expectedPath) => { - const factory = defineFactory({ - meta: { - name: "unsupported-result", - description: "Returns an unsupported value", - phases: [], - }, - run: async () => factoryResult as never, - }); - const session = new CopilotSession("session-unsupported-result", {} as never); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "unsupported-result", - runId: "run-unsupported-result", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toMatchObject({ - message: `Factory result contains a function, symbol, or BigInt at ${expectedPath}`, - data: { - code: "factory_result_not_json", - category: "unsupported_type", - }, - }); - }); - - it.each([ - ["NaN", Number.NaN], - ["Infinity", Number.POSITIVE_INFINITY], - ])("rejects the non-finite number %s in a factory result", async (_label, value) => { - const factory = defineFactory({ - meta: { - name: "non-finite-result", - description: "Returns a non-finite number", - phases: [], - }, - run: async () => ({ value }) as never, - }); - const session = new CopilotSession("session-non-finite-result", {} as never); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "non-finite-result", - runId: "run-non-finite-result", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toMatchObject({ - message: "Factory result contains a non-finite number at $.value", - data: { - code: "factory_result_not_json", - category: "non_finite_number", - }, - }); - }); - - it("rejects a cyclic factory result", async () => { - const factoryResult: Record = {}; - factoryResult.self = factoryResult; - const factory = defineFactory({ - meta: { - name: "cyclic-result", - description: "Returns a cycle", - phases: [], - }, - run: async () => factoryResult as never, - }); - const session = new CopilotSession("session-cyclic-result", {} as never); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "cyclic-result", - runId: "run-cyclic-result", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toMatchObject({ - message: "Factory result contains a cyclic reference at $.self", - data: { - code: "factory_result_not_json", - category: "cyclic_value", - }, - }); - }); - - it.each([ - ["object", { nested: undefined }, "$.nested"], - ["array", [undefined], "$[0]"], - ])( - "rejects nested undefined in a factory result %s", - async (_label, factoryResult, expectedPath) => { - const factory = defineFactory({ - meta: { - name: "nested-undefined-result", - description: "Returns nested undefined", - phases: [], - }, - run: async () => factoryResult as never, - }); - const session = new CopilotSession("session-nested-undefined-result", {} as never); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "nested-undefined-result", - runId: "run-nested-undefined-result", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toMatchObject({ - message: `Factory result contains nested undefined at ${expectedPath}`, - data: { - code: "factory_result_not_json", - category: "nested_undefined", - }, - }); - } - ); - - it("rejects duplicate factory names within a single registration", () => { - const run = async () => null; - const first = defineFactory({ - meta: { name: "dup", description: "first", phases: [] }, - run, - }); - const second = defineFactory({ - meta: { name: "dup", description: "second", phases: [] }, - run, - }); - - const session = new CopilotSession("session-dup", {} as never); - expect(() => session.registerFactories([first, second])).toThrow( - /Duplicate factory name "dup"/ - ); - }); - - it.each([ - ["maxConcurrentSubagents", 0], - ["maxConcurrentSubagents", 1.5], - ["maxTotalSubagents", -1], - ["maxTotalSubagents", Number.POSITIVE_INFINITY], - ["timeoutSeconds", 0], - ["timeoutSeconds", Number.NaN], - ["timeoutSeconds", Number.POSITIVE_INFINITY], - ["maxAiCredits", 0], - ["maxAiCredits", Number.NaN], - ["maxAiCredits", Number.POSITIVE_INFINITY], - ["maxAiCredits", 0.000_000_000_4], - ["maxAiCredits", (Number.MAX_SAFE_INTEGER + 2) / 1_000_000_000], - ] as const)("rejects invalid %s limit %s", (field, value) => { - const definition = { - meta: { - name: `invalid-${field}-${String(value)}`, - description: "Invalid factory", - phases: [], - limits: { [field]: value }, - }, - run: async () => null, - } as FactoryDefinition; - - expect(() => defineFactory(definition)).toThrow(/must be a positive/); - }); - - it("accepts positive fractional timeoutSeconds through the Node timer ceiling", () => { - for (const timeoutSeconds of [0.001, 1.5, 2_147_483.647]) { - expect(() => - defineFactory({ - meta: { - name: `accepted-timeout-${timeoutSeconds}`, - description: "Factory with an accepted active-execution timeout", - phases: [], - limits: { timeoutSeconds }, - }, - run: async () => null, - }) - ).not.toThrow(); - } - }); - - it("accepts AI-credit ceilings that round to a positive safe nano-AIU integer", () => { - for (const maxAiCredits of [ - 0.000_000_000_5, - 1.25, - Number.MAX_SAFE_INTEGER / 1_000_000_000, - ]) { - expect(() => - defineFactory({ - meta: { - name: `accepted-credits-${maxAiCredits}`, - description: "Factory with an accepted AI-credit ceiling", - phases: [], - limits: { maxAiCredits }, - }, - run: async () => null, - }) - ).not.toThrow(); - } - }); - - it("rejects timeoutSeconds above the Node setTimeout ceiling", () => { - const definition = { - meta: { - name: "oversized-timeout", - description: "Factory with an out-of-range timeout", - phases: [], - limits: { timeoutSeconds: 2_147_483.648 }, - }, - run: async () => null, - } as FactoryDefinition; - - expect(() => defineFactory(definition)).toThrow( - 'Factory limit "timeoutSeconds" must not exceed 2147483.647 seconds' - ); - }); - - it("documents timeoutSeconds as accumulated active-execution time in public and generated types", () => { - const publicTypes = readFileSync(new URL("../src/types.ts", import.meta.url), "utf8"); - const generatedRpc = readFileSync( - new URL("../src/generated/rpc.ts", import.meta.url), - "utf8" - ); - - expect(publicTypes).toContain("Maximum accumulated active-execution time, in seconds."); - expect(publicTypes).toContain("subprocess waits, queued-agent waits, and sleeps"); - expect(publicTypes).toContain("timeoutSeconds?: number;"); - expect(generatedRpc).toContain("Maximum accumulated active-execution time in seconds."); - expect(generatedRpc).toContain("subprocess waits, queued-agent waits, and sleeps"); - expect(generatedRpc).toContain("timeoutSeconds?: number;"); - }); - - // A guessed ceiling does not make a run safer: it stops a healthy run partway - // with `factory_limit_reached`, after that run has already taken the user's - // approval and spent credits. Both documents are handed to the model verbatim - // by the `factories_manage` guide, so neither may read as an invitation to - // invent one. - it("documents limits as opt-in rather than inviting an invented ceiling", () => { - const guide = readFileSync(new URL("../docs/factories.md", import.meta.url), "utf8"); - const patterns = readFileSync( - new URL("../docs/factory-patterns.md", import.meta.url), - "utf8" - ); - - expect(guide).toContain( - "Set a ceiling only from real knowledge of what the factory costs, or because the user named one" - ); - expect(guide).toContain("no basis for estimating a number"); - - // The opening `defineFactory` sample is the shape an author copies. Filling - // all four ceilings in there taught the numbers as much as the syntax. - const openingSample = guide.slice(0, guide.indexOf("## Declaring an argument shape")); - expect(openingSample).not.toContain("limits: {"); - - // The Scaling section used to answer "there is no built-in concurrency cap" - // with "so declare one before fanning out widely". - expect(patterns).not.toContain("declare one before fanning out widely"); - expect(patterns).toContain("bound a wide fan-out with the factory's own counters"); - }); - - it("documents factory invocation and list paging behavior accurately", () => { - const guide = readFileSync(new URL("../docs/factories.md", import.meta.url), "utf8"); - const publicApi = readFileSync(new URL("../src/factory.ts", import.meta.url), "utf8"); - const listRunsPagingWording = "newest default page of this session's durable factory runs"; - const listRunsMetadata = ["oldestSeq", "newestSeq", "hasMoreNewer", "omittedOlder"]; - const resumeCodes = [ - "not_found", - "non_resumable", - "already_active", - "factory_already_running", - "factory_limits_invalid", - "factory_session_disposed", - "factory_storage_unavailable", - "factory_storage_corrupt", - ]; - const normalizeJSDoc = (document: string) => - document.replace(/\r?\n\s*\* ?/g, " ").replace(/\s+/g, " "); - const normalizedGuide = normalizeJSDoc(guide); - const normalizedPublicApi = normalizeJSDoc(publicApi); - - for (const document of [guide, publicApi]) { - expect(document).not.toContain("reapproval_declined"); - expect(document).not.toContain("no_approval_provider"); - expect(document).not.toMatch(/declined fresh run[\s\S]*terminal `cancelled` envelope/i); - } - - for (const document of [normalizedGuide, normalizedPublicApi]) { - expect(document).toContain(listRunsPagingWording); - for (const field of listRunsMetadata) { - expect(document).toContain(field); - } - } - - expect(normalizedGuide).toContain( - "SDK-initiated `run` and `resume` do not request permission" - ); - expect(normalizedGuide).toContain( - "`run_factory` tool requests permission before the durable row exists" - ); - expect(normalizedGuide).toContain("declining it creates no run row"); - expect(normalizedGuide).toContain("its maximum number of active top-level runs"); - for (const code of resumeCodes) { - expect(guide).toContain(`\`${code}\``); - } - expect(guide).toContain( - "Options are exactly `label`, `schema`, `model`, `agent`, `reasoningEffort`, and `contextTier`" - ); - expect(normalizedGuide).toContain( - "session returned by `joinSession`. It refuses calls that start, resume, or pause a factory run" - ); - expect(normalizedGuide).toContain( - "A `paused` envelope means that the current attempt settled, not that the durable run is permanently finished" - ); - expect(normalizedGuide).toContain('await ctx.pause("review-ready")'); - expect(normalizedGuide).toContain("session.factory.pause(runId)"); - - expect(normalizedPublicApi).toContain("SDK-initiated runs do not request permission"); - expect(normalizedPublicApi).toContain("declining it creates no run row"); - expect(normalizedPublicApi).toContain( - "while the session is at its active top-level run limit" - ); - expect(normalizedPublicApi).toContain("SDK-initiated resumes do not request permission"); - expect(normalizedPublicApi).toContain("with a documented resume code rejects with"); - expect(normalizedPublicApi).toContain( - "session instance returned by `joinSession`. It refuses calls that start, resume, or pause a factory run" - ); - expect(normalizedPublicApi).toContain( - "`paused` settles the current attempt, but the same durable run can later resume" - ); - }); - - it("carries a declared argsSchema through defineFactory into the registration payload", async () => { - const client = new CopilotClient(); - await client.start(); - onTestFinished(() => stopClient(client)); - - const argsSchema = { - type: "object", - required: ["repoPath"], - properties: { - repoPath: { type: "string" }, - depth: { type: ["integer", "null"] }, - mode: { enum: ["fast", "thorough"] }, - }, - } satisfies FactoryJsonSchema; - const meta = { - name: "declares-args", - description: "Declares the argument shape it expects", - phases: [], - argsSchema, - }; - const factory = defineFactory({ meta, run: async () => ({ ok: true }) }); - - // The declaration is snapshotted and deep-frozen like the rest of the - // metadata, so it cannot be mutated after registration. - expect(factory.meta.argsSchema).toEqual(argsSchema); - expect(factory.meta.argsSchema).not.toBe(argsSchema); - expect(Object.isFrozen(factory.meta.argsSchema)).toBe(true); - expect(() => { - // @ts-expect-error handle.meta.argsSchema is deeply readonly. - factory.meta.argsSchema!.type = "array"; - }).toThrow(TypeError); - - const omitted = defineFactory({ - meta: { name: "omits-args", description: "Declares nothing", phases: [] }, - run: async () => ({ ok: true }), - }); - expect(omitted.meta.argsSchema).toBeUndefined(); - expect("argsSchema" in omitted.meta).toBe(false); - - const sendRequest = vi - .spyOn( - (client as never as { connection: { sendRequest: Function } }).connection, - "sendRequest" - ) - .mockImplementation(async (method: string, params: Record) => { - if (method === "session.resume") { - return { sessionId: params.sessionId }; - } - throw new Error(`Unexpected method: ${method}`); - }); - - await client.resumeSessionForExtension( - "session-args-schema", - { onPermissionRequest: () => ({ kind: "approved" }) }, - [factory, omitted] - ); - - const payload = sendRequest.mock.calls.find( - ([method]) => method === "session.resume" - )![1] as { factories: Array> }; - // The schema has to survive JSON serialization to reach the runtime, which - // validates `args` against it before a run row exists. - expect(JSON.parse(JSON.stringify(payload.factories))[0].argsSchema).toEqual(argsSchema); - expect(payload.factories[1]).not.toHaveProperty("argsSchema"); - }); - - it("documents argsSchema consistently with the runtime's enforced subset", () => { - const publicTypes = readFileSync(new URL("../src/types.ts", import.meta.url), "utf8"); - const publicApi = readFileSync(new URL("../src/factory.ts", import.meta.url), "utf8"); - const guide = readFileSync(new URL("../docs/factories.md", import.meta.url), "utf8"); - const normalizeJSDoc = (document: string) => - document.replace(/\r?\n\s*\* ?/g, " ").replace(/\s+/g, " "); - - expect(publicTypes).toContain("argsSchema?: FactoryJsonSchema;"); - - // The `run_factory` tool tells the model exactly this. The two surfaces - // have to agree about what a declaration does and does not enforce. - for (const document of [normalizeJSDoc(publicTypes), guide]) { - expect(document).toContain("types, required properties, and enum"); - expect(document).toMatch( - /`minLength`, `pattern`,? (?:and|or) `additionalProperties` are recorded/ - ); - } - expect(normalizeJSDoc(publicTypes)).toContain("before** the run starts"); - // Enforcement is tool-path only: `toolRunFactoryValidateArgs` is called from - // the runtime's runFactoryTool, and never from `session.factory.run`. Both - // surfaces must keep saying so, or authors will assume their own SDK-initiated - // runs are checked. - expect(normalizeJSDoc(publicTypes)).toContain( - "`session.factory.run(...)` is not validated against the declaration" - ); - expect(guide).toContain("Validation covers the model's `run_factory` path only"); - expect(normalizeJSDoc(publicApi)).toContain( - "`null`, `boolean`, `integer`, `number`, `string`, `array`, or `object`" - ); - expect(guide).toContain("no run row, permission prompt, or credit spend happens"); - }); - - it("serializes only factory metadata in the extension resume payload", async () => { - const client = new CopilotClient(); - await client.start(); - onTestFinished(() => stopClient(client)); - - const run = vi.fn(async () => ({ ok: true })); - const factory = defineFactory({ - meta: { - name: "registered", - description: "Registration test", - phases: [{ title: "Run" }], - limits: { maxTotalSubagents: 2 }, - }, - run, - }); - const sendRequest = vi - .spyOn( - (client as never as { connection: { sendRequest: Function } }).connection, - "sendRequest" - ) - .mockImplementation(async (method: string, params: Record) => { - if (method === "session.resume") { - const sessions = (client as never as { sessions: Map }) - .sessions; - expect( - sessions.get(params.sessionId as string)?.clientSessionApis.factory - ).toBeDefined(); - return { sessionId: params.sessionId }; - } - throw new Error(`Unexpected method: ${method}`); - }); - - await client.resumeSessionForExtension( - "session-registration", - { onPermissionRequest: () => ({ kind: "approved" }) }, - [factory] - ); - - const payload = sendRequest.mock.calls.find( - ([method]) => method === "session.resume" - )![1] as { - factories: unknown[]; - }; - expect(payload.factories).toEqual([factory.meta]); - expect(payload.factories[0]).not.toHaveProperty("run"); - expect(JSON.stringify(payload.factories)).not.toContain("async"); - }); - - it("passes factories only through the extension join path", async () => { - process.env.SESSION_ID = "session-extension"; - const factory = defineFactory({ - meta: { - name: "extension-only", - description: "Extension-only registration", - phases: [], - }, - run: async () => ({ ok: true }), - }); - const resumeSessionForExtension = vi - .spyOn(CopilotClient.prototype, "resumeSessionForExtension") - .mockResolvedValue({} as CopilotSession); - - await joinSession({ factories: [factory] }); - - expect(resumeSessionForExtension).toHaveBeenCalledWith( - "session-extension", - expect.objectContaining({ suppressResumeEvent: true }), - { factories: [factory], workflows: undefined }, - undefined - ); - }); - - it("builds the factory context with the unrestricted joined session identity", async () => { - process.env.SESSION_ID = "session-context"; - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.log") { - return {}; - } - if (method === "session.tasks.list") { - return { tasks: [] }; - } - throw new Error(`Unexpected method: ${method}`); - }); - const joinedSession = new CopilotSession("session-context", { sendRequest } as never); - const contextSeen = Promise.withResolvers<{ - runId: string; - args: unknown; - session: CopilotSession; - signal: AbortSignal; - }>(); - const factory = defineFactory({ - meta: { - name: "context", - description: "Context test", - phases: [], - }, - run: async (context) => { - contextSeen.resolve(context); - context.phase("A"); - context.log("hi"); - const tasks = await context.session.rpc.tasks.list(); - return { ok: true, taskCount: tasks.tasks.length }; - }, - }); - vi.spyOn(CopilotClient.prototype, "resumeSessionForExtension").mockImplementation( - async (_sessionId, _config, contributions) => { - if (Array.isArray(contributions)) { - throw new Error("joinSession should use the contribution object"); - } - joinedSession.registerFactories(contributions.factories); - return joinedSession; - } - ); - - const joinSessionResult = await joinSession({ factories: [factory] }); - const executeResult = await joinSessionResult.clientSessionApis.factory!.execute({ - sessionId: joinSessionResult.sessionId, - name: "context", - runId: "run-context", - executionToken: "execution-token", - args: { value: 42 }, - }); - const context = await contextSeen.promise; - - expect(context.runId).toBe("run-context"); - expect(context.args).toEqual({ value: 42 }); - expect(context.session).toBe(joinSessionResult); - expect(context.session.rpc).toBe(joinSessionResult.rpc); - expect(context.signal).toBeInstanceOf(AbortSignal); - expect(executeResult).toEqual({ result: { ok: true, taskCount: 0 } }); - expect(sendRequest).toHaveBeenCalledWith("session.tasks.list", { - sessionId: joinSessionResult.sessionId, - }); - expect(sendRequest).toHaveBeenCalledWith("session.factory.log", { - sessionId: joinSessionResult.sessionId, - runId: "run-context", - executionToken: "execution-token", - lines: [ - { seq: 0, kind: "phase", text: "A" }, - { seq: 1, kind: "log", text: "hi" }, - ], - }); - }); - - it("rejects nested factories without forwarding a runNested request", async () => { - const sendRequest = vi.fn(async () => { - throw new Error("Unexpected forward request"); - }); - const session = new CopilotSession("session-no-nesting", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: "no-nesting", - description: "Nested factory rejection test", - phases: [], - }, - run: async (context) => context.factory("nested", { value: 42 }), - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "no-nesting", - runId: "run-no-nesting", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toThrow("nested factories are not supported"); - expect(sendRequest).not.toHaveBeenCalled(); - }); - - it("keeps factory reads and cancellation available inside a factory body", async () => { - const sendRequest = vi.fn(async (method: string) => { - switch (method) { - case "session.factory.getRun": - return { runId: "other-run", status: "completed" }; - case "session.factory.listRuns": - return { runs: [] }; - case "session.factory.cancel": - return {}; - default: - throw new Error(`Unexpected method: ${method}`); - } - }); - const session = new CopilotSession("session-factory-reads", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: "factory-reads", - description: "Read factory state from a factory body", - phases: [], - }, - run: async ({ session: contextSession }) => { - const [run, runs] = await Promise.all([ - contextSession.factory.getRun("other-run"), - contextSession.factory.listRuns(), - contextSession.factory.cancel("other-run"), - ]); - return { runId: run.runId, runCount: runs.length }; - }, - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "factory-reads", - runId: "run-factory-reads", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ result: { runId: "other-run", runCount: 0 } }); - expect(sendRequest).toHaveBeenCalledWith("session.factory.getRun", { - sessionId: session.sessionId, - runId: "other-run", - }); - expect(sendRequest).toHaveBeenCalledWith("session.factory.listRuns", { - sessionId: session.sessionId, - }); - expect(sendRequest).toHaveBeenCalledWith("session.factory.cancel", { - sessionId: session.sessionId, - runId: "other-run", - }); - }); - - it("allows factory.run after a factory body returns", async () => { - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.run") { - return { runId: "run-after-body", status: "completed", result: "started" }; - } - throw new Error(`Unexpected method: ${method}`); - }); - const session = new CopilotSession("session-after-body", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: "returns", - description: "Return before a separate factory run", - phases: [], - }, - run: async () => "finished", - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "returns", - runId: "run-returns", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ result: "finished" }); - await expect(session.factory.run("after-body")).resolves.toMatchObject({ - status: "completed", - result: "started", - }); - }); - - it("allows a factory-body timer to start a factory after the body settles", async () => { - const delayedRun = Promise.withResolvers(); - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.run") { - return { runId: "run-from-timer", status: "completed", result: "started" }; - } - throw new Error(`Unexpected method: ${method}`); - }); - const session = new CopilotSession("session-timer", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: "timer", - description: "Start a factory from an unawaited timer", - phases: [], - }, - run: async () => { - setTimeout(() => { - void session.factory - .run("from-timer") - .then(delayedRun.resolve, delayedRun.reject); - }, 0); - return "finished"; - }, - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "timer", - runId: "run-timer", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ result: "finished" }); - await expect(delayedRun.promise).resolves.toMatchObject({ - status: "completed", - result: "started", - }); - }); - - it("flushes progress incrementally while a factory body is awaiting", async () => { - const sendRequest = vi.fn(async () => ({})); - const session = new CopilotSession("session-live-progress", { sendRequest } as never); - const body = Promise.withResolvers(); - const factory = defineFactory({ - meta: { - name: "live-progress", - description: "Incremental progress test", - phases: [], - }, - run: async ({ log }) => { - log("before await"); - await body.promise; - return "done"; - }, - }); - session.registerFactories([factory]); - - const execution = session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "live-progress", - runId: "run-live-progress", - executionToken: "execution-token", - args: {}, - }); - await vi.waitFor(() => { - expect(sendRequest).toHaveBeenCalledWith("session.factory.log", { - sessionId: session.sessionId, - runId: "run-live-progress", - executionToken: "execution-token", - lines: [{ seq: 0, kind: "log", text: "before await" }], - }); - }); - - body.resolve(); - await expect(execution).resolves.toEqual({ result: "done" }); - }); - - it("calls factory.agent with the current run id and returns its text", async () => { - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.agent") { - return { result: "pong" }; - } - throw new Error(`Unexpected method: ${method}`); - }); - const session = new CopilotSession("session-agent", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: "agent", - description: "Agent context test", - phases: [], - }, - run: async ({ agent }) => - agent("Reply with pong", { - label: "Pong helper", - model: "gpt-test", - schema: { type: "string" }, - effort: "high", - } as FactoryAgentOptions), - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "agent", - runId: "run-agent", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ result: "pong" }); - expect(sendRequest).toHaveBeenCalledWith("session.factory.agent", { - sessionId: session.sessionId, - factoryRunId: "run-agent", - executionToken: "execution-token", - prompt: "Reply with pong", - opts: { - label: "Pong helper", - model: "gpt-test", - schema: { type: "string" }, - }, - }); - }); - - it("forwards every declared factory.agent option", async () => { - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.agent") { - return { result: "pong" }; - } - throw new Error(`Unexpected method: ${method}`); - }); - const session = new CopilotSession("session-agent-options", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: "agent-options", - description: "Agent option forwarding test", - phases: [], - }, - run: async ({ agent }) => - agent("Reply with pong", { - label: "Pong helper", - model: "gpt-test", - schema: { type: "string" }, - agent: "reviewer", - reasoningEffort: "high", - contextTier: "long_context", - }), - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "agent-options", - runId: "run-agent-options", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ result: "pong" }); - expect(sendRequest).toHaveBeenCalledWith("session.factory.agent", { - sessionId: session.sessionId, - factoryRunId: "run-agent-options", - executionToken: "execution-token", - prompt: "Reply with pong", - opts: { - label: "Pong helper", - model: "gpt-test", - schema: { type: "string" }, - agent: "reviewer", - reasoningEffort: "high", - contextTier: "long_context", - }, - }); - }); - - it("sends empty factory.agent options when none are supplied", async () => { - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.agent") { - return { result: "pong" }; - } - throw new Error(`Unexpected method: ${method}`); - }); - const session = new CopilotSession("session-empty-agent-options", { - sendRequest, - } as never); - const factory = defineFactory({ - meta: { - name: "empty-agent-options", - description: "Empty agent option forwarding test", - phases: [], - }, - run: async ({ agent }) => agent("Reply with pong"), - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "empty-agent-options", - runId: "run-empty-agent-options", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ result: "pong" }); - expect(sendRequest).toHaveBeenCalledWith("session.factory.agent", { - sessionId: session.sessionId, - factoryRunId: "run-empty-agent-options", - executionToken: "execution-token", - prompt: "Reply with pong", - opts: {}, - }); - }); - - it("keeps each execution token on callbacks from overlapping contexts with the same run id", async () => { - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.agent") { - return { result: "agent result" }; - } - if (method === "session.factory.journal.get") { - return { hit: false }; - } - return {}; - }); - const session = new CopilotSession("session-overlapping-attempts", { - sendRequest, - } as never); - const contexts: FactoryContext[] = []; - const bodies = [Promise.withResolvers(), Promise.withResolvers()]; - const contextsReady = Promise.withResolvers(); - const factory = defineFactory({ - meta: { - name: "overlapping-attempts", - description: "Execution token capture test", - phases: [], - }, - run: async (context) => { - const invocation = contexts.length; - contexts.push(context); - if (contexts.length === 2) { - contextsReady.resolve(); - } - await bodies[invocation].promise; - return `attempt ${invocation + 1}`; - }, - }); - session.registerFactories([factory]); - const first = session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "overlapping-attempts", - runId: "shared-run", - executionToken: "old-token", - args: {}, - }); - const second = session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "overlapping-attempts", - runId: "shared-run", - executionToken: "current-token", - args: {}, - }); - await contextsReady.promise; - - contexts[0].log("stale log"); - await contexts[0].agent("stale agent"); - await contexts[0].step("stale journal", () => "stale result"); - await contexts[1].agent("current agent"); - - expect(sendRequest).toHaveBeenCalledWith( - "session.factory.log", - expect.objectContaining({ executionToken: "old-token" }) - ); - expect(sendRequest).toHaveBeenCalledWith( - "session.factory.agent", - expect.objectContaining({ executionToken: "old-token", prompt: "stale agent" }) - ); - expect(sendRequest).toHaveBeenCalledWith( - "session.factory.journal.get", - expect.objectContaining({ executionToken: "old-token", key: "stale journal" }) - ); - expect(sendRequest).toHaveBeenCalledWith( - "session.factory.journal.put", - expect.objectContaining({ executionToken: "old-token", key: "stale journal" }) - ); - expect(sendRequest).toHaveBeenCalledWith( - "session.factory.agent", - expect.objectContaining({ executionToken: "current-token", prompt: "current agent" }) - ); - - bodies[0].resolve(); - bodies[1].resolve(); - await expect(first).resolves.toEqual({ result: "attempt 1" }); - await expect(second).resolves.toEqual({ result: "attempt 2" }); - }); - - it("runs a durable step once, serves cached null, and does not cache failures", async () => { - const journal = new Map(); - const sendRequest = vi.fn( - async (method: string, params: { key?: string; resultJson?: unknown }) => { - if (method === "session.factory.journal.get") { - return journal.has(params.key!) - ? { hit: true, resultJson: journal.get(params.key!) } - : { hit: false }; - } - if (method === "session.factory.journal.put") { - journal.set(params.key!, params.resultJson); - return {}; - } - throw new Error(`Unexpected method: ${method}`); - } - ); - const session = new CopilotSession("session-step", { sendRequest } as never); - let cachedProducerCalls = 0; - let failingProducerCalls = 0; - const factory = defineFactory({ - meta: { - name: "step", - description: "Durable step context test", - phases: [], - }, - run: async ({ step }) => { - const first = await step("cached-null", async () => { - cachedProducerCalls++; - return null; - }); - const second = await step("cached-null", async () => { - cachedProducerCalls++; - return "wrong"; - }); - const failed = await step("retry", async () => { - failingProducerCalls++; - throw new Error("transient"); - }).catch(() => "failed"); - const retried = await step("retry", async () => { - failingProducerCalls++; - return "recovered"; - }); - return { first, second, failed, retried }; - }, - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "step", - runId: "run-step", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ - result: { first: null, second: null, failed: "failed", retried: "recovered" }, - }); - expect(cachedProducerCalls).toBe(1); - expect(failingProducerCalls).toBe(2); - expect( - sendRequest.mock.calls.filter(([method]) => method === "session.factory.journal.put") - ).toHaveLength(2); - }); - - it.each([ - ["undefined", () => undefined], - ["NaN", () => Number.NaN], - ["Infinity", () => Number.POSITIVE_INFINITY], - ["function", () => () => undefined], - ["symbol", () => Symbol("invalid")], - ["BigInt", () => 1n], - [ - "cycle", - () => { - const value: Record = {}; - value.self = value; - return value; - }, - ], - ["non-plain object", () => new Date()], - [ - "accessor property", - () => Object.defineProperty({}, "value", { enumerable: true, get: () => "hidden" }), - ], - [ - "non-enumerable property", - () => Object.defineProperty({}, "value", { enumerable: false, value: "hidden" }), - ], - ["array hole", () => new Array(1)], - [ - "array accessor", - () => Object.defineProperty([], "0", { enumerable: true, get: () => "hidden" }), - ], - ["array extra key", () => Object.assign([1], { extra: "dropped" })], - ])("rejects a journaled step %s result", async (_label, makeValue) => { - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.journal.get") { - return { hit: false }; - } - throw new Error(`Unexpected method: ${method}`); - }); - const session = new CopilotSession("session-invalid-step", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: "invalid-step", - description: "Rejects lossy step values", - phases: [], - }, - run: async ({ step }) => { - await step("invalid", async () => makeValue() as never); - return "must-not-complete"; - }, - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "invalid-step", - runId: "run-invalid-step", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toMatchObject({ - data: { - code: "factory_step_not_json", - }, - }); - expect( - sendRequest.mock.calls.filter(([method]) => method === "session.factory.journal.put") - ).toHaveLength(0); - }); - - it("validates a journaled step cache hit before replay", async () => { - const cached = Object.assign([1], { extra: "dropped" }); - const producer = vi.fn(async () => "must-not-run"); - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.journal.get") { - return { hit: true, resultJson: cached }; - } - throw new Error(`Unexpected method: ${method}`); - }); - const session = new CopilotSession("session-invalid-step-cache", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: "invalid-step-cache", - description: "Rejects invalid cached values", - phases: [], - }, - run: async ({ step }) => step("cached", producer), - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "invalid-step-cache", - runId: "run-invalid-step-cache", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toMatchObject({ - data: { - code: "factory_step_not_json", - category: "unsupported_object", - }, - }); - expect(producer).not.toHaveBeenCalled(); - }); - - it("replays a journaled step value identically on resume", async () => { - const journal = new Map(); - const sendRequest = vi.fn( - async (method: string, params: { key?: string; resultJson?: unknown }) => { - if (method === "session.factory.journal.get") { - return journal.has(params.key!) - ? { hit: true, resultJson: journal.get(params.key!) } - : { hit: false }; - } - if (method === "session.factory.journal.put") { - journal.set(params.key!, params.resultJson); - return {}; - } - throw new Error(`Unexpected method: ${method}`); - } - ); - const producer = vi.fn(async () => ({ nested: [1, null, "same"] })); - const session = new CopilotSession("session-step-replay", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: "step-replay", - description: "Replays strict JSON", - phases: [], - }, - run: async ({ step }) => step("same", producer), - }); - session.registerFactories([factory]); - - const first = await session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "step-replay", - runId: "run-step-replay", - executionToken: "execution-token", - args: {}, - }); - const replay = await session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "step-replay", - runId: "run-step-replay", - executionToken: "execution-token", - args: {}, - }); - - expect(replay).toEqual(first); - expect(producer).toHaveBeenCalledOnce(); - }); - - it("bypasses validation and journaling for a volatile step", async () => { - const sendRequest = vi.fn(); - const session = new CopilotSession("session-volatile-step", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: "volatile-step", - description: "Allows author-opted-out volatile values", - phases: [], - }, - run: async ({ step }) => { - const value = await step("volatile", async () => (() => "not JSON") as never, { - volatile: true, - }); - expect(typeof value).toBe("function"); - return "completed"; - }, - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "volatile-step", - runId: "run-volatile-step", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ result: "completed" }); - expect(sendRequest).not.toHaveBeenCalled(); - }); - - it("does not start a volatile step producer after the run is aborted", async () => { - const sendRequest = vi.fn(); - const session = new CopilotSession("session-volatile-abort", { sendRequest } as never); - let producerRan = false; - const factory = defineFactory({ - meta: { - name: "volatile-abort", - description: "Volatile steps honour cancellation", - phases: [], - }, - run: async ({ step, runId }) => { - // Abort mid-run, then attempt a volatile step. The producer must - // not run: cancellation has to stop new extension work starting, - // exactly as it does on the journaled path. - await session.clientSessionApis.factory!.abort({ - sessionId: session.sessionId, - runId, - executionToken: "execution-token", - }); - await step( - "volatile", - () => { - producerRan = true; - return "should not happen"; - }, - { volatile: true } - ); - return "completed"; - }, - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "volatile-abort", - runId: "run-volatile-abort", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toThrow(); - expect(producerRan).toBe(false); - }); - - it("rejects a factory result array with an extra own key", async () => { - const factory = defineFactory({ - meta: { - name: "array-extra-result", - description: "Rejects lossy array keys", - phases: [], - }, - run: async () => Object.assign([1], { extra: 1n }) as never, - }); - const session = new CopilotSession("session-array-extra-result", {} as never); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "array-extra-result", - runId: "run-array-extra-result", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toMatchObject({ - data: { - code: "factory_result_not_json", - category: "unsupported_object", - }, - }); - }); - - it("exposes factory getRun and forwards the run id", async () => { - const envelope = { runId: "run-read", status: "error", error: "failed" }; - const sendRequest = vi.fn(async () => envelope); - const session = new CopilotSession("session-read", { sendRequest } as never); - - await expect(session.factory.getRun("run-read")).resolves.toEqual(envelope); - expect(sendRequest).toHaveBeenCalledWith("session.factory.getRun", { - sessionId: session.sessionId, - runId: "run-read", - }); - }); - - it("exposes factory observability methods and forwards paging options", async () => { - const summary = { - runId: "run-observe", - factoryName: "observe", - description: "Observe", - status: "running" as const, - revision: 4, - createdAt: 1, - startedAt: 2, - updatedAt: 3, - completedAt: null, - currentPhase: { id: "p0", ordinal: 0 }, - declaredPhaseCount: 1, - liveAgentCount: 1, - totalSpawnedAgentCount: 1, - consumed: { activeMs: 10, subagents: 1, nanoAiu: 5 }, - declaredLimits: {}, - approved: {}, - observedAt: 4, - activeSegmentStartedAt: 2, - terminal: null, - }; - const progress = { - records: [], - oldestSeq: null, - newestSeq: null, - hasMoreOlder: false, - hasMoreNewer: false, - revision: 4, - }; - const detail = { ...summary, phases: [], agents: [], progress }; - const runsPage = { - runs: [summary], - oldestSeq: 11, - newestSeq: 12, - hasMoreNewer: true, - omittedOlder: 10, - }; - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.listRuns") return runsPage; - if (method === "session.factory.getRunDetail") return detail; - return progress; - }); - const session = new CopilotSession("session-observe", { sendRequest } as never); - - await expect(session.factory.listRuns()).resolves.toEqual([summary]); - const listedPage = await session.factory.listRuns({ - afterSeq: 10, - beforeSeq: 20, - limit: 50, - }); - expect(listedPage).toEqual(runsPage); - expect(listedPage.oldestSeq).toBe(11); - expect(listedPage.newestSeq).toBe(12); - expect(listedPage.hasMoreNewer).toBe(true); - expect(listedPage.omittedOlder).toBe(10); - await expect(session.factory.getRunDetail("run-observe")).resolves.toEqual(detail); - await expect( - session.factory.getRunProgress("run-observe", { - phaseId: "p0", - afterSeq: 10, - limit: 50, - }) - ).resolves.toEqual(progress); - expect(sendRequest).toHaveBeenNthCalledWith(1, "session.factory.listRuns", { - sessionId: session.sessionId, - }); - expect(sendRequest).toHaveBeenNthCalledWith(2, "session.factory.listRuns", { - sessionId: session.sessionId, - afterSeq: 10, - beforeSeq: 20, - limit: 50, - }); - expect(sendRequest).toHaveBeenNthCalledWith(3, "session.factory.getRunDetail", { - sessionId: session.sessionId, - runId: "run-observe", - }); - expect(sendRequest).toHaveBeenNthCalledWith(4, "session.factory.getRunProgress", { - sessionId: session.sessionId, - runId: "run-observe", - phaseId: "p0", - afterSeq: 10, - limit: 50, - }); - }); - - it("exposes factory cancel and forwards the run id", async () => { - const envelope = { runId: "run-cancel", status: "cancelled", reason: "cancelled" }; - const sendRequest = vi.fn(async () => envelope); - const session = new CopilotSession("session-cancel", { sendRequest } as never); - - await expect(session.factory.cancel("run-cancel")).resolves.toEqual(envelope); - expect(sendRequest).toHaveBeenCalledWith("session.factory.cancel", { - sessionId: session.sessionId, - runId: "run-cancel", - }); - }); - - it("exposes guarded public pause and prevents factory bodies from bypassing ctx.pause", async () => { - const paused = { runId: "run-pause", status: "paused" as const }; - const sendRequest = vi.fn(async () => paused); - const session = new CopilotSession("session-pause", { sendRequest } as never); - - await expect(session.factory.pause("run-pause")).resolves.toEqual(paused); - expect(sendRequest).toHaveBeenCalledWith("session.factory.pause", { - sessionId: session.sessionId, - runId: "run-pause", - }); - - const factory = defineFactory({ - meta: { - name: "pause-bypass", - description: "Public pause cannot bypass context restrictions", - phases: [], - }, - run: ({ runId, session: factorySession }) => factorySession.factory.pause(runId), - }); - session.registerFactories([factory]); - sendRequest.mockClear(); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "pause-bypass", - runId: "run-pause-bypass", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toThrow( - "factory.run, factory.resume, and factory.pause are not allowed while a factory body is running on this call path." - ); - expect(sendRequest).not.toHaveBeenCalled(); - }); - - it("rejects an empty pause checkpoint key before RPC", async () => { - const sendRequest = vi.fn(); - const session = new CopilotSession("session-empty-pause-key", { - sendRequest, - } as never); - const factory = defineFactory({ - meta: { - name: "empty-pause-key", - description: "Empty pause key rejection", - phases: [], - }, - run: ({ pause }) => pause(""), - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "empty-pause-key", - runId: "run-empty-pause-key", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toThrow("must not be empty"); - expect(sendRequest).not.toHaveBeenCalled(); - }); - - it("waits for cooperative abort when a pause checkpoint returns pause", async () => { - const checkpointRequested = Promise.withResolvers(); - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.pauseAtCheckpoint") { - checkpointRequested.resolve(); - return { action: "pause" }; - } - throw new Error(`Unexpected method: ${method}`); - }); - const session = new CopilotSession("session-checkpoint-pause", { - sendRequest, - } as never); - const factory = defineFactory({ - meta: { - name: "checkpoint-pause", - description: "Pause checkpoint abort behavior", - phases: [], - }, - run: ({ pause }) => pause("review-ready"), - }); - session.registerFactories([factory]); - - let settled = false; - const execution = session.clientSessionApis - .factory!.execute({ - sessionId: session.sessionId, - name: "checkpoint-pause", - runId: "run-checkpoint-pause", - executionToken: "execution-token", - args: {}, - }) - .finally(() => { - settled = true; - }); - await checkpointRequested.promise; - await Promise.resolve(); - expect(settled).toBe(false); - - await session.clientSessionApis.factory!.abort({ - sessionId: session.sessionId, - runId: "run-checkpoint-pause", - executionToken: "execution-token", - }); - await expect(execution).rejects.toMatchObject({ name: "AbortError" }); - }); - - it("returns void and continues when a pause checkpoint returns continue", async () => { - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.pauseAtCheckpoint") { - return { action: "continue" }; - } - throw new Error(`Unexpected method: ${method}`); - }); - const session = new CopilotSession("session-checkpoint-continue", { - sendRequest, - } as never); - const factory = defineFactory({ - meta: { - name: "checkpoint-continue", - description: "Continue checkpoint behavior", - phases: [], - }, - run: async ({ pause }) => { - const result = await pause("review-ready"); - return result === undefined ? "continued" : "unexpected"; - }, - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "checkpoint-continue", - runId: "run-checkpoint-continue", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ result: "continued" }); - expect(sendRequest).toHaveBeenCalledWith("session.factory.pauseAtCheckpoint", { - sessionId: session.sessionId, - runId: "run-checkpoint-continue", - executionToken: "execution-token", - key: "review-ready", - }); - }); - - it.each(["parallel", "pipeline"] as const)( - "rejects pause checkpoints inside %s helper branches before RPC", - async (helper) => { - const sendRequest = vi.fn(); - const session = new CopilotSession(`session-pause-${helper}`, { - sendRequest, - } as never); - const factory = defineFactory({ - meta: { - name: `pause-${helper}`, - description: "Pause helper-scope rejection", - phases: [], - }, - run: async ({ pause, parallel, pipeline }) => { - const attempt = async () => { - try { - await pause("review-ready"); - return "unexpected"; - } catch (error) { - return (error as Error).message; - } - }; - return helper === "parallel" - ? parallel([attempt]) - : pipeline(["item"], attempt); - }, - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: `pause-${helper}`, - runId: `run-pause-${helper}`, - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ - result: [`Factory pause checkpoints are not allowed inside ${helper}() branches`], - }); - expect(sendRequest).not.toHaveBeenCalled(); - } - ); - - it("runs parallel as a barrier and maps a throwing thunk to null", async () => { - const first = Promise.withResolvers(); - const second = Promise.withResolvers(); - const started: string[] = []; - const session = new CopilotSession("session-parallel", {} as never); - const factory = defineFactory({ - meta: { - name: "parallel", - description: "Parallel combinator test", - phases: [], - }, - run: async ({ parallel }) => - parallel([ - async () => { - started.push("first"); - return first.promise; - }, - async () => { - started.push("second"); - return second.promise; - }, - async () => { - started.push("throwing"); - throw new Error("expected"); - }, - ]), - }); - session.registerFactories([factory]); - - let settled = false; - const execution = session.clientSessionApis - .factory!.execute({ - sessionId: session.sessionId, - name: "parallel", - runId: "run-parallel", - args: {}, - }) - .finally(() => { - settled = true; - }); - await vi.waitFor(() => expect(started).toEqual(["first", "second", "throwing"])); - - second.resolve("second"); - await Promise.resolve(); - expect(settled).toBe(false); - - first.resolve("first"); - await expect(execution).resolves.toEqual({ result: ["first", "second", null] }); - }); - - it("rejects already-invoked promises passed to parallel with a clear diagnostic", async () => { - const session = new CopilotSession("session-parallel-promises", {} as never); - const factory = defineFactory({ - meta: { - name: "parallel-promises", - description: "Parallel misuse diagnostic", - phases: [], - }, - run: async ({ parallel }) => - parallel([Promise.resolve("already running")] as unknown as Array< - () => Promise - >), - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "parallel-promises", - runId: "run-parallel-promises", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toThrow( - "parallel() expects an array of functions, not promises. Wrap each call: () => agent(...)" - ); - }); - - it("flows pipeline items independently and drops only the item whose stage throws", async () => { - const releaseFirstItem = Promise.withResolvers(); - const secondStageStarted = Promise.withResolvers(); - const finalStageItems: string[] = []; - const session = new CopilotSession("session-pipeline", {} as never); - const factory = defineFactory({ - meta: { - name: "pipeline", - description: "Pipeline combinator test", - phases: [], - }, - run: async ({ pipeline }) => - pipeline( - ["slow", "fast", "throw"], - async (_previous, item) => { - if (item === "slow") { - await releaseFirstItem.promise; - } - if (item === "throw") { - throw new Error("expected"); - } - return `${item}-stage-1`; - }, - async (previous, item) => { - if (item === "fast") { - secondStageStarted.resolve(); - } - finalStageItems.push(item as string); - return `${previous}-stage-2`; - } - ), - }); - session.registerFactories([factory]); - - const execution = session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "pipeline", - runId: "run-pipeline", - executionToken: "execution-token", - args: {}, - }); - await secondStageStarted.promise; - expect(finalStageItems).toEqual(["fast"]); - - releaseFirstItem.resolve(); - await expect(execution).resolves.toEqual({ - result: ["slow-stage-1-stage-2", "fast-stage-1-stage-2", null], - }); - expect(finalStageItems).toEqual(["fast", "slow"]); - }); - - it("enforces the 4096-item cap for parallel and pipeline", async () => { - const session = new CopilotSession("session-fanout-cap", {} as never); - const factory = defineFactory({ - meta: { - name: "fanout-cap", - description: "Fan-out cap test", - phases: [], - }, - run: async ({ parallel, pipeline }) => { - const tooManyItems = Array.from({ length: 4097 }, () => null); - const parallelError = await parallel( - tooManyItems.map(() => async () => null) - ).catch((error: unknown) => error); - const pipelineError = await pipeline(tooManyItems).catch((error: unknown) => error); - return { - parallel: (parallelError as Error).message, - pipeline: (pipelineError as Error).message, - }; - }, - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "fanout-cap", - runId: "run-fanout-cap", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ - result: { - parallel: "parallel() accepts at most 4096 items; got 4097.", - pipeline: "pipeline() accepts at most 4096 items; got 4097.", - }, - }); - }); - - it("does not deadlock nested combinators when only leaf agents use a one-slot limiter", async () => { - let active = 0; - let maxActive = 0; - let tail = Promise.resolve(); - const sendRequest = vi.fn( - async (method: string, params: { prompt: string }): Promise<{ result: string }> => { - if (method !== "session.factory.agent") { - throw new Error(`Unexpected method: ${method}`); - } - const previous = tail; - const done = Promise.withResolvers(); - tail = done.promise; - await previous; - active++; - maxActive = Math.max(maxActive, active); - await Promise.resolve(); - active--; - done.resolve(); - return { result: params.prompt }; - } - ); - const session = new CopilotSession("session-nested-combinators", { - sendRequest, - } as never); - const factory = defineFactory({ - meta: { - name: "nested-combinators", - description: "Nested combinator deadlock regression", - phases: [], - }, - run: async ({ agent, parallel, pipeline }) => - parallel([ - () => parallel([() => agent("a"), () => agent("b")]), - () => pipeline(["c"], (_previous, item) => agent(item as string)), - ]), - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "nested-combinators", - runId: "run-nested-combinators", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ result: [["a", "b"], ["c"]] }); - expect(maxActive).toBe(1); - expect(sendRequest).toHaveBeenCalledTimes(3); - }); - - it("flushes buffered progress in finally when the factory body throws", async () => { - const sendRequest = vi.fn(async () => ({})); - const session = new CopilotSession("session-throw-progress", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: "throw-progress", - description: "Throwing progress test", - phases: [], - }, - run: async ({ log }) => { - log("before throw"); - throw new Error("body failed"); - }, - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "throw-progress", - runId: "run-throw-progress", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toThrow("body failed"); - expect(sendRequest).toHaveBeenCalledWith("session.factory.log", { - sessionId: session.sessionId, - runId: "run-throw-progress", - executionToken: "execution-token", - lines: [{ seq: 0, kind: "log", text: "before throw" }], - }); - }); - - it("keeps a completed execution successful when only the final progress flush fails", async () => { - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.log") { - throw new Error("final transport failure"); - } - return {}; - }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); - const session = new CopilotSession("session-final-flush-failure", { - sendRequest, - } as never); - const factory = defineFactory({ - meta: { - name: "final-flush-failure", - description: "Final flush failure regression test", - phases: [], - }, - run: async ({ log }) => { - log("final line"); - return "done"; - }, - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "final-flush-failure", - runId: "run-final-flush-failure", - executionToken: "execution-token", - args: {}, - }) - ).resolves.toEqual({ result: "done" }); - expect(warning).toHaveBeenCalledWith( - "Failed to flush final factory progress after the factory body settled", - expect.objectContaining({ message: "final transport failure" }) - ); - }); - - it("keeps a completed execution successful when a background progress flush fails", async () => { - vi.useFakeTimers(); - const release = Promise.withResolvers(); - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.log") { - throw new Error("background transport failure"); - } - return {}; - }); - const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); - const session = new CopilotSession("session-background-flush-failure", { - sendRequest, - } as never); - const factory = defineFactory({ - meta: { - name: "background-flush-failure", - description: "Background flush failure regression test", - phases: [], - }, - run: async ({ log }) => { - log("background line"); - await release.promise; - return "done"; - }, - }); - session.registerFactories([factory]); - - try { - const execution = session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "background-flush-failure", - runId: "run-background-flush-failure", - executionToken: "execution-token", - args: {}, - }); - await vi.advanceTimersByTimeAsync(10_000); - await Promise.resolve(); - - release.resolve(); - - await expect(execution).resolves.toEqual({ result: "done" }); - expect(warning).toHaveBeenCalledWith( - "Ignoring a background factory progress flush failure after the factory body settled", - expect.objectContaining({ message: "background transport failure" }) - ); - } finally { - vi.useRealTimers(); - } - }); - - it("keeps a mid-run progress flush failure fatal", async () => { - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.log") { - throw new Error("mid-run transport failure"); - } - if (method === "session.factory.agent") { - return { result: "must not complete" }; - } - return {}; - }); - const session = new CopilotSession("session-mid-run-flush-failure", { - sendRequest, - } as never); - const factory = defineFactory({ - meta: { - name: "mid-run-flush-failure", - description: "Mid-run flush failure regression test", - phases: [], - }, - run: async ({ agent, log }) => { - log("before agent"); - return agent("trigger a flush"); - }, - }); - session.registerFactories([factory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "mid-run-flush-failure", - runId: "run-mid-run-flush-failure", - executionToken: "execution-token", - args: {}, - }) - ).rejects.toThrow("mid-run transport failure"); - expect(sendRequest).not.toHaveBeenCalledWith("session.factory.agent", expect.anything()); - }); - - it("surfaces the per-run abort signal on the factory context", async () => { - const session = new CopilotSession("session-abort-signal", {} as never); - const signalSeen = Promise.withResolvers(); - const factory = defineFactory({ - meta: { - name: "abort-signal", - description: "Abort signal test", - phases: [], - }, - run: async ({ signal }) => { - signalSeen.resolve(signal); - await new Promise((resolve) => - signal.addEventListener("abort", () => resolve(), { once: true }) - ); - return signal.aborted; - }, - }); - session.registerFactories([factory]); - - const execution = session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "abort-signal", - runId: "run-abort-signal", - executionToken: "execution-token", - args: {}, - }); - const signal = await signalSeen.promise; - expect(signal.aborted).toBe(false); - - await session.clientSessionApis.factory!.abort({ - sessionId: session.sessionId, - runId: "run-abort-signal", - executionToken: "execution-token", - }); - - expect(signal.aborted).toBe(true); - await expect(execution).resolves.toEqual({ result: true }); - }); - - it("rejects an in-flight runtime-backed await when factory.abort trips the signal", async () => { - const agentResponse = Promise.withResolvers<{ result: string }>(); - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.agent") { - return agentResponse.promise; - } - return {}; - }); - const session = new CopilotSession("session-abort-await", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: "abort-await", - description: "Abort an in-flight factory await", - phases: [], - }, - run: async ({ agent }) => agent("wait forever"), - }); - session.registerFactories([factory]); - - const execution = session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "abort-await", - runId: "run-abort-await", - executionToken: "execution-token", - args: {}, - }); - await vi.waitFor(() => - expect(sendRequest).toHaveBeenCalledWith("session.factory.agent", expect.anything()) - ); - - await session.clientSessionApis.factory!.abort({ - sessionId: session.sessionId, - runId: "run-abort-await", - executionToken: "execution-token", - }); - - await expect(execution).rejects.toMatchObject({ name: "AbortError" }); - agentResponse.resolve({ result: "late" }); - }); - - it("ignores a late abort for an older execution token with the same run id", async () => { - const oldAgent = Promise.withResolvers<{ result: string }>(); - const currentAgent = Promise.withResolvers<{ result: string }>(); - const sendRequest = vi.fn(async (method: string, params: { executionToken?: string }) => { - if (method !== "session.factory.agent") { - return {}; - } - return params.executionToken === "old-token" ? oldAgent.promise : currentAgent.promise; - }); - const session = new CopilotSession("session-token-scoped-abort", { - sendRequest, - } as never); - const signals: AbortSignal[] = []; - const factory = defineFactory({ - meta: { - name: "token-scoped-abort", - description: "Abort only the matching execution attempt", - phases: [], - }, - run: async ({ agent, signal }) => { - signals.push(signal); - return agent("wait"); - }, - }); - session.registerFactories([factory]); - - const oldExecution = session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "token-scoped-abort", - runId: "shared-run", - executionToken: "old-token", - args: {}, - }); - const currentExecution = session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "token-scoped-abort", - runId: "shared-run", - executionToken: "current-token", - args: {}, - }); - await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(2)); - - await session.clientSessionApis.factory!.abort({ - sessionId: session.sessionId, - runId: "shared-run", - executionToken: "old-token", - }); - expect(signals[0].aborted).toBe(true); - expect(signals[1].aborted).toBe(false); - await expect(oldExecution).rejects.toMatchObject({ name: "AbortError" }); - - currentAgent.resolve({ result: "current completed" }); - await expect(currentExecution).resolves.toEqual({ result: "current completed" }); - oldAgent.resolve({ result: "late old result" }); - }); - - it.each(["parallel", "pipeline"] as const)( - "propagates cancellation out of %s instead of mapping it to null", - async (combinator) => { - const agentResponse = Promise.withResolvers<{ result: string }>(); - const sendRequest = vi.fn(async (method: string) => { - if (method === "session.factory.agent") { - return agentResponse.promise; - } - return {}; - }); - const session = new CopilotSession("session-abort-parallel", { sendRequest } as never); - const factory = defineFactory({ - meta: { - name: `abort-${combinator}`, - description: "Cancellation must bubble out of a combinator", - phases: [], - }, - // If the combinator swallowed the AbortError to null, this run would - // resolve successfully with [null] despite the run being cancelled. - run: async ({ agent, parallel, pipeline }) => - combinator === "parallel" - ? parallel([() => agent("wait forever")]) - : pipeline(["wait forever"], (_previous, item) => agent(item as string)), - }); - session.registerFactories([factory]); - - const execution = session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: `abort-${combinator}`, - runId: `run-abort-${combinator}`, - executionToken: "execution-token", - args: {}, - }); - await vi.waitFor(() => - expect(sendRequest).toHaveBeenCalledWith("session.factory.agent", expect.anything()) - ); - - await session.clientSessionApis.factory!.abort({ - sessionId: session.sessionId, - runId: `run-abort-${combinator}`, - executionToken: "execution-token", - }); - - await expect(execution).rejects.toMatchObject({ name: "AbortError" }); - agentResponse.resolve({ result: "late" }); - } - ); - - it("dispatches factory.execute to the registered factory selected by name", async () => { - const firstRun = vi.fn(async () => ({ selected: "first" })); - const secondRun = vi.fn(async ({ args, log }) => { - log("executing"); - return { selected: "second", echoed: args }; - }); - const firstFactory = defineFactory({ - meta: { - name: "first", - description: "First factory", - phases: [], - }, - run: firstRun, - }); - const secondFactory = defineFactory({ - meta: { - name: "second", - description: "Second factory", - phases: [], - }, - run: secondRun, - }); - const session = new CopilotSession("session-execute", { - sendRequest: vi.fn(async () => ({})), - } as never); - session.registerFactories([firstFactory, secondFactory]); - - await expect( - session.clientSessionApis.factory!.execute({ - sessionId: session.sessionId, - name: "second", - runId: "run-echo", - executionToken: "execution-token", - args: { message: "hello" }, - }) - ).resolves.toEqual({ - result: { selected: "second", echoed: { message: "hello" } }, - }); - expect(firstRun).not.toHaveBeenCalled(); - expect(secondRun).toHaveBeenCalledOnce(); - - const error = await session.clientSessionApis - .factory!.execute({ - sessionId: session.sessionId, - name: "missing", - runId: "run-missing", - args: {}, - }) - .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ResponseError); - expect((error as ResponseError<{ code: string; name: string }>).data).toEqual({ - code: "factory_not_found", - name: "missing", - }); - }); - - it("runs fresh factories and routes direct and legacy resumes by ID without args", async () => { - const factory = defineFactory({ - meta: { - name: "friendly-run", - description: "Friendly run wrapper", - phases: [], - }, - run: async () => ({ unused: true }), - }); - const sendRequest = vi.fn(async (method: string, params: { name?: string }) => - method === "session.factory.resume" - ? { - factoryName: "stored-name", - run: { - runId: "run-prior", - status: "completed", - result: { name: "stored-name", persistedArgs: true }, - }, - } - : { - runId: "run-foreground", - status: "completed", - result: { name: params.name }, - } - ); - const session = new CopilotSession("session-run", { sendRequest } as never); - - await expect( - session.factory.resume("run-prior", { - limits: { maxTotalSubagents: 7 }, - notifyOnComplete: true, - logPhaseNames: true, - }) - ).resolves.toMatchObject({ - status: "completed", - result: { name: "stored-name", persistedArgs: true }, - }); - await expect( - session.factory.run("by-name", { - args: { value: 1 }, - limits: { maxTotalSubagents: 7 }, - notifyOnComplete: false, - logPhaseNames: true, - resumeFromRunId: "run-prior", - }) - ).resolves.toMatchObject({ - status: "completed", - result: { name: "stored-name", persistedArgs: true }, - }); - await expect( - session.factory.run(factory, { - notifyOnComplete: true, - logPhaseNames: false, - }) - ).resolves.toMatchObject({ - status: "completed", - result: { name: "friendly-run" }, - }); - expect(sendRequest).toHaveBeenNthCalledWith(1, "session.factory.resume", { - sessionId: session.sessionId, - runId: "run-prior", - limits: { maxTotalSubagents: 7 }, - notifyOnComplete: true, - logPhaseNames: true, - }); - expect(sendRequest).toHaveBeenNthCalledWith(2, "session.factory.resume", { - sessionId: session.sessionId, - runId: "run-prior", - limits: { maxTotalSubagents: 7 }, - notifyOnComplete: false, - logPhaseNames: true, - }); - expect(sendRequest).toHaveBeenNthCalledWith(3, "session.factory.run", { - sessionId: session.sessionId, - name: "friendly-run", - args: {}, - options: { - limits: undefined, - notifyOnComplete: true, - logPhaseNames: false, - }, - }); - }); - - it("preserves omitted, numeric, and explicit unlimited invocation limit overrides", async () => { - const sendRequest = vi.fn(async (method: string) => - method === "session.factory.resume" - ? { - factoryName: "stored-name", - run: { runId: "run-limits", status: "completed" }, - } - : { runId: "run-limits", status: "completed" } - ); - const session = new CopilotSession("session-limit-overrides", { - sendRequest, - } as never); - - await session.factory.run("omitted"); - await session.factory.run("numeric", { - limits: { maxTotalSubagents: 12 }, - }); - await session.factory.run("unlimited", { - limits: { maxTotalSubagents: null }, - }); - await session.factory.resume("run-limits", { - limits: { timeoutSeconds: null }, - }); - - expect(sendRequest.mock.calls[0][1]).toMatchObject({ - options: { limits: undefined }, - }); - expect(sendRequest.mock.calls[1][1]).toMatchObject({ - options: { limits: { maxTotalSubagents: 12 } }, - }); - expect(sendRequest.mock.calls[2][1]).toMatchObject({ - options: { limits: { maxTotalSubagents: null } }, - }); - expect(sendRequest.mock.calls[3][1]).toMatchObject({ - limits: { timeoutSeconds: null }, - }); - }); - - it("returns the full envelope for a failed foreground run", async () => { - const envelope = { - runId: "run-error", - status: "error" as const, - error: "factory failed", - snapshot: { completed: 1 }, - }; - const session = new CopilotSession("session-error", { - sendRequest: vi.fn(async () => envelope), - } as never); - - // A run that exists resolves with its envelope; only pre-execution - // failures (no run id) reject. - await expect(session.factory.run("failing")).resolves.toEqual(envelope); - }); - - it.each([ - "not_found", - "non_resumable", - "already_active", - "factory_already_running", - "factory_limits_invalid", - "factory_session_disposed", - "factory_storage_unavailable", - "factory_storage_corrupt", - ] as const)( - "throws FactoryResumeError with code %s for pre-execution failures", - async (code) => { - const session = new CopilotSession("session-resume-error", { - sendRequest: vi.fn(async () => { - throw new ResponseError(-32602, `resume failed: ${code}`, { code }); - }), - } as never); - - const error = await session.factory - .resume("run-error") - .catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(FactoryResumeError); - expect((error as FactoryResumeError).code).toBe(code); - } - ); - - it("leaves an unreachable permission_denied response as a raw ResponseError", async () => { - const session = new CopilotSession("session-resume-permission-denied", { - sendRequest: vi.fn(async () => { - throw new ResponseError(-32602, "resume failed: permission_denied", { - code: "permission_denied", - }); - }), - } as never); - - const error = await session.factory.resume("run-error").catch((caught: unknown) => caught); - expect(error).toBeInstanceOf(ResponseError); - expect(error).not.toBeInstanceOf(FactoryResumeError); - expect((error as ResponseError<{ code: string }>).data.code).toBe("permission_denied"); - }); - - it("returns resumed execution failures as envelopes", async () => { - const envelope = { - runId: "run-execution-error", - status: "error" as const, - error: "resumed body failed", - }; - const session = new CopilotSession("session-resumed-run-error", { - sendRequest: vi.fn(async () => ({ factoryName: "stored-name", run: envelope })), - } as never); - - await expect(session.factory.resume("run-execution-error")).resolves.toEqual(envelope); - }); -}); - -describe("factory run settlement", () => { - it.each([ - ["completed", true], - ["error", true], - ["halted", true], - ["paused", true], - ["cancelled", true], - ["pending", false], - ["running", false], - ] as const)("classifies %s as terminal=%s", (status, expected) => { - expect(isFactoryRunTerminal(status)).toBe(expected); - }); - - it("resolves immediately when the run has already settled", async () => { - const envelope = { runId: "run-settled", status: "completed" as const, result: 42 }; - const sendRequest = vi.fn(async () => envelope); - const session = new CopilotSession("session-wait-settled", { sendRequest } as never); - - await expect(session.factory.waitForRun("run-settled")).resolves.toEqual(envelope); - expect(sendRequest).toHaveBeenCalledTimes(1); - expect(sendRequest).toHaveBeenCalledWith("session.factory.getRun", { - sessionId: session.sessionId, - runId: "run-settled", - }); - }); - - it("waits for a running run to reach a terminal status", async () => { - const running = { runId: "run-wait", status: "running" as const }; - const terminal = { runId: "run-wait", status: "completed" as const, result: "done" }; - let current: unknown = running; - const sendRequest = vi.fn(async () => current); - const session = new CopilotSession("session-wait-running", { sendRequest } as never); - - const settled = session.factory.waitForRun("run-wait"); - // The first read observed a running envelope, so the wait is still pending. - await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(1)); - - // An invalidation event for an unrelated run must not trigger a re-read. - (session as never as { _dispatchEvent(event: unknown): void })._dispatchEvent( - runUpdatedEvent("some-other-run", 2) - ); - expect(sendRequest).toHaveBeenCalledTimes(1); - - current = terminal; - (session as never as { _dispatchEvent(event: unknown): void })._dispatchEvent( - runUpdatedEvent("run-wait", 3) - ); - - await expect(settled).resolves.toEqual(terminal); - }); - - it("periodically re-reads when a terminal invalidation is missed", async () => { - vi.useFakeTimers(); - const running = { runId: "run-poll", status: "running" as const }; - const terminal = { runId: "run-poll", status: "completed" as const, result: "polled" }; - let current: unknown = running; - const sendRequest = vi.fn(async () => current); - const session = new CopilotSession("session-wait-poll", { sendRequest } as never); - - try { - const settled = session.factory.waitForRun("run-poll"); - await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(1)); - - current = terminal; - await vi.advanceTimersByTimeAsync(5_000); - - await expect(settled).resolves.toEqual(terminal); - expect(sendRequest).toHaveBeenCalledTimes(2); - } finally { - vi.useRealTimers(); - } - }); - - it("stops watching once the run settles", async () => { - const running = { runId: "run-unsub", status: "running" as const }; - const terminal = { runId: "run-unsub", status: "error" as const, error: "body failed" }; - let current: unknown = running; - const sendRequest = vi.fn(async () => current); - const session = new CopilotSession("session-wait-unsub", { sendRequest } as never); - const handlersFor = (): Set | undefined => - ( - session as never as { - typedEventHandlers: Map>; - } - ).typedEventHandlers.get("factory.run_updated"); - - const settled = session.factory.waitForRun("run-unsub"); - await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(1)); - expect(handlersFor()?.size ?? 0).toBe(1); - - current = terminal; - (session as never as { _dispatchEvent(event: unknown): void })._dispatchEvent( - runUpdatedEvent("run-unsub", 2) - ); - await expect(settled).resolves.toEqual(terminal); - - // The subscription must be released, or every completed wait leaks a - // listener for the lifetime of the session. - expect(handlersFor()?.size ?? 0).toBe(0); - - const callsAtSettlement = sendRequest.mock.calls.length; - // A late event for a settled run must not provoke another read. - (session as never as { _dispatchEvent(event: unknown): void })._dispatchEvent( - runUpdatedEvent("run-unsub", 3) - ); - expect(sendRequest).toHaveBeenCalledTimes(callsAtSettlement); - }); - - it("rejects when the signal is already aborted and never reads", async () => { - const sendRequest = vi.fn(async () => ({ runId: "run-pre", status: "running" })); - const session = new CopilotSession("session-wait-pre-abort", { sendRequest } as never); - - await expect( - session.factory.waitForRun("run-pre", { signal: AbortSignal.abort() }) - ).rejects.toThrow(); - expect(sendRequest).not.toHaveBeenCalled(); - }); - - it("rejects when aborted while waiting, leaving the run untouched", async () => { - const sendRequest = vi.fn(async () => ({ runId: "run-abort", status: "running" })); - const session = new CopilotSession("session-wait-abort", { sendRequest } as never); - const controller = new AbortController(); - - const settled = session.factory.waitForRun("run-abort", { signal: controller.signal }); - await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(1)); - - controller.abort(); - await expect(settled).rejects.toThrow(); - // Aborting the wait must not cancel the run. - expect(sendRequest).not.toHaveBeenCalledWith("session.factory.cancel", expect.anything()); - }); - - it("propagates a read failure", async () => { - const sendRequest = vi.fn(async () => { - throw new Error("factory_storage_unavailable"); - }); - const session = new CopilotSession("session-wait-error", { sendRequest } as never); - - await expect(session.factory.waitForRun("run-broken")).rejects.toThrow( - "factory_storage_unavailable" - ); - }); - - it("collapses a burst of invalidation events into one in-flight read", async () => { - const running = { runId: "run-burst", status: "running" as const }; - const terminal = { runId: "run-burst", status: "completed" as const }; - let release: (() => void) | undefined; - const gate = new Promise((resolve) => (release = resolve)); - let readCount = 0; - const sendRequest = vi.fn(async () => { - readCount += 1; - if (readCount === 2) { - await gate; - } - // Reads 1 and 2 observe a running run; only the coalesced third - // read observes the terminal one. - return readCount >= 3 ? terminal : running; - }); - const session = new CopilotSession("session-wait-burst", { sendRequest } as never); - - const settled = session.factory.waitForRun("run-burst"); - await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(1)); - - const dispatch = (revision: number): void => - (session as never as { _dispatchEvent(event: unknown): void })._dispatchEvent( - runUpdatedEvent("run-burst", revision) - ); - - // Second read is held open while three more events arrive; they must - // collapse into a single follow-up read rather than three. - dispatch(2); - await vi.waitFor(() => expect(sendRequest).toHaveBeenCalledTimes(2)); - dispatch(3); - dispatch(4); - dispatch(5); - expect(sendRequest).toHaveBeenCalledTimes(2); - - release?.(); - await expect(settled).resolves.toEqual(terminal); - // One initial read, the held read, and exactly one coalesced re-read - // standing in for all three queued events. - expect(sendRequest).toHaveBeenCalledTimes(3); - }); -}); diff --git a/nodejs/test/session-event-types.test.ts b/nodejs/test/session-event-types.test.ts index cc5cb12bf1..330b381090 100644 --- a/nodejs/test/session-event-types.test.ts +++ b/nodejs/test/session-event-types.test.ts @@ -16,8 +16,8 @@ import { describe, expect, it } from "vitest"; import { approveAll } from "../src/index.js"; -import { FACTORY_AGENT_OPTION_KEYS } from "../src/factory.js"; -import type { FactoryAgentOptions as WireFactoryAgentOptions } from "../src/generated/rpc.js"; +import { WORKFLOW_AGENT_OPTION_KEYS } from "../src/workflow.js"; +import type { WorkflowAgentOptions as WireWorkflowAgentOptions } from "../src/generated/rpc.js"; import type { // The aggregate union; must still resolve via the package root. SessionEvent, @@ -65,10 +65,10 @@ import type { UserMessageAgentMode, Attachment, WorkingDirectoryContextHostType, - FactoryContext, - FactoryDefinition, - FactoryAgentOptions, - FactoryRunResult, + WorkflowContext, + WorkflowDefinition, + WorkflowAgentOptions, + WorkflowRunResult, JsonValue, } from "../src/index.js"; @@ -100,32 +100,32 @@ type _AssistantMessageEventStaysAlignedWithSessionEventUnion = _AssertEqual< Extract >; const _assistantMessageEventAlignmentCheck: _AssistantMessageEventStaysAlignedWithSessionEventUnion = true; -type _DefaultFactoryArgsAreJsonValue = _AssertEqual; -const _defaultFactoryArgsCheck: _DefaultFactoryArgsAreJsonValue = true; -type _DefaultFactoryResultIsJsonValueOrVoid = _AssertEqual< - Awaited>, +type _DefaultWorkflowArgsAreJsonValue = _AssertEqual; +const _defaultWorkflowArgsCheck: _DefaultWorkflowArgsAreJsonValue = true; +type _DefaultWorkflowResultIsJsonValueOrVoid = _AssertEqual< + Awaited>, JsonValue | void >; -const _defaultFactoryResultCheck: _DefaultFactoryResultIsJsonValueOrVoid = true; -type _FactoryRunResultIsJsonValueOrUndefined = _AssertEqual< - FactoryRunResult["result"], +const _defaultWorkflowResultCheck: _DefaultWorkflowResultIsJsonValueOrVoid = true; +type _WorkflowRunResultIsJsonValueOrUndefined = _AssertEqual< + WorkflowRunResult["result"], JsonValue | undefined >; -const _factoryRunResultCheck: _FactoryRunResultIsJsonValueOrUndefined = true; -type _FactoryAgentOptionKeysMatchPublicInterface = _AssertEqual< - (typeof FACTORY_AGENT_OPTION_KEYS)[number], - keyof FactoryAgentOptions +const _workflowRunResultCheck: _WorkflowRunResultIsJsonValueOrUndefined = true; +type _WorkflowAgentOptionKeysMatchPublicInterface = _AssertEqual< + (typeof WORKFLOW_AGENT_OPTION_KEYS)[number], + keyof WorkflowAgentOptions >; -const _factoryAgentOptionKeysCheck: _FactoryAgentOptionKeysMatchPublicInterface = true; -type _PublicFactoryAgentOptionsMatchWire = _AssertEqual< - keyof FactoryAgentOptions, - keyof WireFactoryAgentOptions +const _workflowAgentOptionKeysCheck: _WorkflowAgentOptionKeysMatchPublicInterface = true; +type _PublicWorkflowAgentOptionsMatchWire = _AssertEqual< + keyof WorkflowAgentOptions, + keyof WireWorkflowAgentOptions >; -const _publicFactoryAgentOptionsCheck: _PublicFactoryAgentOptionsMatchWire = true; -// @ts-expect-error Factory arguments must be representable on the JSON wire. -type _FactoryArgsRejectUndefined = FactoryContext; -// @ts-expect-error Factory results must be JSON values or top-level void. -type _FactoryResultRejectsFunction = FactoryDefinition void>; +const _publicWorkflowAgentOptionsCheck: _PublicWorkflowAgentOptionsMatchWire = true; +// @ts-expect-error Workflow arguments must be representable on the JSON wire. +type _WorkflowArgsRejectUndefined = WorkflowContext; +// @ts-expect-error Workflow results must be JSON values or top-level void. +type _WorkflowResultRejectsFunction = WorkflowDefinition void>; type _PermissionRequestedEventStaysAlignedWithSessionEventUnion = _AssertEqual< PermissionRequestedEvent, Extract diff --git a/nodejs/test/workflow.test.ts b/nodejs/test/workflow.test.ts index 0efb221fc9..2464cf6668 100644 --- a/nodejs/test/workflow.test.ts +++ b/nodejs/test/workflow.test.ts @@ -6,12 +6,11 @@ import { describe, expect, it, vi } from "vitest"; import { ErrorCodes, ResponseError } from "vscode-jsonrpc/node.js"; import { CopilotClient } from "../src/client.js"; import { CopilotSession } from "../src/session.js"; -import { defineFactory } from "../src/factory.js"; import { defineWorkflow } from "../src/workflow.js"; function runUpdatedEvent(runId: string, revision: number): Record { return { - type: "factory.run_updated", + type: "workflow.run_updated", id: `event-${runId}-${revision}`, parentId: null, timestamp: new Date().toISOString(), @@ -109,7 +108,7 @@ describe("dynamic workflows", () => { ); }); - it("serializes workflow metadata and rejects mixed contribution generations", async () => { + it("serializes workflow metadata", async () => { const client = new CopilotClient(); const workflow = defineWorkflow({ meta: { @@ -120,14 +119,6 @@ describe("dynamic workflows", () => { }, run: async () => ({ ok: true }), }); - const factory = defineFactory({ - meta: { - name: "legacy", - description: "Legacy factory", - phases: [], - }, - run: async () => ({ ok: true }), - }); const sendRequest = vi.fn(async (method: string, params: Record) => { if (method === "session.resume") { return { sessionId: params.sessionId }; @@ -145,54 +136,10 @@ describe("dynamic workflows", () => { const payload = sendRequest.mock.calls.find( ([method]) => method === "session.resume" )![1] as { - factories?: unknown[]; workflows?: unknown[]; }; expect(payload.workflows).toEqual([workflow.meta]); - expect(payload.factories).toBeUndefined(); expect(payload.workflows?.[0]).not.toHaveProperty("run"); - - await expect( - client.resumeSessionForExtension( - "session-mixed-registration", - { onPermissionRequest: () => ({ kind: "approved" }) }, - { factories: [factory], workflows: [workflow] } - ) - ).rejects.toThrow("cannot include both factories and workflows"); - }); - - it("preserves the legacy factory-array extension call shape", async () => { - const client = new CopilotClient(); - const factory = defineFactory({ - meta: { - name: "legacy", - description: "Legacy factory", - phases: [], - }, - run: async () => ({ ok: true }), - }); - const sendRequest = vi.fn(async (method: string, params: Record) => { - if (method === "session.resume") { - return { sessionId: params.sessionId }; - } - throw new Error(`Unexpected method: ${method}`); - }); - (client as never as { connection: unknown }).connection = { sendRequest }; - - await client.resumeSessionForExtension( - "session-legacy-factory-registration", - { onPermissionRequest: () => ({ kind: "approved" }) }, - [factory] - ); - - const payload = sendRequest.mock.calls.find( - ([method]) => method === "session.resume" - )![1] as { - factories?: unknown[]; - workflows?: unknown[]; - }; - expect(payload.factories).toEqual([factory.meta]); - expect(payload.workflows).toBeUndefined(); }); it("uses workflow-specific validation errors", async () => { diff --git a/python/copilot/generated/rpc.py b/python/copilot/generated/rpc.py index 12de08401e..9ff3111898 100644 --- a/python/copilot/generated/rpc.py +++ b/python/copilot/generated/rpc.py @@ -454,6 +454,24 @@ def to_dict(self) -> dict: result["resetDate"] = from_union([from_str, from_none], self.reset_date) return result +# Experimental: this type is part of an experimental API and may change or be removed. +class AccountKind(Enum): + """The provider kind stamped on a signed-in account. + + The provider kind of this account. + + The neutral provider kind. + + A provider a consumer may interactively sign in with. + + The provider kind to sign in with. + """ + ENTRA = "entra" + ENTRA_EMU = "entraEmu" + GITHUB_DOT_COM = "githubDotCom" + LOKI = "loki" + PROXIMA = "proxima" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AccountLoginRequest: @@ -554,6 +572,20 @@ def to_dict(self) -> dict: result["hasMoreUsers"] = from_bool(self.has_more_users) return result +class AuthEnumerateQueryKind(Enum): + ACCOUNTS = "accounts" + PROVIDERS = "providers" + +class AuthReadQueryKind(Enum): + ACTIVE_ACCOUNT = "activeAccount" + LAST_ERRORS = "lastErrors" + STATUS = "status" + +class AuthWriteKind(Enum): + LOGOUT = "logout" + SET_CREDENTIALS = "setCredentials" + SWITCH_ACTIVE = "switchActive" + # Experimental: this type is part of an experimental API and may change or be removed. class AdaptiveThinkingSupport(Enum): """Resolved Anthropic adaptive-thinking capability for a model. @@ -760,6 +792,82 @@ def to_dict(self) -> dict: class APIKeyAuthInfoType(Enum): API_KEY = "api-key" +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthLoginAdvanceRequest: + """Advance an in-flight login flow, optionally fulfilling an input-required step.""" + + flow_id: str + """Opaque flow id from begin.""" + + input: str | None = None + """Neutral input fulfilling a preceding input-required step (e.g. a GHEC host); ignored + otherwise. + """ + + @staticmethod + def from_dict(obj: Any) -> 'AuthLoginAdvanceRequest': + assert isinstance(obj, dict) + flow_id = from_str(obj.get("flowId")) + input = from_union([from_str, from_none], obj.get("input")) + return AuthLoginAdvanceRequest(flow_id, input) + + def to_dict(self) -> dict: + result: dict = {} + result["flowId"] = from_str(self.flow_id) + if self.input is not None: + result["input"] = from_union([from_str, from_none], self.input) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +class LoginProviderKind(Enum): + """The neutral provider kind. + + A provider a consumer may interactively sign in with. + + The provider kind to sign in with. + """ + ENTRA = "entra" + GITHUB_DOT_COM = "githubDotCom" + PROXIMA = "proxima" + +class AuthLoginStepKind(Enum): + AWAITING = "awaiting" + COMPLETED = "completed" + ERROR = "error" + INPUT_REQUIRED = "input-required" + NEEDS_INTERACTION = "needs-interaction" + OPEN_URL = "open-url" + +# Experimental: this type is part of an experimental API and may change or be removed. +class AuthLoginResultStatus(Enum): + """Terminal disposition of the login. + + Terminal disposition of a login persistence attempt. + """ + COMPLETED = "completed" + DECLINED = "declined" + NEEDS_PLAINTEXT_CONSENT = "needs-plaintext-consent" + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthLoginCancelRequest: + """Cancel an in-flight login flow.""" + + flow_id: str + """Opaque flow id from begin.""" + + @staticmethod + def from_dict(obj: Any) -> 'AuthLoginCancelRequest': + assert isinstance(obj, dict) + flow_id = from_str(obj.get("flowId")) + return AuthLoginCancelRequest(flow_id) + + def to_dict(self) -> dict: + result: dict = {} + result["flowId"] = from_str(self.flow_id) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AuthValidationError: @@ -787,6 +895,75 @@ def to_dict(self) -> dict: result["githubMessage"] = from_union([from_str, from_none], self.github_message) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthStatusDto: + """The neutral authentication status summary. + + Neutral authentication status summary. + """ + account_count: int + """Number of signed-in accounts in the roster.""" + + is_authenticated: bool + """Whether the session has resolved authentication.""" + + active_host: str | None = None + """Active account host, if authenticated.""" + + active_login: str | None = None + """Active account login, if authenticated.""" + + copilot_plan: str | None = None + """Copilot plan tier of the active account, if known.""" + + @staticmethod + def from_dict(obj: Any) -> 'AuthStatusDto': + assert isinstance(obj, dict) + account_count = from_int(obj.get("accountCount")) + is_authenticated = from_bool(obj.get("isAuthenticated")) + active_host = from_union([from_str, from_none], obj.get("activeHost")) + active_login = from_union([from_str, from_none], obj.get("activeLogin")) + copilot_plan = from_union([from_str, from_none], obj.get("copilotPlan")) + return AuthStatusDto(account_count, is_authenticated, active_host, active_login, copilot_plan) + + def to_dict(self) -> dict: + result: dict = {} + result["accountCount"] = from_int(self.account_count) + result["isAuthenticated"] = from_bool(self.is_authenticated) + if self.active_host is not None: + result["activeHost"] = from_union([from_str, from_none], self.active_host) + if self.active_login is not None: + result["activeLogin"] = from_union([from_str, from_none], self.active_login) + if self.copilot_plan is not None: + result["copilotPlan"] = from_union([from_str, from_none], self.copilot_plan) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthWriteResult: + """Result of a non-interactive accounts mutation.""" + + ok: bool + """Whether the mutation was applied.""" + + more_users: bool | None = None + """For a logout, whether other signed-in accounts remain.""" + + @staticmethod + def from_dict(obj: Any) -> 'AuthWriteResult': + assert isinstance(obj, dict) + ok = from_bool(obj.get("ok")) + more_users = from_union([from_bool, from_none], obj.get("moreUsers")) + return AuthWriteResult(ok, more_users) + + def to_dict(self) -> dict: + result: dict = {} + result["ok"] = from_bool(self.ok) + if self.more_users is not None: + result["moreUsers"] = from_union([from_bool, from_none], self.more_users) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AutopilotObjectiveCreditLimit: @@ -3393,1013 +3570,359 @@ class KindEnum(Enum): # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryAbortRequest: - """Parameters for cooperatively aborting a factory body.""" - - execution_token: str - """Opaque token identifying the execution attempt to abort.""" - - run_id: str - """Factory run identifier.""" - - session_id: str - """Target session identifier""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryAbortRequest': - assert isinstance(obj, dict) - execution_token = from_str(obj.get("executionToken")) - run_id = from_str(obj.get("runId")) - session_id = from_str(obj.get("sessionId")) - return FactoryAbortRequest(execution_token, run_id, session_id) +class FleetStartRequest: + """Parameters for starting fleet orchestration: an optional user prompt combined with the + fleet instructions, plus the send options forwarded to the resulting turn. + """ + attachments: list[Attachment] | None = None + """Optional attachments (files, directories, selections, blobs, GitHub references) to + include with the fleet request + """ + # Internal: this field is an internal SDK API and is not part of the public surface. + billable: bool | None = None + """If false, this request will not trigger a Premium Request Unit charge. User requests + default to billable. + """ + prompt: str | None = None + """Optional user prompt to combine with fleet instructions""" - def to_dict(self) -> dict: - result: dict = {} - result["executionToken"] = from_str(self.execution_token) - result["runId"] = from_str(self.run_id) - result["sessionId"] = from_str(self.session_id) - return result + wait: bool | None = None + """If true, await completion of the agentic loop for this fleet request before returning. + Defaults to false. + """ -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryACKResult: - """Acknowledgement that a factory request was accepted.""" @staticmethod - def from_dict(obj: Any) -> 'FactoryACKResult': + def from_dict(obj: Any) -> 'FleetStartRequest': assert isinstance(obj, dict) - return FactoryACKResult() + attachments = from_union([lambda x: from_list(_load_Attachment, x), from_none], obj.get("attachments")) + billable = from_union([from_bool, from_none], obj.get("billable")) + prompt = from_union([from_str, from_none], obj.get("prompt")) + wait = from_union([from_bool, from_none], obj.get("wait")) + return FleetStartRequest(attachments, billable, prompt, wait) def to_dict(self) -> dict: result: dict = {} + if self.attachments is not None: + result["attachments"] = from_union([lambda x: from_list(lambda x: to_class(Attachment, x), x), from_none], self.attachments) + if self.billable is not None: + result["billable"] = from_union([from_bool, from_none], self.billable) + if self.prompt is not None: + result["prompt"] = from_union([from_str, from_none], self.prompt) + if self.wait is not None: + result["wait"] = from_union([from_bool, from_none], self.wait) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryAgentOptions: - """Options for one factory-scoped subagent call. - - Subagent execution options. - """ - agent: str | None = None - """Optional built-in or custom agent name whose definition configures the subagent.""" - - context_tier: ContextTier | None = None - """Optional context tier override for the subagent.""" - - label: str | None = None - """Optional label distinguishing otherwise identical memoized agent calls.""" - - model: str | None = None - """Optional model identifier for the subagent.""" - - reasoning_effort: str | None = None - """Optional reasoning effort override for the subagent.""" +class FleetStartResult: + """Indicates whether fleet mode was successfully activated.""" - schema: Any = None - """Optional JSON Schema for structured agent output.""" + started: bool + """Whether fleet mode was successfully activated""" @staticmethod - def from_dict(obj: Any) -> 'FactoryAgentOptions': + def from_dict(obj: Any) -> 'FleetStartResult': assert isinstance(obj, dict) - agent = from_union([from_str, from_none], obj.get("agent")) - context_tier = from_union([ContextTier, from_none], obj.get("contextTier")) - label = from_union([from_str, from_none], obj.get("label")) - model = from_union([from_str, from_none], obj.get("model")) - reasoning_effort = from_union([from_str, from_none], obj.get("reasoningEffort")) - schema = obj.get("schema") - return FactoryAgentOptions(agent, context_tier, label, model, reasoning_effort, schema) + started = from_bool(obj.get("started")) + return FleetStartResult(started) def to_dict(self) -> dict: result: dict = {} - if self.agent is not None: - result["agent"] = from_union([from_str, from_none], self.agent) - if self.context_tier is not None: - result["contextTier"] = from_union([lambda x: to_enum(ContextTier, x), from_none], self.context_tier) - if self.label is not None: - result["label"] = from_union([from_str, from_none], self.label) - if self.model is not None: - result["model"] = from_union([from_str, from_none], self.model) - if self.reasoning_effort is not None: - result["reasoningEffort"] = from_union([from_str, from_none], self.reasoning_effort) - if self.schema is not None: - result["schema"] = self.schema + result["started"] = from_bool(self.started) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryAgentResult: - """Result of one factory-scoped subagent call.""" +class FolderTrustAddParams: + """Folder path to add to trusted folders.""" - result: Any = None - """Agent result, omitted when the agent produced no result.""" + path: str + """Folder path to mark as trusted""" @staticmethod - def from_dict(obj: Any) -> 'FactoryAgentResult': + def from_dict(obj: Any) -> 'FolderTrustAddParams': assert isinstance(obj, dict) - result = obj.get("result") - return FactoryAgentResult(result) + path = from_str(obj.get("path")) + return FolderTrustAddParams(path) def to_dict(self) -> dict: result: dict = {} - if self.result is not None: - result["result"] = self.result + result["path"] = from_str(self.path) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryCancelRequest: - """Parameters for cancelling a factory run.""" +class FolderTrustCheckParams: + """Folder path to check for trust.""" - run_id: str - """Factory run identifier.""" + path: str + """Folder path to check""" @staticmethod - def from_dict(obj: Any) -> 'FactoryCancelRequest': + def from_dict(obj: Any) -> 'FolderTrustCheckParams': assert isinstance(obj, dict) - run_id = from_str(obj.get("runId")) - return FactoryCancelRequest(run_id) + path = from_str(obj.get("path")) + return FolderTrustCheckParams(path) def to_dict(self) -> dict: result: dict = {} - result["runId"] = from_str(self.run_id) + result["path"] = from_str(self.path) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryCurrentPhase: - """Current factory phase identity.""" - - id: str - """Current phase identifier.""" +class FolderTrustCheckResult: + """Folder trust check result.""" - ordinal: int | None = None - """Zero-based declared phase ordinal, or null for an undeclared phase.""" + trusted: bool + """Whether the folder is trusted""" @staticmethod - def from_dict(obj: Any) -> 'FactoryCurrentPhase': + def from_dict(obj: Any) -> 'FolderTrustCheckResult': assert isinstance(obj, dict) - id = from_str(obj.get("id")) - ordinal = from_union([from_none, from_int], obj.get("ordinal")) - return FactoryCurrentPhase(id, ordinal) + trusted = from_bool(obj.get("trusted")) + return FolderTrustCheckResult(trusted) def to_dict(self) -> dict: result: dict = {} - result["id"] = from_str(self.id) - result["ordinal"] = from_union([from_none, from_int], self.ordinal) + result["trusted"] = from_bool(self.trusted) return result +class GhCLIAuthInfoType(Enum): + GH_CLI = "gh-cli" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryDeclaredLimits: - """Declared or approved factory resource ceilings. +class GitHubTelemetryClientInfo: + """Client environment metadata describing the process that produced a telemetry event. - Resource ceilings declared by the factory. + Client environment metadata. """ - max_ai_credits: float | None = None - """Maximum AI credits consumed by subagents and descendants.""" - - max_concurrent_subagents: int | None = None - """Maximum concurrently active subagents.""" - - max_total_subagents: int | None = None - """Maximum total subagents spawned by the run.""" - - timeout_seconds: float | None = None - """Maximum accumulated active execution time in seconds.""" + cli_version: str + """Copilot CLI version string.""" - @staticmethod - def from_dict(obj: Any) -> 'FactoryDeclaredLimits': - assert isinstance(obj, dict) - max_ai_credits = from_union([from_float, from_none], obj.get("maxAiCredits")) - max_concurrent_subagents = from_union([from_int, from_none], obj.get("maxConcurrentSubagents")) - max_total_subagents = from_union([from_int, from_none], obj.get("maxTotalSubagents")) - timeout_seconds = from_union([from_float, from_none], obj.get("timeoutSeconds")) - return FactoryDeclaredLimits(max_ai_credits, max_concurrent_subagents, max_total_subagents, timeout_seconds) + node_version: str + """Node.js runtime version string.""" - def to_dict(self) -> dict: - result: dict = {} - if self.max_ai_credits is not None: - result["maxAiCredits"] = from_union([to_float, from_none], self.max_ai_credits) - if self.max_concurrent_subagents is not None: - result["maxConcurrentSubagents"] = from_union([from_int, from_none], self.max_concurrent_subagents) - if self.max_total_subagents is not None: - result["maxTotalSubagents"] = from_union([from_int, from_none], self.max_total_subagents) - if self.timeout_seconds is not None: - result["timeoutSeconds"] = from_union([to_float, from_none], self.timeout_seconds) - return result + os_arch: str + """Operating system architecture (e.g. arm64, x64).""" -# Experimental: this type is part of an experimental API and may change or be removed. -class DurableOperation(Enum): - """Execution-critical factory storage operation. + os_platform: str + """Operating system platform (e.g. darwin, linux, win32).""" - Execution-critical durable operation that failed. + os_version: str + """Operating system version string.""" - Execution-critical workflow storage operation. - """ - ADD_ELAPSED = "addElapsed" - CHARGE_CREDIT = "chargeCredit" - CREATE_RUN = "createRun" - FINISH_RUN = "finishRun" - JOURNAL_GET = "journalGet" - JOURNAL_PUT = "journalPut" - MARK_RUN_STARTED = "markRunStarted" - RECONCILE_CREDIT_TOTAL = "reconcileCreditTotal" - REFRESH_LEASE = "refreshLease" - RELEASE_AGENT = "releaseAgent" - RESERVE_AGENT = "reserveAgent" + client_name: str | None = None + """Name of the client application.""" -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryExecuteRequest: - """Parameters sent to the owning extension to execute a factory closure.""" + client_type: str | None = None + """Type of client.""" - args: Any - """Factory input value.""" + copilot_plan: str | None = None + """Copilot subscription plan, when known.""" - execution_token: str - """Opaque token identifying this factory execution attempt.""" + cpu_count: int | None = None + """Number of logical CPU cores on the host.""" - name: str - """Registered factory name.""" + cpu_model: str | None = None + """Distinct CPU model names for the host, comma-separated.""" - run_id: str - """Factory run identifier.""" + dev_device_id: str | None = None + """Stable machine identifier for the device.""" - session_id: str - """Target session identifier""" + is_staff: bool | None = None + """Whether the user is a GitHub/Microsoft staff member.""" @staticmethod - def from_dict(obj: Any) -> 'FactoryExecuteRequest': + def from_dict(obj: Any) -> 'GitHubTelemetryClientInfo': assert isinstance(obj, dict) - args = obj.get("args") - execution_token = from_str(obj.get("executionToken")) - name = from_str(obj.get("name")) - run_id = from_str(obj.get("runId")) - session_id = from_str(obj.get("sessionId")) - return FactoryExecuteRequest(args, execution_token, name, run_id, session_id) + cli_version = from_str(obj.get("cli_version")) + node_version = from_str(obj.get("node_version")) + os_arch = from_str(obj.get("os_arch")) + os_platform = from_str(obj.get("os_platform")) + os_version = from_str(obj.get("os_version")) + client_name = from_union([from_str, from_none], obj.get("client_name")) + client_type = from_union([from_str, from_none], obj.get("client_type")) + copilot_plan = from_union([from_str, from_none], obj.get("copilot_plan")) + cpu_count = from_union([from_int, from_none], obj.get("cpu_count")) + cpu_model = from_union([from_str, from_none], obj.get("cpu_model")) + dev_device_id = from_union([from_str, from_none], obj.get("dev_device_id")) + is_staff = from_union([from_bool, from_none], obj.get("is_staff")) + return GitHubTelemetryClientInfo(cli_version, node_version, os_arch, os_platform, os_version, client_name, client_type, copilot_plan, cpu_count, cpu_model, dev_device_id, is_staff) def to_dict(self) -> dict: result: dict = {} - result["args"] = self.args - result["executionToken"] = from_str(self.execution_token) - result["name"] = from_str(self.name) - result["runId"] = from_str(self.run_id) - result["sessionId"] = from_str(self.session_id) + result["cli_version"] = from_str(self.cli_version) + result["node_version"] = from_str(self.node_version) + result["os_arch"] = from_str(self.os_arch) + result["os_platform"] = from_str(self.os_platform) + result["os_version"] = from_str(self.os_version) + if self.client_name is not None: + result["client_name"] = from_union([from_str, from_none], self.client_name) + if self.client_type is not None: + result["client_type"] = from_union([from_str, from_none], self.client_type) + if self.copilot_plan is not None: + result["copilot_plan"] = from_union([from_str, from_none], self.copilot_plan) + if self.cpu_count is not None: + result["cpu_count"] = from_union([from_int, from_none], self.cpu_count) + if self.cpu_model is not None: + result["cpu_model"] = from_union([from_str, from_none], self.cpu_model) + if self.dev_device_id is not None: + result["dev_device_id"] = from_union([from_str, from_none], self.dev_device_id) + if self.is_staff is not None: + result["is_staff"] = from_union([from_bool, from_none], self.is_staff) return result +class GitHubTokenAcquireReason(Enum): + """Why the runtime is requesting a GitHub credential.""" + + INITIAL = "initial" + REFRESH = "refresh" + +class GitHubTokenAcquireResultKind(Enum): + CANCELLED = "cancelled" + TOKEN = "token" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryExecuteResult: - """Result returned by an extension factory closure.""" +class HandlePendingToolCallResult: + """Indicates whether the external tool call result was handled successfully.""" - result: Any = None - """Factory result value.""" + success: bool + """Whether the tool call result was handled successfully""" @staticmethod - def from_dict(obj: Any) -> 'FactoryExecuteResult': + def from_dict(obj: Any) -> 'HandlePendingToolCallResult': assert isinstance(obj, dict) - result = obj.get("result") - return FactoryExecuteResult(result) + success = from_bool(obj.get("success")) + return HandlePendingToolCallResult(success) def to_dict(self) -> dict: result: dict = {} - if self.result is not None: - result["result"] = self.result + result["success"] = from_bool(self.success) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryGetRunProgressRequest: - """Parameters for paging factory progress.""" - - run_id: str - """Factory run identifier.""" - - after_seq: int | None = None - """Exclusive forward cursor.""" - - before_seq: int | None = None - """Exclusive backward cursor.""" - - limit: int | None = None - """Maximum records to return. Defaults to 200 and is capped at 500.""" +class HistoryAbortManualCompactionResult: + """Indicates whether an in-progress manual compaction was aborted.""" - phase_id: str | None = None - """Optional phase identifier used to scope records and cursors.""" + aborted: bool + """Whether an in-progress manual compaction was aborted. False when no manual compaction was + running, when its abort controller was already aborted, or when the session is remote. + """ @staticmethod - def from_dict(obj: Any) -> 'FactoryGetRunProgressRequest': + def from_dict(obj: Any) -> 'HistoryAbortManualCompactionResult': assert isinstance(obj, dict) - run_id = from_str(obj.get("runId")) - after_seq = from_union([from_int, from_none], obj.get("afterSeq")) - before_seq = from_union([from_int, from_none], obj.get("beforeSeq")) - limit = from_union([from_int, from_none], obj.get("limit")) - phase_id = from_union([from_str, from_none], obj.get("phaseId")) - return FactoryGetRunProgressRequest(run_id, after_seq, before_seq, limit, phase_id) + aborted = from_bool(obj.get("aborted")) + return HistoryAbortManualCompactionResult(aborted) def to_dict(self) -> dict: result: dict = {} - result["runId"] = from_str(self.run_id) - if self.after_seq is not None: - result["afterSeq"] = from_union([from_int, from_none], self.after_seq) - if self.before_seq is not None: - result["beforeSeq"] = from_union([from_int, from_none], self.before_seq) - if self.limit is not None: - result["limit"] = from_union([from_int, from_none], self.limit) - if self.phase_id is not None: - result["phaseId"] = from_union([from_str, from_none], self.phase_id) + result["aborted"] = from_bool(self.aborted) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryGetRunRequest: - """Parameters for retrieving a factory run.""" +class HistoryCancelBackgroundCompactionResult: + """Indicates whether an in-progress background compaction was cancelled.""" - run_id: str - """Factory run identifier.""" + cancelled: bool + """Whether an in-progress background compaction was cancelled. False when no compaction was + running, when the session is remote, or when the underlying processor was unavailable. + """ @staticmethod - def from_dict(obj: Any) -> 'FactoryGetRunRequest': + def from_dict(obj: Any) -> 'HistoryCancelBackgroundCompactionResult': assert isinstance(obj, dict) - run_id = from_str(obj.get("runId")) - return FactoryGetRunRequest(run_id) + cancelled = from_bool(obj.get("cancelled")) + return HistoryCancelBackgroundCompactionResult(cancelled) def to_dict(self) -> dict: result: dict = {} - result["runId"] = from_str(self.run_id) + result["cancelled"] = from_bool(self.cancelled) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryJournalGetRequest: - """Parameters for reading a factory journal entry.""" - - execution_token: str - """Opaque token identifying the current factory execution attempt.""" - - key: str - """Namespaced journal key.""" +class HistoryClearContextRequest: + """Parameters for clearing the conversation and seeding the window that replaces it.""" - run_id: str - """Factory run identifier.""" + prompt: str + """First user message of the fresh context window. Required: a cleared window holding only + system and developer messages is not a conversation a model can answer, so every clear + seeds the window it creates. Delivered by the enclosing turn driver once the agentic loop + exits, which is why the call must be made from inside a tool handler. + """ @staticmethod - def from_dict(obj: Any) -> 'FactoryJournalGetRequest': + def from_dict(obj: Any) -> 'HistoryClearContextRequest': assert isinstance(obj, dict) - execution_token = from_str(obj.get("executionToken")) - key = from_str(obj.get("key")) - run_id = from_str(obj.get("runId")) - return FactoryJournalGetRequest(execution_token, key, run_id) + prompt = from_str(obj.get("prompt")) + return HistoryClearContextRequest(prompt) def to_dict(self) -> dict: result: dict = {} - result["executionToken"] = from_str(self.execution_token) - result["key"] = from_str(self.key) - result["runId"] = from_str(self.run_id) + result["prompt"] = from_str(self.prompt) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryJournalGetResult: - """Result of reading a factory journal entry.""" - - hit: bool - """Whether the journal contained the requested key.""" - - result_json: Any = None - """Cached JSON result. The hit field distinguishes a cached JSON null from a miss.""" +class HistoryClearContextResult: + """What a successful clear removed. A clear that could not be applied rejects instead of + reporting a count. + """ + messages_cleared: int + """Number of non-system, non-developer messages that were removed from the conversation. + Zero only when the window already held no conversation. + """ @staticmethod - def from_dict(obj: Any) -> 'FactoryJournalGetResult': + def from_dict(obj: Any) -> 'HistoryClearContextResult': assert isinstance(obj, dict) - hit = from_bool(obj.get("hit")) - result_json = obj.get("resultJson") - return FactoryJournalGetResult(hit, result_json) + messages_cleared = from_int(obj.get("messagesCleared")) + return HistoryClearContextResult(messages_cleared) def to_dict(self) -> dict: result: dict = {} - result["hit"] = from_bool(self.hit) - if self.result_json is not None: - result["resultJson"] = self.result_json + result["messagesCleared"] = from_int(self.messages_cleared) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryJournalPutRequest: - """Parameters for storing a factory journal entry.""" +class HistoryCompactContextWindow: + """Post-compaction context window usage breakdown""" - execution_token: str - """Opaque token identifying the current factory execution attempt.""" + current_tokens: int + """Current total tokens in the context window (system + conversation + tool definitions)""" - key: str - """Namespaced journal key.""" + messages_length: int + """Current number of messages in the conversation""" - result_json: Any - """JSON result to memoize.""" + token_limit: int + """Maximum token count for the model's context window""" - run_id: str - """Factory run identifier.""" + conversation_tokens: int | None = None + """Token count from non-system messages (user, assistant, tool)""" + + system_tokens: int | None = None + """Token count from system message(s)""" + + tool_definitions_tokens: int | None = None + """Token count from tool definitions""" @staticmethod - def from_dict(obj: Any) -> 'FactoryJournalPutRequest': + def from_dict(obj: Any) -> 'HistoryCompactContextWindow': assert isinstance(obj, dict) - execution_token = from_str(obj.get("executionToken")) - key = from_str(obj.get("key")) - result_json = obj.get("resultJson") - run_id = from_str(obj.get("runId")) - return FactoryJournalPutRequest(execution_token, key, result_json, run_id) - - def to_dict(self) -> dict: - result: dict = {} - result["executionToken"] = from_str(self.execution_token) - result["key"] = from_str(self.key) - result["resultJson"] = self.result_json - result["runId"] = from_str(self.run_id) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryListRunsRequest: - """Parameters for paging factory runs.""" - - after_seq: int | None = None - """Exclusive forward cursor.""" - - before_seq: int | None = None - """Exclusive backward cursor.""" - - limit: int | None = None - """Maximum terminal runs to return. Defaults to 200 and is capped at 500.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryListRunsRequest': - assert isinstance(obj, dict) - after_seq = from_union([from_int, from_none], obj.get("afterSeq")) - before_seq = from_union([from_int, from_none], obj.get("beforeSeq")) - limit = from_union([from_int, from_none], obj.get("limit")) - return FactoryListRunsRequest(after_seq, before_seq, limit) - - def to_dict(self) -> dict: - result: dict = {} - if self.after_seq is not None: - result["afterSeq"] = from_union([from_int, from_none], self.after_seq) - if self.before_seq is not None: - result["beforeSeq"] = from_union([from_int, from_none], self.before_seq) - if self.limit is not None: - result["limit"] = from_union([from_int, from_none], self.limit) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryRunConsumed: - """Durable resource consumption. - - Durable factory resource consumption. - """ - active_ms: int - """Accumulated active execution time in milliseconds.""" - - nano_aiu: int - """AI usage consumed by the run in nano-AIU.""" - - subagents: int - """Total subagents spawned by the run.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryRunConsumed': - assert isinstance(obj, dict) - active_ms = from_int(obj.get("activeMs")) - nano_aiu = from_int(obj.get("nanoAiu")) - subagents = from_int(obj.get("subagents")) - return FactoryRunConsumed(active_ms, nano_aiu, subagents) - - def to_dict(self) -> dict: - result: dict = {} - result["activeMs"] = from_int(self.active_ms) - result["nanoAiu"] = from_int(self.nano_aiu) - result["subagents"] = from_int(self.subagents) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -class RunStatus(Enum): - """Current factory run status. - - Current or terminal state of a factory run. - - Current or terminal factory run status. - - Current workflow run status. - - Current or terminal state of a workflow run. - - Current or terminal workflow run status. - """ - CANCELLED = "cancelled" - COMPLETED = "completed" - ERROR = "error" - HALTED = "halted" - PAUSED = "paused" - PENDING = "pending" - RUNNING = "running" - -# Experimental: this type is part of an experimental API and may change or be removed. -class RunFailureKind(Enum): - """Resource ceiling that stopped the run. - - Cumulative resource ceiling that stopped a factory run. - - Cumulative resource ceiling that stopped a workflow run. - """ - MAX_AI_CREDITS = "maxAiCredits" - MAX_TOTAL_SUBAGENTS = "maxTotalSubagents" - TIMEOUT_SECONDS = "timeoutSeconds" - -class FactoryRunFailureType(Enum): - FACTORY_ACCOUNTING_INCOMPLETE = "factory_accounting_incomplete" - FACTORY_DURABLE_FAILURE = "factory_durable_failure" - FACTORY_LIMIT_REACHED = "factory_limit_reached" - FACTORY_PROVIDER_DISCONNECTED = "factory_provider_disconnected" - FACTORY_RESUME_DECLINED = "factory_resume_declined" - -class PauseInfoType(Enum): - CHECKPOINT = "checkpoint" - USER = "user" - -# Experimental: this type is part of an experimental API and may change or be removed. -class LogLineKind(Enum): - """Progress line kind. - - Kind of factory progress line. - - Progress record kind. - - Kind of workflow progress line. - """ - LOG = "log" - PHASE = "phase" - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryPauseCheckpointRequest: - """Parameters for an owned durable pause checkpoint.""" - - execution_token: str - """Opaque token identifying the execution attempt that reached the checkpoint.""" - - key: str - """Stable author-defined checkpoint key.""" - - run_id: str - """Factory run identifier.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryPauseCheckpointRequest': - assert isinstance(obj, dict) - execution_token = from_str(obj.get("executionToken")) - key = from_str(obj.get("key")) - run_id = from_str(obj.get("runId")) - return FactoryPauseCheckpointRequest(execution_token, key, run_id) - - def to_dict(self) -> dict: - result: dict = {} - result["executionToken"] = from_str(self.execution_token) - result["key"] = from_str(self.key) - result["runId"] = from_str(self.run_id) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryPauseRequest: - """Parameters for pausing a running factory.""" - - run_id: str - """Factory run identifier.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryPauseRequest': - assert isinstance(obj, dict) - run_id = from_str(obj.get("runId")) - return FactoryPauseRequest(run_id) - - def to_dict(self) -> dict: - result: dict = {} - result["runId"] = from_str(self.run_id) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -class PhaseStatus(Enum): - """Derived lifecycle state of the phase. - - Derived lifecycle state of a factory phase. - - Derived lifecycle state of a workflow phase. - """ - ACTIVE = "active" - COMPLETED = "completed" - PENDING = "pending" - SKIPPED = "skipped" - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryRunLimits: - """Optional per-invocation resource ceiling overrides. - - Wire-only per-invocation factory resource ceiling overrides. - - Per-invocation resource ceiling overrides. - """ - max_ai_credits: float | None = None - """Maximum AI credits consumed by factory subagents and their descendants. The post-paid - ceiling is soft: parallel turns can settle beyond it before the run stops. - """ - max_concurrent_subagents: int | None = None - """Maximum number of factory subagents that may run concurrently.""" - - max_total_subagents: int | None = None - """Maximum total number of factory subagents that may be admitted.""" - - timeout_seconds: float | None = None - """Maximum accumulated active-execution time in seconds. Active execution includes the - entire extension body, subprocess waits, queued-agent waits, and sleeps; time between - resumed attempts is not counted. - """ - - @staticmethod - def from_dict(obj: Any) -> 'FactoryRunLimits': - assert isinstance(obj, dict) - max_ai_credits = from_union([from_float, from_none], obj.get("maxAiCredits")) - max_concurrent_subagents = from_union([from_none, from_int], obj.get("maxConcurrentSubagents")) - max_total_subagents = from_union([from_none, from_int], obj.get("maxTotalSubagents")) - timeout_seconds = from_union([from_none, from_float], obj.get("timeoutSeconds")) - return FactoryRunLimits(max_ai_credits, max_concurrent_subagents, max_total_subagents, timeout_seconds) - - def to_dict(self) -> dict: - result: dict = {} - if self.max_ai_credits is not None: - result["maxAiCredits"] = from_union([to_float, from_none], self.max_ai_credits) - if self.max_concurrent_subagents is not None: - result["maxConcurrentSubagents"] = from_union([from_none, from_int], self.max_concurrent_subagents) - if self.max_total_subagents is not None: - result["maxTotalSubagents"] = from_union([from_none, from_int], self.max_total_subagents) - if self.timeout_seconds is not None: - result["timeoutSeconds"] = from_union([from_none, to_float], self.timeout_seconds) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FleetStartRequest: - """Parameters for starting fleet orchestration: an optional user prompt combined with the - fleet instructions, plus the send options forwarded to the resulting turn. - """ - attachments: list[Attachment] | None = None - """Optional attachments (files, directories, selections, blobs, GitHub references) to - include with the fleet request - """ - # Internal: this field is an internal SDK API and is not part of the public surface. - billable: bool | None = None - """If false, this request will not trigger a Premium Request Unit charge. User requests - default to billable. - """ - prompt: str | None = None - """Optional user prompt to combine with fleet instructions""" - - wait: bool | None = None - """If true, await completion of the agentic loop for this fleet request before returning. - Defaults to false. - """ - - @staticmethod - def from_dict(obj: Any) -> 'FleetStartRequest': - assert isinstance(obj, dict) - attachments = from_union([lambda x: from_list(_load_Attachment, x), from_none], obj.get("attachments")) - billable = from_union([from_bool, from_none], obj.get("billable")) - prompt = from_union([from_str, from_none], obj.get("prompt")) - wait = from_union([from_bool, from_none], obj.get("wait")) - return FleetStartRequest(attachments, billable, prompt, wait) - - def to_dict(self) -> dict: - result: dict = {} - if self.attachments is not None: - result["attachments"] = from_union([lambda x: from_list(lambda x: to_class(Attachment, x), x), from_none], self.attachments) - if self.billable is not None: - result["billable"] = from_union([from_bool, from_none], self.billable) - if self.prompt is not None: - result["prompt"] = from_union([from_str, from_none], self.prompt) - if self.wait is not None: - result["wait"] = from_union([from_bool, from_none], self.wait) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FleetStartResult: - """Indicates whether fleet mode was successfully activated.""" - - started: bool - """Whether fleet mode was successfully activated""" - - @staticmethod - def from_dict(obj: Any) -> 'FleetStartResult': - assert isinstance(obj, dict) - started = from_bool(obj.get("started")) - return FleetStartResult(started) - - def to_dict(self) -> dict: - result: dict = {} - result["started"] = from_bool(self.started) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FolderTrustAddParams: - """Folder path to add to trusted folders.""" - - path: str - """Folder path to mark as trusted""" - - @staticmethod - def from_dict(obj: Any) -> 'FolderTrustAddParams': - assert isinstance(obj, dict) - path = from_str(obj.get("path")) - return FolderTrustAddParams(path) - - def to_dict(self) -> dict: - result: dict = {} - result["path"] = from_str(self.path) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FolderTrustCheckParams: - """Folder path to check for trust.""" - - path: str - """Folder path to check""" - - @staticmethod - def from_dict(obj: Any) -> 'FolderTrustCheckParams': - assert isinstance(obj, dict) - path = from_str(obj.get("path")) - return FolderTrustCheckParams(path) - - def to_dict(self) -> dict: - result: dict = {} - result["path"] = from_str(self.path) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FolderTrustCheckResult: - """Folder trust check result.""" - - trusted: bool - """Whether the folder is trusted""" - - @staticmethod - def from_dict(obj: Any) -> 'FolderTrustCheckResult': - assert isinstance(obj, dict) - trusted = from_bool(obj.get("trusted")) - return FolderTrustCheckResult(trusted) - - def to_dict(self) -> dict: - result: dict = {} - result["trusted"] = from_bool(self.trusted) - return result - -class GhCLIAuthInfoType(Enum): - GH_CLI = "gh-cli" - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class GitHubTelemetryClientInfo: - """Client environment metadata describing the process that produced a telemetry event. - - Client environment metadata. - """ - cli_version: str - """Copilot CLI version string.""" - - node_version: str - """Node.js runtime version string.""" - - os_arch: str - """Operating system architecture (e.g. arm64, x64).""" - - os_platform: str - """Operating system platform (e.g. darwin, linux, win32).""" - - os_version: str - """Operating system version string.""" - - client_name: str | None = None - """Name of the client application.""" - - client_type: str | None = None - """Type of client.""" - - copilot_plan: str | None = None - """Copilot subscription plan, when known.""" - - cpu_count: int | None = None - """Number of logical CPU cores on the host.""" - - cpu_model: str | None = None - """Distinct CPU model names for the host, comma-separated.""" - - dev_device_id: str | None = None - """Stable machine identifier for the device.""" - - is_staff: bool | None = None - """Whether the user is a GitHub/Microsoft staff member.""" - - @staticmethod - def from_dict(obj: Any) -> 'GitHubTelemetryClientInfo': - assert isinstance(obj, dict) - cli_version = from_str(obj.get("cli_version")) - node_version = from_str(obj.get("node_version")) - os_arch = from_str(obj.get("os_arch")) - os_platform = from_str(obj.get("os_platform")) - os_version = from_str(obj.get("os_version")) - client_name = from_union([from_str, from_none], obj.get("client_name")) - client_type = from_union([from_str, from_none], obj.get("client_type")) - copilot_plan = from_union([from_str, from_none], obj.get("copilot_plan")) - cpu_count = from_union([from_int, from_none], obj.get("cpu_count")) - cpu_model = from_union([from_str, from_none], obj.get("cpu_model")) - dev_device_id = from_union([from_str, from_none], obj.get("dev_device_id")) - is_staff = from_union([from_bool, from_none], obj.get("is_staff")) - return GitHubTelemetryClientInfo(cli_version, node_version, os_arch, os_platform, os_version, client_name, client_type, copilot_plan, cpu_count, cpu_model, dev_device_id, is_staff) - - def to_dict(self) -> dict: - result: dict = {} - result["cli_version"] = from_str(self.cli_version) - result["node_version"] = from_str(self.node_version) - result["os_arch"] = from_str(self.os_arch) - result["os_platform"] = from_str(self.os_platform) - result["os_version"] = from_str(self.os_version) - if self.client_name is not None: - result["client_name"] = from_union([from_str, from_none], self.client_name) - if self.client_type is not None: - result["client_type"] = from_union([from_str, from_none], self.client_type) - if self.copilot_plan is not None: - result["copilot_plan"] = from_union([from_str, from_none], self.copilot_plan) - if self.cpu_count is not None: - result["cpu_count"] = from_union([from_int, from_none], self.cpu_count) - if self.cpu_model is not None: - result["cpu_model"] = from_union([from_str, from_none], self.cpu_model) - if self.dev_device_id is not None: - result["dev_device_id"] = from_union([from_str, from_none], self.dev_device_id) - if self.is_staff is not None: - result["is_staff"] = from_union([from_bool, from_none], self.is_staff) - return result - -class GitHubTokenAcquireReason(Enum): - """Why the runtime is requesting a GitHub credential.""" - - INITIAL = "initial" - REFRESH = "refresh" - -class GitHubTokenAcquireResultKind(Enum): - CANCELLED = "cancelled" - TOKEN = "token" - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class HandlePendingToolCallResult: - """Indicates whether the external tool call result was handled successfully.""" - - success: bool - """Whether the tool call result was handled successfully""" - - @staticmethod - def from_dict(obj: Any) -> 'HandlePendingToolCallResult': - assert isinstance(obj, dict) - success = from_bool(obj.get("success")) - return HandlePendingToolCallResult(success) - - def to_dict(self) -> dict: - result: dict = {} - result["success"] = from_bool(self.success) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class HistoryAbortManualCompactionResult: - """Indicates whether an in-progress manual compaction was aborted.""" - - aborted: bool - """Whether an in-progress manual compaction was aborted. False when no manual compaction was - running, when its abort controller was already aborted, or when the session is remote. - """ - - @staticmethod - def from_dict(obj: Any) -> 'HistoryAbortManualCompactionResult': - assert isinstance(obj, dict) - aborted = from_bool(obj.get("aborted")) - return HistoryAbortManualCompactionResult(aborted) - - def to_dict(self) -> dict: - result: dict = {} - result["aborted"] = from_bool(self.aborted) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class HistoryCancelBackgroundCompactionResult: - """Indicates whether an in-progress background compaction was cancelled.""" - - cancelled: bool - """Whether an in-progress background compaction was cancelled. False when no compaction was - running, when the session is remote, or when the underlying processor was unavailable. - """ - - @staticmethod - def from_dict(obj: Any) -> 'HistoryCancelBackgroundCompactionResult': - assert isinstance(obj, dict) - cancelled = from_bool(obj.get("cancelled")) - return HistoryCancelBackgroundCompactionResult(cancelled) - - def to_dict(self) -> dict: - result: dict = {} - result["cancelled"] = from_bool(self.cancelled) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class HistoryClearContextRequest: - """Parameters for clearing the conversation and seeding the window that replaces it.""" - - prompt: str - """First user message of the fresh context window. Required: a cleared window holding only - system and developer messages is not a conversation a model can answer, so every clear - seeds the window it creates. Delivered by the enclosing turn driver once the agentic loop - exits, which is why the call must be made from inside a tool handler. - """ - - @staticmethod - def from_dict(obj: Any) -> 'HistoryClearContextRequest': - assert isinstance(obj, dict) - prompt = from_str(obj.get("prompt")) - return HistoryClearContextRequest(prompt) - - def to_dict(self) -> dict: - result: dict = {} - result["prompt"] = from_str(self.prompt) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class HistoryClearContextResult: - """What a successful clear removed. A clear that could not be applied rejects instead of - reporting a count. - """ - messages_cleared: int - """Number of non-system, non-developer messages that were removed from the conversation. - Zero only when the window already held no conversation. - """ - - @staticmethod - def from_dict(obj: Any) -> 'HistoryClearContextResult': - assert isinstance(obj, dict) - messages_cleared = from_int(obj.get("messagesCleared")) - return HistoryClearContextResult(messages_cleared) - - def to_dict(self) -> dict: - result: dict = {} - result["messagesCleared"] = from_int(self.messages_cleared) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class HistoryCompactContextWindow: - """Post-compaction context window usage breakdown""" - - current_tokens: int - """Current total tokens in the context window (system + conversation + tool definitions)""" - - messages_length: int - """Current number of messages in the conversation""" - - token_limit: int - """Maximum token count for the model's context window""" - - conversation_tokens: int | None = None - """Token count from non-system messages (user, assistant, tool)""" - - system_tokens: int | None = None - """Token count from system message(s)""" - - tool_definitions_tokens: int | None = None - """Token count from tool definitions""" - - @staticmethod - def from_dict(obj: Any) -> 'HistoryCompactContextWindow': - assert isinstance(obj, dict) - current_tokens = from_int(obj.get("currentTokens")) - messages_length = from_int(obj.get("messagesLength")) - token_limit = from_int(obj.get("tokenLimit")) - conversation_tokens = from_union([from_int, from_none], obj.get("conversationTokens")) - system_tokens = from_union([from_int, from_none], obj.get("systemTokens")) - tool_definitions_tokens = from_union([from_int, from_none], obj.get("toolDefinitionsTokens")) - return HistoryCompactContextWindow(current_tokens, messages_length, token_limit, conversation_tokens, system_tokens, tool_definitions_tokens) + current_tokens = from_int(obj.get("currentTokens")) + messages_length = from_int(obj.get("messagesLength")) + token_limit = from_int(obj.get("tokenLimit")) + conversation_tokens = from_union([from_int, from_none], obj.get("conversationTokens")) + system_tokens = from_union([from_int, from_none], obj.get("systemTokens")) + tool_definitions_tokens = from_union([from_int, from_none], obj.get("toolDefinitionsTokens")) + return HistoryCompactContextWindow(current_tokens, messages_length, token_limit, conversation_tokens, system_tokens, tool_definitions_tokens) def to_dict(self) -> dict: result: dict = {} @@ -8139,11 +7662,11 @@ class ApprovalKind(Enum): EXTENSION_ENV_ACCESS = "extension-env-access" EXTENSION_MANAGEMENT = "extension-management" EXTENSION_PERMISSION_ACCESS = "extension-permission-access" - FACTORY = "factory" MCP = "mcp" MCP_SAMPLING = "mcp-sampling" MEMORY = "memory" READ = "read" + WORKFLOW = "workflow" WRITE = "write" class PermissionDecisionKind(Enum): @@ -8181,15 +7704,15 @@ class PermissionDecisionApproveForLocationApprovalExtensionManagementKind(Enum): class PermissionDecisionApproveForLocationApprovalExtensionPermissionAccessKind(Enum): EXTENSION_PERMISSION_ACCESS = "extension-permission-access" -class PermissionDecisionApproveForLocationApprovalFactoryKind(Enum): - FACTORY = "factory" - class PermissionDecisionApproveForLocationApprovalMCPSamplingKind(Enum): MCP_SAMPLING = "mcp-sampling" class PermissionDecisionApproveForLocationApprovalReadKind(Enum): READ = "read" +class PermissionDecisionApproveForLocationApprovalWorkflowKind(Enum): + WORKFLOW = "workflow" + class PermissionDecisionApproveForLocationApprovalWriteKind(Enum): WRITE = "write" @@ -15829,6 +15352,24 @@ def to_dict(self) -> dict: result["timeoutSeconds"] = from_union([to_float, from_none], self.timeout_seconds) return result +# Experimental: this type is part of an experimental API and may change or be removed. +class WorkflowDurableOperation(Enum): + """Execution-critical workflow storage operation. + + Execution-critical durable operation that failed. + """ + ADD_ELAPSED = "addElapsed" + CHARGE_CREDIT = "chargeCredit" + CREATE_RUN = "createRun" + FINISH_RUN = "finishRun" + JOURNAL_GET = "journalGet" + JOURNAL_PUT = "journalPut" + MARK_RUN_STARTED = "markRunStarted" + RECONCILE_CREDIT_TOTAL = "reconcileCreditTotal" + REFRESH_LEASE = "refreshLease" + RELEASE_AGENT = "releaseAgent" + RESERVE_AGENT = "reserveAgent" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class WorkflowExecuteRequest: @@ -16101,6 +15642,32 @@ def to_dict(self) -> dict: result["subagents"] = from_int(self.subagents) return result +# Experimental: this type is part of an experimental API and may change or be removed. +class WorkflowRunStatus(Enum): + """Current workflow run status. + + Current or terminal state of a workflow run. + + Current or terminal workflow run status. + """ + CANCELLED = "cancelled" + COMPLETED = "completed" + ERROR = "error" + HALTED = "halted" + PAUSED = "paused" + PENDING = "pending" + RUNNING = "running" + +# Experimental: this type is part of an experimental API and may change or be removed. +class WorkflowRunFailureKind(Enum): + """Resource ceiling that stopped the run. + + Cumulative resource ceiling that stopped a workflow run. + """ + MAX_AI_CREDITS = "maxAiCredits" + MAX_TOTAL_SUBAGENTS = "maxTotalSubagents" + TIMEOUT_SECONDS = "timeoutSeconds" + class WorkflowRunFailureType(Enum): WORKFLOW_ACCOUNTING_INCOMPLETE = "workflow_accounting_incomplete" WORKFLOW_DURABLE_FAILURE = "workflow_durable_failure" @@ -16108,6 +15675,21 @@ class WorkflowRunFailureType(Enum): WORKFLOW_PROVIDER_DISCONNECTED = "workflow_provider_disconnected" WORKFLOW_RESUME_DECLINED = "workflow_resume_declined" +class PauseInfoType(Enum): + CHECKPOINT = "checkpoint" + USER = "user" + +# Experimental: this type is part of an experimental API and may change or be removed. +class WorkflowLogLineKind(Enum): + """Progress line kind. + + Kind of workflow progress line. + + Progress record kind. + """ + LOG = "log" + PHASE = "phase" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class WorkflowPauseCheckpointRequest: @@ -16156,6 +15738,17 @@ def to_dict(self) -> dict: result["runId"] = from_str(self.run_id) return result +# Experimental: this type is part of an experimental API and may change or be removed. +class WorkflowPhaseStatus(Enum): + """Derived lifecycle state of the phase. + + Derived lifecycle state of a workflow phase. + """ + ACTIVE = "active" + COMPLETED = "completed" + PENDING = "pending" + SKIPPED = "skipped" + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class WorkflowRunLimits: @@ -16777,6 +16370,222 @@ def to_dict(self) -> dict: result["quotaSnapshots"] = from_dict(lambda x: to_class(AccountQuotaSnapshot, x), self.quota_snapshots) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AccountStatus: + """One signed-in account in the roster forest. + + The active account, or absent when not logged in. + """ + active: bool + """Whether this is the active account.""" + + host: str + """Authentication host URL.""" + + kind: AccountKind + """The provider kind of this account.""" + + login: str + """Authenticated login/username.""" + + selection_id: str + """Opaque selection id used to switch to, or log out, this account.""" + + derived_from: str | None = None + """Opaque id of the account this one was derived from (e.g. an EMU account's base Entra + identity); absent for a root account. Matches the base identity account's selectionId, + forming the derivation edge. + """ + + @staticmethod + def from_dict(obj: Any) -> 'AccountStatus': + assert isinstance(obj, dict) + active = from_bool(obj.get("active")) + host = from_str(obj.get("host")) + kind = AccountKind(obj.get("kind")) + login = from_str(obj.get("login")) + selection_id = from_str(obj.get("selectionId")) + derived_from = from_union([from_str, from_none], obj.get("derivedFrom")) + return AccountStatus(active, host, kind, login, selection_id, derived_from) + + def to_dict(self) -> dict: + result: dict = {} + result["active"] = from_bool(self.active) + result["host"] = from_str(self.host) + result["kind"] = to_enum(AccountKind, self.kind) + result["login"] = from_str(self.login) + result["selectionId"] = from_str(self.selection_id) + if self.derived_from is not None: + result["derivedFrom"] = from_union([from_str, from_none], self.derived_from) + return result + +@dataclass +class ItemElement: + """One signed-in account in the roster forest. + + The active account, or absent when not logged in. + + A provider offered for interactive login. + """ + kind: AccountKind + """The provider kind of this account. + + The neutral provider kind. + """ + active: bool | None = None + """Whether this is the active account.""" + + derived_from: str | None = None + """Opaque id of the account this one was derived from (e.g. an EMU account's base Entra + identity); absent for a root account. Matches the base identity account's selectionId, + forming the derivation edge. + """ + host: str | None = None + """Authentication host URL.""" + + login: str | None = None + """Authenticated login/username.""" + + selection_id: str | None = None + """Opaque selection id used to switch to, or log out, this account.""" + + available: bool | None = None + """Whether this provider is currently available to sign in with.""" + + label: str | None = None + """Human-readable menu label, owned by the runtime so every consumer renders identical text.""" + + @staticmethod + def from_dict(obj: Any) -> 'ItemElement': + assert isinstance(obj, dict) + kind = AccountKind(obj.get("kind")) + active = from_union([from_bool, from_none], obj.get("active")) + derived_from = from_union([from_str, from_none], obj.get("derivedFrom")) + host = from_union([from_str, from_none], obj.get("host")) + login = from_union([from_str, from_none], obj.get("login")) + selection_id = from_union([from_str, from_none], obj.get("selectionId")) + available = from_union([from_bool, from_none], obj.get("available")) + label = from_union([from_str, from_none], obj.get("label")) + return ItemElement(kind, active, derived_from, host, login, selection_id, available, label) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = to_enum(AccountKind, self.kind) + if self.active is not None: + result["active"] = from_union([from_bool, from_none], self.active) + if self.derived_from is not None: + result["derivedFrom"] = from_union([from_str, from_none], self.derived_from) + if self.host is not None: + result["host"] = from_union([from_str, from_none], self.host) + if self.login is not None: + result["login"] = from_union([from_str, from_none], self.login) + if self.selection_id is not None: + result["selectionId"] = from_union([from_str, from_none], self.selection_id) + if self.available is not None: + result["available"] = from_union([from_bool, from_none], self.available) + if self.label is not None: + result["label"] = from_union([from_str, from_none], self.label) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthEnumerateQuery: + """Which typed accounts collection to enumerate. + + Selects which accounts collection to enumerate. A no-arg selector is the empty-payload + variant. + """ + kind: AuthEnumerateQueryKind + """Account-collection query variant discriminator.""" + + broker_available: bool | None = None + """Whether an interactive Entra broker is available on the host; gates Entra availability in + the returned list. + """ + + @staticmethod + def from_dict(obj: Any) -> 'AuthEnumerateQuery': + assert isinstance(obj, dict) + kind = AuthEnumerateQueryKind(obj.get("kind")) + broker_available = from_union([from_bool, from_none], obj.get("brokerAvailable")) + return AuthEnumerateQuery(kind, broker_available) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = to_enum(AuthEnumerateQueryKind, self.kind) + if self.broker_available is not None: + result["brokerAvailable"] = from_union([from_bool, from_none], self.broker_available) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthReadQuery: + """Which typed accounts datum to read. + + Selects which typed accounts datum to read. + """ + kind: AuthReadQueryKind + """Account read-datum query variant discriminator.""" + + @staticmethod + def from_dict(obj: Any) -> 'AuthReadQuery': + assert isinstance(obj, dict) + kind = AuthReadQueryKind(obj.get("kind")) + return AuthReadQuery(kind) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = to_enum(AuthReadQueryKind, self.kind) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthWrite: + """The non-interactive mutation command to apply. + + One non-interactive accounts mutation command (the selector is fused with its typed args). + """ + kind: AuthWriteKind + """Account mutation command variant discriminator.""" + + selection_id: str | None = None + """Opaque selection id of the account to make active. + + Opaque selection id of the account to log out; absent logs out the active account. + """ + host: str | None = None + """Authentication host URL.""" + + login: str | None = None + """Login/username for the credential.""" + + token: str | None = None + """GitHub authentication token to install.""" + + @staticmethod + def from_dict(obj: Any) -> 'AuthWrite': + assert isinstance(obj, dict) + kind = AuthWriteKind(obj.get("kind")) + selection_id = from_union([from_str, from_none], obj.get("selectionId")) + host = from_union([from_str, from_none], obj.get("host")) + login = from_union([from_str, from_none], obj.get("login")) + token = from_union([from_str, from_none], obj.get("token")) + return AuthWrite(kind, selection_id, host, login, token) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = to_enum(AuthWriteKind, self.kind) + if self.selection_id is not None: + result["selectionId"] = from_union([from_str, from_none], self.selection_id) + if self.host is not None: + result["host"] = from_union([from_str, from_none], self.host) + if self.login is not None: + result["login"] = from_union([from_str, from_none], self.login) + if self.token is not None: + result["token"] = from_union([from_str, from_none], self.token) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ModelCapabilitiesSupports: @@ -17004,6 +16813,54 @@ def to_dict(self) -> dict: result["field"] = from_union([lambda x: to_enum(AgentRegistrySpawnValidationErrorField, x), from_none], self.field) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthLoginBeginRequest: + """Begin an interactive login flow for a provider kind. Dispatch is kind-only.""" + + kind: LoginProviderKind + """The provider kind to sign in with.""" + + @staticmethod + def from_dict(obj: Any) -> 'AuthLoginBeginRequest': + assert isinstance(obj, dict) + kind = LoginProviderKind(obj.get("kind")) + return AuthLoginBeginRequest(kind) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = to_enum(LoginProviderKind, self.kind) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ProviderDescriptor: + """A provider offered for interactive login.""" + + available: bool + """Whether this provider is currently available to sign in with.""" + + kind: LoginProviderKind + """The neutral provider kind.""" + + label: str + """Human-readable menu label, owned by the runtime so every consumer renders identical text.""" + + @staticmethod + def from_dict(obj: Any) -> 'ProviderDescriptor': + assert isinstance(obj, dict) + available = from_bool(obj.get("available")) + kind = LoginProviderKind(obj.get("kind")) + label = from_str(obj.get("label")) + return ProviderDescriptor(available, kind, label) + + def to_dict(self) -> dict: + result: dict = {} + result["available"] = from_bool(self.available) + result["kind"] = to_enum(LoginProviderKind, self.kind) + result["label"] = from_str(self.label) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AutopilotObjectiveState: @@ -18794,8 +18651,41 @@ def from_dict(obj: Any) -> 'MetadataContextHeaviestMessagesResult': def to_dict(self) -> dict: result: dict = {} - result["messages"] = from_list(lambda x: to_class(ContextHeaviestMessage, x), self.messages) - result["totalTokens"] = from_int(self.total_tokens) + result["messages"] = from_list(lambda x: to_class(ContextHeaviestMessage, x), self.messages) + result["totalTokens"] = from_int(self.total_tokens) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthLoginResultDto: + """The terminal login result. + + Terminal result of an interactive login flow. + """ + status: AuthLoginResultStatus + """Terminal disposition of the login.""" + + host: str | None = None + """Host that was signed in, when completed.""" + + login: str | None = None + """Login that was signed in, when completed.""" + + @staticmethod + def from_dict(obj: Any) -> 'AuthLoginResultDto': + assert isinstance(obj, dict) + status = AuthLoginResultStatus(obj.get("status")) + host = from_union([from_str, from_none], obj.get("host")) + login = from_union([from_str, from_none], obj.get("login")) + return AuthLoginResultDto(status, host, login) + + def to_dict(self) -> dict: + result: dict = {} + result["status"] = to_enum(AuthLoginResultStatus, self.status) + if self.host is not None: + result["host"] = from_union([from_str, from_none], self.host) + if self.login is not None: + result["login"] = from_union([from_str, from_none], self.login) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -19691,919 +19581,283 @@ def to_dict(self) -> dict: result["data"] = from_str(self.data) result["mimeType"] = from_str(self.mime_type) result["type"] = to_enum(ExternalToolTextResultForLlmBinaryResultsForLlmType, self.type) - if self.description is not None: - result["description"] = from_union([from_str, from_none], self.description) - if self.metadata is not None: - result["metadata"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.metadata) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class ExternalToolTextResultForLlmContentResourceLinkIcon: - """Icon image for a resource""" - - src: str - """URL or path to the icon image""" - - mime_type: str | None = None - """MIME type of the icon image""" - - sizes: list[str] | None = None - """Available icon sizes (e.g., ['16x16', '32x32'])""" - - theme: Theme | None = None - """Theme variant this icon is intended for""" - - @staticmethod - def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentResourceLinkIcon': - assert isinstance(obj, dict) - src = from_str(obj.get("src")) - mime_type = from_union([from_str, from_none], obj.get("mimeType")) - sizes = from_union([lambda x: from_list(from_str, x), from_none], obj.get("sizes")) - theme = from_union([Theme, from_none], obj.get("theme")) - return ExternalToolTextResultForLlmContentResourceLinkIcon(src, mime_type, sizes, theme) - - def to_dict(self) -> dict: - result: dict = {} - result["src"] = from_str(self.src) - if self.mime_type is not None: - result["mimeType"] = from_union([from_str, from_none], self.mime_type) - if self.sizes is not None: - result["sizes"] = from_union([lambda x: from_list(from_str, x), from_none], self.sizes) - if self.theme is not None: - result["theme"] = from_union([lambda x: to_enum(Theme, x), from_none], self.theme) - return result - -ExternalToolTextResultForLlmContentResourceDetails = EmbeddedTextResourceContents | EmbeddedBlobResourceContents - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class MCPResourceIcon: - """A resource icon descriptor plus preserved non-standard icon fields.""" - - src: str - """Icon URI""" - - additional_properties: dict[str, Any] | None = None - """Server-provided non-standard icon fields preserved from the MCP response""" - - mime_type: str | None = None - """Icon MIME type, when known""" - - sizes: str | None = None - """Icon sizes hint""" - - theme: str | None = None - """Theme hint for this icon""" - - @staticmethod - def from_dict(obj: Any) -> 'MCPResourceIcon': - assert isinstance(obj, dict) - src = from_str(obj.get("src")) - additional_properties = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("additionalProperties")) - mime_type = from_union([from_str, from_none], obj.get("mimeType")) - sizes = from_union([from_str, from_none], obj.get("sizes")) - theme = from_union([from_str, from_none], obj.get("theme")) - return MCPResourceIcon(src, additional_properties, mime_type, sizes, theme) - - def to_dict(self) -> dict: - result: dict = {} - result["src"] = from_str(self.src) - if self.additional_properties is not None: - result["additionalProperties"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.additional_properties) - if self.mime_type is not None: - result["mimeType"] = from_union([from_str, from_none], self.mime_type) - if self.sizes is not None: - result["sizes"] = from_union([from_str, from_none], self.sizes) - if self.theme is not None: - result["theme"] = from_union([from_str, from_none], self.theme) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class ExternalToolTextResultForLlmContentAudio: - """Audio content block with base64-encoded data""" - - data: str - """Base64-encoded audio data""" - - mime_type: str - """MIME type of the audio (e.g., audio/wav, audio/mpeg)""" - - type: ClassVar[str] = "audio" - """Content block type discriminator""" - - @staticmethod - def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentAudio': - assert isinstance(obj, dict) - data = from_str(obj.get("data")) - mime_type = from_str(obj.get("mimeType")) - return ExternalToolTextResultForLlmContentAudio(data, mime_type) - - def to_dict(self) -> dict: - result: dict = {} - result["data"] = from_str(self.data) - result["mimeType"] = from_str(self.mime_type) - result["type"] = self.type - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class ExternalToolTextResultForLlmContentImage: - """Image content block with base64-encoded data""" - - data: str - """Base64-encoded image data""" - - mime_type: str - """MIME type of the image (e.g., image/png, image/jpeg)""" - - type: ClassVar[str] = "image" - """Content block type discriminator""" - - @staticmethod - def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentImage': - assert isinstance(obj, dict) - data = from_str(obj.get("data")) - mime_type = from_str(obj.get("mimeType")) - return ExternalToolTextResultForLlmContentImage(data, mime_type) - - def to_dict(self) -> dict: - result: dict = {} - result["data"] = from_str(self.data) - result["mimeType"] = from_str(self.mime_type) - result["type"] = self.type - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class ExternalToolTextResultForLlmContentResource: - """Embedded resource content block with inline text or binary data""" - - resource: ExternalToolTextResultForLlmContentResourceDetails - """The embedded resource contents, either text or base64-encoded binary""" - - type: ClassVar[str] = "resource" - """Content block type discriminator""" - - @staticmethod - def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentResource': - assert isinstance(obj, dict) - resource = (lambda x: from_union([EmbeddedTextResourceContents.from_dict, EmbeddedBlobResourceContents.from_dict], x))(obj.get("resource")) - return ExternalToolTextResultForLlmContentResource(resource) - - def to_dict(self) -> dict: - result: dict = {} - result["resource"] = from_union([lambda x: to_class(EmbeddedTextResourceContents, x), lambda x: to_class(EmbeddedBlobResourceContents, x)], self.resource) - result["type"] = self.type - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class ExternalToolTextResultForLlmContentShellExit: - """Shell command exit metadata with optional output preview""" - - exit_code: int - """Exit code from the completed shell command""" - - shell_id: str - """Shell id, as assigned by Copilot runtime""" - - type: ClassVar[str] = "shell_exit" - """Content block type discriminator""" - - cwd: str | None = None - """Working directory where the shell command was executed""" - - output_file_path: str | None = None - """Path reported in the shell session's filesystem namespace when shell output exceeded the - configured large-output threshold. - """ - output_preview: str | None = None - """Output associated with this shell command, if available. May be partial, truncated, or a - preview; not guaranteed to be full output. - """ - output_truncated: bool | None = None - """Whether outputPreview is known to be incomplete or truncated""" - - @staticmethod - def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentShellExit': - assert isinstance(obj, dict) - exit_code = from_int(obj.get("exitCode")) - shell_id = from_str(obj.get("shellId")) - cwd = from_union([from_str, from_none], obj.get("cwd")) - output_file_path = from_union([from_str, from_none], obj.get("outputFilePath")) - output_preview = from_union([from_str, from_none], obj.get("outputPreview")) - output_truncated = from_union([from_bool, from_none], obj.get("outputTruncated")) - return ExternalToolTextResultForLlmContentShellExit(exit_code, shell_id, cwd, output_file_path, output_preview, output_truncated) - - def to_dict(self) -> dict: - result: dict = {} - result["exitCode"] = from_int(self.exit_code) - result["shellId"] = from_str(self.shell_id) - result["type"] = self.type - if self.cwd is not None: - result["cwd"] = from_union([from_str, from_none], self.cwd) - if self.output_file_path is not None: - result["outputFilePath"] = from_union([from_str, from_none], self.output_file_path) - if self.output_preview is not None: - result["outputPreview"] = from_union([from_str, from_none], self.output_preview) - if self.output_truncated is not None: - result["outputTruncated"] = from_union([from_bool, from_none], self.output_truncated) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class ExternalToolTextResultForLlmContentTerminal: - """Terminal/shell output content block with optional exit code and working directory""" - - text: str - """Terminal/shell output text""" - - type: ClassVar[str] = "terminal" - """Content block type discriminator""" - - cwd: str | None = None - """Working directory where the command was executed""" - - exit_code: int | None = None - """Process exit code, if the command has completed""" - - @staticmethod - def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentTerminal': - assert isinstance(obj, dict) - text = from_str(obj.get("text")) - cwd = from_union([from_str, from_none], obj.get("cwd")) - exit_code = from_union([from_int, from_none], obj.get("exitCode")) - return ExternalToolTextResultForLlmContentTerminal(text, cwd, exit_code) - - def to_dict(self) -> dict: - result: dict = {} - result["text"] = from_str(self.text) - result["type"] = self.type - if self.cwd is not None: - result["cwd"] = from_union([from_str, from_none], self.cwd) - if self.exit_code is not None: - result["exitCode"] = from_union([from_int, from_none], self.exit_code) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class ExternalToolTextResultForLlmContentText: - """Plain text content block""" - - text: str - """The text content""" - - type: ClassVar[str] = "text" - """Content block type discriminator""" - - @staticmethod - def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentText': - assert isinstance(obj, dict) - text = from_str(obj.get("text")) - return ExternalToolTextResultForLlmContentText(text) - - def to_dict(self) -> dict: - result: dict = {} - result["text"] = from_str(self.text) - result["type"] = self.type - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryAgentRequest: - """Parameters for one factory-scoped subagent call.""" - - execution_token: str - """Opaque token identifying the current factory execution attempt.""" - - factory_run_id: str - """Factory run identifier that owns the subagent.""" - - opts: FactoryAgentOptions - """Subagent execution options.""" - - prompt: str - """Prompt to send to the subagent.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryAgentRequest': - assert isinstance(obj, dict) - execution_token = from_str(obj.get("executionToken")) - factory_run_id = from_str(obj.get("factoryRunId")) - opts = FactoryAgentOptions.from_dict(obj.get("opts")) - prompt = from_str(obj.get("prompt")) - return FactoryAgentRequest(execution_token, factory_run_id, opts, prompt) - - def to_dict(self) -> dict: - result: dict = {} - result["executionToken"] = from_str(self.execution_token) - result["factoryRunId"] = from_str(self.factory_run_id) - result["opts"] = to_class(FactoryAgentOptions, self.opts) - result["prompt"] = from_str(self.prompt) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryRunFailure: - """Machine-readable terminal failure. - - Machine-readable factory run failure. - - Machine-readable failure details for a halted or errored run. - - The run stopped because its usage accounting could not be completed. - - The extension that owns the factory disconnected while the run was executing, so the host - halted it. The run's journaled subagent results are preserved so a resume can reuse them. - """ - run_id: str - """Factory run identifier. - - Factory run identifier whose changed limits were declined. - """ - type: FactoryRunFailureType - """Factory failure variant discriminator.""" - - kind: RunFailureKind | None = None - """Resource ceiling that stopped the run.""" - - suggested_value: float | None = None - """Suggested larger ceiling when the runtime can derive one safely.""" - - value: float | None = None - """Approved effective ceiling that was reached.""" - - reason: str | None = None - """Human-readable reason the resume did not proceed.""" - - code: str | None = None - """Stable failure code.""" - - operation: DurableOperation | None = None - """Execution-critical durable operation that failed.""" - - drained_nano_aiu: int | None = None - """Confirmed usage in nano-AIU, representing the floor of what the run spent.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryRunFailure': - assert isinstance(obj, dict) - run_id = from_str(obj.get("runId")) - type = FactoryRunFailureType(obj.get("type")) - kind = from_union([RunFailureKind, from_none], obj.get("kind")) - suggested_value = from_union([from_float, from_none], obj.get("suggestedValue")) - value = from_union([from_float, from_none], obj.get("value")) - reason = from_union([from_str, from_none], obj.get("reason")) - code = from_union([from_str, from_none], obj.get("code")) - operation = from_union([DurableOperation, from_none], obj.get("operation")) - drained_nano_aiu = from_union([from_int, from_none], obj.get("drainedNanoAiu")) - return FactoryRunFailure(run_id, type, kind, suggested_value, value, reason, code, operation, drained_nano_aiu) - - def to_dict(self) -> dict: - result: dict = {} - result["runId"] = from_str(self.run_id) - result["type"] = to_enum(FactoryRunFailureType, self.type) - if self.kind is not None: - result["kind"] = from_union([lambda x: to_enum(RunFailureKind, x), from_none], self.kind) - if self.suggested_value is not None: - result["suggestedValue"] = from_union([to_float, from_none], self.suggested_value) - if self.value is not None: - result["value"] = from_union([to_float, from_none], self.value) - if self.reason is not None: - result["reason"] = from_union([from_str, from_none], self.reason) - if self.code is not None: - result["code"] = from_union([from_str, from_none], self.code) - if self.operation is not None: - result["operation"] = from_union([lambda x: to_enum(DurableOperation, x), from_none], self.operation) - if self.drained_nano_aiu is not None: - result["drainedNanoAiu"] = from_union([from_int, from_none], self.drained_nano_aiu) - return result - -@dataclass -class PauseInfoClass: - type: PauseInfoType - """Factory pause initiator discriminator.""" - - key: str | None = None - """Stable author-defined checkpoint key that initiated the pause.""" - - @staticmethod - def from_dict(obj: Any) -> 'PauseInfoClass': - assert isinstance(obj, dict) - type = PauseInfoType(obj.get("type")) - key = from_union([from_str, from_none], obj.get("key")) - return PauseInfoClass(type, key) - - def to_dict(self) -> dict: - result: dict = {} - result["type"] = to_enum(PauseInfoType, self.type) - if self.key is not None: - result["key"] = from_union([from_str, from_none], self.key) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryPauseInfo: - """Durable metadata describing who initiated a factory pause. - - Structured pause initiator metadata for a paused attempt. - """ - type: PauseInfoType - """Factory pause initiator discriminator.""" - - key: str | None = None - """Stable author-defined checkpoint key that initiated the pause.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryPauseInfo': - assert isinstance(obj, dict) - type = PauseInfoType(obj.get("type")) - key = from_union([from_str, from_none], obj.get("key")) - return FactoryPauseInfo(type, key) - - def to_dict(self) -> dict: - result: dict = {} - result["type"] = to_enum(PauseInfoType, self.type) - if self.key is not None: - result["key"] = from_union([from_str, from_none], self.key) - return result - -@dataclass -class WorkflowRunTerminalPauseInfo: - type: PauseInfoType - """Workflow pause initiator discriminator.""" - - key: str | None = None - """Stable author-defined checkpoint key that initiated the pause.""" - - @staticmethod - def from_dict(obj: Any) -> 'WorkflowRunTerminalPauseInfo': - assert isinstance(obj, dict) - type = PauseInfoType(obj.get("type")) - key = from_union([from_str, from_none], obj.get("key")) - return WorkflowRunTerminalPauseInfo(type, key) - - def to_dict(self) -> dict: - result: dict = {} - result["type"] = to_enum(PauseInfoType, self.type) - if self.key is not None: - result["key"] = from_union([from_str, from_none], self.key) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class WorkflowPauseInfo: - """Durable metadata describing who initiated a workflow pause. - - Structured pause initiator metadata for a paused attempt. - """ - type: PauseInfoType - """Workflow pause initiator discriminator.""" - - key: str | None = None - """Stable author-defined checkpoint key that initiated the pause.""" - - @staticmethod - def from_dict(obj: Any) -> 'WorkflowPauseInfo': - assert isinstance(obj, dict) - type = PauseInfoType(obj.get("type")) - key = from_union([from_str, from_none], obj.get("key")) - return WorkflowPauseInfo(type, key) - - def to_dict(self) -> dict: - result: dict = {} - result["type"] = to_enum(PauseInfoType, self.type) - if self.key is not None: - result["key"] = from_union([from_str, from_none], self.key) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryLogLine: - """One ordered factory progress line.""" - - kind: LogLineKind - """Progress line kind.""" - - seq: int - """Monotonic sequence number within the factory run.""" - - text: str - """Progress text.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryLogLine': - assert isinstance(obj, dict) - kind = LogLineKind(obj.get("kind")) - seq = from_int(obj.get("seq")) - text = from_str(obj.get("text")) - return FactoryLogLine(kind, seq, text) - - def to_dict(self) -> dict: - result: dict = {} - result["kind"] = to_enum(LogLineKind, self.kind) - result["seq"] = from_int(self.seq) - result["text"] = from_str(self.text) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryProgressLine: - """One durable factory progress record.""" - - attempt: int - """Resume attempt that emitted this record.""" - - kind: LogLineKind - """Progress record kind.""" - - recorded_at: int - """Epoch milliseconds when the record was persisted.""" - - seq: int - """Global monotonic sequence number within the run.""" - - text: str - """Prompt-safe progress text.""" - - phase_id: str | None = None - """Phase active when the record was emitted, or null before any phase.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryProgressLine': - assert isinstance(obj, dict) - attempt = from_int(obj.get("attempt")) - kind = LogLineKind(obj.get("kind")) - recorded_at = from_int(obj.get("recordedAt")) - seq = from_int(obj.get("seq")) - text = from_str(obj.get("text")) - phase_id = from_union([from_none, from_str], obj.get("phaseId")) - return FactoryProgressLine(attempt, kind, recorded_at, seq, text, phase_id) - - def to_dict(self) -> dict: - result: dict = {} - result["attempt"] = from_int(self.attempt) - result["kind"] = to_enum(LogLineKind, self.kind) - result["recordedAt"] = from_int(self.recorded_at) - result["seq"] = from_int(self.seq) - result["text"] = from_str(self.text) - result["phaseId"] = from_union([from_none, from_str], self.phase_id) + if self.description is not None: + result["description"] = from_union([from_str, from_none], self.description) + if self.metadata is not None: + result["metadata"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.metadata) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class WorkflowLogLine: - """One ordered workflow progress line.""" +class ExternalToolTextResultForLlmContentResourceLinkIcon: + """Icon image for a resource""" - kind: LogLineKind - """Progress line kind.""" + src: str + """URL or path to the icon image""" - seq: int - """Monotonic sequence number within the workflow run.""" + mime_type: str | None = None + """MIME type of the icon image""" - text: str - """Progress text.""" + sizes: list[str] | None = None + """Available icon sizes (e.g., ['16x16', '32x32'])""" + + theme: Theme | None = None + """Theme variant this icon is intended for""" @staticmethod - def from_dict(obj: Any) -> 'WorkflowLogLine': + def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentResourceLinkIcon': assert isinstance(obj, dict) - kind = LogLineKind(obj.get("kind")) - seq = from_int(obj.get("seq")) - text = from_str(obj.get("text")) - return WorkflowLogLine(kind, seq, text) + src = from_str(obj.get("src")) + mime_type = from_union([from_str, from_none], obj.get("mimeType")) + sizes = from_union([lambda x: from_list(from_str, x), from_none], obj.get("sizes")) + theme = from_union([Theme, from_none], obj.get("theme")) + return ExternalToolTextResultForLlmContentResourceLinkIcon(src, mime_type, sizes, theme) def to_dict(self) -> dict: result: dict = {} - result["kind"] = to_enum(LogLineKind, self.kind) - result["seq"] = from_int(self.seq) - result["text"] = from_str(self.text) + result["src"] = from_str(self.src) + if self.mime_type is not None: + result["mimeType"] = from_union([from_str, from_none], self.mime_type) + if self.sizes is not None: + result["sizes"] = from_union([lambda x: from_list(from_str, x), from_none], self.sizes) + if self.theme is not None: + result["theme"] = from_union([lambda x: to_enum(Theme, x), from_none], self.theme) return result +ExternalToolTextResultForLlmContentResourceDetails = EmbeddedTextResourceContents | EmbeddedBlobResourceContents + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class WorkflowProgressLine: - """One durable workflow progress record.""" - - attempt: int - """Resume attempt that emitted this record.""" +class MCPResourceIcon: + """A resource icon descriptor plus preserved non-standard icon fields.""" - kind: LogLineKind - """Progress record kind.""" + src: str + """Icon URI""" - recorded_at: int - """Epoch milliseconds when the record was persisted.""" + additional_properties: dict[str, Any] | None = None + """Server-provided non-standard icon fields preserved from the MCP response""" - seq: int - """Global monotonic sequence number within the run.""" + mime_type: str | None = None + """Icon MIME type, when known""" - text: str - """Prompt-safe progress text.""" + sizes: str | None = None + """Icon sizes hint""" - phase_id: str | None = None - """Phase active when the record was emitted, or null before any phase.""" + theme: str | None = None + """Theme hint for this icon""" @staticmethod - def from_dict(obj: Any) -> 'WorkflowProgressLine': + def from_dict(obj: Any) -> 'MCPResourceIcon': assert isinstance(obj, dict) - attempt = from_int(obj.get("attempt")) - kind = LogLineKind(obj.get("kind")) - recorded_at = from_int(obj.get("recordedAt")) - seq = from_int(obj.get("seq")) - text = from_str(obj.get("text")) - phase_id = from_union([from_none, from_str], obj.get("phaseId")) - return WorkflowProgressLine(attempt, kind, recorded_at, seq, text, phase_id) + src = from_str(obj.get("src")) + additional_properties = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("additionalProperties")) + mime_type = from_union([from_str, from_none], obj.get("mimeType")) + sizes = from_union([from_str, from_none], obj.get("sizes")) + theme = from_union([from_str, from_none], obj.get("theme")) + return MCPResourceIcon(src, additional_properties, mime_type, sizes, theme) def to_dict(self) -> dict: result: dict = {} - result["attempt"] = from_int(self.attempt) - result["kind"] = to_enum(LogLineKind, self.kind) - result["recordedAt"] = from_int(self.recorded_at) - result["seq"] = from_int(self.seq) - result["text"] = from_str(self.text) - result["phaseId"] = from_union([from_none, from_str], self.phase_id) + result["src"] = from_str(self.src) + if self.additional_properties is not None: + result["additionalProperties"] = from_union([lambda x: from_dict(lambda x: x, x), from_none], self.additional_properties) + if self.mime_type is not None: + result["mimeType"] = from_union([from_str, from_none], self.mime_type) + if self.sizes is not None: + result["sizes"] = from_union([from_str, from_none], self.sizes) + if self.theme is not None: + result["theme"] = from_union([from_str, from_none], self.theme) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryPhaseObservation: - """Durable lifecycle and timing for one factory phase.""" - - accumulated_active_ms: int - """Completed active time accumulated by this phase in milliseconds.""" - - current_active_ms: int - """Current live active time for this phase in milliseconds.""" - - entry_count: int - """Number of times execution entered this phase.""" - - id: str - """Phase identifier.""" - - last_entered_run_attempt: int - """Most recent run attempt that entered this phase, or `0` if the phase has never been - entered. - """ - live_agent_count: int - """Direct agents in this phase that are currently live.""" - - status: PhaseStatus - """Derived lifecycle state of the phase.""" - - title: str - """Human-readable phase title.""" - - total_agent_count: int - """Total direct agents associated with this phase.""" +class ExternalToolTextResultForLlmContentAudio: + """Audio content block with base64-encoded data""" - completed_at: int | None = None - """Epoch milliseconds when this phase completed; for a skipped phase, the synthetic skip - timestamp (equal to `startedAt`). - """ - detail: str | None = None - """Optional human-readable phase detail.""" + data: str + """Base64-encoded audio data""" - ordinal: int | None = None - """Zero-based declared phase ordinal, or null for an undeclared phase.""" + mime_type: str + """MIME type of the audio (e.g., audio/wav, audio/mpeg)""" - started_at: int | None = None - """Epoch milliseconds when this phase first started; for a skipped phase, the synthetic skip - timestamp (equal to `completedAt`). - """ + type: ClassVar[str] = "audio" + """Content block type discriminator""" @staticmethod - def from_dict(obj: Any) -> 'FactoryPhaseObservation': + def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentAudio': assert isinstance(obj, dict) - accumulated_active_ms = from_int(obj.get("accumulatedActiveMs")) - current_active_ms = from_int(obj.get("currentActiveMs")) - entry_count = from_int(obj.get("entryCount")) - id = from_str(obj.get("id")) - last_entered_run_attempt = from_int(obj.get("lastEnteredRunAttempt")) - live_agent_count = from_int(obj.get("liveAgentCount")) - status = PhaseStatus(obj.get("status")) - title = from_str(obj.get("title")) - total_agent_count = from_int(obj.get("totalAgentCount")) - completed_at = from_union([from_int, from_none], obj.get("completedAt")) - detail = from_union([from_str, from_none], obj.get("detail")) - ordinal = from_union([from_none, from_int], obj.get("ordinal")) - started_at = from_union([from_int, from_none], obj.get("startedAt")) - return FactoryPhaseObservation(accumulated_active_ms, current_active_ms, entry_count, id, last_entered_run_attempt, live_agent_count, status, title, total_agent_count, completed_at, detail, ordinal, started_at) + data = from_str(obj.get("data")) + mime_type = from_str(obj.get("mimeType")) + return ExternalToolTextResultForLlmContentAudio(data, mime_type) def to_dict(self) -> dict: result: dict = {} - result["accumulatedActiveMs"] = from_int(self.accumulated_active_ms) - result["currentActiveMs"] = from_int(self.current_active_ms) - result["entryCount"] = from_int(self.entry_count) - result["id"] = from_str(self.id) - result["lastEnteredRunAttempt"] = from_int(self.last_entered_run_attempt) - result["liveAgentCount"] = from_int(self.live_agent_count) - result["status"] = to_enum(PhaseStatus, self.status) - result["title"] = from_str(self.title) - result["totalAgentCount"] = from_int(self.total_agent_count) - if self.completed_at is not None: - result["completedAt"] = from_union([from_int, from_none], self.completed_at) - if self.detail is not None: - result["detail"] = from_union([from_str, from_none], self.detail) - result["ordinal"] = from_union([from_none, from_int], self.ordinal) - if self.started_at is not None: - result["startedAt"] = from_union([from_int, from_none], self.started_at) + result["data"] = from_str(self.data) + result["mimeType"] = from_str(self.mime_type) + result["type"] = self.type return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class WorkflowPhaseObservation: - """Durable lifecycle and timing for one workflow phase.""" - - accumulated_active_ms: int - """Completed active time accumulated by this phase in milliseconds.""" - - current_active_ms: int - """Current live active time for this phase in milliseconds.""" - - entry_count: int - """Number of times execution entered this phase.""" +class ExternalToolTextResultForLlmContentImage: + """Image content block with base64-encoded data""" - id: str - """Phase identifier.""" + data: str + """Base64-encoded image data""" - last_entered_run_attempt: int - """Most recent run attempt that entered this phase, or `0` if the phase has never been - entered. - """ - live_agent_count: int - """Direct agents in this phase that are currently live.""" + mime_type: str + """MIME type of the image (e.g., image/png, image/jpeg)""" - status: PhaseStatus - """Derived lifecycle state of the phase.""" + type: ClassVar[str] = "image" + """Content block type discriminator""" - title: str - """Human-readable phase title.""" + @staticmethod + def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentImage': + assert isinstance(obj, dict) + data = from_str(obj.get("data")) + mime_type = from_str(obj.get("mimeType")) + return ExternalToolTextResultForLlmContentImage(data, mime_type) - total_agent_count: int - """Total direct agents associated with this phase.""" + def to_dict(self) -> dict: + result: dict = {} + result["data"] = from_str(self.data) + result["mimeType"] = from_str(self.mime_type) + result["type"] = self.type + return result - completed_at: int | None = None - """Epoch milliseconds when this phase completed; for a skipped phase, the synthetic skip - timestamp (equal to `startedAt`). - """ - detail: str | None = None - """Optional human-readable phase detail.""" +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class ExternalToolTextResultForLlmContentResource: + """Embedded resource content block with inline text or binary data""" - ordinal: int | None = None - """Zero-based declared phase ordinal, or null for an undeclared phase.""" + resource: ExternalToolTextResultForLlmContentResourceDetails + """The embedded resource contents, either text or base64-encoded binary""" - started_at: int | None = None - """Epoch milliseconds when this phase first started; for a skipped phase, the synthetic skip - timestamp (equal to `completedAt`). - """ + type: ClassVar[str] = "resource" + """Content block type discriminator""" @staticmethod - def from_dict(obj: Any) -> 'WorkflowPhaseObservation': + def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentResource': assert isinstance(obj, dict) - accumulated_active_ms = from_int(obj.get("accumulatedActiveMs")) - current_active_ms = from_int(obj.get("currentActiveMs")) - entry_count = from_int(obj.get("entryCount")) - id = from_str(obj.get("id")) - last_entered_run_attempt = from_int(obj.get("lastEnteredRunAttempt")) - live_agent_count = from_int(obj.get("liveAgentCount")) - status = PhaseStatus(obj.get("status")) - title = from_str(obj.get("title")) - total_agent_count = from_int(obj.get("totalAgentCount")) - completed_at = from_union([from_int, from_none], obj.get("completedAt")) - detail = from_union([from_str, from_none], obj.get("detail")) - ordinal = from_union([from_none, from_int], obj.get("ordinal")) - started_at = from_union([from_int, from_none], obj.get("startedAt")) - return WorkflowPhaseObservation(accumulated_active_ms, current_active_ms, entry_count, id, last_entered_run_attempt, live_agent_count, status, title, total_agent_count, completed_at, detail, ordinal, started_at) + resource = (lambda x: from_union([EmbeddedTextResourceContents.from_dict, EmbeddedBlobResourceContents.from_dict], x))(obj.get("resource")) + return ExternalToolTextResultForLlmContentResource(resource) def to_dict(self) -> dict: result: dict = {} - result["accumulatedActiveMs"] = from_int(self.accumulated_active_ms) - result["currentActiveMs"] = from_int(self.current_active_ms) - result["entryCount"] = from_int(self.entry_count) - result["id"] = from_str(self.id) - result["lastEnteredRunAttempt"] = from_int(self.last_entered_run_attempt) - result["liveAgentCount"] = from_int(self.live_agent_count) - result["status"] = to_enum(PhaseStatus, self.status) - result["title"] = from_str(self.title) - result["totalAgentCount"] = from_int(self.total_agent_count) - if self.completed_at is not None: - result["completedAt"] = from_union([from_int, from_none], self.completed_at) - if self.detail is not None: - result["detail"] = from_union([from_str, from_none], self.detail) - result["ordinal"] = from_union([from_none, from_int], self.ordinal) - if self.started_at is not None: - result["startedAt"] = from_union([from_int, from_none], self.started_at) + result["resource"] = from_union([lambda x: to_class(EmbeddedTextResourceContents, x), lambda x: to_class(EmbeddedBlobResourceContents, x)], self.resource) + result["type"] = self.type return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class FactoryResumeRequest: - """Parameters for resuming a factory run from its persisted identity.""" +class ExternalToolTextResultForLlmContentShellExit: + """Shell command exit metadata with optional output preview""" - run_id: str - """Factory run identifier.""" + exit_code: int + """Exit code from the completed shell command""" - limits: FactoryRunLimits | None = None - """Optional per-invocation resource ceiling overrides.""" + shell_id: str + """Shell id, as assigned by Copilot runtime""" - log_phase_names: bool | None = None - """Whether to emit factory phase names to the session transcript.""" + type: ClassVar[str] = "shell_exit" + """Content block type discriminator""" - notify_on_complete: bool | None = None - """Whether to notify the originating session when the factory completes.""" + cwd: str | None = None + """Working directory where the shell command was executed""" + + output_file_path: str | None = None + """Path reported in the shell session's filesystem namespace when shell output exceeded the + configured large-output threshold. + """ + output_preview: str | None = None + """Output associated with this shell command, if available. May be partial, truncated, or a + preview; not guaranteed to be full output. + """ + output_truncated: bool | None = None + """Whether outputPreview is known to be incomplete or truncated""" @staticmethod - def from_dict(obj: Any) -> 'FactoryResumeRequest': + def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentShellExit': assert isinstance(obj, dict) - run_id = from_str(obj.get("runId")) - limits = from_union([FactoryRunLimits.from_dict, from_none], obj.get("limits")) - log_phase_names = from_union([from_bool, from_none], obj.get("logPhaseNames")) - notify_on_complete = from_union([from_bool, from_none], obj.get("notifyOnComplete")) - return FactoryResumeRequest(run_id, limits, log_phase_names, notify_on_complete) + exit_code = from_int(obj.get("exitCode")) + shell_id = from_str(obj.get("shellId")) + cwd = from_union([from_str, from_none], obj.get("cwd")) + output_file_path = from_union([from_str, from_none], obj.get("outputFilePath")) + output_preview = from_union([from_str, from_none], obj.get("outputPreview")) + output_truncated = from_union([from_bool, from_none], obj.get("outputTruncated")) + return ExternalToolTextResultForLlmContentShellExit(exit_code, shell_id, cwd, output_file_path, output_preview, output_truncated) def to_dict(self) -> dict: result: dict = {} - result["runId"] = from_str(self.run_id) - if self.limits is not None: - result["limits"] = from_union([lambda x: to_class(FactoryRunLimits, x), from_none], self.limits) - if self.log_phase_names is not None: - result["logPhaseNames"] = from_union([from_bool, from_none], self.log_phase_names) - if self.notify_on_complete is not None: - result["notifyOnComplete"] = from_union([from_bool, from_none], self.notify_on_complete) + result["exitCode"] = from_int(self.exit_code) + result["shellId"] = from_str(self.shell_id) + result["type"] = self.type + if self.cwd is not None: + result["cwd"] = from_union([from_str, from_none], self.cwd) + if self.output_file_path is not None: + result["outputFilePath"] = from_union([from_str, from_none], self.output_file_path) + if self.output_preview is not None: + result["outputPreview"] = from_union([from_str, from_none], self.output_preview) + if self.output_truncated is not None: + result["outputTruncated"] = from_union([from_bool, from_none], self.output_truncated) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass -class RunOptions: - """Factory invocation options. +class ExternalToolTextResultForLlmContentTerminal: + """Terminal/shell output content block with optional exit code and working directory""" - Options controlling factory invocation. - """ - limits: FactoryRunLimits | None = None - """Per-invocation resource ceiling overrides.""" + text: str + """Terminal/shell output text""" - log_phase_names: bool | None = None - """Whether to emit factory phase names to the session transcript.""" + type: ClassVar[str] = "terminal" + """Content block type discriminator""" - notify_on_complete: bool | None = None - """Whether to notify the originating session when the factory completes.""" + cwd: str | None = None + """Working directory where the command was executed""" - resume_from_run_id: str | None = None - """Run identifier whose journal and progress should seed this resumed run.""" + exit_code: int | None = None + """Process exit code, if the command has completed""" @staticmethod - def from_dict(obj: Any) -> 'RunOptions': + def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentTerminal': assert isinstance(obj, dict) - limits = from_union([FactoryRunLimits.from_dict, from_none], obj.get("limits")) - log_phase_names = from_union([from_bool, from_none], obj.get("logPhaseNames")) - notify_on_complete = from_union([from_bool, from_none], obj.get("notifyOnComplete")) - resume_from_run_id = from_union([from_str, from_none], obj.get("resumeFromRunId")) - return RunOptions(limits, log_phase_names, notify_on_complete, resume_from_run_id) + text = from_str(obj.get("text")) + cwd = from_union([from_str, from_none], obj.get("cwd")) + exit_code = from_union([from_int, from_none], obj.get("exitCode")) + return ExternalToolTextResultForLlmContentTerminal(text, cwd, exit_code) def to_dict(self) -> dict: result: dict = {} - if self.limits is not None: - result["limits"] = from_union([lambda x: to_class(FactoryRunLimits, x), from_none], self.limits) - if self.log_phase_names is not None: - result["logPhaseNames"] = from_union([from_bool, from_none], self.log_phase_names) - if self.notify_on_complete is not None: - result["notifyOnComplete"] = from_union([from_bool, from_none], self.notify_on_complete) - if self.resume_from_run_id is not None: - result["resumeFromRunId"] = from_union([from_str, from_none], self.resume_from_run_id) + result["text"] = from_str(self.text) + result["type"] = self.type + if self.cwd is not None: + result["cwd"] = from_union([from_str, from_none], self.cwd) + if self.exit_code is not None: + result["exitCode"] = from_union([from_int, from_none], self.exit_code) return result # Experimental: this type is part of an experimental API and may change or be removed. -# Internal: this type is an internal SDK API and is not part of the public surface. @dataclass -class _FactoryToolResumeRequest: - """Internal parameters for resuming a factory run from a tool.""" - - run_id: str - """Factory run identifier.""" +class ExternalToolTextResultForLlmContentText: + """Plain text content block""" - limits: FactoryRunLimits | None = None - """Optional per-invocation resource ceiling overrides.""" + text: str + """The text content""" - tool_call_id: str | None = None - """Opaque identifier of the originating tool call.""" + type: ClassVar[str] = "text" + """Content block type discriminator""" @staticmethod - def from_dict(obj: Any) -> '_FactoryToolResumeRequest': + def from_dict(obj: Any) -> 'ExternalToolTextResultForLlmContentText': assert isinstance(obj, dict) - run_id = from_str(obj.get("runId")) - limits = from_union([FactoryRunLimits.from_dict, from_none], obj.get("limits")) - tool_call_id = from_union([from_str, from_none], obj.get("toolCallId")) - return _FactoryToolResumeRequest(run_id, limits, tool_call_id) + text = from_str(obj.get("text")) + return ExternalToolTextResultForLlmContentText(text) def to_dict(self) -> dict: result: dict = {} - result["runId"] = from_str(self.run_id) - if self.limits is not None: - result["limits"] = from_union([lambda x: to_class(FactoryRunLimits, x), from_none], self.limits) - if self.tool_call_id is not None: - result["toolCallId"] = from_union([from_str, from_none], self.tool_call_id) + result["text"] = from_str(self.text) + result["type"] = self.type return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -23562,84 +22816,6 @@ def to_dict(self) -> dict: result["operation"] = from_union([from_str, from_none], self.operation) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class PermissionDecisionApproveForLocationApprovalFactory: - """Location-scoped factory approval, optionally narrowed by approval key.""" - - kind: ClassVar[str] = "factory" - """Approval covering factory operations.""" - - approval_key: str | None = None - """Optional factory operation name or canonical approval key; when omitted, the approval - covers all factory operations. - """ - - @staticmethod - def from_dict(obj: Any) -> 'PermissionDecisionApproveForLocationApprovalFactory': - assert isinstance(obj, dict) - approval_key = from_union([from_str, from_none], obj.get("approvalKey")) - return PermissionDecisionApproveForLocationApprovalFactory(approval_key) - - def to_dict(self) -> dict: - result: dict = {} - result["kind"] = self.kind - if self.approval_key is not None: - result["approvalKey"] = from_union([from_str, from_none], self.approval_key) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class PermissionDecisionApproveForSessionApprovalFactory: - """Session-scoped factory approval, optionally narrowed by approval key.""" - - kind: ClassVar[str] = "factory" - """Approval covering factory operations.""" - - approval_key: str | None = None - """Optional factory operation name or canonical approval key; when omitted, the approval - covers all factory operations. - """ - - @staticmethod - def from_dict(obj: Any) -> 'PermissionDecisionApproveForSessionApprovalFactory': - assert isinstance(obj, dict) - approval_key = from_union([from_str, from_none], obj.get("approvalKey")) - return PermissionDecisionApproveForSessionApprovalFactory(approval_key) - - def to_dict(self) -> dict: - result: dict = {} - result["kind"] = self.kind - if self.approval_key is not None: - result["approvalKey"] = from_union([from_str, from_none], self.approval_key) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class PermissionsLocationsAddToolApprovalDetailsFactory: - """Location-persisted factory approval, optionally narrowed by approval key.""" - - kind: ClassVar[str] = "factory" - """Approval covering factory operations.""" - - approval_key: str | None = None - """Optional factory operation name or canonical approval key; when omitted, the approval - covers all factory operations. - """ - - @staticmethod - def from_dict(obj: Any) -> 'PermissionsLocationsAddToolApprovalDetailsFactory': - assert isinstance(obj, dict) - approval_key = from_union([from_str, from_none], obj.get("approvalKey")) - return PermissionsLocationsAddToolApprovalDetailsFactory(approval_key) - - def to_dict(self) -> dict: - result: dict = {} - result["kind"] = self.kind - if self.approval_key is not None: - result["approvalKey"] = from_union([from_str, from_none], self.approval_key) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForLocationApprovalMCPSampling: @@ -23763,6 +22939,84 @@ def to_dict(self) -> dict: result["kind"] = self.kind return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PermissionDecisionApproveForLocationApprovalWorkflow: + """Location-scoped workflow approval, optionally narrowed by approval key.""" + + kind: ClassVar[str] = "workflow" + """Approval covering workflow operations.""" + + approval_key: str | None = None + """Optional workflow operation name or canonical approval key; when omitted, the approval + covers all workflow operations. + """ + + @staticmethod + def from_dict(obj: Any) -> 'PermissionDecisionApproveForLocationApprovalWorkflow': + assert isinstance(obj, dict) + approval_key = from_union([from_str, from_none], obj.get("approvalKey")) + return PermissionDecisionApproveForLocationApprovalWorkflow(approval_key) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = self.kind + if self.approval_key is not None: + result["approvalKey"] = from_union([from_str, from_none], self.approval_key) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PermissionDecisionApproveForSessionApprovalWorkflow: + """Session-scoped workflow approval, optionally narrowed by approval key.""" + + kind: ClassVar[str] = "workflow" + """Approval covering workflow operations.""" + + approval_key: str | None = None + """Optional workflow operation name or canonical approval key; when omitted, the approval + covers all workflow operations. + """ + + @staticmethod + def from_dict(obj: Any) -> 'PermissionDecisionApproveForSessionApprovalWorkflow': + assert isinstance(obj, dict) + approval_key = from_union([from_str, from_none], obj.get("approvalKey")) + return PermissionDecisionApproveForSessionApprovalWorkflow(approval_key) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = self.kind + if self.approval_key is not None: + result["approvalKey"] = from_union([from_str, from_none], self.approval_key) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class PermissionsLocationsAddToolApprovalDetailsWorkflow: + """Location-persisted workflow approval, optionally narrowed by approval key.""" + + kind: ClassVar[str] = "workflow" + """Approval covering workflow operations.""" + + approval_key: str | None = None + """Optional workflow operation name or canonical approval key; when omitted, the approval + covers all workflow operations. + """ + + @staticmethod + def from_dict(obj: Any) -> 'PermissionsLocationsAddToolApprovalDetailsWorkflow': + assert isinstance(obj, dict) + approval_key = from_union([from_str, from_none], obj.get("approvalKey")) + return PermissionsLocationsAddToolApprovalDetailsWorkflow(approval_key) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = self.kind + if self.approval_key is not None: + result["approvalKey"] = from_union([from_str, from_none], self.approval_key) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionDecisionApproveForLocationApprovalWrite: @@ -25047,17 +24301,6 @@ def to_dict(self) -> dict: result["input"] = self.input return result -# Experimental: this type is part of an experimental API and may change or be removed. -class PauseCheckpointAction(Enum): - """Action the runtime selected for a durable factory pause checkpoint. - - Whether this execution attempt must pause or may continue. - - Action the runtime selected for a durable workflow pause checkpoint. - """ - CONTINUE = "continue" - PAUSE = "pause" - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class ModeSetRequest: @@ -25185,6 +24428,15 @@ def to_dict(self) -> dict: result["action"] = from_str(self.action) return result +# Experimental: this type is part of an experimental API and may change or be removed. +class WorkflowPauseCheckpointAction(Enum): + """Whether this execution attempt must pause or may continue. + + Action the runtime selected for a durable workflow pause checkpoint. + """ + CONTINUE = "continue" + PAUSE = "pause" + # Experimental: this type is part of an experimental API and may change or be removed. class UISessionLimitsExhaustedResponseAction(Enum): """Action selected by the user. @@ -28630,7 +27882,7 @@ class WorkflowRunFailure: type: WorkflowRunFailureType """Workflow failure variant discriminator.""" - kind: RunFailureKind | None = None + kind: WorkflowRunFailureKind | None = None """Resource ceiling that stopped the run.""" suggested_value: float | None = None @@ -28645,7 +27897,7 @@ class WorkflowRunFailure: code: str | None = None """Stable failure code.""" - operation: DurableOperation | None = None + operation: WorkflowDurableOperation | None = None """Execution-critical durable operation that failed.""" drained_nano_aiu: int | None = None @@ -28656,12 +27908,12 @@ def from_dict(obj: Any) -> 'WorkflowRunFailure': assert isinstance(obj, dict) run_id = from_str(obj.get("runId")) type = WorkflowRunFailureType(obj.get("type")) - kind = from_union([RunFailureKind, from_none], obj.get("kind")) + kind = from_union([WorkflowRunFailureKind, from_none], obj.get("kind")) suggested_value = from_union([from_float, from_none], obj.get("suggestedValue")) value = from_union([from_float, from_none], obj.get("value")) reason = from_union([from_str, from_none], obj.get("reason")) code = from_union([from_str, from_none], obj.get("code")) - operation = from_union([DurableOperation, from_none], obj.get("operation")) + operation = from_union([WorkflowDurableOperation, from_none], obj.get("operation")) drained_nano_aiu = from_union([from_int, from_none], obj.get("drainedNanoAiu")) return WorkflowRunFailure(run_id, type, kind, suggested_value, value, reason, code, operation, drained_nano_aiu) @@ -28670,7 +27922,7 @@ def to_dict(self) -> dict: result["runId"] = from_str(self.run_id) result["type"] = to_enum(WorkflowRunFailureType, self.type) if self.kind is not None: - result["kind"] = from_union([lambda x: to_enum(RunFailureKind, x), from_none], self.kind) + result["kind"] = from_union([lambda x: to_enum(WorkflowRunFailureKind, x), from_none], self.kind) if self.suggested_value is not None: result["suggestedValue"] = from_union([to_float, from_none], self.suggested_value) if self.value is not None: @@ -28680,11 +27932,219 @@ def to_dict(self) -> dict: if self.code is not None: result["code"] = from_union([from_str, from_none], self.code) if self.operation is not None: - result["operation"] = from_union([lambda x: to_enum(DurableOperation, x), from_none], self.operation) + result["operation"] = from_union([lambda x: to_enum(WorkflowDurableOperation, x), from_none], self.operation) if self.drained_nano_aiu is not None: result["drainedNanoAiu"] = from_union([from_int, from_none], self.drained_nano_aiu) return result +@dataclass +class PauseInfoClass: + type: PauseInfoType + """Workflow pause initiator discriminator.""" + + key: str | None = None + """Stable author-defined checkpoint key that initiated the pause.""" + + @staticmethod + def from_dict(obj: Any) -> 'PauseInfoClass': + assert isinstance(obj, dict) + type = PauseInfoType(obj.get("type")) + key = from_union([from_str, from_none], obj.get("key")) + return PauseInfoClass(type, key) + + def to_dict(self) -> dict: + result: dict = {} + result["type"] = to_enum(PauseInfoType, self.type) + if self.key is not None: + result["key"] = from_union([from_str, from_none], self.key) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkflowPauseInfo: + """Durable metadata describing who initiated a workflow pause. + + Structured pause initiator metadata for a paused attempt. + """ + type: PauseInfoType + """Workflow pause initiator discriminator.""" + + key: str | None = None + """Stable author-defined checkpoint key that initiated the pause.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkflowPauseInfo': + assert isinstance(obj, dict) + type = PauseInfoType(obj.get("type")) + key = from_union([from_str, from_none], obj.get("key")) + return WorkflowPauseInfo(type, key) + + def to_dict(self) -> dict: + result: dict = {} + result["type"] = to_enum(PauseInfoType, self.type) + if self.key is not None: + result["key"] = from_union([from_str, from_none], self.key) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkflowLogLine: + """One ordered workflow progress line.""" + + kind: WorkflowLogLineKind + """Progress line kind.""" + + seq: int + """Monotonic sequence number within the workflow run.""" + + text: str + """Progress text.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkflowLogLine': + assert isinstance(obj, dict) + kind = WorkflowLogLineKind(obj.get("kind")) + seq = from_int(obj.get("seq")) + text = from_str(obj.get("text")) + return WorkflowLogLine(kind, seq, text) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = to_enum(WorkflowLogLineKind, self.kind) + result["seq"] = from_int(self.seq) + result["text"] = from_str(self.text) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkflowProgressLine: + """One durable workflow progress record.""" + + attempt: int + """Resume attempt that emitted this record.""" + + kind: WorkflowLogLineKind + """Progress record kind.""" + + recorded_at: int + """Epoch milliseconds when the record was persisted.""" + + seq: int + """Global monotonic sequence number within the run.""" + + text: str + """Prompt-safe progress text.""" + + phase_id: str | None = None + """Phase active when the record was emitted, or null before any phase.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkflowProgressLine': + assert isinstance(obj, dict) + attempt = from_int(obj.get("attempt")) + kind = WorkflowLogLineKind(obj.get("kind")) + recorded_at = from_int(obj.get("recordedAt")) + seq = from_int(obj.get("seq")) + text = from_str(obj.get("text")) + phase_id = from_union([from_none, from_str], obj.get("phaseId")) + return WorkflowProgressLine(attempt, kind, recorded_at, seq, text, phase_id) + + def to_dict(self) -> dict: + result: dict = {} + result["attempt"] = from_int(self.attempt) + result["kind"] = to_enum(WorkflowLogLineKind, self.kind) + result["recordedAt"] = from_int(self.recorded_at) + result["seq"] = from_int(self.seq) + result["text"] = from_str(self.text) + result["phaseId"] = from_union([from_none, from_str], self.phase_id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkflowPhaseObservation: + """Durable lifecycle and timing for one workflow phase.""" + + accumulated_active_ms: int + """Completed active time accumulated by this phase in milliseconds.""" + + current_active_ms: int + """Current live active time for this phase in milliseconds.""" + + entry_count: int + """Number of times execution entered this phase.""" + + id: str + """Phase identifier.""" + + last_entered_run_attempt: int + """Most recent run attempt that entered this phase, or `0` if the phase has never been + entered. + """ + live_agent_count: int + """Direct agents in this phase that are currently live.""" + + status: WorkflowPhaseStatus + """Derived lifecycle state of the phase.""" + + title: str + """Human-readable phase title.""" + + total_agent_count: int + """Total direct agents associated with this phase.""" + + completed_at: int | None = None + """Epoch milliseconds when this phase completed; for a skipped phase, the synthetic skip + timestamp (equal to `startedAt`). + """ + detail: str | None = None + """Optional human-readable phase detail.""" + + ordinal: int | None = None + """Zero-based declared phase ordinal, or null for an undeclared phase.""" + + started_at: int | None = None + """Epoch milliseconds when this phase first started; for a skipped phase, the synthetic skip + timestamp (equal to `completedAt`). + """ + + @staticmethod + def from_dict(obj: Any) -> 'WorkflowPhaseObservation': + assert isinstance(obj, dict) + accumulated_active_ms = from_int(obj.get("accumulatedActiveMs")) + current_active_ms = from_int(obj.get("currentActiveMs")) + entry_count = from_int(obj.get("entryCount")) + id = from_str(obj.get("id")) + last_entered_run_attempt = from_int(obj.get("lastEnteredRunAttempt")) + live_agent_count = from_int(obj.get("liveAgentCount")) + status = WorkflowPhaseStatus(obj.get("status")) + title = from_str(obj.get("title")) + total_agent_count = from_int(obj.get("totalAgentCount")) + completed_at = from_union([from_int, from_none], obj.get("completedAt")) + detail = from_union([from_str, from_none], obj.get("detail")) + ordinal = from_union([from_none, from_int], obj.get("ordinal")) + started_at = from_union([from_int, from_none], obj.get("startedAt")) + return WorkflowPhaseObservation(accumulated_active_ms, current_active_ms, entry_count, id, last_entered_run_attempt, live_agent_count, status, title, total_agent_count, completed_at, detail, ordinal, started_at) + + def to_dict(self) -> dict: + result: dict = {} + result["accumulatedActiveMs"] = from_int(self.accumulated_active_ms) + result["currentActiveMs"] = from_int(self.current_active_ms) + result["entryCount"] = from_int(self.entry_count) + result["id"] = from_str(self.id) + result["lastEnteredRunAttempt"] = from_int(self.last_entered_run_attempt) + result["liveAgentCount"] = from_int(self.live_agent_count) + result["status"] = to_enum(WorkflowPhaseStatus, self.status) + result["title"] = from_str(self.title) + result["totalAgentCount"] = from_int(self.total_agent_count) + if self.completed_at is not None: + result["completedAt"] = from_union([from_int, from_none], self.completed_at) + if self.detail is not None: + result["detail"] = from_union([from_str, from_none], self.detail) + result["ordinal"] = from_union([from_none, from_int], self.ordinal) + if self.started_at is not None: + result["startedAt"] = from_union([from_int, from_none], self.started_at) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class WorkflowResumeRequest: @@ -28883,6 +28343,126 @@ def to_dict(self) -> dict: result["saved"] = from_union([lambda x: to_class(Saved, x), from_none], self.saved) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthReadValue: + """The read result, keyed by the same selector as the query.""" + + kind: AuthReadQueryKind + """Account read-datum variant discriminator.""" + + account: AccountStatus | None = None + """The active account, or absent when not logged in.""" + + status: AuthStatusDto | None = None + """The neutral authentication status summary.""" + + errors: list[AuthValidationError] | None = None + """Validation errors from the most recent authentication attempt.""" + + @staticmethod + def from_dict(obj: Any) -> 'AuthReadValue': + assert isinstance(obj, dict) + kind = AuthReadQueryKind(obj.get("kind")) + account = from_union([AccountStatus.from_dict, from_none], obj.get("account")) + status = from_union([AuthStatusDto.from_dict, from_none], obj.get("status")) + errors = from_union([lambda x: from_list(AuthValidationError.from_dict, x), from_none], obj.get("errors")) + return AuthReadValue(kind, account, status, errors) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = to_enum(AuthReadQueryKind, self.kind) + if self.account is not None: + result["account"] = from_union([lambda x: to_class(AccountStatus, x), from_none], self.account) + if self.status is not None: + result["status"] = from_union([lambda x: to_class(AuthStatusDto, x), from_none], self.status) + if self.errors is not None: + result["errors"] = from_union([lambda x: from_list(lambda x: to_class(AuthValidationError, x), x), from_none], self.errors) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthEnumerateValue: + """The enumerated collection, keyed by the same selector as the query.""" + + items: list[ItemElement] + """The signed-in account forest; empty when not logged in. + + The providers offered for interactive login. + """ + kind: AuthEnumerateQueryKind + """Enumerated account-collection variant discriminator.""" + + @staticmethod + def from_dict(obj: Any) -> 'AuthEnumerateValue': + assert isinstance(obj, dict) + items = from_list(ItemElement.from_dict, obj.get("items")) + kind = AuthEnumerateQueryKind(obj.get("kind")) + return AuthEnumerateValue(items, kind) + + def to_dict(self) -> dict: + result: dict = {} + result["items"] = from_list(lambda x: to_class(ItemElement, x), self.items) + result["kind"] = to_enum(AuthEnumerateQueryKind, self.kind) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AccountsEnumerateRequest: + """Enumerate request carrying the typed collection query.""" + + query: AuthEnumerateQuery + """Which typed accounts collection to enumerate.""" + + @staticmethod + def from_dict(obj: Any) -> 'AccountsEnumerateRequest': + assert isinstance(obj, dict) + query = AuthEnumerateQuery.from_dict(obj.get("query")) + return AccountsEnumerateRequest(query) + + def to_dict(self) -> dict: + result: dict = {} + result["query"] = to_class(AuthEnumerateQuery, self.query) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AccountsGetRequest: + """Read request carrying the typed datum query.""" + + query: AuthReadQuery + """Which typed accounts datum to read.""" + + @staticmethod + def from_dict(obj: Any) -> 'AccountsGetRequest': + assert isinstance(obj, dict) + query = AuthReadQuery.from_dict(obj.get("query")) + return AccountsGetRequest(query) + + def to_dict(self) -> dict: + result: dict = {} + result["query"] = to_class(AuthReadQuery, self.query) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AccountsSetRequest: + """Mutation request carrying the typed write command.""" + + command: AuthWrite + """The non-interactive mutation command to apply.""" + + @staticmethod + def from_dict(obj: Any) -> 'AccountsSetRequest': + assert isinstance(obj, dict) + command = AuthWrite.from_dict(obj.get("command")) + return AccountsSetRequest(command) + + def to_dict(self) -> dict: + result: dict = {} + result["command"] = to_class(AuthWrite, self.command) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class AgentDiscoveryPathList: @@ -28951,35 +28531,6 @@ def to_dict(self) -> dict: result["state"] = from_union([lambda x: to_class(AutopilotObjectiveState, x), from_none], self.state) return result -# Experimental: this type is part of an experimental API and may change or be removed. -# Internal: this type is an internal SDK API and is not part of the public surface. -@dataclass -class _FactoryToolRunOptions: - """Options for an internal tool-originated factory invocation. - - Tool-originated factory invocation options. - """ - limits: FactoryRunLimits | None = None - """Per-invocation resource ceiling overrides.""" - - resume_from_run_id: str | None = None - """Run identifier whose journal and progress should seed this resumed run.""" - - @staticmethod - def from_dict(obj: Any) -> '_FactoryToolRunOptions': - assert isinstance(obj, dict) - limits = from_union([FactoryRunLimits.from_dict, from_none], obj.get("limits")) - resume_from_run_id = from_union([from_str, from_none], obj.get("resumeFromRunId")) - return _FactoryToolRunOptions(limits, resume_from_run_id) - - def to_dict(self) -> dict: - result: dict = {} - if self.limits is not None: - result["limits"] = from_union([lambda x: to_class(FactoryRunLimits, x), from_none], self.limits) - if self.resume_from_run_id is not None: - result["resumeFromRunId"] = from_union([from_str, from_none], self.resume_from_run_id) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPAppsCallToolRequest: @@ -29792,6 +29343,56 @@ def to_dict(self) -> dict: result["revision"] = from_int(self.revision) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthLoginStep: + """The first step of the flow. + + One step in an interactive login flow. The consumer acts on the step and calls advance to + proceed. Browser-open is encoded as two distinct steps by design: `open-url` is + CONSUMER-driven (the provider surfaces the authorize URL and the consumer opens it — + github.com/GHEC web), while `needs-interaction` is PROVIDER-driven (the provider opens + the browser or broker UI itself and does not surface a URL — Entra). + """ + kind: AuthLoginStepKind + """Login flow step variant discriminator.""" + + url: str | None = None + """Authorize URL the consumer should open in a browser (consumer-driven browser-open).""" + + prompt: str | None = None + """Prompt for the value the provider needs; the consumer supplies it as advance input (e.g. + a GitHub Enterprise Cloud host, *.ghe.com). + """ + result: AuthLoginResultDto | None = None + """The terminal login result.""" + + message: str | None = None + """Human-readable failure message.""" + + @staticmethod + def from_dict(obj: Any) -> 'AuthLoginStep': + assert isinstance(obj, dict) + kind = AuthLoginStepKind(obj.get("kind")) + url = from_union([from_str, from_none], obj.get("url")) + prompt = from_union([from_str, from_none], obj.get("prompt")) + result = from_union([AuthLoginResultDto.from_dict, from_none], obj.get("result")) + message = from_union([from_str, from_none], obj.get("message")) + return AuthLoginStep(kind, url, prompt, result, message) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = to_enum(AuthLoginStepKind, self.kind) + if self.url is not None: + result["url"] = from_union([from_str, from_none], self.url) + if self.prompt is not None: + result["prompt"] = from_union([from_str, from_none], self.prompt) + if self.result is not None: + result["result"] = from_union([lambda x: to_class(AuthLoginResultDto, x), from_none], self.result) + if self.message is not None: + result["message"] = from_union([from_str, from_none], self.message) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CanvasHostContext: @@ -30592,298 +30193,6 @@ def to_dict(self) -> dict: result["title"] = from_union([from_str, from_none], self.title) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryRunTerminal: - """Prompt-safe terminal factory outcome.""" - - error: str | None = None - """Human-readable terminal error.""" - - failure: FactoryRunFailure | None = None - """Machine-readable terminal failure.""" - - pause_info: PauseInfoClass | None = None - """Pause initiator metadata, or null when the run did not pause.""" - - reason: str | None = None - """Human-readable terminal reason.""" - - result_preview: str | None = None - """Prompt-safe preview of the completed result.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryRunTerminal': - assert isinstance(obj, dict) - error = from_union([from_str, from_none], obj.get("error")) - failure = from_union([FactoryRunFailure.from_dict, from_none], obj.get("failure")) - pause_info = from_union([PauseInfoClass.from_dict, from_none], obj.get("pauseInfo")) - reason = from_union([from_str, from_none], obj.get("reason")) - result_preview = from_union([from_str, from_none], obj.get("resultPreview")) - return FactoryRunTerminal(error, failure, pause_info, reason, result_preview) - - def to_dict(self) -> dict: - result: dict = {} - if self.error is not None: - result["error"] = from_union([from_str, from_none], self.error) - if self.failure is not None: - result["failure"] = from_union([lambda x: to_class(FactoryRunFailure, x), from_none], self.failure) - result["pauseInfo"] = from_union([lambda x: to_class(PauseInfoClass, x), from_none], self.pause_info) - if self.reason is not None: - result["reason"] = from_union([from_str, from_none], self.reason) - if self.result_preview is not None: - result["resultPreview"] = from_union([from_str, from_none], self.result_preview) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryRunResult: - """Terminal resumed run envelope. - - Complete current or terminal factory run envelope. - """ - run_id: str - """Factory run identifier.""" - - status: RunStatus - """Current or terminal factory run status.""" - - attempt: int | None = None - """One-based execution attempt represented by this envelope. Absent before the first attempt - starts or when returned by an older runtime. - """ - error: str | None = None - """Error message for an errored run.""" - - failure: FactoryRunFailure | None = None - """Machine-readable failure details for a halted or errored run.""" - - pause_info: FactoryPauseInfo | None = None - """Structured pause initiator metadata for a paused attempt.""" - - reason: str | None = None - """Reason for a halted or cancelled run.""" - - result: Any = None - """Completed factory result.""" - - snapshot: Any = None - """Partial journal and progress snapshot for a halted, cancelled, or errored run.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryRunResult': - assert isinstance(obj, dict) - run_id = from_str(obj.get("runId")) - status = RunStatus(obj.get("status")) - attempt = from_union([from_int, from_none], obj.get("attempt")) - error = from_union([from_str, from_none], obj.get("error")) - failure = from_union([FactoryRunFailure.from_dict, from_none], obj.get("failure")) - pause_info = from_union([FactoryPauseInfo.from_dict, from_none], obj.get("pauseInfo")) - reason = from_union([from_str, from_none], obj.get("reason")) - result = obj.get("result") - snapshot = obj.get("snapshot") - return FactoryRunResult(run_id, status, attempt, error, failure, pause_info, reason, result, snapshot) - - def to_dict(self) -> dict: - result: dict = {} - result["runId"] = from_str(self.run_id) - result["status"] = to_enum(RunStatus, self.status) - if self.attempt is not None: - result["attempt"] = from_union([from_int, from_none], self.attempt) - if self.error is not None: - result["error"] = from_union([from_str, from_none], self.error) - if self.failure is not None: - result["failure"] = from_union([lambda x: to_class(FactoryRunFailure, x), from_none], self.failure) - if self.pause_info is not None: - result["pauseInfo"] = from_union([lambda x: to_class(FactoryPauseInfo, x), from_none], self.pause_info) - if self.reason is not None: - result["reason"] = from_union([from_str, from_none], self.reason) - if self.result is not None: - result["result"] = self.result - if self.snapshot is not None: - result["snapshot"] = self.snapshot - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryLogRequest: - """Parameters for recording factory progress.""" - - execution_token: str - """Opaque token identifying the current factory execution attempt.""" - - lines: list[FactoryLogLine] - """Ordered progress lines to append.""" - - run_id: str - """Factory run identifier.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryLogRequest': - assert isinstance(obj, dict) - execution_token = from_str(obj.get("executionToken")) - lines = from_list(FactoryLogLine.from_dict, obj.get("lines")) - run_id = from_str(obj.get("runId")) - return FactoryLogRequest(execution_token, lines, run_id) - - def to_dict(self) -> dict: - result: dict = {} - result["executionToken"] = from_str(self.execution_token) - result["lines"] = from_list(lambda x: to_class(FactoryLogLine, x), self.lines) - result["runId"] = from_str(self.run_id) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryProgressPage: - """A bidirectional page of factory progress. - - Bidirectional page of durable factory progress. - """ - has_more_newer: bool - """Whether progress records newer than this page exist.""" - - has_more_older: bool - """Whether progress records older than this page exist.""" - - records: list[FactoryProgressLine] - """Progress records in sequence order.""" - - revision: int - """Run revision reflected by this page.""" - - newest_seq: int | None = None - """Newest sequence number in this page, or null when empty.""" - - oldest_seq: int | None = None - """Oldest sequence number in this page, or null when empty.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryProgressPage': - assert isinstance(obj, dict) - has_more_newer = from_bool(obj.get("hasMoreNewer")) - has_more_older = from_bool(obj.get("hasMoreOlder")) - records = from_list(FactoryProgressLine.from_dict, obj.get("records")) - revision = from_int(obj.get("revision")) - newest_seq = from_union([from_int, from_none], obj.get("newestSeq")) - oldest_seq = from_union([from_int, from_none], obj.get("oldestSeq")) - return FactoryProgressPage(has_more_newer, has_more_older, records, revision, newest_seq, oldest_seq) - - def to_dict(self) -> dict: - result: dict = {} - result["hasMoreNewer"] = from_bool(self.has_more_newer) - result["hasMoreOlder"] = from_bool(self.has_more_older) - result["records"] = from_list(lambda x: to_class(FactoryProgressLine, x), self.records) - result["revision"] = from_int(self.revision) - result["newestSeq"] = from_union([from_int, from_none], self.newest_seq) - result["oldestSeq"] = from_union([from_int, from_none], self.oldest_seq) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class WorkflowLogRequest: - """Parameters for recording workflow progress.""" - - execution_token: str - """Opaque token identifying the current workflow execution attempt.""" - - lines: list[WorkflowLogLine] - """Ordered progress lines to append.""" - - run_id: str - """Workflow run identifier.""" - - @staticmethod - def from_dict(obj: Any) -> 'WorkflowLogRequest': - assert isinstance(obj, dict) - execution_token = from_str(obj.get("executionToken")) - lines = from_list(WorkflowLogLine.from_dict, obj.get("lines")) - run_id = from_str(obj.get("runId")) - return WorkflowLogRequest(execution_token, lines, run_id) - - def to_dict(self) -> dict: - result: dict = {} - result["executionToken"] = from_str(self.execution_token) - result["lines"] = from_list(lambda x: to_class(WorkflowLogLine, x), self.lines) - result["runId"] = from_str(self.run_id) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class WorkflowProgressPage: - """A bidirectional page of workflow progress. - - Bidirectional page of durable workflow progress. - """ - has_more_newer: bool - """Whether progress records newer than this page exist.""" - - has_more_older: bool - """Whether progress records older than this page exist.""" - - records: list[WorkflowProgressLine] - """Progress records in sequence order.""" - - revision: int - """Run revision reflected by this page.""" - - newest_seq: int | None = None - """Newest sequence number in this page, or null when empty.""" - - oldest_seq: int | None = None - """Oldest sequence number in this page, or null when empty.""" - - @staticmethod - def from_dict(obj: Any) -> 'WorkflowProgressPage': - assert isinstance(obj, dict) - has_more_newer = from_bool(obj.get("hasMoreNewer")) - has_more_older = from_bool(obj.get("hasMoreOlder")) - records = from_list(WorkflowProgressLine.from_dict, obj.get("records")) - revision = from_int(obj.get("revision")) - newest_seq = from_union([from_int, from_none], obj.get("newestSeq")) - oldest_seq = from_union([from_int, from_none], obj.get("oldestSeq")) - return WorkflowProgressPage(has_more_newer, has_more_older, records, revision, newest_seq, oldest_seq) - - def to_dict(self) -> dict: - result: dict = {} - result["hasMoreNewer"] = from_bool(self.has_more_newer) - result["hasMoreOlder"] = from_bool(self.has_more_older) - result["records"] = from_list(lambda x: to_class(WorkflowProgressLine, x), self.records) - result["revision"] = from_int(self.revision) - result["newestSeq"] = from_union([from_int, from_none], self.newest_seq) - result["oldestSeq"] = from_union([from_int, from_none], self.oldest_seq) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryRunRequest: - """Parameters for invoking a registered factory.""" - - args: Any - """Factory input value.""" - - name: str - """Registered factory name.""" - - options: RunOptions | None = None - """Factory invocation options.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryRunRequest': - assert isinstance(obj, dict) - args = obj.get("args") - name = from_str(obj.get("name")) - options = from_union([RunOptions.from_dict, from_none], obj.get("options")) - return FactoryRunRequest(args, name, options) - - def to_dict(self) -> dict: - result: dict = {} - result["args"] = self.args - result["name"] = from_str(self.name) - if self.options is not None: - result["options"] = from_union([lambda x: to_class(RunOptions, x), from_none], self.options) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPOauthHandlePendingRequest: @@ -32484,72 +31793,38 @@ def to_dict(self) -> dict: result["inputSchema"] = self.input_schema return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryPauseCheckpointResult: - action: PauseCheckpointAction - """Whether this execution attempt must pause or may continue.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryPauseCheckpointResult': - assert isinstance(obj, dict) - action = PauseCheckpointAction(obj.get("action")) - return FactoryPauseCheckpointResult(action) - - def to_dict(self) -> dict: - result: dict = {} - result["action"] = to_enum(PauseCheckpointAction, self.action) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class SessionFactoryPauseAtCheckpointResult: - action: PauseCheckpointAction - """Whether this execution attempt must pause or may continue.""" - - @staticmethod - def from_dict(obj: Any) -> 'SessionFactoryPauseAtCheckpointResult': - assert isinstance(obj, dict) - action = PauseCheckpointAction(obj.get("action")) - return SessionFactoryPauseAtCheckpointResult(action) - - def to_dict(self) -> dict: - result: dict = {} - result["action"] = to_enum(PauseCheckpointAction, self.action) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionWorkflowPauseAtCheckpointResult: - action: PauseCheckpointAction + action: WorkflowPauseCheckpointAction """Whether this execution attempt must pause or may continue.""" @staticmethod def from_dict(obj: Any) -> 'SessionWorkflowPauseAtCheckpointResult': assert isinstance(obj, dict) - action = PauseCheckpointAction(obj.get("action")) + action = WorkflowPauseCheckpointAction(obj.get("action")) return SessionWorkflowPauseAtCheckpointResult(action) def to_dict(self) -> dict: result: dict = {} - result["action"] = to_enum(PauseCheckpointAction, self.action) + result["action"] = to_enum(WorkflowPauseCheckpointAction, self.action) return result # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class WorkflowPauseCheckpointResult: - action: PauseCheckpointAction + action: WorkflowPauseCheckpointAction """Whether this execution attempt must pause or may continue.""" @staticmethod def from_dict(obj: Any) -> 'WorkflowPauseCheckpointResult': assert isinstance(obj, dict) - action = PauseCheckpointAction(obj.get("action")) + action = WorkflowPauseCheckpointAction(obj.get("action")) return WorkflowPauseCheckpointResult(action) def to_dict(self) -> dict: result: dict = {} - result["action"] = to_enum(PauseCheckpointAction, self.action) + result["action"] = to_enum(WorkflowPauseCheckpointAction, self.action) return result # Experimental: this type is part of an experimental API and may change or be removed. @@ -34099,7 +33374,7 @@ class WorkflowRunTerminal: failure: WorkflowRunFailure | None = None """Machine-readable terminal failure.""" - pause_info: WorkflowRunTerminalPauseInfo | None = None + pause_info: PauseInfoClass | None = None """Pause initiator metadata, or null when the run did not pause.""" reason: str | None = None @@ -34113,7 +33388,7 @@ def from_dict(obj: Any) -> 'WorkflowRunTerminal': assert isinstance(obj, dict) error = from_union([from_str, from_none], obj.get("error")) failure = from_union([WorkflowRunFailure.from_dict, from_none], obj.get("failure")) - pause_info = from_union([WorkflowRunTerminalPauseInfo.from_dict, from_none], obj.get("pauseInfo")) + pause_info = from_union([PauseInfoClass.from_dict, from_none], obj.get("pauseInfo")) reason = from_union([from_str, from_none], obj.get("reason")) result_preview = from_union([from_str, from_none], obj.get("resultPreview")) return WorkflowRunTerminal(error, failure, pause_info, reason, result_preview) @@ -34124,7 +33399,7 @@ def to_dict(self) -> dict: result["error"] = from_union([from_str, from_none], self.error) if self.failure is not None: result["failure"] = from_union([lambda x: to_class(WorkflowRunFailure, x), from_none], self.failure) - result["pauseInfo"] = from_union([lambda x: to_class(WorkflowRunTerminalPauseInfo, x), from_none], self.pause_info) + result["pauseInfo"] = from_union([lambda x: to_class(PauseInfoClass, x), from_none], self.pause_info) if self.reason is not None: result["reason"] = from_union([from_str, from_none], self.reason) if self.result_preview is not None: @@ -34141,7 +33416,7 @@ class WorkflowRunResult: run_id: str """Workflow run identifier.""" - status: RunStatus + status: WorkflowRunStatus """Current or terminal workflow run status.""" attempt: int | None = None @@ -34170,7 +33445,7 @@ class WorkflowRunResult: def from_dict(obj: Any) -> 'WorkflowRunResult': assert isinstance(obj, dict) run_id = from_str(obj.get("runId")) - status = RunStatus(obj.get("status")) + status = WorkflowRunStatus(obj.get("status")) attempt = from_union([from_int, from_none], obj.get("attempt")) error = from_union([from_str, from_none], obj.get("error")) failure = from_union([WorkflowRunFailure.from_dict, from_none], obj.get("failure")) @@ -34183,7 +33458,7 @@ def from_dict(obj: Any) -> 'WorkflowRunResult': def to_dict(self) -> dict: result: dict = {} result["runId"] = from_str(self.run_id) - result["status"] = to_enum(RunStatus, self.status) + result["status"] = to_enum(WorkflowRunStatus, self.status) if self.attempt is not None: result["attempt"] = from_union([from_int, from_none], self.attempt) if self.error is not None: @@ -34200,6 +33475,81 @@ def to_dict(self) -> dict: result["snapshot"] = self.snapshot return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkflowLogRequest: + """Parameters for recording workflow progress.""" + + execution_token: str + """Opaque token identifying the current workflow execution attempt.""" + + lines: list[WorkflowLogLine] + """Ordered progress lines to append.""" + + run_id: str + """Workflow run identifier.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkflowLogRequest': + assert isinstance(obj, dict) + execution_token = from_str(obj.get("executionToken")) + lines = from_list(WorkflowLogLine.from_dict, obj.get("lines")) + run_id = from_str(obj.get("runId")) + return WorkflowLogRequest(execution_token, lines, run_id) + + def to_dict(self) -> dict: + result: dict = {} + result["executionToken"] = from_str(self.execution_token) + result["lines"] = from_list(lambda x: to_class(WorkflowLogLine, x), self.lines) + result["runId"] = from_str(self.run_id) + return result + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkflowProgressPage: + """A bidirectional page of workflow progress. + + Bidirectional page of durable workflow progress. + """ + has_more_newer: bool + """Whether progress records newer than this page exist.""" + + has_more_older: bool + """Whether progress records older than this page exist.""" + + records: list[WorkflowProgressLine] + """Progress records in sequence order.""" + + revision: int + """Run revision reflected by this page.""" + + newest_seq: int | None = None + """Newest sequence number in this page, or null when empty.""" + + oldest_seq: int | None = None + """Oldest sequence number in this page, or null when empty.""" + + @staticmethod + def from_dict(obj: Any) -> 'WorkflowProgressPage': + assert isinstance(obj, dict) + has_more_newer = from_bool(obj.get("hasMoreNewer")) + has_more_older = from_bool(obj.get("hasMoreOlder")) + records = from_list(WorkflowProgressLine.from_dict, obj.get("records")) + revision = from_int(obj.get("revision")) + newest_seq = from_union([from_int, from_none], obj.get("newestSeq")) + oldest_seq = from_union([from_int, from_none], obj.get("oldestSeq")) + return WorkflowProgressPage(has_more_newer, has_more_older, records, revision, newest_seq, oldest_seq) + + def to_dict(self) -> dict: + result: dict = {} + result["hasMoreNewer"] = from_bool(self.has_more_newer) + result["hasMoreOlder"] = from_bool(self.has_more_older) + result["records"] = from_list(lambda x: to_class(WorkflowProgressLine, x), self.records) + result["revision"] = from_int(self.revision) + result["newestSeq"] = from_union([from_int, from_none], self.newest_seq) + result["oldestSeq"] = from_union([from_int, from_none], self.oldest_seq) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class WorkflowRunRequest: @@ -34284,43 +33634,6 @@ def to_dict(self) -> dict: result["unavailableReason"] = from_union([lambda x: to_enum(HistoryRewindUnavailableReason, x), from_none], self.unavailable_reason) return result -# Experimental: this type is part of an experimental API and may change or be removed. -# Internal: this type is an internal SDK API and is not part of the public surface. -@dataclass -class _FactoryToolRunRequest: - """Internal parameters for invoking a registered factory from a tool.""" - - args: Any - """Factory input value.""" - - name: str - """Registered factory name.""" - - options: _FactoryToolRunOptions | None = None - """Tool-originated factory invocation options.""" - - tool_call_id: str | None = None - """Opaque identifier of the originating tool call.""" - - @staticmethod - def from_dict(obj: Any) -> '_FactoryToolRunRequest': - assert isinstance(obj, dict) - args = obj.get("args") - name = from_str(obj.get("name")) - options = from_union([_FactoryToolRunOptions.from_dict, from_none], obj.get("options")) - tool_call_id = from_union([from_str, from_none], obj.get("toolCallId")) - return _FactoryToolRunRequest(args, name, options, tool_call_id) - - def to_dict(self) -> dict: - result: dict = {} - result["args"] = self.args - result["name"] = from_str(self.name) - if self.options is not None: - result["options"] = from_union([lambda x: to_class(_FactoryToolRunOptions, x), from_none], self.options) - if self.tool_call_id is not None: - result["toolCallId"] = from_union([from_str, from_none], self.tool_call_id) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class MCPSerializableServerConfig: @@ -35218,6 +34531,30 @@ def to_dict(self) -> dict: result["catalog"] = from_union([lambda x: to_class(ConnectorCatalogResult, x), from_none], self.catalog) return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class AuthLoginBegun: + """A started login flow: its opaque id and first step.""" + + flow_id: str + """Opaque flow id used to advance or cancel this login.""" + + step: AuthLoginStep + """The first step of the flow.""" + + @staticmethod + def from_dict(obj: Any) -> 'AuthLoginBegun': + assert isinstance(obj, dict) + flow_id = from_str(obj.get("flowId")) + step = AuthLoginStep.from_dict(obj.get("step")) + return AuthLoginBegun(flow_id, step) + + def to_dict(self) -> dict: + result: dict = {} + result["flowId"] = from_str(self.flow_id) + result["step"] = to_class(AuthLoginStep, self.step) + return result + # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CanvasProviderCloseRequest: @@ -35468,144 +34805,6 @@ def to_dict(self) -> dict: result["toolArgs"] = self.tool_args return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryRunSummary: - """Durable factory run summary with read-time live overlays.""" - - can_resume: bool - """Whether the durable run state currently passes runtime resume eligibility checks.""" - - consumed: FactoryRunConsumed - """Durable resource consumption.""" - - created_at: int - """Epoch milliseconds when the run was created.""" - - declared_limits: FactoryDeclaredLimits - """Resource ceilings declared by the factory.""" - - declared_phase_count: int - """Number of phases declared by the factory.""" - - description: str - """Human-readable factory description.""" - - factory_name: str - """Registered factory name.""" - - live_agent_count: int - """Number of direct factory agents currently live.""" - - observed_at: int - """Epoch milliseconds when this live-overlay snapshot was observed.""" - - revision: int - """Monotonic durable run revision.""" - - run_id: str - """Factory run identifier.""" - - status: RunStatus - """Current factory run status.""" - - total_spawned_agent_count: int - """Total direct factory agents spawned across all attempts.""" - - updated_at: int - """Epoch milliseconds when the durable run was last updated.""" - - active_segment_started_at: int | None = None - """Epoch milliseconds when the current active segment started, or null while inactive.""" - - approved: FactoryDeclaredLimits | None = None - """Approved effective resource ceilings, or null until approved.""" - - completed_at: int | None = None - """Epoch milliseconds when the run completed, or null while nonterminal.""" - - current_phase: FactoryCurrentPhase | None = None - """Current phase identity, or null before any phase is entered.""" - - started_at: int | None = None - """Epoch milliseconds when execution first started, or null before start.""" - - terminal: FactoryRunTerminal | None = None - """Terminal run outcome, or null while nonterminal.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryRunSummary': - assert isinstance(obj, dict) - can_resume = from_bool(obj.get("canResume")) - consumed = FactoryRunConsumed.from_dict(obj.get("consumed")) - created_at = from_int(obj.get("createdAt")) - declared_limits = FactoryDeclaredLimits.from_dict(obj.get("declaredLimits")) - declared_phase_count = from_int(obj.get("declaredPhaseCount")) - description = from_str(obj.get("description")) - factory_name = from_str(obj.get("factoryName")) - live_agent_count = from_int(obj.get("liveAgentCount")) - observed_at = from_int(obj.get("observedAt")) - revision = from_int(obj.get("revision")) - run_id = from_str(obj.get("runId")) - status = RunStatus(obj.get("status")) - total_spawned_agent_count = from_int(obj.get("totalSpawnedAgentCount")) - updated_at = from_int(obj.get("updatedAt")) - active_segment_started_at = from_union([from_int, from_none], obj.get("activeSegmentStartedAt")) - approved = from_union([FactoryDeclaredLimits.from_dict, from_none], obj.get("approved")) - completed_at = from_union([from_int, from_none], obj.get("completedAt")) - current_phase = from_union([FactoryCurrentPhase.from_dict, from_none], obj.get("currentPhase")) - started_at = from_union([from_int, from_none], obj.get("startedAt")) - terminal = from_union([FactoryRunTerminal.from_dict, from_none], obj.get("terminal")) - return FactoryRunSummary(can_resume, consumed, created_at, declared_limits, declared_phase_count, description, factory_name, live_agent_count, observed_at, revision, run_id, status, total_spawned_agent_count, updated_at, active_segment_started_at, approved, completed_at, current_phase, started_at, terminal) - - def to_dict(self) -> dict: - result: dict = {} - result["canResume"] = from_bool(self.can_resume) - result["consumed"] = to_class(FactoryRunConsumed, self.consumed) - result["createdAt"] = from_int(self.created_at) - result["declaredLimits"] = to_class(FactoryDeclaredLimits, self.declared_limits) - result["declaredPhaseCount"] = from_int(self.declared_phase_count) - result["description"] = from_str(self.description) - result["factoryName"] = from_str(self.factory_name) - result["liveAgentCount"] = from_int(self.live_agent_count) - result["observedAt"] = from_int(self.observed_at) - result["revision"] = from_int(self.revision) - result["runId"] = from_str(self.run_id) - result["status"] = to_enum(RunStatus, self.status) - result["totalSpawnedAgentCount"] = from_int(self.total_spawned_agent_count) - result["updatedAt"] = from_int(self.updated_at) - result["activeSegmentStartedAt"] = from_union([from_int, from_none], self.active_segment_started_at) - result["approved"] = from_union([lambda x: to_class(FactoryDeclaredLimits, x), from_none], self.approved) - result["completedAt"] = from_union([from_int, from_none], self.completed_at) - result["currentPhase"] = from_union([lambda x: to_class(FactoryCurrentPhase, x), from_none], self.current_phase) - result["startedAt"] = from_union([from_int, from_none], self.started_at) - result["terminal"] = from_union([lambda x: to_class(FactoryRunTerminal, x), from_none], self.terminal) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryResumeResult: - """Resolved persisted factory identity and resumed run envelope.""" - - factory_name: str - """Persisted factory name resolved for the resumed run.""" - - run: FactoryRunResult - """Terminal resumed run envelope.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryResumeResult': - assert isinstance(obj, dict) - factory_name = from_str(obj.get("factoryName")) - run = FactoryRunResult.from_dict(obj.get("run")) - return FactoryResumeResult(factory_name, run) - - def to_dict(self) -> dict: - result: dict = {} - result["factoryName"] = from_str(self.factory_name) - result["run"] = to_class(FactoryRunResult, self.run) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class SessionsSetAdditionalPluginsRequest: @@ -36792,7 +35991,7 @@ class WorkflowRunSummary: run_id: str """Workflow run identifier.""" - status: RunStatus + status: WorkflowRunStatus """Current workflow run status.""" total_spawned_agent_count: int @@ -36835,7 +36034,7 @@ def from_dict(obj: Any) -> 'WorkflowRunSummary': observed_at = from_int(obj.get("observedAt")) revision = from_int(obj.get("revision")) run_id = from_str(obj.get("runId")) - status = RunStatus(obj.get("status")) + status = WorkflowRunStatus(obj.get("status")) total_spawned_agent_count = from_int(obj.get("totalSpawnedAgentCount")) updated_at = from_int(obj.get("updatedAt")) workflow_name = from_str(obj.get("workflowName")) @@ -36859,7 +36058,7 @@ def to_dict(self) -> dict: result["observedAt"] = from_int(self.observed_at) result["revision"] = from_int(self.revision) result["runId"] = from_str(self.run_id) - result["status"] = to_enum(RunStatus, self.status) + result["status"] = to_enum(WorkflowRunStatus, self.status) result["totalSpawnedAgentCount"] = from_int(self.total_spawned_agent_count) result["updatedAt"] = from_int(self.updated_at) result["workflowName"] = from_str(self.workflow_name) @@ -37137,49 +36336,6 @@ def to_dict(self) -> dict: result["status"] = to_class(ConnectorStatus, self.status) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryListRunsResult: - """A page of factory runs in durable creation order.""" - - runs: list[FactoryRunSummary] - """Factory run summaries in durable creation order.""" - - has_more_newer: bool | None = None - """Whether terminal runs newer than this page exist.""" - - newest_seq: int | None = None - """Newest terminal-run cursor in this page, or null when the terminal window is empty.""" - - oldest_seq: int | None = None - """Oldest terminal-run cursor in this page, or null when the terminal window is empty.""" - - omitted_older: int | None = None - """Number of terminal runs older than this page.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryListRunsResult': - assert isinstance(obj, dict) - runs = from_list(FactoryRunSummary.from_dict, obj.get("runs")) - has_more_newer = from_union([from_bool, from_none], obj.get("hasMoreNewer")) - newest_seq = from_union([from_int, from_none], obj.get("newestSeq")) - oldest_seq = from_union([from_int, from_none], obj.get("oldestSeq")) - omitted_older = from_union([from_int, from_none], obj.get("omittedOlder")) - return FactoryListRunsResult(runs, has_more_newer, newest_seq, oldest_seq, omitted_older) - - def to_dict(self) -> dict: - result: dict = {} - result["runs"] = from_list(lambda x: to_class(FactoryRunSummary, x), self.runs) - if self.has_more_newer is not None: - result["hasMoreNewer"] = from_union([from_bool, from_none], self.has_more_newer) - if self.newest_seq is not None: - result["newestSeq"] = from_union([from_int, from_none], self.newest_seq) - if self.oldest_seq is not None: - result["oldestSeq"] = from_union([from_int, from_none], self.oldest_seq) - if self.omitted_older is not None: - result["omittedOlder"] = from_union([from_int, from_none], self.omitted_older) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class CatalogSearchSucceeded: @@ -38568,225 +37724,6 @@ def to_dict(self) -> dict: result["hasMore"] = from_bool(self.has_more) return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryAgentSummary: - """Prompt-safe durable identity and live status for a direct factory agent.""" - - active_ms: int - """Accumulated active agent time in milliseconds.""" - - agent_id: str - """Stable direct-agent identifier.""" - - agent_type: str - """Registered agent type.""" - - label: str - """Friendly, non-unique name intended for display""" - - run_id: str - """Owning factory run identifier.""" - - status: str - """Current durable or live agent status.""" - - tool_call_id: str - """Tool-call identifier that launched the agent.""" - - activity: str | None = None - """Prompt-safe live activity text.""" - - completed_at: int | None = None - """Epoch milliseconds when the agent completed.""" - - display_name: str | None = None - """Friendly, non-unique name intended for display""" - - phase_id: str | None = None - """Phase identifier active when the agent was launched, or null.""" - - requested_model: str | None = None - """Model requested when the agent was launched.""" - - resolved_model: str | None = None - """Concrete model resolved for the agent.""" - - started_at: int | None = None - """Epoch milliseconds when the agent started.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryAgentSummary': - assert isinstance(obj, dict) - active_ms = from_int(obj.get("activeMs")) - agent_id = from_str(obj.get("agentId")) - agent_type = from_str(obj.get("agentType")) - label = from_str(obj.get("label")) - run_id = from_str(obj.get("runId")) - status = from_str(obj.get("status")) - tool_call_id = from_str(obj.get("toolCallId")) - activity = from_union([from_str, from_none], obj.get("activity")) - completed_at = from_union([from_int, from_none], obj.get("completedAt")) - display_name = from_union([from_str, from_none], obj.get("displayName")) - phase_id = from_union([from_none, from_str], obj.get("phaseId")) - requested_model = from_union([from_str, from_none], obj.get("requestedModel")) - resolved_model = from_union([from_str, from_none], obj.get("resolvedModel")) - started_at = from_union([from_int, from_none], obj.get("startedAt")) - return FactoryAgentSummary(active_ms, agent_id, agent_type, label, run_id, status, tool_call_id, activity, completed_at, display_name, phase_id, requested_model, resolved_model, started_at) - - def to_dict(self) -> dict: - result: dict = {} - result["activeMs"] = from_int(self.active_ms) - result["agentId"] = from_str(self.agent_id) - result["agentType"] = from_str(self.agent_type) - result["label"] = from_str(self.label) - result["runId"] = from_str(self.run_id) - result["status"] = from_str(self.status) - result["toolCallId"] = from_str(self.tool_call_id) - if self.activity is not None: - result["activity"] = from_union([from_str, from_none], self.activity) - if self.completed_at is not None: - result["completedAt"] = from_union([from_int, from_none], self.completed_at) - if self.display_name is not None: - result["displayName"] = from_union([from_str, from_none], self.display_name) - result["phaseId"] = from_union([from_none, from_str], self.phase_id) - if self.requested_model is not None: - result["requestedModel"] = from_union([from_str, from_none], self.requested_model) - if self.resolved_model is not None: - result["resolvedModel"] = from_union([from_str, from_none], self.resolved_model) - if self.started_at is not None: - result["startedAt"] = from_union([from_int, from_none], self.started_at) - return result - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryRunDetail: - """Full factory run observability detail.""" - - agents: list[FactoryAgentSummary] - """Durable identities and live statuses for direct factory agents.""" - - can_resume: bool - """Whether the durable run state currently passes runtime resume eligibility checks.""" - - consumed: FactoryRunConsumed - """Durable resource consumption.""" - - created_at: int - """Epoch milliseconds when the run was created.""" - - declared_limits: FactoryDeclaredLimits - """Resource ceilings declared by the factory.""" - - declared_phase_count: int - """Number of phases declared by the factory.""" - - description: str - """Human-readable factory description.""" - - factory_name: str - """Registered factory name.""" - - live_agent_count: int - """Number of direct factory agents currently live.""" - - observed_at: int - """Epoch milliseconds when this live-overlay snapshot was observed.""" - - phases: list[FactoryPhaseObservation] - """Lifecycle and timing observations for each factory phase.""" - - progress: FactoryProgressPage - """Bidirectional page of durable factory progress.""" - - revision: int - """Monotonic durable run revision.""" - - run_id: str - """Factory run identifier.""" - - status: RunStatus - """Current factory run status.""" - - total_spawned_agent_count: int - """Total direct factory agents spawned across all attempts.""" - - updated_at: int - """Epoch milliseconds when the durable run was last updated.""" - - active_segment_started_at: int | None = None - """Epoch milliseconds when the current active segment started, or null while inactive.""" - - approved: FactoryDeclaredLimits | None = None - """Approved effective resource ceilings, or null until approved.""" - - completed_at: int | None = None - """Epoch milliseconds when the run completed, or null while nonterminal.""" - - current_phase: FactoryCurrentPhase | None = None - """Current phase identity, or null before any phase is entered.""" - - started_at: int | None = None - """Epoch milliseconds when execution first started, or null before start.""" - - terminal: FactoryRunTerminal | None = None - """Terminal run outcome, or null while nonterminal.""" - - @staticmethod - def from_dict(obj: Any) -> 'FactoryRunDetail': - assert isinstance(obj, dict) - agents = from_list(FactoryAgentSummary.from_dict, obj.get("agents")) - can_resume = from_bool(obj.get("canResume")) - consumed = FactoryRunConsumed.from_dict(obj.get("consumed")) - created_at = from_int(obj.get("createdAt")) - declared_limits = FactoryDeclaredLimits.from_dict(obj.get("declaredLimits")) - declared_phase_count = from_int(obj.get("declaredPhaseCount")) - description = from_str(obj.get("description")) - factory_name = from_str(obj.get("factoryName")) - live_agent_count = from_int(obj.get("liveAgentCount")) - observed_at = from_int(obj.get("observedAt")) - phases = from_list(FactoryPhaseObservation.from_dict, obj.get("phases")) - progress = FactoryProgressPage.from_dict(obj.get("progress")) - revision = from_int(obj.get("revision")) - run_id = from_str(obj.get("runId")) - status = RunStatus(obj.get("status")) - total_spawned_agent_count = from_int(obj.get("totalSpawnedAgentCount")) - updated_at = from_int(obj.get("updatedAt")) - active_segment_started_at = from_union([from_int, from_none], obj.get("activeSegmentStartedAt")) - approved = from_union([FactoryDeclaredLimits.from_dict, from_none], obj.get("approved")) - completed_at = from_union([from_int, from_none], obj.get("completedAt")) - current_phase = from_union([FactoryCurrentPhase.from_dict, from_none], obj.get("currentPhase")) - started_at = from_union([from_int, from_none], obj.get("startedAt")) - terminal = from_union([FactoryRunTerminal.from_dict, from_none], obj.get("terminal")) - return FactoryRunDetail(agents, can_resume, consumed, created_at, declared_limits, declared_phase_count, description, factory_name, live_agent_count, observed_at, phases, progress, revision, run_id, status, total_spawned_agent_count, updated_at, active_segment_started_at, approved, completed_at, current_phase, started_at, terminal) - - def to_dict(self) -> dict: - result: dict = {} - result["agents"] = from_list(lambda x: to_class(FactoryAgentSummary, x), self.agents) - result["canResume"] = from_bool(self.can_resume) - result["consumed"] = to_class(FactoryRunConsumed, self.consumed) - result["createdAt"] = from_int(self.created_at) - result["declaredLimits"] = to_class(FactoryDeclaredLimits, self.declared_limits) - result["declaredPhaseCount"] = from_int(self.declared_phase_count) - result["description"] = from_str(self.description) - result["factoryName"] = from_str(self.factory_name) - result["liveAgentCount"] = from_int(self.live_agent_count) - result["observedAt"] = from_int(self.observed_at) - result["phases"] = from_list(lambda x: to_class(FactoryPhaseObservation, x), self.phases) - result["progress"] = to_class(FactoryProgressPage, self.progress) - result["revision"] = from_int(self.revision) - result["runId"] = from_str(self.run_id) - result["status"] = to_enum(RunStatus, self.status) - result["totalSpawnedAgentCount"] = from_int(self.total_spawned_agent_count) - result["updatedAt"] = from_int(self.updated_at) - result["activeSegmentStartedAt"] = from_union([from_int, from_none], self.active_segment_started_at) - result["approved"] = from_union([lambda x: to_class(FactoryDeclaredLimits, x), from_none], self.approved) - result["completedAt"] = from_union([from_int, from_none], self.completed_at) - result["currentPhase"] = from_union([lambda x: to_class(FactoryCurrentPhase, x), from_none], self.current_phase) - result["startedAt"] = from_union([from_int, from_none], self.started_at) - result["terminal"] = from_union([lambda x: to_class(FactoryRunTerminal, x), from_none], self.terminal) - return result - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class GhCLIAuthInfo: @@ -40018,6 +38955,16 @@ class ModelApplyStartupOverlayRequest: device_managed_model: str | None = None """Model required by device-managed policy, when configured.""" + managed_context_tier: str | None = None + """Context tier paired with the effective organization-managed model. Applies only when that + concrete managed model is selected; it is ignored for Auto and for CLI, resume, or user + overrides. + """ + managed_reasoning_effort: str | None = None + """Reasoning effort paired with the effective organization-managed model. Applies only when + that concrete managed model is selected; it is ignored for Auto and for CLI, resume, or + user overrides. + """ policy_helper_model: str | None = None """Startup default model from the enterprise policy helper, when configured. Weakest of the managed sources: it applies only when neither device nor server policy names a model, and @@ -40046,13 +38993,15 @@ def from_dict(obj: Any) -> 'ModelApplyStartupOverlayRequest': cli_model = from_union([from_str, from_none], obj.get("cliModel")) deferred_resume = from_union([from_bool, from_none], obj.get("deferredResume")) device_managed_model = from_union([from_str, from_none], obj.get("deviceManagedModel")) + managed_context_tier = from_union([from_str, from_none], obj.get("managedContextTier")) + managed_reasoning_effort = from_union([from_str, from_none], obj.get("managedReasoningEffort")) policy_helper_model = from_union([from_str, from_none], obj.get("policyHelperModel")) repo_auto_tier = from_union([from_str, from_none], obj.get("repoAutoTier")) repo_context_tier = from_union([from_str, from_none], obj.get("repoContextTier")) repo_model = from_union([from_str, from_none], obj.get("repoModel")) repo_reasoning_effort = from_union([from_str, from_none], obj.get("repoReasoningEffort")) server_managed_model = from_union([from_str, from_none], obj.get("serverManagedModel")) - return ModelApplyStartupOverlayRequest(auto_tier, cli_model, deferred_resume, device_managed_model, policy_helper_model, repo_auto_tier, repo_context_tier, repo_model, repo_reasoning_effort, server_managed_model) + return ModelApplyStartupOverlayRequest(auto_tier, cli_model, deferred_resume, device_managed_model, managed_context_tier, managed_reasoning_effort, policy_helper_model, repo_auto_tier, repo_context_tier, repo_model, repo_reasoning_effort, server_managed_model) def to_dict(self) -> dict: result: dict = {} @@ -40064,6 +39013,10 @@ def to_dict(self) -> dict: result["deferredResume"] = from_union([from_bool, from_none], self.deferred_resume) if self.device_managed_model is not None: result["deviceManagedModel"] = from_union([from_str, from_none], self.device_managed_model) + if self.managed_context_tier is not None: + result["managedContextTier"] = from_union([from_str, from_none], self.managed_context_tier) + if self.managed_reasoning_effort is not None: + result["managedReasoningEffort"] = from_union([from_str, from_none], self.managed_reasoning_effort) if self.policy_helper_model is not None: result["policyHelperModel"] = from_union([from_str, from_none], self.policy_helper_model) if self.repo_auto_tier is not None: @@ -41625,6 +40578,9 @@ class SlashCommandSetModelResult: model: str """Model selected by the command.""" + auto_tier: AutoTier | None = None + """Auto routing profile selected by the command, when the model is Auto.""" + reasoning_effort: str | None = None """Reasoning effort selected for the model.""" @@ -41647,18 +40603,21 @@ class SlashCommandSetModelResult: def from_dict(obj: Any) -> 'SlashCommandSetModelResult': assert isinstance(obj, dict) model = from_str(obj.get("model")) + auto_tier = from_union([AutoTier, from_none], obj.get("autoTier")) reasoning_effort = from_union([from_str, from_none], obj.get("reasoningEffort")) repo_scope = from_union([from_str, from_none], obj.get("repoScope")) revert_on_cancel = from_union([lambda x: from_dict(lambda x: x, x), from_none], obj.get("revertOnCancel")) runtime_settings_changed = from_union([from_bool, from_none], obj.get("runtimeSettingsChanged")) scope = from_union([from_str, from_none], obj.get("scope")) warning = from_union([from_str, from_none], obj.get("warning")) - return SlashCommandSetModelResult(model, reasoning_effort, repo_scope, revert_on_cancel, runtime_settings_changed, scope, warning) + return SlashCommandSetModelResult(model, auto_tier, reasoning_effort, repo_scope, revert_on_cancel, runtime_settings_changed, scope, warning) def to_dict(self) -> dict: result: dict = {} result["kind"] = self.kind result["model"] = from_str(self.model) + if self.auto_tier is not None: + result["autoTier"] = from_union([lambda x: to_enum(AutoTier, x), from_none], self.auto_tier) if self.reasoning_effort is not None: result["reasoningEffort"] = from_union([from_str, from_none], self.reasoning_effort) if self.repo_scope is not None: @@ -42113,7 +41072,7 @@ class WorkflowRunDetail: run_id: str """Workflow run identifier.""" - status: RunStatus + status: WorkflowRunStatus """Current workflow run status.""" total_spawned_agent_count: int @@ -42159,7 +41118,7 @@ def from_dict(obj: Any) -> 'WorkflowRunDetail': progress = WorkflowProgressPage.from_dict(obj.get("progress")) revision = from_int(obj.get("revision")) run_id = from_str(obj.get("runId")) - status = RunStatus(obj.get("status")) + status = WorkflowRunStatus(obj.get("status")) total_spawned_agent_count = from_int(obj.get("totalSpawnedAgentCount")) updated_at = from_int(obj.get("updatedAt")) workflow_name = from_str(obj.get("workflowName")) @@ -42186,7 +41145,7 @@ def to_dict(self) -> dict: result["progress"] = to_class(WorkflowProgressPage, self.progress) result["revision"] = from_int(self.revision) result["runId"] = from_str(self.run_id) - result["status"] = to_enum(RunStatus, self.status) + result["status"] = to_enum(WorkflowRunStatus, self.status) result["totalSpawnedAgentCount"] = from_int(self.total_spawned_agent_count) result["updatedAt"] = from_int(self.updated_at) result["workflowName"] = from_str(self.workflow_name) @@ -42208,11 +41167,16 @@ class RPC: account_get_current_auth_result: AccountGetCurrentAuthResult account_get_quota_request: AccountGetQuotaRequest account_get_quota_result: AccountGetQuotaResult + account_kind: AccountKind account_login_request: AccountLoginRequest account_login_result: AccountLoginResult account_logout_request: AccountLogoutRequest account_logout_result: AccountLogoutResult account_quota_snapshot: AccountQuotaSnapshot + accounts_enumerate_request: AccountsEnumerateRequest + accounts_get_request: AccountsGetRequest + accounts_set_request: AccountsSetRequest + account_status: AccountStatus adaptive_thinking_support: AdaptiveThinkingSupport agent_discovery_path: AgentDiscoveryPath agent_discovery_path_list: AgentDiscoveryPathList @@ -42245,11 +41209,25 @@ class RPC: agent_set_prompt_request: AgentSetPromptRequest agents_get_discovery_paths_request: AgentsGetDiscoveryPathsRequest api_key_auth_info: APIKeyAuthInfo + auth_enumerate_query: AuthEnumerateQuery + auth_enumerate_value: AuthEnumerateValue auth_identity: AuthIdentity auth_info: AuthInfo auth_info_type: AuthInfoType + auth_login_advance_request: AuthLoginAdvanceRequest + auth_login_begin_request: AuthLoginBeginRequest + auth_login_begun: AuthLoginBegun + auth_login_cancel_request: AuthLoginCancelRequest + auth_login_result_dto: AuthLoginResultDto + auth_login_result_status: AuthLoginResultStatus + auth_login_step: AuthLoginStep + auth_read_query: AuthReadQuery + auth_read_value: AuthReadValue + auth_status_dto: AuthStatusDto auth_validation_error: AuthValidationError auth_validation_errors: list[AuthValidationError] + auth_write: AuthWrite + auth_write_result: AuthWriteResult autopilot_objective_credit_limit: AutopilotObjectiveCreditLimit autopilot_objective_get_state_result: AutopilotObjectiveGetStateResult autopilot_objective_state: AutopilotObjectiveState @@ -42501,52 +41479,6 @@ class RPC: external_tool_text_result_for_llm_content_shell_exit: ExternalToolTextResultForLlmContentShellExit external_tool_text_result_for_llm_content_terminal: ExternalToolTextResultForLlmContentTerminal external_tool_text_result_for_llm_content_text: ExternalToolTextResultForLlmContentText - factory_abort_request: FactoryAbortRequest - factory_ack_result: FactoryACKResult - factory_agent_options: FactoryAgentOptions - factory_agent_request: FactoryAgentRequest - factory_agent_result: FactoryAgentResult - factory_agent_summary: FactoryAgentSummary - factory_cancel_request: FactoryCancelRequest - factory_current_phase: FactoryCurrentPhase - factory_declared_limits: FactoryDeclaredLimits - factory_durable_operation: DurableOperation - factory_execute_request: FactoryExecuteRequest - factory_execute_result: FactoryExecuteResult - factory_get_run_progress_request: FactoryGetRunProgressRequest - factory_get_run_request: FactoryGetRunRequest - factory_journal_get_request: FactoryJournalGetRequest - factory_journal_get_result: FactoryJournalGetResult - factory_journal_put_request: FactoryJournalPutRequest - factory_list_runs_request: FactoryListRunsRequest - factory_list_runs_result: FactoryListRunsResult - factory_log_line: FactoryLogLine - factory_log_line_kind: LogLineKind - factory_log_request: FactoryLogRequest - factory_pause_checkpoint_action: PauseCheckpointAction - factory_pause_checkpoint_request: FactoryPauseCheckpointRequest - factory_pause_checkpoint_result: FactoryPauseCheckpointResult - factory_pause_info: FactoryPauseInfo - factory_pause_request: FactoryPauseRequest - factory_phase_observation: FactoryPhaseObservation - factory_phase_status: PhaseStatus - factory_progress_line: FactoryProgressLine - factory_progress_page: FactoryProgressPage - factory_resume_request: FactoryResumeRequest - factory_resume_result: FactoryResumeResult - factory_run_consumed: FactoryRunConsumed - factory_run_detail: FactoryRunDetail - factory_run_failure: FactoryRunFailure - factory_run_failure_kind: RunFailureKind - factory_run_limits: FactoryRunLimits - factory_run_request: FactoryRunRequest - factory_run_result: FactoryRunResult - factory_run_status: RunStatus - factory_run_summary: FactoryRunSummary - factory_run_terminal: FactoryRunTerminal - factory_tool_resume_request: _FactoryToolResumeRequest - factory_tool_run_options: _FactoryToolRunOptions - factory_tool_run_request: _FactoryToolRunRequest filter_mapping: dict[str, ContentFilterMode] | ContentFilterMode fleet_start_request: FleetStartRequest fleet_start_result: FleetStartResult @@ -42624,6 +41556,7 @@ class RPC: llm_inference_http_response_start_result: LlmInferenceHTTPResponseStartResult llm_inference_set_provider_result: LlmInferenceSetProviderResult local_session_metadata_value: LocalSessionMetadataValue + login_provider_kind: LoginProviderKind log_request: LogRequest log_result: LogResult lsp_initialize_request: LspInitializeRequest @@ -42879,11 +41812,11 @@ class RPC: permission_decision_approve_for_location_approval_extension_env_access: PermissionDecisionApproveForLocationApprovalExtensionEnvAccess permission_decision_approve_for_location_approval_extension_management: PermissionDecisionApproveForLocationApprovalExtensionManagement permission_decision_approve_for_location_approval_extension_permission_access: PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess - permission_decision_approve_for_location_approval_factory: PermissionDecisionApproveForLocationApprovalFactory permission_decision_approve_for_location_approval_mcp: PermissionDecisionApproveForLocationApprovalMCP permission_decision_approve_for_location_approval_mcp_sampling: PermissionDecisionApproveForLocationApprovalMCPSampling permission_decision_approve_for_location_approval_memory: PermissionDecisionApproveForLocationApprovalMemory permission_decision_approve_for_location_approval_read: PermissionDecisionApproveForLocationApprovalRead + permission_decision_approve_for_location_approval_workflow: PermissionDecisionApproveForLocationApprovalWorkflow permission_decision_approve_for_location_approval_write: PermissionDecisionApproveForLocationApprovalWrite permission_decision_approve_for_session: PermissionDecisionApproveForSession permission_decision_approve_for_session_approval: PermissionDecisionApproveForSessionApproval @@ -42892,11 +41825,11 @@ class RPC: permission_decision_approve_for_session_approval_extension_env_access: PermissionDecisionApproveForSessionApprovalExtensionEnvAccess permission_decision_approve_for_session_approval_extension_management: PermissionDecisionApproveForSessionApprovalExtensionManagement permission_decision_approve_for_session_approval_extension_permission_access: PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess - permission_decision_approve_for_session_approval_factory: PermissionDecisionApproveForSessionApprovalFactory permission_decision_approve_for_session_approval_mcp: PermissionDecisionApproveForSessionApprovalMCP permission_decision_approve_for_session_approval_mcp_sampling: PermissionDecisionApproveForSessionApprovalMCPSampling permission_decision_approve_for_session_approval_memory: PermissionDecisionApproveForSessionApprovalMemory permission_decision_approve_for_session_approval_read: PermissionDecisionApproveForSessionApprovalRead + permission_decision_approve_for_session_approval_workflow: PermissionDecisionApproveForSessionApprovalWorkflow permission_decision_approve_for_session_approval_write: PermissionDecisionApproveForSessionApprovalWrite permission_decision_approve_once: PermissionDecisionApproveOnce permission_decision_approve_permanently: PermissionDecisionApprovePermanently @@ -42946,11 +41879,11 @@ class RPC: permissions_locations_add_tool_approval_details_extension_env_access: PermissionsLocationsAddToolApprovalDetailsExtensionEnvAccess permissions_locations_add_tool_approval_details_extension_management: PermissionsLocationsAddToolApprovalDetailsExtensionManagement permissions_locations_add_tool_approval_details_extension_permission_access: PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess - permissions_locations_add_tool_approval_details_factory: PermissionsLocationsAddToolApprovalDetailsFactory permissions_locations_add_tool_approval_details_mcp: PermissionsLocationsAddToolApprovalDetailsMCP permissions_locations_add_tool_approval_details_mcp_sampling: PermissionsLocationsAddToolApprovalDetailsMCPSampling permissions_locations_add_tool_approval_details_memory: PermissionsLocationsAddToolApprovalDetailsMemory permissions_locations_add_tool_approval_details_read: PermissionsLocationsAddToolApprovalDetailsRead + permissions_locations_add_tool_approval_details_workflow: PermissionsLocationsAddToolApprovalDetailsWorkflow permissions_locations_add_tool_approval_details_write: PermissionsLocationsAddToolApprovalDetailsWrite permissions_locations_add_tool_approval_result: PermissionsLocationsAddToolApprovalResult permissions_modify_rules_params: PermissionsModifyRulesParams @@ -43020,6 +41953,7 @@ class RPC: provider_config_transport: ProviderTransport provider_config_type: ProviderType provider_config_wire_api: ProviderWireAPI + provider_descriptor: ProviderDescriptor provider_endpoint: ProviderEndpoint provider_endpoint_transport: ProviderTransport provider_endpoint_type: ProviderType @@ -43112,7 +42046,6 @@ class RPC: remote_session_mode: RemoteSessionMode remote_session_repository: RemoteSessionRepository response_format: ResponseFormat - run_options: RunOptions sandbox_config: SandboxConfig sandbox_config_auth: SandboxConfigAuth sandbox_config_source: _SandboxConfigSource @@ -43170,7 +42103,6 @@ class RPC: session_context: SessionContext session_context_host_type: HostType session_enrich_metadata_result: SessionEnrichMetadataResult - session_factory_pause_at_checkpoint_result: SessionFactoryPauseAtCheckpointResult session_fs_append_file_request: SessionFSAppendFileRequest session_fs_error: SessionFSError session_fs_error_code: SessionFSErrorCode @@ -43514,7 +42446,7 @@ class RPC: workflow_cancel_request: WorkflowCancelRequest workflow_current_phase: WorkflowCurrentPhase workflow_declared_limits: WorkflowDeclaredLimits - workflow_durable_operation: DurableOperation + workflow_durable_operation: WorkflowDurableOperation workflow_execute_request: WorkflowExecuteRequest workflow_execute_result: WorkflowExecuteResult workflow_get_run_progress_request: WorkflowGetRunProgressRequest @@ -43525,15 +42457,15 @@ class RPC: workflow_list_runs_request: WorkflowListRunsRequest workflow_list_runs_result: WorkflowListRunsResult workflow_log_line: WorkflowLogLine - workflow_log_line_kind: LogLineKind + workflow_log_line_kind: WorkflowLogLineKind workflow_log_request: WorkflowLogRequest - workflow_pause_checkpoint_action: PauseCheckpointAction + workflow_pause_checkpoint_action: WorkflowPauseCheckpointAction workflow_pause_checkpoint_request: WorkflowPauseCheckpointRequest workflow_pause_checkpoint_result: WorkflowPauseCheckpointResult workflow_pause_info: WorkflowPauseInfo workflow_pause_request: WorkflowPauseRequest workflow_phase_observation: WorkflowPhaseObservation - workflow_phase_status: PhaseStatus + workflow_phase_status: WorkflowPhaseStatus workflow_progress_line: WorkflowProgressLine workflow_progress_page: WorkflowProgressPage workflow_resume_request: WorkflowResumeRequest @@ -43541,12 +42473,12 @@ class RPC: workflow_run_consumed: WorkflowRunConsumed workflow_run_detail: WorkflowRunDetail workflow_run_failure: WorkflowRunFailure - workflow_run_failure_kind: RunFailureKind + workflow_run_failure_kind: WorkflowRunFailureKind workflow_run_limits: WorkflowRunLimits workflow_run_options: WorkflowRunOptions workflow_run_request: WorkflowRunRequest workflow_run_result: WorkflowRunResult - workflow_run_status: RunStatus + workflow_run_status: WorkflowRunStatus workflow_run_summary: WorkflowRunSummary workflow_run_terminal: WorkflowRunTerminal workflow_tool_resume_request: _WorkflowToolResumeRequest @@ -43603,11 +42535,16 @@ def from_dict(obj: Any) -> 'RPC': account_get_current_auth_result = AccountGetCurrentAuthResult.from_dict(obj.get("AccountGetCurrentAuthResult")) account_get_quota_request = AccountGetQuotaRequest.from_dict(obj.get("AccountGetQuotaRequest")) account_get_quota_result = AccountGetQuotaResult.from_dict(obj.get("AccountGetQuotaResult")) + account_kind = AccountKind(obj.get("AccountKind")) account_login_request = AccountLoginRequest.from_dict(obj.get("AccountLoginRequest")) account_login_result = AccountLoginResult.from_dict(obj.get("AccountLoginResult")) account_logout_request = AccountLogoutRequest.from_dict(obj.get("AccountLogoutRequest")) account_logout_result = AccountLogoutResult.from_dict(obj.get("AccountLogoutResult")) account_quota_snapshot = AccountQuotaSnapshot.from_dict(obj.get("AccountQuotaSnapshot")) + accounts_enumerate_request = AccountsEnumerateRequest.from_dict(obj.get("AccountsEnumerateRequest")) + accounts_get_request = AccountsGetRequest.from_dict(obj.get("AccountsGetRequest")) + accounts_set_request = AccountsSetRequest.from_dict(obj.get("AccountsSetRequest")) + account_status = AccountStatus.from_dict(obj.get("AccountStatus")) adaptive_thinking_support = AdaptiveThinkingSupport(obj.get("AdaptiveThinkingSupport")) agent_discovery_path = AgentDiscoveryPath.from_dict(obj.get("AgentDiscoveryPath")) agent_discovery_path_list = AgentDiscoveryPathList.from_dict(obj.get("AgentDiscoveryPathList")) @@ -43640,11 +42577,25 @@ def from_dict(obj: Any) -> 'RPC': agent_set_prompt_request = AgentSetPromptRequest.from_dict(obj.get("AgentSetPromptRequest")) agents_get_discovery_paths_request = AgentsGetDiscoveryPathsRequest.from_dict(obj.get("AgentsGetDiscoveryPathsRequest")) api_key_auth_info = APIKeyAuthInfo.from_dict(obj.get("ApiKeyAuthInfo")) + auth_enumerate_query = AuthEnumerateQuery.from_dict(obj.get("AuthEnumerateQuery")) + auth_enumerate_value = AuthEnumerateValue.from_dict(obj.get("AuthEnumerateValue")) auth_identity = AuthIdentity.from_dict(obj.get("AuthIdentity")) auth_info = _load_AuthInfo(obj.get("AuthInfo")) auth_info_type = AuthInfoType(obj.get("AuthInfoType")) + auth_login_advance_request = AuthLoginAdvanceRequest.from_dict(obj.get("AuthLoginAdvanceRequest")) + auth_login_begin_request = AuthLoginBeginRequest.from_dict(obj.get("AuthLoginBeginRequest")) + auth_login_begun = AuthLoginBegun.from_dict(obj.get("AuthLoginBegun")) + auth_login_cancel_request = AuthLoginCancelRequest.from_dict(obj.get("AuthLoginCancelRequest")) + auth_login_result_dto = AuthLoginResultDto.from_dict(obj.get("AuthLoginResultDto")) + auth_login_result_status = AuthLoginResultStatus(obj.get("AuthLoginResultStatus")) + auth_login_step = AuthLoginStep.from_dict(obj.get("AuthLoginStep")) + auth_read_query = AuthReadQuery.from_dict(obj.get("AuthReadQuery")) + auth_read_value = AuthReadValue.from_dict(obj.get("AuthReadValue")) + auth_status_dto = AuthStatusDto.from_dict(obj.get("AuthStatusDto")) auth_validation_error = AuthValidationError.from_dict(obj.get("AuthValidationError")) auth_validation_errors = from_list(AuthValidationError.from_dict, obj.get("AuthValidationErrors")) + auth_write = AuthWrite.from_dict(obj.get("AuthWrite")) + auth_write_result = AuthWriteResult.from_dict(obj.get("AuthWriteResult")) autopilot_objective_credit_limit = AutopilotObjectiveCreditLimit.from_dict(obj.get("AutopilotObjectiveCreditLimit")) autopilot_objective_get_state_result = AutopilotObjectiveGetStateResult.from_dict(obj.get("AutopilotObjectiveGetStateResult")) autopilot_objective_state = AutopilotObjectiveState.from_dict(obj.get("AutopilotObjectiveState")) @@ -43896,52 +42847,6 @@ def from_dict(obj: Any) -> 'RPC': external_tool_text_result_for_llm_content_shell_exit = ExternalToolTextResultForLlmContentShellExit.from_dict(obj.get("ExternalToolTextResultForLlmContentShellExit")) external_tool_text_result_for_llm_content_terminal = ExternalToolTextResultForLlmContentTerminal.from_dict(obj.get("ExternalToolTextResultForLlmContentTerminal")) external_tool_text_result_for_llm_content_text = ExternalToolTextResultForLlmContentText.from_dict(obj.get("ExternalToolTextResultForLlmContentText")) - factory_abort_request = FactoryAbortRequest.from_dict(obj.get("FactoryAbortRequest")) - factory_ack_result = FactoryACKResult.from_dict(obj.get("FactoryAckResult")) - factory_agent_options = FactoryAgentOptions.from_dict(obj.get("FactoryAgentOptions")) - factory_agent_request = FactoryAgentRequest.from_dict(obj.get("FactoryAgentRequest")) - factory_agent_result = FactoryAgentResult.from_dict(obj.get("FactoryAgentResult")) - factory_agent_summary = FactoryAgentSummary.from_dict(obj.get("FactoryAgentSummary")) - factory_cancel_request = FactoryCancelRequest.from_dict(obj.get("FactoryCancelRequest")) - factory_current_phase = FactoryCurrentPhase.from_dict(obj.get("FactoryCurrentPhase")) - factory_declared_limits = FactoryDeclaredLimits.from_dict(obj.get("FactoryDeclaredLimits")) - factory_durable_operation = DurableOperation(obj.get("FactoryDurableOperation")) - factory_execute_request = FactoryExecuteRequest.from_dict(obj.get("FactoryExecuteRequest")) - factory_execute_result = FactoryExecuteResult.from_dict(obj.get("FactoryExecuteResult")) - factory_get_run_progress_request = FactoryGetRunProgressRequest.from_dict(obj.get("FactoryGetRunProgressRequest")) - factory_get_run_request = FactoryGetRunRequest.from_dict(obj.get("FactoryGetRunRequest")) - factory_journal_get_request = FactoryJournalGetRequest.from_dict(obj.get("FactoryJournalGetRequest")) - factory_journal_get_result = FactoryJournalGetResult.from_dict(obj.get("FactoryJournalGetResult")) - factory_journal_put_request = FactoryJournalPutRequest.from_dict(obj.get("FactoryJournalPutRequest")) - factory_list_runs_request = FactoryListRunsRequest.from_dict(obj.get("FactoryListRunsRequest")) - factory_list_runs_result = FactoryListRunsResult.from_dict(obj.get("FactoryListRunsResult")) - factory_log_line = FactoryLogLine.from_dict(obj.get("FactoryLogLine")) - factory_log_line_kind = LogLineKind(obj.get("FactoryLogLineKind")) - factory_log_request = FactoryLogRequest.from_dict(obj.get("FactoryLogRequest")) - factory_pause_checkpoint_action = PauseCheckpointAction(obj.get("FactoryPauseCheckpointAction")) - factory_pause_checkpoint_request = FactoryPauseCheckpointRequest.from_dict(obj.get("FactoryPauseCheckpointRequest")) - factory_pause_checkpoint_result = FactoryPauseCheckpointResult.from_dict(obj.get("FactoryPauseCheckpointResult")) - factory_pause_info = FactoryPauseInfo.from_dict(obj.get("FactoryPauseInfo")) - factory_pause_request = FactoryPauseRequest.from_dict(obj.get("FactoryPauseRequest")) - factory_phase_observation = FactoryPhaseObservation.from_dict(obj.get("FactoryPhaseObservation")) - factory_phase_status = PhaseStatus(obj.get("FactoryPhaseStatus")) - factory_progress_line = FactoryProgressLine.from_dict(obj.get("FactoryProgressLine")) - factory_progress_page = FactoryProgressPage.from_dict(obj.get("FactoryProgressPage")) - factory_resume_request = FactoryResumeRequest.from_dict(obj.get("FactoryResumeRequest")) - factory_resume_result = FactoryResumeResult.from_dict(obj.get("FactoryResumeResult")) - factory_run_consumed = FactoryRunConsumed.from_dict(obj.get("FactoryRunConsumed")) - factory_run_detail = FactoryRunDetail.from_dict(obj.get("FactoryRunDetail")) - factory_run_failure = FactoryRunFailure.from_dict(obj.get("FactoryRunFailure")) - factory_run_failure_kind = RunFailureKind(obj.get("FactoryRunFailureKind")) - factory_run_limits = FactoryRunLimits.from_dict(obj.get("FactoryRunLimits")) - factory_run_request = FactoryRunRequest.from_dict(obj.get("FactoryRunRequest")) - factory_run_result = FactoryRunResult.from_dict(obj.get("FactoryRunResult")) - factory_run_status = RunStatus(obj.get("FactoryRunStatus")) - factory_run_summary = FactoryRunSummary.from_dict(obj.get("FactoryRunSummary")) - factory_run_terminal = FactoryRunTerminal.from_dict(obj.get("FactoryRunTerminal")) - factory_tool_resume_request = _FactoryToolResumeRequest.from_dict(obj.get("FactoryToolResumeRequest")) - factory_tool_run_options = _FactoryToolRunOptions.from_dict(obj.get("FactoryToolRunOptions")) - factory_tool_run_request = _FactoryToolRunRequest.from_dict(obj.get("FactoryToolRunRequest")) filter_mapping = from_union([lambda x: from_dict(ContentFilterMode, x), ContentFilterMode], obj.get("FilterMapping")) fleet_start_request = FleetStartRequest.from_dict(obj.get("FleetStartRequest")) fleet_start_result = FleetStartResult.from_dict(obj.get("FleetStartResult")) @@ -44019,6 +42924,7 @@ def from_dict(obj: Any) -> 'RPC': llm_inference_http_response_start_result = LlmInferenceHTTPResponseStartResult.from_dict(obj.get("LlmInferenceHttpResponseStartResult")) llm_inference_set_provider_result = LlmInferenceSetProviderResult.from_dict(obj.get("LlmInferenceSetProviderResult")) local_session_metadata_value = LocalSessionMetadataValue.from_dict(obj.get("LocalSessionMetadataValue")) + login_provider_kind = LoginProviderKind(obj.get("LoginProviderKind")) log_request = LogRequest.from_dict(obj.get("LogRequest")) log_result = LogResult.from_dict(obj.get("LogResult")) lsp_initialize_request = LspInitializeRequest.from_dict(obj.get("LspInitializeRequest")) @@ -44274,11 +43180,11 @@ def from_dict(obj: Any) -> 'RPC': permission_decision_approve_for_location_approval_extension_env_access = PermissionDecisionApproveForLocationApprovalExtensionEnvAccess.from_dict(obj.get("PermissionDecisionApproveForLocationApprovalExtensionEnvAccess")) permission_decision_approve_for_location_approval_extension_management = PermissionDecisionApproveForLocationApprovalExtensionManagement.from_dict(obj.get("PermissionDecisionApproveForLocationApprovalExtensionManagement")) permission_decision_approve_for_location_approval_extension_permission_access = PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess.from_dict(obj.get("PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess")) - permission_decision_approve_for_location_approval_factory = PermissionDecisionApproveForLocationApprovalFactory.from_dict(obj.get("PermissionDecisionApproveForLocationApprovalFactory")) permission_decision_approve_for_location_approval_mcp = PermissionDecisionApproveForLocationApprovalMCP.from_dict(obj.get("PermissionDecisionApproveForLocationApprovalMcp")) permission_decision_approve_for_location_approval_mcp_sampling = PermissionDecisionApproveForLocationApprovalMCPSampling.from_dict(obj.get("PermissionDecisionApproveForLocationApprovalMcpSampling")) permission_decision_approve_for_location_approval_memory = PermissionDecisionApproveForLocationApprovalMemory.from_dict(obj.get("PermissionDecisionApproveForLocationApprovalMemory")) permission_decision_approve_for_location_approval_read = PermissionDecisionApproveForLocationApprovalRead.from_dict(obj.get("PermissionDecisionApproveForLocationApprovalRead")) + permission_decision_approve_for_location_approval_workflow = PermissionDecisionApproveForLocationApprovalWorkflow.from_dict(obj.get("PermissionDecisionApproveForLocationApprovalWorkflow")) permission_decision_approve_for_location_approval_write = PermissionDecisionApproveForLocationApprovalWrite.from_dict(obj.get("PermissionDecisionApproveForLocationApprovalWrite")) permission_decision_approve_for_session = PermissionDecisionApproveForSession.from_dict(obj.get("PermissionDecisionApproveForSession")) permission_decision_approve_for_session_approval = _load_PermissionDecisionApproveForSessionApproval(obj.get("PermissionDecisionApproveForSessionApproval")) @@ -44287,11 +43193,11 @@ def from_dict(obj: Any) -> 'RPC': permission_decision_approve_for_session_approval_extension_env_access = PermissionDecisionApproveForSessionApprovalExtensionEnvAccess.from_dict(obj.get("PermissionDecisionApproveForSessionApprovalExtensionEnvAccess")) permission_decision_approve_for_session_approval_extension_management = PermissionDecisionApproveForSessionApprovalExtensionManagement.from_dict(obj.get("PermissionDecisionApproveForSessionApprovalExtensionManagement")) permission_decision_approve_for_session_approval_extension_permission_access = PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess.from_dict(obj.get("PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess")) - permission_decision_approve_for_session_approval_factory = PermissionDecisionApproveForSessionApprovalFactory.from_dict(obj.get("PermissionDecisionApproveForSessionApprovalFactory")) permission_decision_approve_for_session_approval_mcp = PermissionDecisionApproveForSessionApprovalMCP.from_dict(obj.get("PermissionDecisionApproveForSessionApprovalMcp")) permission_decision_approve_for_session_approval_mcp_sampling = PermissionDecisionApproveForSessionApprovalMCPSampling.from_dict(obj.get("PermissionDecisionApproveForSessionApprovalMcpSampling")) permission_decision_approve_for_session_approval_memory = PermissionDecisionApproveForSessionApprovalMemory.from_dict(obj.get("PermissionDecisionApproveForSessionApprovalMemory")) permission_decision_approve_for_session_approval_read = PermissionDecisionApproveForSessionApprovalRead.from_dict(obj.get("PermissionDecisionApproveForSessionApprovalRead")) + permission_decision_approve_for_session_approval_workflow = PermissionDecisionApproveForSessionApprovalWorkflow.from_dict(obj.get("PermissionDecisionApproveForSessionApprovalWorkflow")) permission_decision_approve_for_session_approval_write = PermissionDecisionApproveForSessionApprovalWrite.from_dict(obj.get("PermissionDecisionApproveForSessionApprovalWrite")) permission_decision_approve_once = PermissionDecisionApproveOnce.from_dict(obj.get("PermissionDecisionApproveOnce")) permission_decision_approve_permanently = PermissionDecisionApprovePermanently.from_dict(obj.get("PermissionDecisionApprovePermanently")) @@ -44341,11 +43247,11 @@ def from_dict(obj: Any) -> 'RPC': permissions_locations_add_tool_approval_details_extension_env_access = PermissionsLocationsAddToolApprovalDetailsExtensionEnvAccess.from_dict(obj.get("PermissionsLocationsAddToolApprovalDetailsExtensionEnvAccess")) permissions_locations_add_tool_approval_details_extension_management = PermissionsLocationsAddToolApprovalDetailsExtensionManagement.from_dict(obj.get("PermissionsLocationsAddToolApprovalDetailsExtensionManagement")) permissions_locations_add_tool_approval_details_extension_permission_access = PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess.from_dict(obj.get("PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess")) - permissions_locations_add_tool_approval_details_factory = PermissionsLocationsAddToolApprovalDetailsFactory.from_dict(obj.get("PermissionsLocationsAddToolApprovalDetailsFactory")) permissions_locations_add_tool_approval_details_mcp = PermissionsLocationsAddToolApprovalDetailsMCP.from_dict(obj.get("PermissionsLocationsAddToolApprovalDetailsMcp")) permissions_locations_add_tool_approval_details_mcp_sampling = PermissionsLocationsAddToolApprovalDetailsMCPSampling.from_dict(obj.get("PermissionsLocationsAddToolApprovalDetailsMcpSampling")) permissions_locations_add_tool_approval_details_memory = PermissionsLocationsAddToolApprovalDetailsMemory.from_dict(obj.get("PermissionsLocationsAddToolApprovalDetailsMemory")) permissions_locations_add_tool_approval_details_read = PermissionsLocationsAddToolApprovalDetailsRead.from_dict(obj.get("PermissionsLocationsAddToolApprovalDetailsRead")) + permissions_locations_add_tool_approval_details_workflow = PermissionsLocationsAddToolApprovalDetailsWorkflow.from_dict(obj.get("PermissionsLocationsAddToolApprovalDetailsWorkflow")) permissions_locations_add_tool_approval_details_write = PermissionsLocationsAddToolApprovalDetailsWrite.from_dict(obj.get("PermissionsLocationsAddToolApprovalDetailsWrite")) permissions_locations_add_tool_approval_result = PermissionsLocationsAddToolApprovalResult.from_dict(obj.get("PermissionsLocationsAddToolApprovalResult")) permissions_modify_rules_params = PermissionsModifyRulesParams.from_dict(obj.get("PermissionsModifyRulesParams")) @@ -44415,6 +43321,7 @@ def from_dict(obj: Any) -> 'RPC': provider_config_transport = ProviderTransport(obj.get("ProviderConfigTransport")) provider_config_type = ProviderType(obj.get("ProviderConfigType")) provider_config_wire_api = ProviderWireAPI(obj.get("ProviderConfigWireApi")) + provider_descriptor = ProviderDescriptor.from_dict(obj.get("ProviderDescriptor")) provider_endpoint = ProviderEndpoint.from_dict(obj.get("ProviderEndpoint")) provider_endpoint_transport = ProviderTransport(obj.get("ProviderEndpointTransport")) provider_endpoint_type = ProviderType(obj.get("ProviderEndpointType")) @@ -44507,7 +43414,6 @@ def from_dict(obj: Any) -> 'RPC': remote_session_mode = RemoteSessionMode(obj.get("RemoteSessionMode")) remote_session_repository = RemoteSessionRepository.from_dict(obj.get("RemoteSessionRepository")) response_format = ResponseFormat.from_dict(obj.get("ResponseFormat")) - run_options = RunOptions.from_dict(obj.get("RunOptions")) sandbox_config = SandboxConfig.from_dict(obj.get("SandboxConfig")) sandbox_config_auth = SandboxConfigAuth.from_dict(obj.get("SandboxConfigAuth")) sandbox_config_source = _SandboxConfigSource(obj.get("SandboxConfigSource")) @@ -44565,7 +43471,6 @@ def from_dict(obj: Any) -> 'RPC': session_context = SessionContext.from_dict(obj.get("SessionContext")) session_context_host_type = HostType(obj.get("SessionContextHostType")) session_enrich_metadata_result = SessionEnrichMetadataResult.from_dict(obj.get("SessionEnrichMetadataResult")) - session_factory_pause_at_checkpoint_result = SessionFactoryPauseAtCheckpointResult.from_dict(obj.get("SessionFactoryPauseAtCheckpointResult")) session_fs_append_file_request = SessionFSAppendFileRequest.from_dict(obj.get("SessionFsAppendFileRequest")) session_fs_error = SessionFSError.from_dict(obj.get("SessionFsError")) session_fs_error_code = SessionFSErrorCode(obj.get("SessionFsErrorCode")) @@ -44909,7 +43814,7 @@ def from_dict(obj: Any) -> 'RPC': workflow_cancel_request = WorkflowCancelRequest.from_dict(obj.get("WorkflowCancelRequest")) workflow_current_phase = WorkflowCurrentPhase.from_dict(obj.get("WorkflowCurrentPhase")) workflow_declared_limits = WorkflowDeclaredLimits.from_dict(obj.get("WorkflowDeclaredLimits")) - workflow_durable_operation = DurableOperation(obj.get("WorkflowDurableOperation")) + workflow_durable_operation = WorkflowDurableOperation(obj.get("WorkflowDurableOperation")) workflow_execute_request = WorkflowExecuteRequest.from_dict(obj.get("WorkflowExecuteRequest")) workflow_execute_result = WorkflowExecuteResult.from_dict(obj.get("WorkflowExecuteResult")) workflow_get_run_progress_request = WorkflowGetRunProgressRequest.from_dict(obj.get("WorkflowGetRunProgressRequest")) @@ -44920,15 +43825,15 @@ def from_dict(obj: Any) -> 'RPC': workflow_list_runs_request = WorkflowListRunsRequest.from_dict(obj.get("WorkflowListRunsRequest")) workflow_list_runs_result = WorkflowListRunsResult.from_dict(obj.get("WorkflowListRunsResult")) workflow_log_line = WorkflowLogLine.from_dict(obj.get("WorkflowLogLine")) - workflow_log_line_kind = LogLineKind(obj.get("WorkflowLogLineKind")) + workflow_log_line_kind = WorkflowLogLineKind(obj.get("WorkflowLogLineKind")) workflow_log_request = WorkflowLogRequest.from_dict(obj.get("WorkflowLogRequest")) - workflow_pause_checkpoint_action = PauseCheckpointAction(obj.get("WorkflowPauseCheckpointAction")) + workflow_pause_checkpoint_action = WorkflowPauseCheckpointAction(obj.get("WorkflowPauseCheckpointAction")) workflow_pause_checkpoint_request = WorkflowPauseCheckpointRequest.from_dict(obj.get("WorkflowPauseCheckpointRequest")) workflow_pause_checkpoint_result = WorkflowPauseCheckpointResult.from_dict(obj.get("WorkflowPauseCheckpointResult")) workflow_pause_info = WorkflowPauseInfo.from_dict(obj.get("WorkflowPauseInfo")) workflow_pause_request = WorkflowPauseRequest.from_dict(obj.get("WorkflowPauseRequest")) workflow_phase_observation = WorkflowPhaseObservation.from_dict(obj.get("WorkflowPhaseObservation")) - workflow_phase_status = PhaseStatus(obj.get("WorkflowPhaseStatus")) + workflow_phase_status = WorkflowPhaseStatus(obj.get("WorkflowPhaseStatus")) workflow_progress_line = WorkflowProgressLine.from_dict(obj.get("WorkflowProgressLine")) workflow_progress_page = WorkflowProgressPage.from_dict(obj.get("WorkflowProgressPage")) workflow_resume_request = WorkflowResumeRequest.from_dict(obj.get("WorkflowResumeRequest")) @@ -44936,12 +43841,12 @@ def from_dict(obj: Any) -> 'RPC': workflow_run_consumed = WorkflowRunConsumed.from_dict(obj.get("WorkflowRunConsumed")) workflow_run_detail = WorkflowRunDetail.from_dict(obj.get("WorkflowRunDetail")) workflow_run_failure = WorkflowRunFailure.from_dict(obj.get("WorkflowRunFailure")) - workflow_run_failure_kind = RunFailureKind(obj.get("WorkflowRunFailureKind")) + workflow_run_failure_kind = WorkflowRunFailureKind(obj.get("WorkflowRunFailureKind")) workflow_run_limits = WorkflowRunLimits.from_dict(obj.get("WorkflowRunLimits")) workflow_run_options = WorkflowRunOptions.from_dict(obj.get("WorkflowRunOptions")) workflow_run_request = WorkflowRunRequest.from_dict(obj.get("WorkflowRunRequest")) workflow_run_result = WorkflowRunResult.from_dict(obj.get("WorkflowRunResult")) - workflow_run_status = RunStatus(obj.get("WorkflowRunStatus")) + workflow_run_status = WorkflowRunStatus(obj.get("WorkflowRunStatus")) workflow_run_summary = WorkflowRunSummary.from_dict(obj.get("WorkflowRunSummary")) workflow_run_terminal = WorkflowRunTerminal.from_dict(obj.get("WorkflowRunTerminal")) workflow_tool_resume_request = _WorkflowToolResumeRequest.from_dict(obj.get("WorkflowToolResumeRequest")) @@ -44986,7 +43891,7 @@ def from_dict(obj: Any) -> 'RPC': subagent_settings = from_union([SubagentSettings.from_dict, from_none], obj.get("SubagentSettings")) task_progress = from_union([TaskProgress.from_dict, from_none], obj.get("TaskProgress")) workspace_summary = from_union([WorkspaceSummary.from_dict, from_none], obj.get("WorkspaceSummary")) - return RPC(abort_request, abort_result, accepted_enqueue_command_result, account_all_users, account_get_all_users_result, account_get_current_auth_result, account_get_quota_request, account_get_quota_result, account_login_request, account_login_result, account_logout_request, account_logout_result, account_quota_snapshot, adaptive_thinking_support, agent_discovery_path, agent_discovery_path_list, agent_discovery_path_scope, agent_get_current_result, agent_info, agent_info_source, agent_list, agent_list_request, agent_registry_live_target_entry, agent_registry_live_target_entry_attention_kind, agent_registry_live_target_entry_kind, agent_registry_live_target_entry_last_terminal_event, agent_registry_live_target_entry_status, agent_registry_log_capture, agent_registry_log_capture_open_error_reason, agent_registry_spawn_error, agent_registry_spawn_permission_mode, agent_registry_spawn_registry_timeout, agent_registry_spawn_request, agent_registry_spawn_result, agent_registry_spawn_spawned, agent_registry_spawn_validation_error, agent_registry_spawn_validation_error_field, agent_registry_spawn_validation_error_reason, agent_reload_result, agents_discover_request, agent_select_request, agent_select_result, agent_set_prompt_request, agents_get_discovery_paths_request, api_key_auth_info, auth_identity, auth_info, auth_info_type, auth_validation_error, auth_validation_errors, autopilot_objective_credit_limit, autopilot_objective_get_state_result, autopilot_objective_state, autopilot_objective_status, built_in_model_catalog, built_in_model_catalog_entry, builtin_tool_descriptor, builtin_tool_format, builtin_tool_format_type, builtin_tool_input_schema, builtin_tool_input_schema_type, builtin_tool_safe_for_telemetry, builtin_tool_safe_telemetry_fields, cancel_user_requested_shell_command_result, canvas_action, canvas_action_invoke_request, canvas_action_invoke_result, canvas_close_request, canvas_host_context, canvas_host_context_capabilities, canvas_json_schema, canvas_list, canvas_list_open_result, canvas_open_request, canvas_provider_close_request, canvas_provider_invoke_action_request, canvas_provider_open_request, canvas_provider_open_result, canvas_provider_register_request, canvas_provider_unregister_request, canvas_session_context, capi_session_options, card_digest, card_digest_algorithm, card_digest_value, catalog_agent_plugin_candidate, catalog_agent_plugin_candidate_kind, catalog_agent_plugin_candidate_provenance, catalog_agent_plugin_compatibility_tag, catalog_agent_plugin_media_type, catalog_ai_skill_candidate, catalog_ai_skill_candidate_kind, catalog_ai_skill_candidate_provenance, catalog_ai_skill_installability, catalog_ai_skill_media_type, catalog_authentication_required_error, catalog_authentication_required_reason, catalog_candidate, catalog_candidate_kind, catalog_candidate_source, catalog_candidate_source_embedded, catalog_candidate_source_url, catalog_capability, catalog_capability_id, catalog_client_contract, catalog_contract_violation_error, catalog_contract_violation_reason, catalog_handle_rejected_error, catalog_handle_rejection_reason, catalog_handle_type, catalog_invalid_request_error, catalog_invalid_request_field, catalog_malformed_card_error, catalog_malformed_card_reason, catalog_mcp_server_candidate, catalog_mcp_server_candidate_kind, catalog_mcp_server_candidate_provenance, catalog_mcp_server_installability, catalog_media_type, catalog_negotiated_contract, catalog_negotiation_refused_error, catalog_negotiation_refused_reason, catalog_network_failure_error, catalog_network_failure_reason, catalog_not_installable_error, catalog_not_installable_reason, catalog_plugin_repository_source, catalog_policy_rejected_error, catalog_resource_identity, catalog_resource_version, catalog_search_page, catalog_search_pagination, catalog_search_request, catalog_search_result, catalog_search_succeeded, catalog_search_total_count_relation, catalog_selection_cancelled, catalog_selection_decision, catalog_selection_declined, catalog_selection_foreign, catalog_selection_invalid, catalog_selection_replayed, catalog_selection_request, catalog_selection_result, catalog_selection_selected, catalog_selection_stale, catalog_selection_timed_out, catalog_selection_wrong_kind, catalog_trust_eligibility, catalog_trust_provenance, catalog_trust_snapshot, catalog_trust_snapshot_absent, catalog_trust_snapshot_absent_status, catalog_trust_snapshot_current, catalog_trust_snapshot_current_status, catalog_trust_snapshot_downgraded, catalog_trust_snapshot_downgraded_status, catalog_trust_snapshot_malformed, catalog_trust_snapshot_malformed_status, catalog_trust_snapshot_revoked, catalog_trust_snapshot_revoked_status, catalog_trust_snapshot_schema_version, catalog_trust_snapshot_stale, catalog_trust_snapshot_stale_status, catalog_trust_snapshot_unsupported, catalog_trust_snapshot_unsupported_status, catalog_trust_source, catalog_trust_tier, catalog_unavailable_error, catalog_unavailable_reason, catalog_unavailable_transport_error, catalog_unavailable_transport_reason, catalog_unsafe_retrieval_error, catalog_unsafe_retrieval_reason, catalog_unsupported_kind_error, client_metadata, client_task_cancel_reason, client_task_cancel_request, client_task_cancel_result, command_list, commands_finalize_invocation_effect_request, commands_finalize_invocation_effect_result, commands_handle_pending_command_request, commands_handle_pending_command_result, commands_invocation_effect_outcome, commands_invocation_origin, commands_invoke_request, commands_list_request, commands_respond_to_queued_command_request, commands_respond_to_queued_command_result, completions_get_trigger_characters_result, completions_request_request, completions_request_result, configure_session_extensions_params, connect_client_info, connected_remote_session_metadata, connected_remote_session_metadata_kind, connected_remote_session_metadata_repository, connector_account_request, connector_authorization_requirement, connector_authorization_scope, connector_availability, connector_capabilities, connector_catalog_entry, connector_catalog_result, connector_catalog_status, connector_connect_request, connector_connect_result, connector_continue_request, connector_disconnect_result, connector_mcp_status, connector_reconcile_request, connector_runtime_status, connector_status, connect_remote_session_params, connect_request, connect_result, content_exclusion_check_paths_request, content_exclusion_check_paths_result, content_exclusion_path_check, content_filter_mode, context_heaviest_message, copilot_api_token_auth_info, copilot_user_response, copilot_user_response_endpoints, copilot_user_response_quota_snapshots, copilot_user_response_quota_snapshots_chat, copilot_user_response_quota_snapshots_completions, copilot_user_response_quota_snapshots_premium_interactions, current_model, current_tool_metadata, debug_collect_logs_collected_entry, debug_collect_logs_destination, debug_collect_logs_entry, debug_collect_logs_entry_kind, debug_collect_logs_include, debug_collect_logs_redaction, debug_collect_logs_request, debug_collect_logs_result, debug_collect_logs_result_kind, debug_collect_logs_skipped_entry, debug_collect_logs_source, diagnostic_cursor_status, diagnostic_entry, diagnostic_log_level, diagnostics_configuration, diagnostics_configure_request, diagnostic_severity, diagnostic_source, diagnostic_sources_configuration, diagnostics_read_request, diagnostics_read_result, discovered_canvas, discovered_extension, discovered_extension_mode, discovered_extension_plugin, discovered_extensions, discovered_extensions_disable_request, discovered_extensions_enable_request, discovered_extension_source, discovered_hook, discovered_mcp_server, discovered_mcp_server_type, enqueue_command_params, enqueue_command_result, env_auth_info, event_log_read_request, event_log_release_interest_result, event_log_tail_result, event_log_types, events_agent_scope, events_cursor_status, events_read_direction, events_read_result, execute_command_params, execute_command_result, extension, extension_context_push_input, extension_launch_profile, extension_launch_provider_resolve_request, extension_launch_provider_resolve_result, extension_list, extensions_disable_request, extensions_enable_request, extension_source, extension_status, external_tool_result, external_tool_text_result_for_llm, external_tool_text_result_for_llm_binary_results_for_llm, external_tool_text_result_for_llm_binary_results_for_llm_type, external_tool_text_result_for_llm_content, external_tool_text_result_for_llm_content_audio, external_tool_text_result_for_llm_content_image, external_tool_text_result_for_llm_content_resource, external_tool_text_result_for_llm_content_resource_details, external_tool_text_result_for_llm_content_resource_link, external_tool_text_result_for_llm_content_resource_link_icon, external_tool_text_result_for_llm_content_resource_link_icon_theme, external_tool_text_result_for_llm_content_shell_exit, external_tool_text_result_for_llm_content_terminal, external_tool_text_result_for_llm_content_text, factory_abort_request, factory_ack_result, factory_agent_options, factory_agent_request, factory_agent_result, factory_agent_summary, factory_cancel_request, factory_current_phase, factory_declared_limits, factory_durable_operation, factory_execute_request, factory_execute_result, factory_get_run_progress_request, factory_get_run_request, factory_journal_get_request, factory_journal_get_result, factory_journal_put_request, factory_list_runs_request, factory_list_runs_result, factory_log_line, factory_log_line_kind, factory_log_request, factory_pause_checkpoint_action, factory_pause_checkpoint_request, factory_pause_checkpoint_result, factory_pause_info, factory_pause_request, factory_phase_observation, factory_phase_status, factory_progress_line, factory_progress_page, factory_resume_request, factory_resume_result, factory_run_consumed, factory_run_detail, factory_run_failure, factory_run_failure_kind, factory_run_limits, factory_run_request, factory_run_result, factory_run_status, factory_run_summary, factory_run_terminal, factory_tool_resume_request, factory_tool_run_options, factory_tool_run_request, filter_mapping, fleet_start_request, fleet_start_result, folder_trust_add_params, folder_trust_check_params, folder_trust_check_result, gh_cli_auth_info, git_hub_telemetry_client_info, git_hub_telemetry_event, git_hub_telemetry_notification, git_hub_token_acquire_reason, git_hub_token_acquire_request, git_hub_token_acquire_result, handle_pending_tool_call_request, handle_pending_tool_call_result, history_abort_manual_compaction_result, history_cancel_background_compaction_result, history_clear_context_request, history_clear_context_result, history_compact_context_window, history_compact_request, history_compact_result, history_file_restore_skip_reason, history_list_rewind_points_result, history_preview_rewind_request, history_preview_rewind_result, history_rewind_change_type, history_rewind_file_preview, history_rewind_mode, history_rewind_outcome, history_rewind_point, history_rewind_request, history_rewind_result, history_rewind_unavailable_reason, history_skipped_file_restore, history_summarize_for_handoff_result, history_truncate_request, history_truncate_result, hmac_auth_info, hook_invoke_request, hook_invoke_response, hook_origin, hooks_discover_request, hooks_discover_result, hook_type, installed_plugin, installed_plugin_info, installed_plugin_source, installed_plugin_source_git_hub, installed_plugin_source_local, installed_plugin_source_url, instruction_discovery_path, instruction_discovery_path_kind, instruction_discovery_path_list, instruction_discovery_path_location, instructions_discover_request, instructions_get_discovery_paths_request, instructions_get_sources_result, instruction_source, instruction_source_location, instruction_source_type, interrupt_main_turn_request, interrupt_main_turn_result, json_schema_response_format, llm_inference_headers, llm_inference_http_request_chunk_request, llm_inference_http_request_chunk_result, llm_inference_http_request_start_request, llm_inference_http_request_start_result, llm_inference_http_request_start_transport, llm_inference_http_response_chunk_error, llm_inference_http_response_chunk_request, llm_inference_http_response_chunk_result, llm_inference_http_response_start_request, llm_inference_http_response_start_result, llm_inference_set_provider_result, local_session_metadata_value, log_request, log_result, lsp_initialize_request, managed_mcp_server_config, managed_settings_read_result, managed_settings_resolved_data, marketplace_add_result, marketplace_browse_result, marketplace_info, marketplace_list_result, marketplace_plugin_info, marketplace_refresh_entry, marketplace_refresh_result, marketplace_remove_result, mcp_allowed_server, mcp_apps_call_tool_request, mcp_apps_diagnose_capability, mcp_apps_diagnose_request, mcp_apps_diagnose_result, mcp_apps_diagnose_server, mcp_apps_host_context, mcp_apps_host_context_details, mcp_apps_host_context_details_available_display_mode, mcp_apps_host_context_details_display_mode, mcp_apps_host_context_details_platform, mcp_apps_host_context_details_theme, mcp_apps_list_tools_request, mcp_apps_list_tools_result, mcp_apps_read_resource_request, mcp_apps_read_resource_result, mcp_apps_resource_content, mcp_apps_set_host_context_details, mcp_apps_set_host_context_details_available_display_mode, mcp_apps_set_host_context_details_display_mode, mcp_apps_set_host_context_details_platform, mcp_apps_set_host_context_details_theme, mcp_apps_set_host_context_request, mcp_cancel_sampling_execution_params, mcp_cancel_sampling_execution_result, mcp_config_add_request, mcp_config_disable_request, mcp_config_enable_request, mcp_config_list, mcp_config_remove_request, mcp_config_update_request, mcp_configure_git_hub_request, mcp_configure_git_hub_result, mcp_diagnostic_details, mcp_diagnostic_direction, mcp_diagnostic_kind, mcp_diagnostic_source_configuration, mcp_disable_request, mcp_discover_request, mcp_discover_result, mcp_elicitation_form_mode, mcp_enable_request, mcp_execute_sampling_params, mcp_execute_sampling_request, mcp_execute_sampling_result, mcp_failed_server, mcp_filtered_server, mcp_headers_handle_pending_headers_refresh_request, mcp_headers_handle_pending_headers_refresh_request_request, mcp_headers_handle_pending_headers_refresh_request_result, mcp_host_state, mcp_install_plan, mcp_is_server_running_request, mcp_is_server_running_result, mcp_list_tools_request, mcp_list_tools_result, mcp_oauth_authentication_state_changed_request, mcp_oauth_handle_pending_request, mcp_oauth_handle_pending_result, mcp_oauth_login_grant_type, mcp_oauth_login_request, mcp_oauth_login_result, mcp_oauth_pending_request_response, mcp_oauth_probe_needs_auth_reason, mcp_oauth_probe_request, mcp_oauth_probe_result, mcp_oauth_respond_request, mcp_oauth_respond_result, mcp_plan_configuration_change, mcp_plan_configuration_operation, mcp_plan_enum_value_type, mcp_plan_install_planned, mcp_plan_install_request, mcp_plan_install_result, mcp_plan_install_source, mcp_plan_install_source_candidate, mcp_plan_install_source_candidate_kind, mcp_plan_install_source_card, mcp_plan_install_source_card_kind, mcp_plan_package_install_method, mcp_plan_package_transport, mcp_plan_policy_decision, mcp_plan_policy_result, mcp_plan_policy_source, mcp_plan_provenance, mcp_plan_remote_install_method, mcp_plan_remote_transport, mcp_plan_required_value, mcp_plan_required_value_enum, mcp_plan_required_value_enum_kind, mcp_plan_required_value_scalar, mcp_plan_required_value_scalar_kind, mcp_plan_resource_identity, mcp_plan_scalar_value_type, mcp_plan_scope, mcp_plan_secret_placeholder, mcp_plan_secret_reference, mcp_plan_target, mcp_plan_transport_choice, mcp_plan_transport_choice_package, mcp_plan_transport_choice_remote, mcp_plan_value_category, mcp_register_external_client_request, mcp_reload_config, mcp_reload_with_config_request, mcp_remove_git_hub_result, mcp_resource, mcp_resource_annotations, mcp_resource_content, mcp_resource_icon, mcp_resources_list_request, mcp_resources_list_result, mcp_resources_list_templates_request, mcp_resources_list_templates_result, mcp_resources_read_request, mcp_resources_read_result, mcp_resource_template, mcp_restart_server_request, mcp_safe_for_telemetry, mcp_safe_for_telemetry_fields, mcp_sampling_execution_action, mcp_sampling_execution_result, mcp_serializable_server_config, mcp_server, mcp_server_auth_config, mcp_server_auth_config_redirect_port, mcp_server_card_embedded, mcp_server_card_embedded_kind, mcp_server_card_media_type, mcp_server_card_reference, mcp_server_card_url, mcp_server_card_url_kind, mcp_server_config, mcp_server_config_defer_tools, mcp_server_config_http, mcp_server_config_http_oauth_grant_type, mcp_server_config_http_type, mcp_server_config_memory, mcp_server_config_memory_type, mcp_server_config_stdio, mcp_server_config_stdio_type, mcp_server_failure_info, mcp_server_list, mcp_server_needs_auth_info, mcp_set_env_value_mode_details, mcp_set_env_value_mode_params, mcp_set_env_value_mode_result, mcp_source_file, mcp_source_plugin, mcp_source_ref, mcp_start_server_request, mcp_start_servers_result, mcp_stop_server_request, mcp_task_metadata, mcp_tools, mcp_tool_ui, mcp_tool_ui_visibility, mcp_unregister_external_client_request, memory_configuration, metadata_context_attribution_result, metadata_context_heaviest_messages_request, metadata_context_heaviest_messages_result, metadata_context_info_request, metadata_context_info_result, metadata_is_processing_result, metadata_recompute_context_tokens_request, metadata_recompute_context_tokens_result, metadata_record_context_change_request, metadata_record_context_change_result, metadata_set_working_directory_request, metadata_set_working_directory_result, metadata_snapshot_current_mode, metadata_snapshot_remote_metadata, metadata_snapshot_remote_metadata_repository, metadata_snapshot_remote_metadata_task_type, metadata_update_client_metadata_request, model, model_apply_startup_overlay_request, model_billing, model_billing_promo, model_billing_token_prices, model_billing_token_prices_long_context, model_capabilities, model_capabilities_limits, model_capabilities_limits_vision, model_capabilities_override, model_capabilities_override_limits, model_capabilities_override_limits_vision, model_capabilities_override_supports, model_capabilities_supports, model_list, model_list_request, model_message, model_picker_category, model_picker_persistence_request, model_picker_price_category, model_picker_settings_context, model_policy, model_policy_state, model_set_allowed_models_request, model_set_allowed_models_result, model_set_reasoning_effort_request, model_set_reasoning_effort_result, models_list_request, model_switch_auto_tier_request, model_switch_auto_tier_result, model_switch_auto_tier_status, model_switch_confirmation, model_switch_to_request, model_switch_to_result, model_warning_text, mode_set_request, mode_set_result, move_mcp_loading_to_background_result, named_provider_config, name_get_result, name_set_auto_request, name_set_auto_result, name_set_request, open_canvas_instance, options_update_additional_content_exclusion_policy, options_update_additional_content_exclusion_policy_rule, options_update_additional_content_exclusion_policy_rule_source, options_update_additional_content_exclusion_policy_scope, options_update_context_tier, options_update_env_value_mode, options_update_reasoning_summary, options_update_tool_filter_precedence, pending_permission_request, pending_permission_request_list, permission_decision, permission_decision_approved, permission_decision_approved_for_location, permission_decision_approved_for_session, permission_decision_approve_for_location, permission_decision_approve_for_location_approval, permission_decision_approve_for_location_approval_commands, permission_decision_approve_for_location_approval_custom_tool, permission_decision_approve_for_location_approval_extension_env_access, permission_decision_approve_for_location_approval_extension_management, permission_decision_approve_for_location_approval_extension_permission_access, permission_decision_approve_for_location_approval_factory, permission_decision_approve_for_location_approval_mcp, permission_decision_approve_for_location_approval_mcp_sampling, permission_decision_approve_for_location_approval_memory, permission_decision_approve_for_location_approval_read, permission_decision_approve_for_location_approval_write, permission_decision_approve_for_session, permission_decision_approve_for_session_approval, permission_decision_approve_for_session_approval_commands, permission_decision_approve_for_session_approval_custom_tool, permission_decision_approve_for_session_approval_extension_env_access, permission_decision_approve_for_session_approval_extension_management, permission_decision_approve_for_session_approval_extension_permission_access, permission_decision_approve_for_session_approval_factory, permission_decision_approve_for_session_approval_mcp, permission_decision_approve_for_session_approval_mcp_sampling, permission_decision_approve_for_session_approval_memory, permission_decision_approve_for_session_approval_read, permission_decision_approve_for_session_approval_write, permission_decision_approve_once, permission_decision_approve_permanently, permission_decision_cancelled, permission_decision_context, permission_decision_denied_by_content_exclusion_policy, permission_decision_denied_by_permission_request_hook, permission_decision_denied_by_rules, permission_decision_denied_interactively_by_user, permission_decision_denied_no_approval_rule_and_could_not_request_from_user, permission_decision_outcome, permission_decision_reject, permission_decision_request, permission_decision_surface, permission_decision_user_not_available, permission_location_add_tool_approval_params, permission_location_apply_params, permission_location_apply_result, permission_location_resolve_params, permission_location_resolve_result, permission_location_type, permission_mode_source, permission_paths_add_params, permission_paths_allowed_check_params, permission_paths_allowed_check_result, permission_paths_config, permission_paths_list, permission_paths_update_primary_params, permission_paths_workspace_check_params, permission_paths_workspace_check_result, permission_prompt_shown_notification, permission_request_result, permission_response_capability, permission_rules_set, permissions_configure_additional_content_exclusion_policy, permissions_configure_additional_content_exclusion_policy_rule, permissions_configure_additional_content_exclusion_policy_rule_source, permissions_configure_additional_content_exclusion_policy_scope, permissions_configure_params, permissions_configure_result, permissions_folder_trust_add_trusted_result, permissions_get_mode_request, permissions_get_mode_result, permissions_locations_add_tool_approval_details, permissions_locations_add_tool_approval_details_commands, permissions_locations_add_tool_approval_details_custom_tool, permissions_locations_add_tool_approval_details_extension_env_access, permissions_locations_add_tool_approval_details_extension_management, permissions_locations_add_tool_approval_details_extension_permission_access, permissions_locations_add_tool_approval_details_factory, permissions_locations_add_tool_approval_details_mcp, permissions_locations_add_tool_approval_details_mcp_sampling, permissions_locations_add_tool_approval_details_memory, permissions_locations_add_tool_approval_details_read, permissions_locations_add_tool_approval_details_write, permissions_locations_add_tool_approval_result, permissions_modify_rules_params, permissions_modify_rules_result, permissions_modify_rules_scope, permissions_notify_prompt_shown_result, permissions_paths_add_result, permissions_paths_list_request, permissions_paths_update_primary_result, permissions_pending_requests_request, permissions_reset_session_approvals_request, permissions_reset_session_approvals_result, permissions_set_approve_all_request, permissions_set_approve_all_result, permissions_set_approve_all_source, permissions_set_mode_request, permissions_set_mode_result, permissions_set_required_request, permissions_set_required_result, permissions_urls_set_unrestricted_mode_result, permission_urls_config, permission_urls_set_unrestricted_mode_params, ping_request, ping_result, plan_read_result, plan_read_sql_todos_result, plan_read_sql_todos_with_dependencies_result, plan_sql_todo_dependency, plan_sql_todos_row, plan_update_request, plugin, plugin_install_result, plugin_install_staging_mode, plugin_list, plugin_list_result, plugins_builtin_set_request, plugins_disable_request, plugins_enable_request, plugins_install_request, plugins_marketplaces_add_request, plugins_marketplaces_browse_request, plugins_marketplaces_refresh_request, plugins_marketplaces_remove_request, plugins_reload_request, plugins_uninstall_request, plugins_update_request, plugin_update_all_entry, plugin_update_all_result, plugin_update_result, protocol_append_mode, protocol_customize_mode, protocol_external_tool_defer, protocol_external_tool_definition, protocol_marker_section_override, protocol_replace_mode, protocol_section_override, protocol_static_section_action, protocol_static_section_override, protocol_system_message_append_config, protocol_system_message_config, protocol_system_message_customize_config, protocol_system_message_replace_config, provider_add_request, provider_add_result, provider_config, provider_config_azure, provider_config_transport, provider_config_type, provider_config_wire_api, provider_endpoint, provider_endpoint_transport, provider_endpoint_type, provider_endpoint_wire_api, provider_get_endpoint_request, provider_model_config, provider_session_token, provider_sync_request, provider_sync_result, provider_token_acquire_request, provider_token_acquire_result, push_attachment, push_attachment_blob, push_attachment_directory, push_attachment_file, push_attachment_file_line_range, push_attachment_git_hub_actions_job, push_attachment_git_hub_commit, push_attachment_git_hub_file, push_attachment_git_hub_file_diff, push_attachment_git_hub_file_diff_side, push_attachment_git_hub_reference, push_attachment_git_hub_reference_type, push_attachment_git_hub_release, push_attachment_git_hub_repository, push_attachment_git_hub_snippet, push_attachment_git_hub_tree_comparison, push_attachment_git_hub_tree_comparison_side, push_attachment_git_hub_url, push_attachment_selection, push_attachment_selection_details, push_attachment_selection_details_end, push_attachment_selection_details_start, push_git_hub_repo_ref, queue_append_steering_request, queue_begin_deferred_idle_drain_request, queue_begin_deferred_idle_drain_result, queue_consume_system_notifications_request, queued_command_handled, queued_command_not_handled, queued_command_result, queue_defer_session_idle_request, queue_duplicate_at_request, queue_duplicate_at_result, queue_enqueue_resume_pending_result, queue_finish_deferred_idle_drain_request, queue_finish_deferred_idle_drain_result, queue_has_pending_result, queue_insert_at_request, queue_insert_at_result, queue_insert_message, queue_move_item_request, queue_move_item_result, queue_pending_items, queue_pending_items_kind, queue_pending_items_result, queue_remove_at_request, queue_remove_at_result, queue_remove_most_recent_result, queue_send_now_request, queue_send_now_result, queue_set_drain_paused_request, queue_snapshot_result, queue_update_text_request, queue_update_text_result, queue_withdraw_message_request, queue_withdraw_message_result, register_event_interest_params, register_event_interest_result, release_event_interest_params, remote_control_config, remote_control_config_existing_mc_session, remote_control_status, remote_control_status_active, remote_control_status_connecting, remote_control_status_error, remote_control_status_off, remote_control_status_result, remote_control_stop_result, remote_control_transfer_result, remote_enable_request, remote_enable_result, remote_notify_steerable_changed_request, remote_notify_steerable_changed_result, remote_session_connection_result, remote_session_host_status, remote_session_metadata_repository, remote_session_metadata_task_type, remote_session_metadata_value, remote_session_mode, remote_session_repository, response_format, run_options, sandbox_config, sandbox_config_auth, sandbox_config_source, sandbox_config_user_policy, sandbox_config_user_policy_experimental, sandbox_config_user_policy_experimental_seatbelt, sandbox_config_user_policy_filesystem, sandbox_config_user_policy_network, sandbox_config_user_policy_network_proxy, sandbox_config_user_policy_seatbelt, sandbox_disable_for_session_request, sandbox_disable_for_session_result, sandbox_enforcement_status, sandbox_host_capability, sandbox_host_capability_name, sandbox_host_support, sandbox_session_change, schedule_add_at_request, schedule_add_cron_request, schedule_add_request, schedule_add_result, schedule_add_self_paced_request, schedule_entry, schedule_has_self_paced_result, schedule_list, schedule_rearm_self_paced_request, schedule_stop_request, schedule_stop_result, secrets_add_filter_values_request, secrets_add_filter_values_result, send_agent_mode, send_attachments_to_message_params, send_message_item, send_messages_request, send_messages_result, send_mode, send_request, send_result, send_system_notification_request, server_agent_list, server_instruction_source_list, server_skill, server_skill_list, session_activity, session_agent_list_request, session_auth_login_request, session_auth_logout_user_request, session_auth_status, session_auth_switch_request, session_bulk_delete_result, session_cancel_all_background_agents_result, session_capability, session_commands_list_request, session_completion_item, session_context, session_context_host_type, session_enrich_metadata_result, session_factory_pause_at_checkpoint_result, session_fs_append_file_request, session_fs_error, session_fs_error_code, session_fs_exists_request, session_fs_exists_result, session_fs_mkdir_request, session_fs_readdir_request, session_fs_readdir_result, session_fs_readdir_with_types_entry, session_fs_readdir_with_types_entry_type, session_fs_readdir_with_types_request, session_fs_readdir_with_types_result, session_fs_read_file_request, session_fs_read_file_result, session_fs_rename_request, session_fs_rm_request, session_fs_set_provider_capabilities, session_fs_set_provider_conventions, session_fs_set_provider_request, session_fs_set_provider_result, session_fs_sqlite_exists_request, session_fs_sqlite_exists_result, session_fs_sqlite_query_request, session_fs_sqlite_query_result, session_fs_sqlite_query_type, session_fs_sqlite_transaction_error, session_fs_sqlite_transaction_error_class, session_fs_sqlite_transaction_request, session_fs_sqlite_transaction_result, session_fs_sqlite_transaction_statement, session_fs_stat_request, session_fs_stat_result, session_fs_write_file_request, session_git_hub_auth_get_all_auth_available_result, session_git_hub_auth_logout_result, session_git_hub_auth_logout_user_result, session_history_compact_request, session_installed_plugin, session_installed_plugin_source, session_installed_plugin_source_git_hub, session_installed_plugin_source_local, session_installed_plugin_source_url, session_limit_prediction_baseline_data, session_limit_prediction_client_type, session_limit_prediction_details, session_limit_prediction_predict_request, session_limit_prediction_request, session_limit_prediction_result, session_limit_prediction_source, session_limit_prediction_tier, session_limit_prediction_tier_option, session_limit_prediction_unavailable_reason, session_list, session_list_entry, session_list_filter, session_load_deferred_repo_hooks_result, session_log_level, session_managed_permissions, session_managed_settings, session_mcp_apps_call_tool_result, session_metadata_snapshot, session_mode, session_model_list, session_model_list_request, session_model_price_category, session_open_options, session_open_options_additional_content_exclusion_policy, session_open_options_additional_content_exclusion_policy_rule, session_open_options_additional_content_exclusion_policy_rule_source, session_open_options_additional_content_exclusion_policy_scope, session_open_options_env_value_mode, session_open_options_reasoning_summary, session_open_params, session_open_result, session_plugins_disable_request, session_plugins_enable_request, session_plugins_install_request, session_plugins_marketplaces_refresh_request, session_plugins_reload_request, session_provider_get_endpoint_request, session_prune_result, sessions_bulk_delete_request, sessions_check_in_use_request, sessions_check_in_use_result, sessions_client_metadata_entry, sessions_close_request, sessions_close_result, sessions_delete_request, sessions_enrich_metadata_request, session_set_credentials_params, session_set_credentials_result, session_settings_built_in_tool_availability_snapshot, session_settings_evaluate_predicate_request, session_settings_evaluate_predicate_result, session_settings_job_snapshot, session_settings_model_snapshot, session_settings_online_evaluation_snapshot, session_settings_predicate_name, session_settings_repo_snapshot, session_settings_snapshot, session_settings_validation_snapshot, sessions_find_by_prefix_request, sessions_find_by_prefix_result, sessions_find_by_task_id_request, sessions_find_by_task_id_result, sessions_fork_request, sessions_fork_result, sessions_get_board_entry_count_request, sessions_get_board_entry_count_result, sessions_get_client_metadata_request, sessions_get_client_metadata_result, sessions_get_event_file_path_request, sessions_get_event_file_path_result, sessions_get_last_for_context_request, sessions_get_last_for_context_result, sessions_get_metadata_request, sessions_get_metadata_result, sessions_get_persisted_remote_steerable_request, sessions_get_persisted_remote_steerable_result, session_sizes, sessions_list_non_empty_session_ids_request, sessions_list_non_empty_session_ids_result, sessions_list_request, sessions_load_deferred_repo_hooks_request, sessions_open_attach, sessions_open_cloud, sessions_open_create, sessions_open_handoff, sessions_open_handoff_task_type, sessions_open_progress, sessions_open_progress_status, sessions_open_progress_step, sessions_open_remote, sessions_open_resume, sessions_open_resume_last, sessions_open_status, session_source, sessions_prune_old_request, sessions_read_persisted_events_request, sessions_release_lock_request, sessions_release_lock_result, sessions_reload_plugin_hooks_request, sessions_reload_plugin_hooks_result, sessions_save_request, sessions_save_result, sessions_set_additional_plugins_request, sessions_set_additional_plugins_result, sessions_set_remote_control_steering_request, sessions_start_remote_control_request, sessions_stop_remote_control_request, sessions_transfer_remote_control_request, session_telemetry_engagement, session_update_options_params, session_update_options_result, session_visibility_status, session_workflow_pause_at_checkpoint_result, session_working_directory_context, session_working_directory_context_host_type, settable_auth_info, settable_token_auth_info, shell_cancel_user_requested_request, shell_credentials, shell_exec_request, shell_exec_result, shell_execute_user_requested_request, shell_init_profile, shell_init_script, shell_init_script_shell, shell_kill_request, shell_kill_result, shell_kill_signal, shell_options, shutdown_request, skill, skill_discovery_path, skill_discovery_path_list, skill_discovery_scope, skill_list, skill_provider_descriptor, skill_provider_list_request, skill_provider_list_result, skill_provider_read_request, skill_provider_read_result, skills_config_set_disabled_skills_request, skills_config_set_skill_disabled_request, skills_disable_request, skills_discover_request, skills_enable_request, skills_get_discovery_paths_request, skills_get_invoked_result, skills_invoked_skill, skills_load_diagnostics, slash_command_add_timeline_entry_result, slash_command_agent_prompt_result, slash_command_completed_result, slash_command_info, slash_command_input, slash_command_input_choice, slash_command_input_completion, slash_command_invocation_result, slash_command_kind, slash_command_model_picker_dialog, slash_command_select_subcommand_option, slash_command_select_subcommand_result, slash_command_set_model_result, slash_command_set_plan_model_result, slash_command_show_dialog_result, slash_command_text_result, slash_command_timeline_entry, subagent_settings_entry, subagent_settings_entry_context_tier, system_message_block, task_agent_info, task_agent_progress, task_client_active_status, task_client_execution_mode, task_client_info, task_client_owner, task_client_owner_kind, task_client_owner_presence, task_client_progress, task_client_status, task_client_type, task_client_update, task_complete_data, task_completion_decision, task_execution_mode, task_info, task_kind, task_list, task_progress_line, tasks_cancel_request, tasks_cancel_result, tasks_get_current_promotable_result, tasks_get_progress_request, tasks_get_progress_result, task_shell_info, task_shell_info_attachment_mode, task_shell_progress, tasks_promote_current_to_background_result, tasks_promote_to_background_request, tasks_promote_to_background_result, tasks_refresh_result, tasks_register_request, tasks_register_result, tasks_remove_request, tasks_remove_result, tasks_send_message_request, tasks_send_message_result, tasks_start_agent_request, tasks_start_agent_result, task_status, tasks_update_request, tasks_update_result, tasks_wait_for_pending_result, telemetry_set_feature_overrides_request, token_auth_info, token_provider_auth_info, tool, tool_list, tool_result, tool_result_expanded, tool_result_new_message, tool_result_type, tools_execute_request, tools_get_builtin_descriptors_request, tools_get_builtin_descriptors_result, tools_get_current_metadata_result, tools_initialize_and_validate_result, tools_list_request, tools_set_request, tools_set_result, tools_shell_descriptor_config, tools_task_complete_event_data_request, tools_update_subagent_settings_result, ui_auto_mode_switch_response, ui_elicitation_array_any_of_field, ui_elicitation_array_any_of_field_items, ui_elicitation_array_any_of_field_items_any_of, ui_elicitation_array_enum_field, ui_elicitation_array_enum_field_items, ui_elicitation_field_value, ui_elicitation_request, ui_elicitation_response, ui_elicitation_response_action, ui_elicitation_response_content, ui_elicitation_result, ui_elicitation_schema, ui_elicitation_schema_property, ui_elicitation_schema_property_boolean, ui_elicitation_schema_property_number, ui_elicitation_schema_property_number_type, ui_elicitation_schema_property_string, ui_elicitation_schema_property_string_format, ui_elicitation_string_enum_field, ui_elicitation_string_one_of_field, ui_elicitation_string_one_of_field_one_of, ui_ephemeral_query_request, ui_ephemeral_query_result, ui_exit_plan_mode_action, ui_exit_plan_mode_response, ui_handle_pending_auto_mode_switch_request, ui_handle_pending_elicitation_request, ui_handle_pending_exit_plan_mode_request, ui_handle_pending_result, ui_handle_pending_sampling_request, ui_handle_pending_sampling_response, ui_handle_pending_session_limits_exhausted_request, ui_handle_pending_user_input_request, ui_register_direct_auto_mode_switch_handler_result, ui_session_limits_exhausted_response, ui_session_limits_exhausted_response_action, ui_unregister_direct_auto_mode_switch_handler_request, ui_unregister_direct_auto_mode_switch_handler_result, ui_user_input_response, unsupported_enqueue_command_result, update_subagent_settings_request, usage_get_metrics_result, usage_metrics_agent_metric, usage_metrics_code_changes, usage_metrics_model_metric, usage_metrics_model_metric_requests, usage_metrics_model_metric_token_detail, usage_metrics_model_metric_usage, usage_metrics_token_detail, user_auth_info, user_requested_shell_command_result, user_setting_metadata, user_settings_get_result, user_settings_set_request, user_settings_set_result, visibility_get_result, visibility_set_request, visibility_set_result, workflow_abort_request, workflow_ack_result, workflow_agent_options, workflow_agent_request, workflow_agent_result, workflow_agent_summary, workflow_cancel_request, workflow_current_phase, workflow_declared_limits, workflow_durable_operation, workflow_execute_request, workflow_execute_result, workflow_get_run_progress_request, workflow_get_run_request, workflow_journal_get_request, workflow_journal_get_result, workflow_journal_put_request, workflow_list_runs_request, workflow_list_runs_result, workflow_log_line, workflow_log_line_kind, workflow_log_request, workflow_pause_checkpoint_action, workflow_pause_checkpoint_request, workflow_pause_checkpoint_result, workflow_pause_info, workflow_pause_request, workflow_phase_observation, workflow_phase_status, workflow_progress_line, workflow_progress_page, workflow_resume_request, workflow_resume_result, workflow_run_consumed, workflow_run_detail, workflow_run_failure, workflow_run_failure_kind, workflow_run_limits, workflow_run_options, workflow_run_request, workflow_run_result, workflow_run_status, workflow_run_summary, workflow_run_terminal, workflow_tool_resume_request, workflow_tool_run_options, workflow_tool_run_request, workspace_diff_file_change, workspace_diff_file_change_type, workspace_diff_mode, workspace_diff_result, workspaces_add_summary_request, workspaces_add_summary_result, workspaces_autopilot_objective_exists_result, workspaces_checkpoints, workspaces_create_directory_request, workspaces_create_file_request, workspaces_delete_autopilot_objective_result, workspaces_diff_request, workspaces_ensure_request, workspaces_get_workspace_result, workspaces_list_checkpoints_result, workspaces_list_files_result, workspaces_read_autopilot_objective_result, workspaces_read_checkpoint_request, workspaces_read_checkpoint_result, workspaces_read_file_request, workspaces_read_file_result, workspaces_remove_path_request, workspaces_rename_path_request, workspaces_save_large_paste_request, workspaces_save_large_paste_result, workspaces_stat_file_request, workspaces_stat_file_result, workspaces_truncate_summaries_request, workspace_summary_host_type, workspaces_update_metadata_request, workspaces_workspace_details_host_type, workspaces_write_autopilot_objective_request, workspaces_write_autopilot_objective_result, session_auth_info_result, session_context_attribution, session_context_info, subagent_settings, task_progress, workspace_summary) + return RPC(abort_request, abort_result, accepted_enqueue_command_result, account_all_users, account_get_all_users_result, account_get_current_auth_result, account_get_quota_request, account_get_quota_result, account_kind, account_login_request, account_login_result, account_logout_request, account_logout_result, account_quota_snapshot, accounts_enumerate_request, accounts_get_request, accounts_set_request, account_status, adaptive_thinking_support, agent_discovery_path, agent_discovery_path_list, agent_discovery_path_scope, agent_get_current_result, agent_info, agent_info_source, agent_list, agent_list_request, agent_registry_live_target_entry, agent_registry_live_target_entry_attention_kind, agent_registry_live_target_entry_kind, agent_registry_live_target_entry_last_terminal_event, agent_registry_live_target_entry_status, agent_registry_log_capture, agent_registry_log_capture_open_error_reason, agent_registry_spawn_error, agent_registry_spawn_permission_mode, agent_registry_spawn_registry_timeout, agent_registry_spawn_request, agent_registry_spawn_result, agent_registry_spawn_spawned, agent_registry_spawn_validation_error, agent_registry_spawn_validation_error_field, agent_registry_spawn_validation_error_reason, agent_reload_result, agents_discover_request, agent_select_request, agent_select_result, agent_set_prompt_request, agents_get_discovery_paths_request, api_key_auth_info, auth_enumerate_query, auth_enumerate_value, auth_identity, auth_info, auth_info_type, auth_login_advance_request, auth_login_begin_request, auth_login_begun, auth_login_cancel_request, auth_login_result_dto, auth_login_result_status, auth_login_step, auth_read_query, auth_read_value, auth_status_dto, auth_validation_error, auth_validation_errors, auth_write, auth_write_result, autopilot_objective_credit_limit, autopilot_objective_get_state_result, autopilot_objective_state, autopilot_objective_status, built_in_model_catalog, built_in_model_catalog_entry, builtin_tool_descriptor, builtin_tool_format, builtin_tool_format_type, builtin_tool_input_schema, builtin_tool_input_schema_type, builtin_tool_safe_for_telemetry, builtin_tool_safe_telemetry_fields, cancel_user_requested_shell_command_result, canvas_action, canvas_action_invoke_request, canvas_action_invoke_result, canvas_close_request, canvas_host_context, canvas_host_context_capabilities, canvas_json_schema, canvas_list, canvas_list_open_result, canvas_open_request, canvas_provider_close_request, canvas_provider_invoke_action_request, canvas_provider_open_request, canvas_provider_open_result, canvas_provider_register_request, canvas_provider_unregister_request, canvas_session_context, capi_session_options, card_digest, card_digest_algorithm, card_digest_value, catalog_agent_plugin_candidate, catalog_agent_plugin_candidate_kind, catalog_agent_plugin_candidate_provenance, catalog_agent_plugin_compatibility_tag, catalog_agent_plugin_media_type, catalog_ai_skill_candidate, catalog_ai_skill_candidate_kind, catalog_ai_skill_candidate_provenance, catalog_ai_skill_installability, catalog_ai_skill_media_type, catalog_authentication_required_error, catalog_authentication_required_reason, catalog_candidate, catalog_candidate_kind, catalog_candidate_source, catalog_candidate_source_embedded, catalog_candidate_source_url, catalog_capability, catalog_capability_id, catalog_client_contract, catalog_contract_violation_error, catalog_contract_violation_reason, catalog_handle_rejected_error, catalog_handle_rejection_reason, catalog_handle_type, catalog_invalid_request_error, catalog_invalid_request_field, catalog_malformed_card_error, catalog_malformed_card_reason, catalog_mcp_server_candidate, catalog_mcp_server_candidate_kind, catalog_mcp_server_candidate_provenance, catalog_mcp_server_installability, catalog_media_type, catalog_negotiated_contract, catalog_negotiation_refused_error, catalog_negotiation_refused_reason, catalog_network_failure_error, catalog_network_failure_reason, catalog_not_installable_error, catalog_not_installable_reason, catalog_plugin_repository_source, catalog_policy_rejected_error, catalog_resource_identity, catalog_resource_version, catalog_search_page, catalog_search_pagination, catalog_search_request, catalog_search_result, catalog_search_succeeded, catalog_search_total_count_relation, catalog_selection_cancelled, catalog_selection_decision, catalog_selection_declined, catalog_selection_foreign, catalog_selection_invalid, catalog_selection_replayed, catalog_selection_request, catalog_selection_result, catalog_selection_selected, catalog_selection_stale, catalog_selection_timed_out, catalog_selection_wrong_kind, catalog_trust_eligibility, catalog_trust_provenance, catalog_trust_snapshot, catalog_trust_snapshot_absent, catalog_trust_snapshot_absent_status, catalog_trust_snapshot_current, catalog_trust_snapshot_current_status, catalog_trust_snapshot_downgraded, catalog_trust_snapshot_downgraded_status, catalog_trust_snapshot_malformed, catalog_trust_snapshot_malformed_status, catalog_trust_snapshot_revoked, catalog_trust_snapshot_revoked_status, catalog_trust_snapshot_schema_version, catalog_trust_snapshot_stale, catalog_trust_snapshot_stale_status, catalog_trust_snapshot_unsupported, catalog_trust_snapshot_unsupported_status, catalog_trust_source, catalog_trust_tier, catalog_unavailable_error, catalog_unavailable_reason, catalog_unavailable_transport_error, catalog_unavailable_transport_reason, catalog_unsafe_retrieval_error, catalog_unsafe_retrieval_reason, catalog_unsupported_kind_error, client_metadata, client_task_cancel_reason, client_task_cancel_request, client_task_cancel_result, command_list, commands_finalize_invocation_effect_request, commands_finalize_invocation_effect_result, commands_handle_pending_command_request, commands_handle_pending_command_result, commands_invocation_effect_outcome, commands_invocation_origin, commands_invoke_request, commands_list_request, commands_respond_to_queued_command_request, commands_respond_to_queued_command_result, completions_get_trigger_characters_result, completions_request_request, completions_request_result, configure_session_extensions_params, connect_client_info, connected_remote_session_metadata, connected_remote_session_metadata_kind, connected_remote_session_metadata_repository, connector_account_request, connector_authorization_requirement, connector_authorization_scope, connector_availability, connector_capabilities, connector_catalog_entry, connector_catalog_result, connector_catalog_status, connector_connect_request, connector_connect_result, connector_continue_request, connector_disconnect_result, connector_mcp_status, connector_reconcile_request, connector_runtime_status, connector_status, connect_remote_session_params, connect_request, connect_result, content_exclusion_check_paths_request, content_exclusion_check_paths_result, content_exclusion_path_check, content_filter_mode, context_heaviest_message, copilot_api_token_auth_info, copilot_user_response, copilot_user_response_endpoints, copilot_user_response_quota_snapshots, copilot_user_response_quota_snapshots_chat, copilot_user_response_quota_snapshots_completions, copilot_user_response_quota_snapshots_premium_interactions, current_model, current_tool_metadata, debug_collect_logs_collected_entry, debug_collect_logs_destination, debug_collect_logs_entry, debug_collect_logs_entry_kind, debug_collect_logs_include, debug_collect_logs_redaction, debug_collect_logs_request, debug_collect_logs_result, debug_collect_logs_result_kind, debug_collect_logs_skipped_entry, debug_collect_logs_source, diagnostic_cursor_status, diagnostic_entry, diagnostic_log_level, diagnostics_configuration, diagnostics_configure_request, diagnostic_severity, diagnostic_source, diagnostic_sources_configuration, diagnostics_read_request, diagnostics_read_result, discovered_canvas, discovered_extension, discovered_extension_mode, discovered_extension_plugin, discovered_extensions, discovered_extensions_disable_request, discovered_extensions_enable_request, discovered_extension_source, discovered_hook, discovered_mcp_server, discovered_mcp_server_type, enqueue_command_params, enqueue_command_result, env_auth_info, event_log_read_request, event_log_release_interest_result, event_log_tail_result, event_log_types, events_agent_scope, events_cursor_status, events_read_direction, events_read_result, execute_command_params, execute_command_result, extension, extension_context_push_input, extension_launch_profile, extension_launch_provider_resolve_request, extension_launch_provider_resolve_result, extension_list, extensions_disable_request, extensions_enable_request, extension_source, extension_status, external_tool_result, external_tool_text_result_for_llm, external_tool_text_result_for_llm_binary_results_for_llm, external_tool_text_result_for_llm_binary_results_for_llm_type, external_tool_text_result_for_llm_content, external_tool_text_result_for_llm_content_audio, external_tool_text_result_for_llm_content_image, external_tool_text_result_for_llm_content_resource, external_tool_text_result_for_llm_content_resource_details, external_tool_text_result_for_llm_content_resource_link, external_tool_text_result_for_llm_content_resource_link_icon, external_tool_text_result_for_llm_content_resource_link_icon_theme, external_tool_text_result_for_llm_content_shell_exit, external_tool_text_result_for_llm_content_terminal, external_tool_text_result_for_llm_content_text, filter_mapping, fleet_start_request, fleet_start_result, folder_trust_add_params, folder_trust_check_params, folder_trust_check_result, gh_cli_auth_info, git_hub_telemetry_client_info, git_hub_telemetry_event, git_hub_telemetry_notification, git_hub_token_acquire_reason, git_hub_token_acquire_request, git_hub_token_acquire_result, handle_pending_tool_call_request, handle_pending_tool_call_result, history_abort_manual_compaction_result, history_cancel_background_compaction_result, history_clear_context_request, history_clear_context_result, history_compact_context_window, history_compact_request, history_compact_result, history_file_restore_skip_reason, history_list_rewind_points_result, history_preview_rewind_request, history_preview_rewind_result, history_rewind_change_type, history_rewind_file_preview, history_rewind_mode, history_rewind_outcome, history_rewind_point, history_rewind_request, history_rewind_result, history_rewind_unavailable_reason, history_skipped_file_restore, history_summarize_for_handoff_result, history_truncate_request, history_truncate_result, hmac_auth_info, hook_invoke_request, hook_invoke_response, hook_origin, hooks_discover_request, hooks_discover_result, hook_type, installed_plugin, installed_plugin_info, installed_plugin_source, installed_plugin_source_git_hub, installed_plugin_source_local, installed_plugin_source_url, instruction_discovery_path, instruction_discovery_path_kind, instruction_discovery_path_list, instruction_discovery_path_location, instructions_discover_request, instructions_get_discovery_paths_request, instructions_get_sources_result, instruction_source, instruction_source_location, instruction_source_type, interrupt_main_turn_request, interrupt_main_turn_result, json_schema_response_format, llm_inference_headers, llm_inference_http_request_chunk_request, llm_inference_http_request_chunk_result, llm_inference_http_request_start_request, llm_inference_http_request_start_result, llm_inference_http_request_start_transport, llm_inference_http_response_chunk_error, llm_inference_http_response_chunk_request, llm_inference_http_response_chunk_result, llm_inference_http_response_start_request, llm_inference_http_response_start_result, llm_inference_set_provider_result, local_session_metadata_value, login_provider_kind, log_request, log_result, lsp_initialize_request, managed_mcp_server_config, managed_settings_read_result, managed_settings_resolved_data, marketplace_add_result, marketplace_browse_result, marketplace_info, marketplace_list_result, marketplace_plugin_info, marketplace_refresh_entry, marketplace_refresh_result, marketplace_remove_result, mcp_allowed_server, mcp_apps_call_tool_request, mcp_apps_diagnose_capability, mcp_apps_diagnose_request, mcp_apps_diagnose_result, mcp_apps_diagnose_server, mcp_apps_host_context, mcp_apps_host_context_details, mcp_apps_host_context_details_available_display_mode, mcp_apps_host_context_details_display_mode, mcp_apps_host_context_details_platform, mcp_apps_host_context_details_theme, mcp_apps_list_tools_request, mcp_apps_list_tools_result, mcp_apps_read_resource_request, mcp_apps_read_resource_result, mcp_apps_resource_content, mcp_apps_set_host_context_details, mcp_apps_set_host_context_details_available_display_mode, mcp_apps_set_host_context_details_display_mode, mcp_apps_set_host_context_details_platform, mcp_apps_set_host_context_details_theme, mcp_apps_set_host_context_request, mcp_cancel_sampling_execution_params, mcp_cancel_sampling_execution_result, mcp_config_add_request, mcp_config_disable_request, mcp_config_enable_request, mcp_config_list, mcp_config_remove_request, mcp_config_update_request, mcp_configure_git_hub_request, mcp_configure_git_hub_result, mcp_diagnostic_details, mcp_diagnostic_direction, mcp_diagnostic_kind, mcp_diagnostic_source_configuration, mcp_disable_request, mcp_discover_request, mcp_discover_result, mcp_elicitation_form_mode, mcp_enable_request, mcp_execute_sampling_params, mcp_execute_sampling_request, mcp_execute_sampling_result, mcp_failed_server, mcp_filtered_server, mcp_headers_handle_pending_headers_refresh_request, mcp_headers_handle_pending_headers_refresh_request_request, mcp_headers_handle_pending_headers_refresh_request_result, mcp_host_state, mcp_install_plan, mcp_is_server_running_request, mcp_is_server_running_result, mcp_list_tools_request, mcp_list_tools_result, mcp_oauth_authentication_state_changed_request, mcp_oauth_handle_pending_request, mcp_oauth_handle_pending_result, mcp_oauth_login_grant_type, mcp_oauth_login_request, mcp_oauth_login_result, mcp_oauth_pending_request_response, mcp_oauth_probe_needs_auth_reason, mcp_oauth_probe_request, mcp_oauth_probe_result, mcp_oauth_respond_request, mcp_oauth_respond_result, mcp_plan_configuration_change, mcp_plan_configuration_operation, mcp_plan_enum_value_type, mcp_plan_install_planned, mcp_plan_install_request, mcp_plan_install_result, mcp_plan_install_source, mcp_plan_install_source_candidate, mcp_plan_install_source_candidate_kind, mcp_plan_install_source_card, mcp_plan_install_source_card_kind, mcp_plan_package_install_method, mcp_plan_package_transport, mcp_plan_policy_decision, mcp_plan_policy_result, mcp_plan_policy_source, mcp_plan_provenance, mcp_plan_remote_install_method, mcp_plan_remote_transport, mcp_plan_required_value, mcp_plan_required_value_enum, mcp_plan_required_value_enum_kind, mcp_plan_required_value_scalar, mcp_plan_required_value_scalar_kind, mcp_plan_resource_identity, mcp_plan_scalar_value_type, mcp_plan_scope, mcp_plan_secret_placeholder, mcp_plan_secret_reference, mcp_plan_target, mcp_plan_transport_choice, mcp_plan_transport_choice_package, mcp_plan_transport_choice_remote, mcp_plan_value_category, mcp_register_external_client_request, mcp_reload_config, mcp_reload_with_config_request, mcp_remove_git_hub_result, mcp_resource, mcp_resource_annotations, mcp_resource_content, mcp_resource_icon, mcp_resources_list_request, mcp_resources_list_result, mcp_resources_list_templates_request, mcp_resources_list_templates_result, mcp_resources_read_request, mcp_resources_read_result, mcp_resource_template, mcp_restart_server_request, mcp_safe_for_telemetry, mcp_safe_for_telemetry_fields, mcp_sampling_execution_action, mcp_sampling_execution_result, mcp_serializable_server_config, mcp_server, mcp_server_auth_config, mcp_server_auth_config_redirect_port, mcp_server_card_embedded, mcp_server_card_embedded_kind, mcp_server_card_media_type, mcp_server_card_reference, mcp_server_card_url, mcp_server_card_url_kind, mcp_server_config, mcp_server_config_defer_tools, mcp_server_config_http, mcp_server_config_http_oauth_grant_type, mcp_server_config_http_type, mcp_server_config_memory, mcp_server_config_memory_type, mcp_server_config_stdio, mcp_server_config_stdio_type, mcp_server_failure_info, mcp_server_list, mcp_server_needs_auth_info, mcp_set_env_value_mode_details, mcp_set_env_value_mode_params, mcp_set_env_value_mode_result, mcp_source_file, mcp_source_plugin, mcp_source_ref, mcp_start_server_request, mcp_start_servers_result, mcp_stop_server_request, mcp_task_metadata, mcp_tools, mcp_tool_ui, mcp_tool_ui_visibility, mcp_unregister_external_client_request, memory_configuration, metadata_context_attribution_result, metadata_context_heaviest_messages_request, metadata_context_heaviest_messages_result, metadata_context_info_request, metadata_context_info_result, metadata_is_processing_result, metadata_recompute_context_tokens_request, metadata_recompute_context_tokens_result, metadata_record_context_change_request, metadata_record_context_change_result, metadata_set_working_directory_request, metadata_set_working_directory_result, metadata_snapshot_current_mode, metadata_snapshot_remote_metadata, metadata_snapshot_remote_metadata_repository, metadata_snapshot_remote_metadata_task_type, metadata_update_client_metadata_request, model, model_apply_startup_overlay_request, model_billing, model_billing_promo, model_billing_token_prices, model_billing_token_prices_long_context, model_capabilities, model_capabilities_limits, model_capabilities_limits_vision, model_capabilities_override, model_capabilities_override_limits, model_capabilities_override_limits_vision, model_capabilities_override_supports, model_capabilities_supports, model_list, model_list_request, model_message, model_picker_category, model_picker_persistence_request, model_picker_price_category, model_picker_settings_context, model_policy, model_policy_state, model_set_allowed_models_request, model_set_allowed_models_result, model_set_reasoning_effort_request, model_set_reasoning_effort_result, models_list_request, model_switch_auto_tier_request, model_switch_auto_tier_result, model_switch_auto_tier_status, model_switch_confirmation, model_switch_to_request, model_switch_to_result, model_warning_text, mode_set_request, mode_set_result, move_mcp_loading_to_background_result, named_provider_config, name_get_result, name_set_auto_request, name_set_auto_result, name_set_request, open_canvas_instance, options_update_additional_content_exclusion_policy, options_update_additional_content_exclusion_policy_rule, options_update_additional_content_exclusion_policy_rule_source, options_update_additional_content_exclusion_policy_scope, options_update_context_tier, options_update_env_value_mode, options_update_reasoning_summary, options_update_tool_filter_precedence, pending_permission_request, pending_permission_request_list, permission_decision, permission_decision_approved, permission_decision_approved_for_location, permission_decision_approved_for_session, permission_decision_approve_for_location, permission_decision_approve_for_location_approval, permission_decision_approve_for_location_approval_commands, permission_decision_approve_for_location_approval_custom_tool, permission_decision_approve_for_location_approval_extension_env_access, permission_decision_approve_for_location_approval_extension_management, permission_decision_approve_for_location_approval_extension_permission_access, permission_decision_approve_for_location_approval_mcp, permission_decision_approve_for_location_approval_mcp_sampling, permission_decision_approve_for_location_approval_memory, permission_decision_approve_for_location_approval_read, permission_decision_approve_for_location_approval_workflow, permission_decision_approve_for_location_approval_write, permission_decision_approve_for_session, permission_decision_approve_for_session_approval, permission_decision_approve_for_session_approval_commands, permission_decision_approve_for_session_approval_custom_tool, permission_decision_approve_for_session_approval_extension_env_access, permission_decision_approve_for_session_approval_extension_management, permission_decision_approve_for_session_approval_extension_permission_access, permission_decision_approve_for_session_approval_mcp, permission_decision_approve_for_session_approval_mcp_sampling, permission_decision_approve_for_session_approval_memory, permission_decision_approve_for_session_approval_read, permission_decision_approve_for_session_approval_workflow, permission_decision_approve_for_session_approval_write, permission_decision_approve_once, permission_decision_approve_permanently, permission_decision_cancelled, permission_decision_context, permission_decision_denied_by_content_exclusion_policy, permission_decision_denied_by_permission_request_hook, permission_decision_denied_by_rules, permission_decision_denied_interactively_by_user, permission_decision_denied_no_approval_rule_and_could_not_request_from_user, permission_decision_outcome, permission_decision_reject, permission_decision_request, permission_decision_surface, permission_decision_user_not_available, permission_location_add_tool_approval_params, permission_location_apply_params, permission_location_apply_result, permission_location_resolve_params, permission_location_resolve_result, permission_location_type, permission_mode_source, permission_paths_add_params, permission_paths_allowed_check_params, permission_paths_allowed_check_result, permission_paths_config, permission_paths_list, permission_paths_update_primary_params, permission_paths_workspace_check_params, permission_paths_workspace_check_result, permission_prompt_shown_notification, permission_request_result, permission_response_capability, permission_rules_set, permissions_configure_additional_content_exclusion_policy, permissions_configure_additional_content_exclusion_policy_rule, permissions_configure_additional_content_exclusion_policy_rule_source, permissions_configure_additional_content_exclusion_policy_scope, permissions_configure_params, permissions_configure_result, permissions_folder_trust_add_trusted_result, permissions_get_mode_request, permissions_get_mode_result, permissions_locations_add_tool_approval_details, permissions_locations_add_tool_approval_details_commands, permissions_locations_add_tool_approval_details_custom_tool, permissions_locations_add_tool_approval_details_extension_env_access, permissions_locations_add_tool_approval_details_extension_management, permissions_locations_add_tool_approval_details_extension_permission_access, permissions_locations_add_tool_approval_details_mcp, permissions_locations_add_tool_approval_details_mcp_sampling, permissions_locations_add_tool_approval_details_memory, permissions_locations_add_tool_approval_details_read, permissions_locations_add_tool_approval_details_workflow, permissions_locations_add_tool_approval_details_write, permissions_locations_add_tool_approval_result, permissions_modify_rules_params, permissions_modify_rules_result, permissions_modify_rules_scope, permissions_notify_prompt_shown_result, permissions_paths_add_result, permissions_paths_list_request, permissions_paths_update_primary_result, permissions_pending_requests_request, permissions_reset_session_approvals_request, permissions_reset_session_approvals_result, permissions_set_approve_all_request, permissions_set_approve_all_result, permissions_set_approve_all_source, permissions_set_mode_request, permissions_set_mode_result, permissions_set_required_request, permissions_set_required_result, permissions_urls_set_unrestricted_mode_result, permission_urls_config, permission_urls_set_unrestricted_mode_params, ping_request, ping_result, plan_read_result, plan_read_sql_todos_result, plan_read_sql_todos_with_dependencies_result, plan_sql_todo_dependency, plan_sql_todos_row, plan_update_request, plugin, plugin_install_result, plugin_install_staging_mode, plugin_list, plugin_list_result, plugins_builtin_set_request, plugins_disable_request, plugins_enable_request, plugins_install_request, plugins_marketplaces_add_request, plugins_marketplaces_browse_request, plugins_marketplaces_refresh_request, plugins_marketplaces_remove_request, plugins_reload_request, plugins_uninstall_request, plugins_update_request, plugin_update_all_entry, plugin_update_all_result, plugin_update_result, protocol_append_mode, protocol_customize_mode, protocol_external_tool_defer, protocol_external_tool_definition, protocol_marker_section_override, protocol_replace_mode, protocol_section_override, protocol_static_section_action, protocol_static_section_override, protocol_system_message_append_config, protocol_system_message_config, protocol_system_message_customize_config, protocol_system_message_replace_config, provider_add_request, provider_add_result, provider_config, provider_config_azure, provider_config_transport, provider_config_type, provider_config_wire_api, provider_descriptor, provider_endpoint, provider_endpoint_transport, provider_endpoint_type, provider_endpoint_wire_api, provider_get_endpoint_request, provider_model_config, provider_session_token, provider_sync_request, provider_sync_result, provider_token_acquire_request, provider_token_acquire_result, push_attachment, push_attachment_blob, push_attachment_directory, push_attachment_file, push_attachment_file_line_range, push_attachment_git_hub_actions_job, push_attachment_git_hub_commit, push_attachment_git_hub_file, push_attachment_git_hub_file_diff, push_attachment_git_hub_file_diff_side, push_attachment_git_hub_reference, push_attachment_git_hub_reference_type, push_attachment_git_hub_release, push_attachment_git_hub_repository, push_attachment_git_hub_snippet, push_attachment_git_hub_tree_comparison, push_attachment_git_hub_tree_comparison_side, push_attachment_git_hub_url, push_attachment_selection, push_attachment_selection_details, push_attachment_selection_details_end, push_attachment_selection_details_start, push_git_hub_repo_ref, queue_append_steering_request, queue_begin_deferred_idle_drain_request, queue_begin_deferred_idle_drain_result, queue_consume_system_notifications_request, queued_command_handled, queued_command_not_handled, queued_command_result, queue_defer_session_idle_request, queue_duplicate_at_request, queue_duplicate_at_result, queue_enqueue_resume_pending_result, queue_finish_deferred_idle_drain_request, queue_finish_deferred_idle_drain_result, queue_has_pending_result, queue_insert_at_request, queue_insert_at_result, queue_insert_message, queue_move_item_request, queue_move_item_result, queue_pending_items, queue_pending_items_kind, queue_pending_items_result, queue_remove_at_request, queue_remove_at_result, queue_remove_most_recent_result, queue_send_now_request, queue_send_now_result, queue_set_drain_paused_request, queue_snapshot_result, queue_update_text_request, queue_update_text_result, queue_withdraw_message_request, queue_withdraw_message_result, register_event_interest_params, register_event_interest_result, release_event_interest_params, remote_control_config, remote_control_config_existing_mc_session, remote_control_status, remote_control_status_active, remote_control_status_connecting, remote_control_status_error, remote_control_status_off, remote_control_status_result, remote_control_stop_result, remote_control_transfer_result, remote_enable_request, remote_enable_result, remote_notify_steerable_changed_request, remote_notify_steerable_changed_result, remote_session_connection_result, remote_session_host_status, remote_session_metadata_repository, remote_session_metadata_task_type, remote_session_metadata_value, remote_session_mode, remote_session_repository, response_format, sandbox_config, sandbox_config_auth, sandbox_config_source, sandbox_config_user_policy, sandbox_config_user_policy_experimental, sandbox_config_user_policy_experimental_seatbelt, sandbox_config_user_policy_filesystem, sandbox_config_user_policy_network, sandbox_config_user_policy_network_proxy, sandbox_config_user_policy_seatbelt, sandbox_disable_for_session_request, sandbox_disable_for_session_result, sandbox_enforcement_status, sandbox_host_capability, sandbox_host_capability_name, sandbox_host_support, sandbox_session_change, schedule_add_at_request, schedule_add_cron_request, schedule_add_request, schedule_add_result, schedule_add_self_paced_request, schedule_entry, schedule_has_self_paced_result, schedule_list, schedule_rearm_self_paced_request, schedule_stop_request, schedule_stop_result, secrets_add_filter_values_request, secrets_add_filter_values_result, send_agent_mode, send_attachments_to_message_params, send_message_item, send_messages_request, send_messages_result, send_mode, send_request, send_result, send_system_notification_request, server_agent_list, server_instruction_source_list, server_skill, server_skill_list, session_activity, session_agent_list_request, session_auth_login_request, session_auth_logout_user_request, session_auth_status, session_auth_switch_request, session_bulk_delete_result, session_cancel_all_background_agents_result, session_capability, session_commands_list_request, session_completion_item, session_context, session_context_host_type, session_enrich_metadata_result, session_fs_append_file_request, session_fs_error, session_fs_error_code, session_fs_exists_request, session_fs_exists_result, session_fs_mkdir_request, session_fs_readdir_request, session_fs_readdir_result, session_fs_readdir_with_types_entry, session_fs_readdir_with_types_entry_type, session_fs_readdir_with_types_request, session_fs_readdir_with_types_result, session_fs_read_file_request, session_fs_read_file_result, session_fs_rename_request, session_fs_rm_request, session_fs_set_provider_capabilities, session_fs_set_provider_conventions, session_fs_set_provider_request, session_fs_set_provider_result, session_fs_sqlite_exists_request, session_fs_sqlite_exists_result, session_fs_sqlite_query_request, session_fs_sqlite_query_result, session_fs_sqlite_query_type, session_fs_sqlite_transaction_error, session_fs_sqlite_transaction_error_class, session_fs_sqlite_transaction_request, session_fs_sqlite_transaction_result, session_fs_sqlite_transaction_statement, session_fs_stat_request, session_fs_stat_result, session_fs_write_file_request, session_git_hub_auth_get_all_auth_available_result, session_git_hub_auth_logout_result, session_git_hub_auth_logout_user_result, session_history_compact_request, session_installed_plugin, session_installed_plugin_source, session_installed_plugin_source_git_hub, session_installed_plugin_source_local, session_installed_plugin_source_url, session_limit_prediction_baseline_data, session_limit_prediction_client_type, session_limit_prediction_details, session_limit_prediction_predict_request, session_limit_prediction_request, session_limit_prediction_result, session_limit_prediction_source, session_limit_prediction_tier, session_limit_prediction_tier_option, session_limit_prediction_unavailable_reason, session_list, session_list_entry, session_list_filter, session_load_deferred_repo_hooks_result, session_log_level, session_managed_permissions, session_managed_settings, session_mcp_apps_call_tool_result, session_metadata_snapshot, session_mode, session_model_list, session_model_list_request, session_model_price_category, session_open_options, session_open_options_additional_content_exclusion_policy, session_open_options_additional_content_exclusion_policy_rule, session_open_options_additional_content_exclusion_policy_rule_source, session_open_options_additional_content_exclusion_policy_scope, session_open_options_env_value_mode, session_open_options_reasoning_summary, session_open_params, session_open_result, session_plugins_disable_request, session_plugins_enable_request, session_plugins_install_request, session_plugins_marketplaces_refresh_request, session_plugins_reload_request, session_provider_get_endpoint_request, session_prune_result, sessions_bulk_delete_request, sessions_check_in_use_request, sessions_check_in_use_result, sessions_client_metadata_entry, sessions_close_request, sessions_close_result, sessions_delete_request, sessions_enrich_metadata_request, session_set_credentials_params, session_set_credentials_result, session_settings_built_in_tool_availability_snapshot, session_settings_evaluate_predicate_request, session_settings_evaluate_predicate_result, session_settings_job_snapshot, session_settings_model_snapshot, session_settings_online_evaluation_snapshot, session_settings_predicate_name, session_settings_repo_snapshot, session_settings_snapshot, session_settings_validation_snapshot, sessions_find_by_prefix_request, sessions_find_by_prefix_result, sessions_find_by_task_id_request, sessions_find_by_task_id_result, sessions_fork_request, sessions_fork_result, sessions_get_board_entry_count_request, sessions_get_board_entry_count_result, sessions_get_client_metadata_request, sessions_get_client_metadata_result, sessions_get_event_file_path_request, sessions_get_event_file_path_result, sessions_get_last_for_context_request, sessions_get_last_for_context_result, sessions_get_metadata_request, sessions_get_metadata_result, sessions_get_persisted_remote_steerable_request, sessions_get_persisted_remote_steerable_result, session_sizes, sessions_list_non_empty_session_ids_request, sessions_list_non_empty_session_ids_result, sessions_list_request, sessions_load_deferred_repo_hooks_request, sessions_open_attach, sessions_open_cloud, sessions_open_create, sessions_open_handoff, sessions_open_handoff_task_type, sessions_open_progress, sessions_open_progress_status, sessions_open_progress_step, sessions_open_remote, sessions_open_resume, sessions_open_resume_last, sessions_open_status, session_source, sessions_prune_old_request, sessions_read_persisted_events_request, sessions_release_lock_request, sessions_release_lock_result, sessions_reload_plugin_hooks_request, sessions_reload_plugin_hooks_result, sessions_save_request, sessions_save_result, sessions_set_additional_plugins_request, sessions_set_additional_plugins_result, sessions_set_remote_control_steering_request, sessions_start_remote_control_request, sessions_stop_remote_control_request, sessions_transfer_remote_control_request, session_telemetry_engagement, session_update_options_params, session_update_options_result, session_visibility_status, session_workflow_pause_at_checkpoint_result, session_working_directory_context, session_working_directory_context_host_type, settable_auth_info, settable_token_auth_info, shell_cancel_user_requested_request, shell_credentials, shell_exec_request, shell_exec_result, shell_execute_user_requested_request, shell_init_profile, shell_init_script, shell_init_script_shell, shell_kill_request, shell_kill_result, shell_kill_signal, shell_options, shutdown_request, skill, skill_discovery_path, skill_discovery_path_list, skill_discovery_scope, skill_list, skill_provider_descriptor, skill_provider_list_request, skill_provider_list_result, skill_provider_read_request, skill_provider_read_result, skills_config_set_disabled_skills_request, skills_config_set_skill_disabled_request, skills_disable_request, skills_discover_request, skills_enable_request, skills_get_discovery_paths_request, skills_get_invoked_result, skills_invoked_skill, skills_load_diagnostics, slash_command_add_timeline_entry_result, slash_command_agent_prompt_result, slash_command_completed_result, slash_command_info, slash_command_input, slash_command_input_choice, slash_command_input_completion, slash_command_invocation_result, slash_command_kind, slash_command_model_picker_dialog, slash_command_select_subcommand_option, slash_command_select_subcommand_result, slash_command_set_model_result, slash_command_set_plan_model_result, slash_command_show_dialog_result, slash_command_text_result, slash_command_timeline_entry, subagent_settings_entry, subagent_settings_entry_context_tier, system_message_block, task_agent_info, task_agent_progress, task_client_active_status, task_client_execution_mode, task_client_info, task_client_owner, task_client_owner_kind, task_client_owner_presence, task_client_progress, task_client_status, task_client_type, task_client_update, task_complete_data, task_completion_decision, task_execution_mode, task_info, task_kind, task_list, task_progress_line, tasks_cancel_request, tasks_cancel_result, tasks_get_current_promotable_result, tasks_get_progress_request, tasks_get_progress_result, task_shell_info, task_shell_info_attachment_mode, task_shell_progress, tasks_promote_current_to_background_result, tasks_promote_to_background_request, tasks_promote_to_background_result, tasks_refresh_result, tasks_register_request, tasks_register_result, tasks_remove_request, tasks_remove_result, tasks_send_message_request, tasks_send_message_result, tasks_start_agent_request, tasks_start_agent_result, task_status, tasks_update_request, tasks_update_result, tasks_wait_for_pending_result, telemetry_set_feature_overrides_request, token_auth_info, token_provider_auth_info, tool, tool_list, tool_result, tool_result_expanded, tool_result_new_message, tool_result_type, tools_execute_request, tools_get_builtin_descriptors_request, tools_get_builtin_descriptors_result, tools_get_current_metadata_result, tools_initialize_and_validate_result, tools_list_request, tools_set_request, tools_set_result, tools_shell_descriptor_config, tools_task_complete_event_data_request, tools_update_subagent_settings_result, ui_auto_mode_switch_response, ui_elicitation_array_any_of_field, ui_elicitation_array_any_of_field_items, ui_elicitation_array_any_of_field_items_any_of, ui_elicitation_array_enum_field, ui_elicitation_array_enum_field_items, ui_elicitation_field_value, ui_elicitation_request, ui_elicitation_response, ui_elicitation_response_action, ui_elicitation_response_content, ui_elicitation_result, ui_elicitation_schema, ui_elicitation_schema_property, ui_elicitation_schema_property_boolean, ui_elicitation_schema_property_number, ui_elicitation_schema_property_number_type, ui_elicitation_schema_property_string, ui_elicitation_schema_property_string_format, ui_elicitation_string_enum_field, ui_elicitation_string_one_of_field, ui_elicitation_string_one_of_field_one_of, ui_ephemeral_query_request, ui_ephemeral_query_result, ui_exit_plan_mode_action, ui_exit_plan_mode_response, ui_handle_pending_auto_mode_switch_request, ui_handle_pending_elicitation_request, ui_handle_pending_exit_plan_mode_request, ui_handle_pending_result, ui_handle_pending_sampling_request, ui_handle_pending_sampling_response, ui_handle_pending_session_limits_exhausted_request, ui_handle_pending_user_input_request, ui_register_direct_auto_mode_switch_handler_result, ui_session_limits_exhausted_response, ui_session_limits_exhausted_response_action, ui_unregister_direct_auto_mode_switch_handler_request, ui_unregister_direct_auto_mode_switch_handler_result, ui_user_input_response, unsupported_enqueue_command_result, update_subagent_settings_request, usage_get_metrics_result, usage_metrics_agent_metric, usage_metrics_code_changes, usage_metrics_model_metric, usage_metrics_model_metric_requests, usage_metrics_model_metric_token_detail, usage_metrics_model_metric_usage, usage_metrics_token_detail, user_auth_info, user_requested_shell_command_result, user_setting_metadata, user_settings_get_result, user_settings_set_request, user_settings_set_result, visibility_get_result, visibility_set_request, visibility_set_result, workflow_abort_request, workflow_ack_result, workflow_agent_options, workflow_agent_request, workflow_agent_result, workflow_agent_summary, workflow_cancel_request, workflow_current_phase, workflow_declared_limits, workflow_durable_operation, workflow_execute_request, workflow_execute_result, workflow_get_run_progress_request, workflow_get_run_request, workflow_journal_get_request, workflow_journal_get_result, workflow_journal_put_request, workflow_list_runs_request, workflow_list_runs_result, workflow_log_line, workflow_log_line_kind, workflow_log_request, workflow_pause_checkpoint_action, workflow_pause_checkpoint_request, workflow_pause_checkpoint_result, workflow_pause_info, workflow_pause_request, workflow_phase_observation, workflow_phase_status, workflow_progress_line, workflow_progress_page, workflow_resume_request, workflow_resume_result, workflow_run_consumed, workflow_run_detail, workflow_run_failure, workflow_run_failure_kind, workflow_run_limits, workflow_run_options, workflow_run_request, workflow_run_result, workflow_run_status, workflow_run_summary, workflow_run_terminal, workflow_tool_resume_request, workflow_tool_run_options, workflow_tool_run_request, workspace_diff_file_change, workspace_diff_file_change_type, workspace_diff_mode, workspace_diff_result, workspaces_add_summary_request, workspaces_add_summary_result, workspaces_autopilot_objective_exists_result, workspaces_checkpoints, workspaces_create_directory_request, workspaces_create_file_request, workspaces_delete_autopilot_objective_result, workspaces_diff_request, workspaces_ensure_request, workspaces_get_workspace_result, workspaces_list_checkpoints_result, workspaces_list_files_result, workspaces_read_autopilot_objective_result, workspaces_read_checkpoint_request, workspaces_read_checkpoint_result, workspaces_read_file_request, workspaces_read_file_result, workspaces_remove_path_request, workspaces_rename_path_request, workspaces_save_large_paste_request, workspaces_save_large_paste_result, workspaces_stat_file_request, workspaces_stat_file_result, workspaces_truncate_summaries_request, workspace_summary_host_type, workspaces_update_metadata_request, workspaces_workspace_details_host_type, workspaces_write_autopilot_objective_request, workspaces_write_autopilot_objective_result, session_auth_info_result, session_context_attribution, session_context_info, subagent_settings, task_progress, workspace_summary) def to_dict(self) -> dict: result: dict = {} @@ -44998,11 +43903,16 @@ def to_dict(self) -> dict: result["AccountGetCurrentAuthResult"] = to_class(AccountGetCurrentAuthResult, self.account_get_current_auth_result) result["AccountGetQuotaRequest"] = to_class(AccountGetQuotaRequest, self.account_get_quota_request) result["AccountGetQuotaResult"] = to_class(AccountGetQuotaResult, self.account_get_quota_result) + result["AccountKind"] = to_enum(AccountKind, self.account_kind) result["AccountLoginRequest"] = to_class(AccountLoginRequest, self.account_login_request) result["AccountLoginResult"] = to_class(AccountLoginResult, self.account_login_result) result["AccountLogoutRequest"] = to_class(AccountLogoutRequest, self.account_logout_request) result["AccountLogoutResult"] = to_class(AccountLogoutResult, self.account_logout_result) result["AccountQuotaSnapshot"] = to_class(AccountQuotaSnapshot, self.account_quota_snapshot) + result["AccountsEnumerateRequest"] = to_class(AccountsEnumerateRequest, self.accounts_enumerate_request) + result["AccountsGetRequest"] = to_class(AccountsGetRequest, self.accounts_get_request) + result["AccountsSetRequest"] = to_class(AccountsSetRequest, self.accounts_set_request) + result["AccountStatus"] = to_class(AccountStatus, self.account_status) result["AdaptiveThinkingSupport"] = to_enum(AdaptiveThinkingSupport, self.adaptive_thinking_support) result["AgentDiscoveryPath"] = to_class(AgentDiscoveryPath, self.agent_discovery_path) result["AgentDiscoveryPathList"] = to_class(AgentDiscoveryPathList, self.agent_discovery_path_list) @@ -45035,11 +43945,25 @@ def to_dict(self) -> dict: result["AgentSetPromptRequest"] = to_class(AgentSetPromptRequest, self.agent_set_prompt_request) result["AgentsGetDiscoveryPathsRequest"] = to_class(AgentsGetDiscoveryPathsRequest, self.agents_get_discovery_paths_request) result["ApiKeyAuthInfo"] = to_class(APIKeyAuthInfo, self.api_key_auth_info) + result["AuthEnumerateQuery"] = to_class(AuthEnumerateQuery, self.auth_enumerate_query) + result["AuthEnumerateValue"] = to_class(AuthEnumerateValue, self.auth_enumerate_value) result["AuthIdentity"] = to_class(AuthIdentity, self.auth_identity) result["AuthInfo"] = (self.auth_info).to_dict() result["AuthInfoType"] = to_enum(AuthInfoType, self.auth_info_type) + result["AuthLoginAdvanceRequest"] = to_class(AuthLoginAdvanceRequest, self.auth_login_advance_request) + result["AuthLoginBeginRequest"] = to_class(AuthLoginBeginRequest, self.auth_login_begin_request) + result["AuthLoginBegun"] = to_class(AuthLoginBegun, self.auth_login_begun) + result["AuthLoginCancelRequest"] = to_class(AuthLoginCancelRequest, self.auth_login_cancel_request) + result["AuthLoginResultDto"] = to_class(AuthLoginResultDto, self.auth_login_result_dto) + result["AuthLoginResultStatus"] = to_enum(AuthLoginResultStatus, self.auth_login_result_status) + result["AuthLoginStep"] = to_class(AuthLoginStep, self.auth_login_step) + result["AuthReadQuery"] = to_class(AuthReadQuery, self.auth_read_query) + result["AuthReadValue"] = to_class(AuthReadValue, self.auth_read_value) + result["AuthStatusDto"] = to_class(AuthStatusDto, self.auth_status_dto) result["AuthValidationError"] = to_class(AuthValidationError, self.auth_validation_error) result["AuthValidationErrors"] = from_list(lambda x: to_class(AuthValidationError, x), self.auth_validation_errors) + result["AuthWrite"] = to_class(AuthWrite, self.auth_write) + result["AuthWriteResult"] = to_class(AuthWriteResult, self.auth_write_result) result["AutopilotObjectiveCreditLimit"] = to_class(AutopilotObjectiveCreditLimit, self.autopilot_objective_credit_limit) result["AutopilotObjectiveGetStateResult"] = to_class(AutopilotObjectiveGetStateResult, self.autopilot_objective_get_state_result) result["AutopilotObjectiveState"] = to_class(AutopilotObjectiveState, self.autopilot_objective_state) @@ -45291,52 +44215,6 @@ def to_dict(self) -> dict: result["ExternalToolTextResultForLlmContentShellExit"] = to_class(ExternalToolTextResultForLlmContentShellExit, self.external_tool_text_result_for_llm_content_shell_exit) result["ExternalToolTextResultForLlmContentTerminal"] = to_class(ExternalToolTextResultForLlmContentTerminal, self.external_tool_text_result_for_llm_content_terminal) result["ExternalToolTextResultForLlmContentText"] = to_class(ExternalToolTextResultForLlmContentText, self.external_tool_text_result_for_llm_content_text) - result["FactoryAbortRequest"] = to_class(FactoryAbortRequest, self.factory_abort_request) - result["FactoryAckResult"] = to_class(FactoryACKResult, self.factory_ack_result) - result["FactoryAgentOptions"] = to_class(FactoryAgentOptions, self.factory_agent_options) - result["FactoryAgentRequest"] = to_class(FactoryAgentRequest, self.factory_agent_request) - result["FactoryAgentResult"] = to_class(FactoryAgentResult, self.factory_agent_result) - result["FactoryAgentSummary"] = to_class(FactoryAgentSummary, self.factory_agent_summary) - result["FactoryCancelRequest"] = to_class(FactoryCancelRequest, self.factory_cancel_request) - result["FactoryCurrentPhase"] = to_class(FactoryCurrentPhase, self.factory_current_phase) - result["FactoryDeclaredLimits"] = to_class(FactoryDeclaredLimits, self.factory_declared_limits) - result["FactoryDurableOperation"] = to_enum(DurableOperation, self.factory_durable_operation) - result["FactoryExecuteRequest"] = to_class(FactoryExecuteRequest, self.factory_execute_request) - result["FactoryExecuteResult"] = to_class(FactoryExecuteResult, self.factory_execute_result) - result["FactoryGetRunProgressRequest"] = to_class(FactoryGetRunProgressRequest, self.factory_get_run_progress_request) - result["FactoryGetRunRequest"] = to_class(FactoryGetRunRequest, self.factory_get_run_request) - result["FactoryJournalGetRequest"] = to_class(FactoryJournalGetRequest, self.factory_journal_get_request) - result["FactoryJournalGetResult"] = to_class(FactoryJournalGetResult, self.factory_journal_get_result) - result["FactoryJournalPutRequest"] = to_class(FactoryJournalPutRequest, self.factory_journal_put_request) - result["FactoryListRunsRequest"] = to_class(FactoryListRunsRequest, self.factory_list_runs_request) - result["FactoryListRunsResult"] = to_class(FactoryListRunsResult, self.factory_list_runs_result) - result["FactoryLogLine"] = to_class(FactoryLogLine, self.factory_log_line) - result["FactoryLogLineKind"] = to_enum(LogLineKind, self.factory_log_line_kind) - result["FactoryLogRequest"] = to_class(FactoryLogRequest, self.factory_log_request) - result["FactoryPauseCheckpointAction"] = to_enum(PauseCheckpointAction, self.factory_pause_checkpoint_action) - result["FactoryPauseCheckpointRequest"] = to_class(FactoryPauseCheckpointRequest, self.factory_pause_checkpoint_request) - result["FactoryPauseCheckpointResult"] = to_class(FactoryPauseCheckpointResult, self.factory_pause_checkpoint_result) - result["FactoryPauseInfo"] = to_class(FactoryPauseInfo, self.factory_pause_info) - result["FactoryPauseRequest"] = to_class(FactoryPauseRequest, self.factory_pause_request) - result["FactoryPhaseObservation"] = to_class(FactoryPhaseObservation, self.factory_phase_observation) - result["FactoryPhaseStatus"] = to_enum(PhaseStatus, self.factory_phase_status) - result["FactoryProgressLine"] = to_class(FactoryProgressLine, self.factory_progress_line) - result["FactoryProgressPage"] = to_class(FactoryProgressPage, self.factory_progress_page) - result["FactoryResumeRequest"] = to_class(FactoryResumeRequest, self.factory_resume_request) - result["FactoryResumeResult"] = to_class(FactoryResumeResult, self.factory_resume_result) - result["FactoryRunConsumed"] = to_class(FactoryRunConsumed, self.factory_run_consumed) - result["FactoryRunDetail"] = to_class(FactoryRunDetail, self.factory_run_detail) - result["FactoryRunFailure"] = to_class(FactoryRunFailure, self.factory_run_failure) - result["FactoryRunFailureKind"] = to_enum(RunFailureKind, self.factory_run_failure_kind) - result["FactoryRunLimits"] = to_class(FactoryRunLimits, self.factory_run_limits) - result["FactoryRunRequest"] = to_class(FactoryRunRequest, self.factory_run_request) - result["FactoryRunResult"] = to_class(FactoryRunResult, self.factory_run_result) - result["FactoryRunStatus"] = to_enum(RunStatus, self.factory_run_status) - result["FactoryRunSummary"] = to_class(FactoryRunSummary, self.factory_run_summary) - result["FactoryRunTerminal"] = to_class(FactoryRunTerminal, self.factory_run_terminal) - result["FactoryToolResumeRequest"] = to_class(_FactoryToolResumeRequest, self.factory_tool_resume_request) - result["FactoryToolRunOptions"] = to_class(_FactoryToolRunOptions, self.factory_tool_run_options) - result["FactoryToolRunRequest"] = to_class(_FactoryToolRunRequest, self.factory_tool_run_request) result["FilterMapping"] = from_union([lambda x: from_dict(lambda x: to_enum(ContentFilterMode, x), x), lambda x: to_enum(ContentFilterMode, x)], self.filter_mapping) result["FleetStartRequest"] = to_class(FleetStartRequest, self.fleet_start_request) result["FleetStartResult"] = to_class(FleetStartResult, self.fleet_start_result) @@ -45414,6 +44292,7 @@ def to_dict(self) -> dict: result["LlmInferenceHttpResponseStartResult"] = to_class(LlmInferenceHTTPResponseStartResult, self.llm_inference_http_response_start_result) result["LlmInferenceSetProviderResult"] = to_class(LlmInferenceSetProviderResult, self.llm_inference_set_provider_result) result["LocalSessionMetadataValue"] = to_class(LocalSessionMetadataValue, self.local_session_metadata_value) + result["LoginProviderKind"] = to_enum(LoginProviderKind, self.login_provider_kind) result["LogRequest"] = to_class(LogRequest, self.log_request) result["LogResult"] = to_class(LogResult, self.log_result) result["LspInitializeRequest"] = to_class(LspInitializeRequest, self.lsp_initialize_request) @@ -45669,11 +44548,11 @@ def to_dict(self) -> dict: result["PermissionDecisionApproveForLocationApprovalExtensionEnvAccess"] = to_class(PermissionDecisionApproveForLocationApprovalExtensionEnvAccess, self.permission_decision_approve_for_location_approval_extension_env_access) result["PermissionDecisionApproveForLocationApprovalExtensionManagement"] = to_class(PermissionDecisionApproveForLocationApprovalExtensionManagement, self.permission_decision_approve_for_location_approval_extension_management) result["PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess"] = to_class(PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess, self.permission_decision_approve_for_location_approval_extension_permission_access) - result["PermissionDecisionApproveForLocationApprovalFactory"] = to_class(PermissionDecisionApproveForLocationApprovalFactory, self.permission_decision_approve_for_location_approval_factory) result["PermissionDecisionApproveForLocationApprovalMcp"] = to_class(PermissionDecisionApproveForLocationApprovalMCP, self.permission_decision_approve_for_location_approval_mcp) result["PermissionDecisionApproveForLocationApprovalMcpSampling"] = to_class(PermissionDecisionApproveForLocationApprovalMCPSampling, self.permission_decision_approve_for_location_approval_mcp_sampling) result["PermissionDecisionApproveForLocationApprovalMemory"] = to_class(PermissionDecisionApproveForLocationApprovalMemory, self.permission_decision_approve_for_location_approval_memory) result["PermissionDecisionApproveForLocationApprovalRead"] = to_class(PermissionDecisionApproveForLocationApprovalRead, self.permission_decision_approve_for_location_approval_read) + result["PermissionDecisionApproveForLocationApprovalWorkflow"] = to_class(PermissionDecisionApproveForLocationApprovalWorkflow, self.permission_decision_approve_for_location_approval_workflow) result["PermissionDecisionApproveForLocationApprovalWrite"] = to_class(PermissionDecisionApproveForLocationApprovalWrite, self.permission_decision_approve_for_location_approval_write) result["PermissionDecisionApproveForSession"] = to_class(PermissionDecisionApproveForSession, self.permission_decision_approve_for_session) result["PermissionDecisionApproveForSessionApproval"] = (self.permission_decision_approve_for_session_approval).to_dict() @@ -45682,11 +44561,11 @@ def to_dict(self) -> dict: result["PermissionDecisionApproveForSessionApprovalExtensionEnvAccess"] = to_class(PermissionDecisionApproveForSessionApprovalExtensionEnvAccess, self.permission_decision_approve_for_session_approval_extension_env_access) result["PermissionDecisionApproveForSessionApprovalExtensionManagement"] = to_class(PermissionDecisionApproveForSessionApprovalExtensionManagement, self.permission_decision_approve_for_session_approval_extension_management) result["PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess"] = to_class(PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess, self.permission_decision_approve_for_session_approval_extension_permission_access) - result["PermissionDecisionApproveForSessionApprovalFactory"] = to_class(PermissionDecisionApproveForSessionApprovalFactory, self.permission_decision_approve_for_session_approval_factory) result["PermissionDecisionApproveForSessionApprovalMcp"] = to_class(PermissionDecisionApproveForSessionApprovalMCP, self.permission_decision_approve_for_session_approval_mcp) result["PermissionDecisionApproveForSessionApprovalMcpSampling"] = to_class(PermissionDecisionApproveForSessionApprovalMCPSampling, self.permission_decision_approve_for_session_approval_mcp_sampling) result["PermissionDecisionApproveForSessionApprovalMemory"] = to_class(PermissionDecisionApproveForSessionApprovalMemory, self.permission_decision_approve_for_session_approval_memory) result["PermissionDecisionApproveForSessionApprovalRead"] = to_class(PermissionDecisionApproveForSessionApprovalRead, self.permission_decision_approve_for_session_approval_read) + result["PermissionDecisionApproveForSessionApprovalWorkflow"] = to_class(PermissionDecisionApproveForSessionApprovalWorkflow, self.permission_decision_approve_for_session_approval_workflow) result["PermissionDecisionApproveForSessionApprovalWrite"] = to_class(PermissionDecisionApproveForSessionApprovalWrite, self.permission_decision_approve_for_session_approval_write) result["PermissionDecisionApproveOnce"] = to_class(PermissionDecisionApproveOnce, self.permission_decision_approve_once) result["PermissionDecisionApprovePermanently"] = to_class(PermissionDecisionApprovePermanently, self.permission_decision_approve_permanently) @@ -45736,11 +44615,11 @@ def to_dict(self) -> dict: result["PermissionsLocationsAddToolApprovalDetailsExtensionEnvAccess"] = to_class(PermissionsLocationsAddToolApprovalDetailsExtensionEnvAccess, self.permissions_locations_add_tool_approval_details_extension_env_access) result["PermissionsLocationsAddToolApprovalDetailsExtensionManagement"] = to_class(PermissionsLocationsAddToolApprovalDetailsExtensionManagement, self.permissions_locations_add_tool_approval_details_extension_management) result["PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess"] = to_class(PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess, self.permissions_locations_add_tool_approval_details_extension_permission_access) - result["PermissionsLocationsAddToolApprovalDetailsFactory"] = to_class(PermissionsLocationsAddToolApprovalDetailsFactory, self.permissions_locations_add_tool_approval_details_factory) result["PermissionsLocationsAddToolApprovalDetailsMcp"] = to_class(PermissionsLocationsAddToolApprovalDetailsMCP, self.permissions_locations_add_tool_approval_details_mcp) result["PermissionsLocationsAddToolApprovalDetailsMcpSampling"] = to_class(PermissionsLocationsAddToolApprovalDetailsMCPSampling, self.permissions_locations_add_tool_approval_details_mcp_sampling) result["PermissionsLocationsAddToolApprovalDetailsMemory"] = to_class(PermissionsLocationsAddToolApprovalDetailsMemory, self.permissions_locations_add_tool_approval_details_memory) result["PermissionsLocationsAddToolApprovalDetailsRead"] = to_class(PermissionsLocationsAddToolApprovalDetailsRead, self.permissions_locations_add_tool_approval_details_read) + result["PermissionsLocationsAddToolApprovalDetailsWorkflow"] = to_class(PermissionsLocationsAddToolApprovalDetailsWorkflow, self.permissions_locations_add_tool_approval_details_workflow) result["PermissionsLocationsAddToolApprovalDetailsWrite"] = to_class(PermissionsLocationsAddToolApprovalDetailsWrite, self.permissions_locations_add_tool_approval_details_write) result["PermissionsLocationsAddToolApprovalResult"] = to_class(PermissionsLocationsAddToolApprovalResult, self.permissions_locations_add_tool_approval_result) result["PermissionsModifyRulesParams"] = to_class(PermissionsModifyRulesParams, self.permissions_modify_rules_params) @@ -45810,6 +44689,7 @@ def to_dict(self) -> dict: result["ProviderConfigTransport"] = to_enum(ProviderTransport, self.provider_config_transport) result["ProviderConfigType"] = to_enum(ProviderType, self.provider_config_type) result["ProviderConfigWireApi"] = to_enum(ProviderWireAPI, self.provider_config_wire_api) + result["ProviderDescriptor"] = to_class(ProviderDescriptor, self.provider_descriptor) result["ProviderEndpoint"] = to_class(ProviderEndpoint, self.provider_endpoint) result["ProviderEndpointTransport"] = to_enum(ProviderTransport, self.provider_endpoint_transport) result["ProviderEndpointType"] = to_enum(ProviderType, self.provider_endpoint_type) @@ -45902,7 +44782,6 @@ def to_dict(self) -> dict: result["RemoteSessionMode"] = to_enum(RemoteSessionMode, self.remote_session_mode) result["RemoteSessionRepository"] = to_class(RemoteSessionRepository, self.remote_session_repository) result["ResponseFormat"] = to_class(ResponseFormat, self.response_format) - result["RunOptions"] = to_class(RunOptions, self.run_options) result["SandboxConfig"] = to_class(SandboxConfig, self.sandbox_config) result["SandboxConfigAuth"] = to_class(SandboxConfigAuth, self.sandbox_config_auth) result["SandboxConfigSource"] = to_enum(_SandboxConfigSource, self.sandbox_config_source) @@ -45960,7 +44839,6 @@ def to_dict(self) -> dict: result["SessionContext"] = to_class(SessionContext, self.session_context) result["SessionContextHostType"] = to_enum(HostType, self.session_context_host_type) result["SessionEnrichMetadataResult"] = to_class(SessionEnrichMetadataResult, self.session_enrich_metadata_result) - result["SessionFactoryPauseAtCheckpointResult"] = to_class(SessionFactoryPauseAtCheckpointResult, self.session_factory_pause_at_checkpoint_result) result["SessionFsAppendFileRequest"] = to_class(SessionFSAppendFileRequest, self.session_fs_append_file_request) result["SessionFsError"] = to_class(SessionFSError, self.session_fs_error) result["SessionFsErrorCode"] = to_enum(SessionFSErrorCode, self.session_fs_error_code) @@ -46304,7 +45182,7 @@ def to_dict(self) -> dict: result["WorkflowCancelRequest"] = to_class(WorkflowCancelRequest, self.workflow_cancel_request) result["WorkflowCurrentPhase"] = to_class(WorkflowCurrentPhase, self.workflow_current_phase) result["WorkflowDeclaredLimits"] = to_class(WorkflowDeclaredLimits, self.workflow_declared_limits) - result["WorkflowDurableOperation"] = to_enum(DurableOperation, self.workflow_durable_operation) + result["WorkflowDurableOperation"] = to_enum(WorkflowDurableOperation, self.workflow_durable_operation) result["WorkflowExecuteRequest"] = to_class(WorkflowExecuteRequest, self.workflow_execute_request) result["WorkflowExecuteResult"] = to_class(WorkflowExecuteResult, self.workflow_execute_result) result["WorkflowGetRunProgressRequest"] = to_class(WorkflowGetRunProgressRequest, self.workflow_get_run_progress_request) @@ -46315,15 +45193,15 @@ def to_dict(self) -> dict: result["WorkflowListRunsRequest"] = to_class(WorkflowListRunsRequest, self.workflow_list_runs_request) result["WorkflowListRunsResult"] = to_class(WorkflowListRunsResult, self.workflow_list_runs_result) result["WorkflowLogLine"] = to_class(WorkflowLogLine, self.workflow_log_line) - result["WorkflowLogLineKind"] = to_enum(LogLineKind, self.workflow_log_line_kind) + result["WorkflowLogLineKind"] = to_enum(WorkflowLogLineKind, self.workflow_log_line_kind) result["WorkflowLogRequest"] = to_class(WorkflowLogRequest, self.workflow_log_request) - result["WorkflowPauseCheckpointAction"] = to_enum(PauseCheckpointAction, self.workflow_pause_checkpoint_action) + result["WorkflowPauseCheckpointAction"] = to_enum(WorkflowPauseCheckpointAction, self.workflow_pause_checkpoint_action) result["WorkflowPauseCheckpointRequest"] = to_class(WorkflowPauseCheckpointRequest, self.workflow_pause_checkpoint_request) result["WorkflowPauseCheckpointResult"] = to_class(WorkflowPauseCheckpointResult, self.workflow_pause_checkpoint_result) result["WorkflowPauseInfo"] = to_class(WorkflowPauseInfo, self.workflow_pause_info) result["WorkflowPauseRequest"] = to_class(WorkflowPauseRequest, self.workflow_pause_request) result["WorkflowPhaseObservation"] = to_class(WorkflowPhaseObservation, self.workflow_phase_observation) - result["WorkflowPhaseStatus"] = to_enum(PhaseStatus, self.workflow_phase_status) + result["WorkflowPhaseStatus"] = to_enum(WorkflowPhaseStatus, self.workflow_phase_status) result["WorkflowProgressLine"] = to_class(WorkflowProgressLine, self.workflow_progress_line) result["WorkflowProgressPage"] = to_class(WorkflowProgressPage, self.workflow_progress_page) result["WorkflowResumeRequest"] = to_class(WorkflowResumeRequest, self.workflow_resume_request) @@ -46331,12 +45209,12 @@ def to_dict(self) -> dict: result["WorkflowRunConsumed"] = to_class(WorkflowRunConsumed, self.workflow_run_consumed) result["WorkflowRunDetail"] = to_class(WorkflowRunDetail, self.workflow_run_detail) result["WorkflowRunFailure"] = to_class(WorkflowRunFailure, self.workflow_run_failure) - result["WorkflowRunFailureKind"] = to_enum(RunFailureKind, self.workflow_run_failure_kind) + result["WorkflowRunFailureKind"] = to_enum(WorkflowRunFailureKind, self.workflow_run_failure_kind) result["WorkflowRunLimits"] = to_class(WorkflowRunLimits, self.workflow_run_limits) result["WorkflowRunOptions"] = to_class(WorkflowRunOptions, self.workflow_run_options) result["WorkflowRunRequest"] = to_class(WorkflowRunRequest, self.workflow_run_request) result["WorkflowRunResult"] = to_class(WorkflowRunResult, self.workflow_run_result) - result["WorkflowRunStatus"] = to_enum(RunStatus, self.workflow_run_status) + result["WorkflowRunStatus"] = to_enum(WorkflowRunStatus, self.workflow_run_status) result["WorkflowRunSummary"] = to_class(WorkflowRunSummary, self.workflow_run_summary) result["WorkflowRunTerminal"] = to_class(WorkflowRunTerminal, self.workflow_run_terminal) result["WorkflowToolResumeRequest"] = to_class(_WorkflowToolResumeRequest, self.workflow_tool_resume_request) @@ -46605,7 +45483,7 @@ def _load_PermissionDecision(obj: Any) -> "PermissionDecision": case _: raise ValueError(f"Unknown PermissionDecision kind: {kind!r}") # Approval to persist for this location -PermissionDecisionApproveForLocationApproval = PermissionDecisionApproveForLocationApprovalCommands | PermissionDecisionApproveForLocationApprovalRead | PermissionDecisionApproveForLocationApprovalWrite | PermissionDecisionApproveForLocationApprovalMCP | PermissionDecisionApproveForLocationApprovalMCPSampling | PermissionDecisionApproveForLocationApprovalMemory | PermissionDecisionApproveForLocationApprovalCustomTool | PermissionDecisionApproveForLocationApprovalExtensionManagement | PermissionDecisionApproveForLocationApprovalFactory | PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess | PermissionDecisionApproveForLocationApprovalExtensionEnvAccess +PermissionDecisionApproveForLocationApproval = PermissionDecisionApproveForLocationApprovalCommands | PermissionDecisionApproveForLocationApprovalRead | PermissionDecisionApproveForLocationApprovalWrite | PermissionDecisionApproveForLocationApprovalMCP | PermissionDecisionApproveForLocationApprovalMCPSampling | PermissionDecisionApproveForLocationApprovalMemory | PermissionDecisionApproveForLocationApprovalCustomTool | PermissionDecisionApproveForLocationApprovalExtensionManagement | PermissionDecisionApproveForLocationApprovalWorkflow | PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess | PermissionDecisionApproveForLocationApprovalExtensionEnvAccess def _load_PermissionDecisionApproveForLocationApproval(obj: Any) -> "PermissionDecisionApproveForLocationApproval": assert isinstance(obj, dict) @@ -46619,13 +45497,13 @@ def _load_PermissionDecisionApproveForLocationApproval(obj: Any) -> "PermissionD case "memory": return PermissionDecisionApproveForLocationApprovalMemory.from_dict(obj) case "custom-tool": return PermissionDecisionApproveForLocationApprovalCustomTool.from_dict(obj) case "extension-management": return PermissionDecisionApproveForLocationApprovalExtensionManagement.from_dict(obj) - case "factory": return PermissionDecisionApproveForLocationApprovalFactory.from_dict(obj) + case "workflow": return PermissionDecisionApproveForLocationApprovalWorkflow.from_dict(obj) case "extension-permission-access": return PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess.from_dict(obj) case "extension-env-access": return PermissionDecisionApproveForLocationApprovalExtensionEnvAccess.from_dict(obj) case _: raise ValueError(f"Unknown PermissionDecisionApproveForLocationApproval kind: {kind!r}") # Session-scoped approval to remember (tool prompts only; omitted for path/url prompts) -PermissionDecisionApproveForSessionApproval = PermissionDecisionApproveForSessionApprovalCommands | PermissionDecisionApproveForSessionApprovalRead | PermissionDecisionApproveForSessionApprovalWrite | PermissionDecisionApproveForSessionApprovalMCP | PermissionDecisionApproveForSessionApprovalMCPSampling | PermissionDecisionApproveForSessionApprovalMemory | PermissionDecisionApproveForSessionApprovalCustomTool | PermissionDecisionApproveForSessionApprovalExtensionManagement | PermissionDecisionApproveForSessionApprovalFactory | PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess | PermissionDecisionApproveForSessionApprovalExtensionEnvAccess +PermissionDecisionApproveForSessionApproval = PermissionDecisionApproveForSessionApprovalCommands | PermissionDecisionApproveForSessionApprovalRead | PermissionDecisionApproveForSessionApprovalWrite | PermissionDecisionApproveForSessionApprovalMCP | PermissionDecisionApproveForSessionApprovalMCPSampling | PermissionDecisionApproveForSessionApprovalMemory | PermissionDecisionApproveForSessionApprovalCustomTool | PermissionDecisionApproveForSessionApprovalExtensionManagement | PermissionDecisionApproveForSessionApprovalWorkflow | PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess | PermissionDecisionApproveForSessionApprovalExtensionEnvAccess def _load_PermissionDecisionApproveForSessionApproval(obj: Any) -> "PermissionDecisionApproveForSessionApproval": assert isinstance(obj, dict) @@ -46639,13 +45517,13 @@ def _load_PermissionDecisionApproveForSessionApproval(obj: Any) -> "PermissionDe case "memory": return PermissionDecisionApproveForSessionApprovalMemory.from_dict(obj) case "custom-tool": return PermissionDecisionApproveForSessionApprovalCustomTool.from_dict(obj) case "extension-management": return PermissionDecisionApproveForSessionApprovalExtensionManagement.from_dict(obj) - case "factory": return PermissionDecisionApproveForSessionApprovalFactory.from_dict(obj) + case "workflow": return PermissionDecisionApproveForSessionApprovalWorkflow.from_dict(obj) case "extension-permission-access": return PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess.from_dict(obj) case "extension-env-access": return PermissionDecisionApproveForSessionApprovalExtensionEnvAccess.from_dict(obj) case _: raise ValueError(f"Unknown PermissionDecisionApproveForSessionApproval kind: {kind!r}") # Tool approval to persist and apply -PermissionsLocationsAddToolApprovalDetails = PermissionsLocationsAddToolApprovalDetailsCommands | PermissionsLocationsAddToolApprovalDetailsRead | PermissionsLocationsAddToolApprovalDetailsWrite | PermissionsLocationsAddToolApprovalDetailsMCP | PermissionsLocationsAddToolApprovalDetailsMCPSampling | PermissionsLocationsAddToolApprovalDetailsMemory | PermissionsLocationsAddToolApprovalDetailsCustomTool | PermissionsLocationsAddToolApprovalDetailsExtensionManagement | PermissionsLocationsAddToolApprovalDetailsFactory | PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess | PermissionsLocationsAddToolApprovalDetailsExtensionEnvAccess +PermissionsLocationsAddToolApprovalDetails = PermissionsLocationsAddToolApprovalDetailsCommands | PermissionsLocationsAddToolApprovalDetailsRead | PermissionsLocationsAddToolApprovalDetailsWrite | PermissionsLocationsAddToolApprovalDetailsMCP | PermissionsLocationsAddToolApprovalDetailsMCPSampling | PermissionsLocationsAddToolApprovalDetailsMemory | PermissionsLocationsAddToolApprovalDetailsCustomTool | PermissionsLocationsAddToolApprovalDetailsExtensionManagement | PermissionsLocationsAddToolApprovalDetailsWorkflow | PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess | PermissionsLocationsAddToolApprovalDetailsExtensionEnvAccess def _load_PermissionsLocationsAddToolApprovalDetails(obj: Any) -> "PermissionsLocationsAddToolApprovalDetails": assert isinstance(obj, dict) @@ -46659,7 +45537,7 @@ def _load_PermissionsLocationsAddToolApprovalDetails(obj: Any) -> "PermissionsLo case "memory": return PermissionsLocationsAddToolApprovalDetailsMemory.from_dict(obj) case "custom-tool": return PermissionsLocationsAddToolApprovalDetailsCustomTool.from_dict(obj) case "extension-management": return PermissionsLocationsAddToolApprovalDetailsExtensionManagement.from_dict(obj) - case "factory": return PermissionsLocationsAddToolApprovalDetailsFactory.from_dict(obj) + case "workflow": return PermissionsLocationsAddToolApprovalDetailsWorkflow.from_dict(obj) case "extension-permission-access": return PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess.from_dict(obj) case "extension-env-access": return PermissionsLocationsAddToolApprovalDetailsExtensionEnvAccess.from_dict(obj) case _: raise ValueError(f"Unknown PermissionsLocationsAddToolApprovalDetails kind: {kind!r}") @@ -46802,12 +45680,6 @@ def _load_TaskInfo(obj: Any) -> "TaskInfo": EventsCursorStatus = CursorStatus ExternalToolResult = ExternalToolTextResultForLlm ExternalToolTextResultForLlmContentResourceLinkIconTheme = Theme -FactoryDurableOperation = DurableOperation -FactoryLogLineKind = LogLineKind -FactoryPauseCheckpointAction = PauseCheckpointAction -FactoryPhaseStatus = PhaseStatus -FactoryRunFailureKind = RunFailureKind -FactoryRunStatus = RunStatus FilterMapping = dict HistoryCompactRequest = Any InstructionDiscoveryPathKind = DebugCollectLogsEntryKind @@ -46871,12 +45743,6 @@ def _load_TaskInfo(obj: Any) -> "TaskInfo": TaskInfoExecutionMode = TaskExecutionMode TaskInfoStatus = TaskStatus ToolResult = ToolResultExpanded -WorkflowDurableOperation = DurableOperation -WorkflowLogLineKind = LogLineKind -WorkflowPauseCheckpointAction = PauseCheckpointAction -WorkflowPhaseStatus = PhaseStatus -WorkflowRunFailureKind = RunFailureKind -WorkflowRunStatus = RunStatus WorkspaceSummaryHostType = HostType WorkspacesWorkspaceDetailsHostType = HostType @@ -47589,144 +46455,108 @@ async def set_credentials(self, params: SessionSetCredentialsParams, *, timeout: # Experimental: this API group is experimental and may change or be removed. -class DebugApi: +class AccountsLoginApi: def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id - async def collect_logs(self, params: DebugCollectLogsRequest, *, timeout: float | None = None) -> DebugCollectLogsResult: - "Collects a session debug log bundle into a local archive or staging directory. Logs are redacted by default; redaction can be configured per caller-provided diagnostic entry. The runtime includes session-owned logs by default and accepts caller-provided diagnostic entries so host applications can add their own files without changing this API shape.\n\nArgs:\n params: Options for collecting a session debug bundle with configurable redaction.\n\nReturns:\n Result of collecting a session debug bundle." + async def begin(self, params: AuthLoginBeginRequest, *, timeout: float | None = None) -> AuthLoginBegun: + "Begin an interactive login flow for a provider kind (dispatch is kind-only) and return its opaque flow id and first step.\n\nArgs:\n params: Begin an interactive login flow for a provider kind. Dispatch is kind-only.\n\nReturns:\n A started login flow: its opaque id and first step." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id - return DebugCollectLogsResult.from_dict(await self._client.request("session.debug.collectLogs", params_dict, **_timeout_kwargs(timeout))) - + return AuthLoginBegun.from_dict(await self._client.request("session.accounts.login.begin", params_dict, **_timeout_kwargs(timeout))) -# Experimental: this API group is experimental and may change or be removed. -class CanvasActionApi: - def __init__(self, client: "JsonRpcClient", session_id: str): - self._client = client - self._session_id = session_id + async def advance(self, params: AuthLoginAdvanceRequest, *, timeout: float | None = None) -> AuthLoginStep: + "Advance an in-flight login flow, optionally fulfilling an input-required step, and return the next step.\n\nArgs:\n params: Advance an in-flight login flow, optionally fulfilling an input-required step.\n\nReturns:\n One step in an interactive login flow. The consumer acts on the step and calls advance to proceed. Browser-open is encoded as two distinct steps by design: `open-url` is CONSUMER-driven (the provider surfaces the authorize URL and the consumer opens it — github.com/GHEC web), while `needs-interaction` is PROVIDER-driven (the provider opens the browser or broker UI itself and does not surface a URL — Entra)." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return AuthLoginStep.from_dict(await self._client.request("session.accounts.login.advance", params_dict, **_timeout_kwargs(timeout))) - async def invoke(self, params: CanvasActionInvokeRequest, *, timeout: float | None = None) -> Any: - "Invokes an action on an open canvas instance.\n\nArgs:\n params: Canvas action invocation parameters.\n\nReturns:\n Canvas action invocation result." + async def cancel(self, params: AuthLoginCancelRequest, *, timeout: float | None = None) -> None: + "Cancel an in-flight login flow and release its resources.\n\nArgs:\n params: Cancel an in-flight login flow." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id - return await self._client.request("session.canvas.action.invoke", params_dict, **_timeout_kwargs(timeout)) + await self._client.request("session.accounts.login.cancel", params_dict, **_timeout_kwargs(timeout)) # Experimental: this API group is experimental and may change or be removed. -class CanvasApi: +class AccountsApi: def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id - self.action = CanvasActionApi(client, session_id) + self.login = AccountsLoginApi(client, session_id) - async def list(self, *, timeout: float | None = None) -> CanvasList: - "Lists canvases declared for the session.\n\nReturns:\n Declared canvases available in this session." - return CanvasList.from_dict(await self._client.request("session.canvas.list", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) - - async def list_open(self, *, timeout: float | None = None) -> CanvasListOpenResult: - "Lists currently open canvas instances for the live session.\n\nReturns:\n Live open-canvas snapshot." - return CanvasListOpenResult.from_dict(await self._client.request("session.canvas.listOpen", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) + async def enumerate(self, params: AccountsEnumerateRequest, *, timeout: float | None = None) -> AuthEnumerateValue: + "Enumerate a typed accounts collection: the signed-in accounts, or the providers offered for interactive login.\n\nArgs:\n params: Enumerate request carrying the typed collection query.\n\nReturns:\n The enumerated collection, keyed by the same selector as the query." + params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} + params_dict["sessionId"] = self._session_id + return AuthEnumerateValue.from_dict(await self._client.request("session.accounts.enumerate", params_dict, **_timeout_kwargs(timeout))) - async def open(self, params: CanvasOpenRequest, *, timeout: float | None = None) -> OpenCanvasInstance: - "Opens or focuses a canvas instance.\n\nArgs:\n params: Canvas open parameters.\n\nReturns:\n Open canvas instance snapshot." + async def get(self, params: AccountsGetRequest, *, timeout: float | None = None) -> AuthReadValue: + "Read one typed accounts datum: the active account, a neutral status summary, or the last authentication errors.\n\nArgs:\n params: Read request carrying the typed datum query.\n\nReturns:\n The read result, keyed by the same selector as the query." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id - return OpenCanvasInstance.from_dict(await self._client.request("session.canvas.open", params_dict, **_timeout_kwargs(timeout))) + return AuthReadValue.from_dict(await self._client.request("session.accounts.get", params_dict, **_timeout_kwargs(timeout))) - async def close(self, params: CanvasCloseRequest, *, timeout: float | None = None) -> None: - "Closes an open canvas instance.\n\nArgs:\n params: Canvas close parameters." + async def set(self, params: AccountsSetRequest, *, timeout: float | None = None) -> AuthWriteResult: + "Apply one non-interactive accounts mutation: switch the active account, log an account out, or set credentials from a token.\n\nArgs:\n params: Mutation request carrying the typed write command.\n\nReturns:\n Result of a non-interactive accounts mutation." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id - await self._client.request("session.canvas.close", params_dict, **_timeout_kwargs(timeout)) + return AuthWriteResult.from_dict(await self._client.request("session.accounts.set", params_dict, **_timeout_kwargs(timeout))) # Experimental: this API group is experimental and may change or be removed. -class FactoryJournalApi: +class DebugApi: def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id - async def get(self, params: FactoryJournalGetRequest, *, timeout: float | None = None) -> FactoryJournalGetResult: - "Reads a memoized factory journal entry.\n\nArgs:\n params: Parameters for reading a factory journal entry.\n\nReturns:\n Result of reading a factory journal entry." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - return FactoryJournalGetResult.from_dict(await self._client.request("session.factory.journal.get", params_dict, **_timeout_kwargs(timeout))) - - async def put(self, params: FactoryJournalPutRequest, *, timeout: float | None = None) -> FactoryACKResult: - "Stores a memoized factory journal entry.\n\nArgs:\n params: Parameters for storing a factory journal entry.\n\nReturns:\n Acknowledgement that a factory request was accepted." + async def collect_logs(self, params: DebugCollectLogsRequest, *, timeout: float | None = None) -> DebugCollectLogsResult: + "Collects a session debug log bundle into a local archive or staging directory. Logs are redacted by default; redaction can be configured per caller-provided diagnostic entry. The runtime includes session-owned logs by default and accepts caller-provided diagnostic entries so host applications can add their own files without changing this API shape.\n\nArgs:\n params: Options for collecting a session debug bundle with configurable redaction.\n\nReturns:\n Result of collecting a session debug bundle." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id - return FactoryACKResult.from_dict(await self._client.request("session.factory.journal.put", params_dict, **_timeout_kwargs(timeout))) + return DebugCollectLogsResult.from_dict(await self._client.request("session.debug.collectLogs", params_dict, **_timeout_kwargs(timeout))) # Experimental: this API group is experimental and may change or be removed. -class FactoryApi: +class CanvasActionApi: def __init__(self, client: "JsonRpcClient", session_id: str): self._client = client self._session_id = session_id - self.journal = FactoryJournalApi(client, session_id) - - async def run(self, params: FactoryRunRequest, *, timeout: float | None = None) -> FactoryRunResult: - "Runs a registered factory by name at the top level.\n\nArgs:\n params: Parameters for invoking a registered factory.\n\nReturns:\n Complete current or terminal factory run envelope." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - return FactoryRunResult.from_dict(await self._client.request("session.factory.run", params_dict, **_timeout_kwargs(timeout))) - - async def resume(self, params: FactoryResumeRequest, *, timeout: float | None = None) -> FactoryResumeResult: - "Resumes a factory run using its persisted name, arguments, journal, and accounting.\n\nArgs:\n params: Parameters for resuming a factory run from its persisted identity.\n\nReturns:\n Resolved persisted factory identity and resumed run envelope." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - return FactoryResumeResult.from_dict(await self._client.request("session.factory.resume", params_dict, **_timeout_kwargs(timeout))) - async def get_run(self, params: FactoryGetRunRequest, *, timeout: float | None = None) -> FactoryRunResult: - "Gets the current or settled envelope for a factory run.\n\nArgs:\n params: Parameters for retrieving a factory run.\n\nReturns:\n Complete current or terminal factory run envelope." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - return FactoryRunResult.from_dict(await self._client.request("session.factory.getRun", params_dict, **_timeout_kwargs(timeout))) - - async def list_runs(self, params: FactoryListRunsRequest, *, timeout: float | None = None) -> FactoryListRunsResult: - "Lists durable factory runs for this session in creation order.\n\nArgs:\n params: Parameters for paging factory runs.\n\nReturns:\n A page of factory runs in durable creation order." + async def invoke(self, params: CanvasActionInvokeRequest, *, timeout: float | None = None) -> Any: + "Invokes an action on an open canvas instance.\n\nArgs:\n params: Canvas action invocation parameters.\n\nReturns:\n Canvas action invocation result." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id - return FactoryListRunsResult.from_dict(await self._client.request("session.factory.listRuns", params_dict, **_timeout_kwargs(timeout))) + return await self._client.request("session.canvas.action.invoke", params_dict, **_timeout_kwargs(timeout)) - async def get_run_detail(self, params: FactoryGetRunRequest, *, timeout: float | None = None) -> FactoryRunDetail: - "Gets durable and live observability detail for one factory run.\n\nArgs:\n params: Parameters for retrieving a factory run.\n\nReturns:\n Full factory run observability detail." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - return FactoryRunDetail.from_dict(await self._client.request("session.factory.getRunDetail", params_dict, **_timeout_kwargs(timeout))) - async def get_run_progress(self, params: FactoryGetRunProgressRequest, *, timeout: float | None = None) -> FactoryProgressPage: - "Pages durable progress for one factory run.\n\nArgs:\n params: Parameters for paging factory progress.\n\nReturns:\n A bidirectional page of factory progress." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - return FactoryProgressPage.from_dict(await self._client.request("session.factory.getRunProgress", params_dict, **_timeout_kwargs(timeout))) +# Experimental: this API group is experimental and may change or be removed. +class CanvasApi: + def __init__(self, client: "JsonRpcClient", session_id: str): + self._client = client + self._session_id = session_id + self.action = CanvasActionApi(client, session_id) - async def cancel(self, params: FactoryCancelRequest, *, timeout: float | None = None) -> FactoryRunResult: - "Requests cancellation of a factory run and returns its run envelope.\n\nArgs:\n params: Parameters for cancelling a factory run.\n\nReturns:\n Complete current or terminal factory run envelope." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - return FactoryRunResult.from_dict(await self._client.request("session.factory.cancel", params_dict, **_timeout_kwargs(timeout))) + async def list(self, *, timeout: float | None = None) -> CanvasList: + "Lists canvases declared for the session.\n\nReturns:\n Declared canvases available in this session." + return CanvasList.from_dict(await self._client.request("session.canvas.list", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) - async def pause(self, params: FactoryPauseRequest, *, timeout: float | None = None) -> FactoryRunResult: - "Pauses a running factory and returns its settled run envelope.\n\nArgs:\n params: Parameters for pausing a running factory.\n\nReturns:\n Complete current or terminal factory run envelope." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - return FactoryRunResult.from_dict(await self._client.request("session.factory.pause", params_dict, **_timeout_kwargs(timeout))) + async def list_open(self, *, timeout: float | None = None) -> CanvasListOpenResult: + "Lists currently open canvas instances for the live session.\n\nReturns:\n Live open-canvas snapshot." + return CanvasListOpenResult.from_dict(await self._client.request("session.canvas.listOpen", {"sessionId": self._session_id}, **_timeout_kwargs(timeout))) - async def log(self, params: FactoryLogRequest, *, timeout: float | None = None) -> FactoryACKResult: - "Records a batch of ordered factory progress lines.\n\nArgs:\n params: Parameters for recording factory progress.\n\nReturns:\n Acknowledgement that a factory request was accepted." + async def open(self, params: CanvasOpenRequest, *, timeout: float | None = None) -> OpenCanvasInstance: + "Opens or focuses a canvas instance.\n\nArgs:\n params: Canvas open parameters.\n\nReturns:\n Open canvas instance snapshot." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id - return FactoryACKResult.from_dict(await self._client.request("session.factory.log", params_dict, **_timeout_kwargs(timeout))) + return OpenCanvasInstance.from_dict(await self._client.request("session.canvas.open", params_dict, **_timeout_kwargs(timeout))) - async def agent(self, params: FactoryAgentRequest, *, timeout: float | None = None) -> FactoryAgentResult: - "Runs one factory-scoped subagent and returns its result.\n\nArgs:\n params: Parameters for one factory-scoped subagent call.\n\nReturns:\n Result of one factory-scoped subagent call." + async def close(self, params: CanvasCloseRequest, *, timeout: float | None = None) -> None: + "Closes an open canvas instance.\n\nArgs:\n params: Canvas close parameters." params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} params_dict["sessionId"] = self._session_id - return FactoryAgentResult.from_dict(await self._client.request("session.factory.agent", params_dict, **_timeout_kwargs(timeout))) + await self._client.request("session.canvas.close", params_dict, **_timeout_kwargs(timeout)) # Experimental: this API group is experimental and may change or be removed. @@ -49397,9 +48227,9 @@ def __init__(self, client: "JsonRpcClient", session_id: str): self._session_id = session_id self.sandbox = SandboxApi(client, session_id) self.git_hub_auth = GitHubAuthApi(client, session_id) + self.accounts = AccountsApi(client, session_id) self.debug = DebugApi(client, session_id) self.canvas = CanvasApi(client, session_id) - self.factory = FactoryApi(client, session_id) self.workflow = WorkflowApi(client, session_id) self.model = ModelApi(client, session_id) self.mode = ModeApi(client, session_id) @@ -49559,31 +48389,6 @@ def __init__(self, client: "JsonRpcClient", session_id: str): self.provider = _InternalCanvasProviderApi(client, session_id) -# Experimental: this API group is experimental and may change or be removed. -class _InternalFactoryApi: - def __init__(self, client: "JsonRpcClient", session_id: str): - self._client = client - self._session_id = session_id - - async def _run_from_tool(self, params: _FactoryToolRunRequest, *, timeout: float | None = None) -> FactoryRunResult: - "Internal tool-originated factory invocation.\n\nArgs:\n params: Internal parameters for invoking a registered factory from a tool.\n\nReturns:\n Complete current or terminal factory run envelope.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - return FactoryRunResult.from_dict(await self._client.request("session.factory.runFromTool", params_dict, **_timeout_kwargs(timeout))) - - async def _resume_from_tool(self, params: _FactoryToolResumeRequest, *, timeout: float | None = None) -> FactoryResumeResult: - "Internal tool-originated factory resume.\n\nArgs:\n params: Internal parameters for resuming a factory run from a tool.\n\nReturns:\n Resolved persisted factory identity and resumed run envelope.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - return FactoryResumeResult.from_dict(await self._client.request("session.factory.resumeFromTool", params_dict, **_timeout_kwargs(timeout))) - - async def _pause_at_checkpoint(self, params: FactoryPauseCheckpointRequest, *, timeout: float | None = None) -> SessionFactoryPauseAtCheckpointResult: - "Atomically pauses an owned factory attempt at a durable checkpoint.\n\nArgs:\n params: Parameters for an owned durable pause checkpoint.\n\n:meta private:\n\nInternal SDK API; not part of the public surface." - params_dict: dict[str, Any] = {k: v for k, v in params.to_dict().items() if v is not None} - params_dict["sessionId"] = self._session_id - return SessionFactoryPauseAtCheckpointResult.from_dict(await self._client.request("session.factory.pauseAtCheckpoint", params_dict, **_timeout_kwargs(timeout))) - - # Experimental: this API group is experimental and may change or be removed. class _InternalWorkflowApi: def __init__(self, client: "JsonRpcClient", session_id: str): @@ -49799,7 +48604,6 @@ def __init__(self, client: "JsonRpcClient", session_id: str): self._session_id = session_id self.git_hub_auth = _InternalGitHubAuthApi(client, session_id) self.canvas = _InternalCanvasApi(client, session_id) - self.factory = _InternalFactoryApi(client, session_id) self.workflow = _InternalWorkflowApi(client, session_id) self.model = _InternalModelApi(client, session_id) self.mcp = _InternalMcpApi(client, session_id) @@ -49822,15 +48626,6 @@ async def get_token(self, params: ProviderTokenAcquireRequest) -> ProviderTokenA "Asks the SDK client to get a bearer token for a BYOK provider whose config set `hasBearerTokenProvider: true`. Session-scoped: the runtime calls it back on the connection that most recently supplied that provider's config for the session (the creating connection, or a resuming connection if the session was resumed — distinct providers may be owned by different connections), passing the provider name, and uses the returned token as the Authorization header for the outbound model request. The runtime does no caching — it calls this once per outbound request; the SDK consumer owns token acquisition, caching, and refresh.\n\nArgs:\n params: Asks the SDK client to acquire a bearer token for a BYOK provider whose config set `hasBearerTokenProvider: true`. Issued by the runtime before each outbound model request; the runtime does no caching, so this is sent once per request.\n\nReturns:\n A bearer token supplied by the SDK client for a BYOK provider. The runtime sets it as `Authorization: Bearer ` on the outbound request and does no caching; the SDK consumer owns token caching and refresh." pass -# Experimental: this API group is experimental and may change or be removed. -class FactoryHandler(Protocol): - async def execute(self, params: FactoryExecuteRequest) -> FactoryExecuteResult: - "Asks the owning extension connection to execute a registered factory closure.\n\nArgs:\n params: Parameters sent to the owning extension to execute a factory closure.\n\nReturns:\n Result returned by an extension factory closure." - pass - async def abort(self, params: FactoryAbortRequest) -> FactoryACKResult: - "Asks the owning extension connection to abort a running factory cooperatively.\n\nArgs:\n params: Parameters for cooperatively aborting a factory body.\n\nReturns:\n Acknowledgement that a factory request was accepted." - pass - # Experimental: this API group is experimental and may change or be removed. class WorkflowHandler(Protocol): async def execute(self, params: WorkflowExecuteRequest) -> WorkflowExecuteResult: @@ -49903,7 +48698,6 @@ async def invoke(self, params: CanvasProviderInvokeActionRequest) -> Any: @dataclass class ClientSessionApiHandlers: provider_token: ProviderTokenHandler | None = None - factory: FactoryHandler | None = None workflow: WorkflowHandler | None = None tasks: TasksHandler | None = None session_fs: SessionFsHandler | None = None @@ -49921,20 +48715,6 @@ async def handle_provider_token_get_token(params: dict) -> dict | None: result = await handler.get_token(request) return result.to_dict() client.set_request_handler("providerToken.getToken", handle_provider_token_get_token) - async def handle_factory_execute(params: dict) -> dict | None: - request = FactoryExecuteRequest.from_dict(params) - handler = get_handlers(request.session_id).factory - if handler is None: raise RuntimeError(f"No factory handler registered for session: {request.session_id}") - result = await handler.execute(request) - return result.to_dict() - client.set_request_handler("factory.execute", handle_factory_execute) - async def handle_factory_abort(params: dict) -> dict | None: - request = FactoryAbortRequest.from_dict(params) - handler = get_handlers(request.session_id).factory - if handler is None: raise RuntimeError(f"No factory handler registered for session: {request.session_id}") - result = await handler.abort(request) - return result.to_dict() - client.set_request_handler("factory.abort", handle_factory_abort) async def handle_workflow_execute(params: dict) -> dict | None: request = WorkflowExecuteRequest.from_dict(params) handler = get_handlers(request.session_id).workflow @@ -50174,11 +48954,18 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "AccountGetCurrentAuthResult", "AccountGetQuotaRequest", "AccountGetQuotaResult", + "AccountKind", "AccountLoginRequest", "AccountLoginResult", "AccountLogoutRequest", "AccountLogoutResult", "AccountQuotaSnapshot", + "AccountStatus", + "AccountsApi", + "AccountsEnumerateRequest", + "AccountsGetRequest", + "AccountsLoginApi", + "AccountsSetRequest", "Action", "AdaptiveThinkingSupport", "AdditionalContentExclusionPolicyScope", @@ -50219,11 +49006,29 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "AgentsDiscoverRequest", "AgentsGetDiscoveryPathsRequest", "ApprovalKind", + "AuthEnumerateQuery", + "AuthEnumerateQueryKind", + "AuthEnumerateValue", "AuthIdentity", "AuthInfo", "AuthInfoType", + "AuthLoginAdvanceRequest", + "AuthLoginBeginRequest", + "AuthLoginBegun", + "AuthLoginCancelRequest", + "AuthLoginResultDto", + "AuthLoginResultStatus", + "AuthLoginStep", + "AuthLoginStepKind", + "AuthReadQuery", + "AuthReadQueryKind", + "AuthReadValue", + "AuthStatusDto", "AuthValidationError", "AuthValidationErrors", + "AuthWrite", + "AuthWriteKind", + "AuthWriteResult", "AutopilotObjectiveApi", "AutopilotObjectiveCreditLimit", "AutopilotObjectiveGetStateResult", @@ -50482,7 +49287,6 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "DiscoveredHook", "DiscoveredMCPServer", "DiscoveredMCPServerType", - "DurableOperation", "EnqueueCommandParams", "EnqueueCommandResult", "EnterpriseList", @@ -50535,53 +49339,6 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "ExternalToolTextResultForLlmContentTerminalType", "ExternalToolTextResultForLlmContentText", "ExternalToolTextResultForLlmContentType", - "FactoryACKResult", - "FactoryAbortRequest", - "FactoryAgentOptions", - "FactoryAgentRequest", - "FactoryAgentResult", - "FactoryAgentSummary", - "FactoryApi", - "FactoryCancelRequest", - "FactoryCurrentPhase", - "FactoryDeclaredLimits", - "FactoryDurableOperation", - "FactoryExecuteRequest", - "FactoryExecuteResult", - "FactoryGetRunProgressRequest", - "FactoryGetRunRequest", - "FactoryHandler", - "FactoryJournalApi", - "FactoryJournalGetRequest", - "FactoryJournalGetResult", - "FactoryJournalPutRequest", - "FactoryListRunsRequest", - "FactoryListRunsResult", - "FactoryLogLine", - "FactoryLogLineKind", - "FactoryLogRequest", - "FactoryPauseCheckpointAction", - "FactoryPauseCheckpointRequest", - "FactoryPauseCheckpointResult", - "FactoryPauseInfo", - "FactoryPauseRequest", - "FactoryPhaseObservation", - "FactoryPhaseStatus", - "FactoryProgressLine", - "FactoryProgressPage", - "FactoryResumeRequest", - "FactoryResumeResult", - "FactoryRunConsumed", - "FactoryRunDetail", - "FactoryRunFailure", - "FactoryRunFailureKind", - "FactoryRunFailureType", - "FactoryRunLimits", - "FactoryRunRequest", - "FactoryRunResult", - "FactoryRunStatus", - "FactoryRunSummary", - "FactoryRunTerminal", "FilterMapping", "FleetApi", "FleetStartRequest", @@ -50659,6 +49416,7 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "InstructionsGetSourcesResult", "InterruptMainTurnRequest", "InterruptMainTurnResult", + "ItemElement", "JSONSchemaResponseFormat", "KindEnum", "LimitPredictionApi", @@ -50676,9 +49434,9 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "LlmInferenceHeaders", "LlmInferenceSetProviderResult", "LocalSessionMetadataValue", - "LogLineKind", "LogRequest", "LogResult", + "LoginProviderKind", "LspApi", "LspInitializeRequest", "MCPAllowedServer", @@ -50951,7 +49709,6 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "OptionsUpdateEnvValueMode", "OptionsUpdateReasoningSummary", "OptionsUpdateToolFilterPrecedence", - "PauseCheckpointAction", "PauseInfoClass", "PauseInfoType", "PendingPermissionRequest", @@ -50969,14 +49726,14 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "PermissionDecisionApproveForLocationApprovalExtensionManagementKind", "PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess", "PermissionDecisionApproveForLocationApprovalExtensionPermissionAccessKind", - "PermissionDecisionApproveForLocationApprovalFactory", - "PermissionDecisionApproveForLocationApprovalFactoryKind", "PermissionDecisionApproveForLocationApprovalMCP", "PermissionDecisionApproveForLocationApprovalMCPSampling", "PermissionDecisionApproveForLocationApprovalMCPSamplingKind", "PermissionDecisionApproveForLocationApprovalMemory", "PermissionDecisionApproveForLocationApprovalRead", "PermissionDecisionApproveForLocationApprovalReadKind", + "PermissionDecisionApproveForLocationApprovalWorkflow", + "PermissionDecisionApproveForLocationApprovalWorkflowKind", "PermissionDecisionApproveForLocationApprovalWrite", "PermissionDecisionApproveForLocationApprovalWriteKind", "PermissionDecisionApproveForLocationKind", @@ -50987,11 +49744,11 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "PermissionDecisionApproveForSessionApprovalExtensionEnvAccess", "PermissionDecisionApproveForSessionApprovalExtensionManagement", "PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess", - "PermissionDecisionApproveForSessionApprovalFactory", "PermissionDecisionApproveForSessionApprovalMCP", "PermissionDecisionApproveForSessionApprovalMCPSampling", "PermissionDecisionApproveForSessionApprovalMemory", "PermissionDecisionApproveForSessionApprovalRead", + "PermissionDecisionApproveForSessionApprovalWorkflow", "PermissionDecisionApproveForSessionApprovalWrite", "PermissionDecisionApproveForSessionKind", "PermissionDecisionApproveOnce", @@ -51062,11 +49819,11 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "PermissionsLocationsAddToolApprovalDetailsExtensionEnvAccess", "PermissionsLocationsAddToolApprovalDetailsExtensionManagement", "PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess", - "PermissionsLocationsAddToolApprovalDetailsFactory", "PermissionsLocationsAddToolApprovalDetailsMCP", "PermissionsLocationsAddToolApprovalDetailsMCPSampling", "PermissionsLocationsAddToolApprovalDetailsMemory", "PermissionsLocationsAddToolApprovalDetailsRead", + "PermissionsLocationsAddToolApprovalDetailsWorkflow", "PermissionsLocationsAddToolApprovalDetailsWrite", "PermissionsLocationsAddToolApprovalResult", "PermissionsLocationsApi", @@ -51090,7 +49847,6 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "PermissionsSetRequiredResult", "PermissionsUrlsApi", "PermissionsUrlsSetUnrestrictedModeResult", - "PhaseStatus", "PingRequest", "PingResult", "PlanApi", @@ -51144,6 +49900,7 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "ProviderConfigTransport", "ProviderConfigType", "ProviderConfigWireApi", + "ProviderDescriptor", "ProviderEndpoint", "ProviderEndpointTransport", "ProviderEndpointType", @@ -51264,9 +50021,6 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "RemoteSessionRepository", "ResponseFormat", "ResponseFormatType", - "RunFailureKind", - "RunOptions", - "RunStatus", "SandboxApi", "SandboxConfig", "SandboxConfigAuth", @@ -51388,7 +50142,6 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "SessionFSStatRequest", "SessionFSStatResult", "SessionFSWriteFileRequest", - "SessionFactoryPauseAtCheckpointResult", "SessionFsHandler", "SessionFsReaddirWithTypesEntryType", "SessionGitHubAuthGetAllAuthAvailableResult", @@ -51780,7 +50533,6 @@ async def handle_git_hub_token_get_token(params: dict) -> dict | None: "WorkflowRunStatus", "WorkflowRunSummary", "WorkflowRunTerminal", - "WorkflowRunTerminalPauseInfo", "Workspace", "WorkspaceDiffFileChange", "WorkspaceDiffFileChangeType", diff --git a/python/copilot/generated/session_events.py b/python/copilot/generated/session_events.py index 6fef3e2ac2..fd7920350a 100644 --- a/python/copilot/generated/session_events.py +++ b/python/copilot/generated/session_events.py @@ -277,11 +277,11 @@ class SessionEventType(Enum): SESSION_TOOLS_UPDATED = "session.tools_updated" SESSION_BACKGROUND_TASKS_CHANGED = "session.background_tasks_changed" # Experimental: this event is part of an experimental API and may change or be removed. - FACTORY_RUN_UPDATED = "factory.run_updated" + WORKFLOW_RUN_UPDATED = "workflow.run_updated" # Experimental: this event is part of an experimental API and may change or be removed. - FACTORY_RUN_STARTED = "factory.run_started" + WORKFLOW_RUN_STARTED = "workflow.run_started" # Experimental: this event is part of an experimental API and may change or be removed. - FACTORY_RUN_SETTLED = "factory.run_settled" + WORKFLOW_RUN_SETTLED = "workflow.run_settled" SESSION_SKILLS_LOADED = "session.skills_loaded" SESSION_CUSTOM_AGENTS_UPDATED = "session.custom_agents_updated" SESSION_MCP_SERVERS_LOADED = "session.mcp_servers_loaded" @@ -1102,99 +1102,6 @@ def to_dict(self) -> dict: return result -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryRunSettledData: - "Ephemeral signal that a factory run reached a terminal status." - consumed_nano_aiu: int - consumed_subagents: int - elapsed_ms: int - run_id: str - status: FactoryRunSettledStatus - failure_type: str | None = None - - @staticmethod - def from_dict(obj: Any) -> "FactoryRunSettledData": - assert isinstance(obj, dict) - consumed_nano_aiu = from_int(obj.get("consumedNanoAiu")) - consumed_subagents = from_int(obj.get("consumedSubagents")) - elapsed_ms = from_int(obj.get("elapsedMs")) - run_id = from_str(obj.get("runId")) - status = parse_enum(FactoryRunSettledStatus, obj.get("status")) - failure_type = from_union([from_none, from_str], obj.get("failureType")) - return FactoryRunSettledData( - consumed_nano_aiu=consumed_nano_aiu, - consumed_subagents=consumed_subagents, - elapsed_ms=elapsed_ms, - run_id=run_id, - status=status, - failure_type=failure_type, - ) - - def to_dict(self) -> dict: - result: dict = {} - result["consumedNanoAiu"] = to_int(self.consumed_nano_aiu) - result["consumedSubagents"] = to_int(self.consumed_subagents) - result["elapsedMs"] = to_int(self.elapsed_ms) - result["runId"] = from_str(self.run_id) - result["status"] = to_enum(FactoryRunSettledStatus, self.status) - if self.failure_type is not None: - result["failureType"] = from_union([from_none, from_str], self.failure_type) - return result - - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryRunStartedData: - "Ephemeral signal that a factory run attempt began executing." - attempt: int - factory_name: str - run_id: str - - @staticmethod - def from_dict(obj: Any) -> "FactoryRunStartedData": - assert isinstance(obj, dict) - attempt = from_int(obj.get("attempt")) - factory_name = from_str(obj.get("factoryName")) - run_id = from_str(obj.get("runId")) - return FactoryRunStartedData( - attempt=attempt, - factory_name=factory_name, - run_id=run_id, - ) - - def to_dict(self) -> dict: - result: dict = {} - result["attempt"] = to_int(self.attempt) - result["factoryName"] = from_str(self.factory_name) - result["runId"] = from_str(self.run_id) - return result - - -# Experimental: this type is part of an experimental API and may change or be removed. -@dataclass -class FactoryRunUpdatedData: - "Ephemeral invalidation signal for a changed factory run." - revision: int - run_id: str - - @staticmethod - def from_dict(obj: Any) -> "FactoryRunUpdatedData": - assert isinstance(obj, dict) - revision = from_int(obj.get("revision")) - run_id = from_str(obj.get("runId")) - return FactoryRunUpdatedData( - revision=revision, - run_id=run_id, - ) - - def to_dict(self) -> dict: - result: dict = {} - result["revision"] = to_int(self.revision) - result["runId"] = from_str(self.run_id) - return result - - # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class FusionAttribution: @@ -1477,7 +1384,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionAssentDetectedData: - "Records that deterministic text recognition found likely assent in the human turn immediately following a root Autopilot permission request that was blocked because no interactive response was available. This event grants no authority; its model-facing projection only suggests retrying the unchanged operation." + "Historical decode-only contextual-assent marker. Current runtimes do not project it into the conversation or permission flow." # Experimental: this field is part of an experimental API and may change or be removed. request_id: str # Experimental: this field is part of an experimental API and may change or be removed. @@ -1543,7 +1450,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionCarriedForwardData: - "Records that a live authorization record from an earlier human decision in this session contained a permission proposal, so it ran without another prompt. This mints no authority: it accounts for one more effect against the prior grant, which is what lets a replayed session agree with the live one about how much of that grant is left." + "Historical decode-only receipt from the retired Assisted Permissions authorization extractor. Current runtimes ignore it for permission decisions." # Experimental: this field is part of an experimental API and may change or be removed. decision_source: PermissionDecisionSource # Experimental: this field is part of an experimental API and may change or be removed. @@ -1579,7 +1486,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionContextualAuthorizationData: - "Freezes a blinded contextual authorization proposal whose verbatim human span was deterministically bound to the immediately preceding blocked permission request. The event carries no action fields; replay re-derives the exact action from the earlier permission request and mints a one-shot message grant only when the binding and span still verify." + "Historical decode-only contextual authorization claim. Current runtimes preserve the payload but do not establish authority from it." # Experimental: this field is part of an experimental API and may change or be removed. polarity: PermissionMessageAuthorizationPolarity # Experimental: this field is part of an experimental API and may change or be removed. @@ -1625,7 +1532,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionMessageAuthorizationData: - "Freezes one blinded, verbatim-verified authorization claim the runtime minted from a human user message, so a resumed session re-establishes the same grant deterministically instead of re-running the extraction model. This mints no authority on its own: it records what a blinded proposer pointed at and the trusted discriminator the runtime established, and deterministic establishment runs on replay. Persisted so recorded authority survives compaction and process resume." + "Historical decode-only claim from the retired Assisted Permissions authorization extractor. Current runtimes preserve the payload but do not establish authority from it." # Experimental: this field is part of an experimental API and may change or be removed. action_class: str # Experimental: this field is part of an experimental API and may change or be removed. @@ -1689,7 +1596,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionMessageAuthorizationDegradedData: - "Records that message-backed authorization could not safely represent one human turn before compaction. The runtime may compact the original message after this marker is durable, but message-derived carry-forward and assisted auto-approval remain disabled for the rest of the session so subsequent commands continue through the ordinary permission prompt." + "Historical decode-only degradation marker from the retired extractor. Current runtimes ignore it for permission decisions." # Experimental: this field is part of an experimental API and may change or be removed. turn_index: int @@ -1710,7 +1617,7 @@ def to_dict(self) -> dict: # Experimental: this type is part of an experimental API and may change or be removed. @dataclass class PermissionMessageAuthorizationReadData: - "Records that one human turn has been read by the blinded authorization proposer, whether or not it minted anything, so a resumed session does not re-run the extraction model on a turn the live session already read. Also records whether that pass activates ongoing extraction; contextual-assent-only passes do not, so unrelated future messages remain outside extraction." + "Historical decode-only extractor progress marker. Current runtimes do not run or resume extraction from it." # Experimental: this field is part of an experimental API and may change or be removed. turn_index: int # Experimental: this field is part of an experimental API and may change or be removed. @@ -2607,6 +2514,99 @@ def to_dict(self) -> dict: return result +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkflowRunSettledData: + "Ephemeral signal that a workflow run reached a terminal status." + consumed_nano_aiu: int + consumed_subagents: int + elapsed_ms: int + run_id: str + status: WorkflowRunSettledStatus + failure_type: str | None = None + + @staticmethod + def from_dict(obj: Any) -> "WorkflowRunSettledData": + assert isinstance(obj, dict) + consumed_nano_aiu = from_int(obj.get("consumedNanoAiu")) + consumed_subagents = from_int(obj.get("consumedSubagents")) + elapsed_ms = from_int(obj.get("elapsedMs")) + run_id = from_str(obj.get("runId")) + status = parse_enum(WorkflowRunSettledStatus, obj.get("status")) + failure_type = from_union([from_none, from_str], obj.get("failureType")) + return WorkflowRunSettledData( + consumed_nano_aiu=consumed_nano_aiu, + consumed_subagents=consumed_subagents, + elapsed_ms=elapsed_ms, + run_id=run_id, + status=status, + failure_type=failure_type, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["consumedNanoAiu"] = to_int(self.consumed_nano_aiu) + result["consumedSubagents"] = to_int(self.consumed_subagents) + result["elapsedMs"] = to_int(self.elapsed_ms) + result["runId"] = from_str(self.run_id) + result["status"] = to_enum(WorkflowRunSettledStatus, self.status) + if self.failure_type is not None: + result["failureType"] = from_union([from_none, from_str], self.failure_type) + return result + + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkflowRunStartedData: + "Ephemeral signal that a workflow run attempt began executing." + attempt: int + run_id: str + workflow_name: str + + @staticmethod + def from_dict(obj: Any) -> "WorkflowRunStartedData": + assert isinstance(obj, dict) + attempt = from_int(obj.get("attempt")) + run_id = from_str(obj.get("runId")) + workflow_name = from_str(obj.get("workflowName")) + return WorkflowRunStartedData( + attempt=attempt, + run_id=run_id, + workflow_name=workflow_name, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["attempt"] = to_int(self.attempt) + result["runId"] = from_str(self.run_id) + result["workflowName"] = from_str(self.workflow_name) + return result + + +# Experimental: this type is part of an experimental API and may change or be removed. +@dataclass +class WorkflowRunUpdatedData: + "Ephemeral invalidation signal for a changed workflow run." + revision: int + run_id: str + + @staticmethod + def from_dict(obj: Any) -> "WorkflowRunUpdatedData": + assert isinstance(obj, dict) + revision = from_int(obj.get("revision")) + run_id = from_str(obj.get("runId")) + return WorkflowRunUpdatedData( + revision=revision, + run_id=run_id, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["revision"] = to_int(self.revision) + result["runId"] = from_str(self.run_id) + return result + + @dataclass class AbortData: "Turn abort information including the reason for termination" @@ -5093,30 +5093,6 @@ def to_dict(self) -> dict: return result -@dataclass -class FactoryPermissionPhase: - "A declared phase shown in a factory permission prompt." - title: str - detail: str | None = None - - @staticmethod - def from_dict(obj: Any) -> "FactoryPermissionPhase": - assert isinstance(obj, dict) - title = from_str(obj.get("title")) - detail = from_union([from_none, from_str], obj.get("detail")) - return FactoryPermissionPhase( - title=title, - detail=detail, - ) - - def to_dict(self) -> dict: - result: dict = {} - result["title"] = from_str(self.title) - if self.detail is not None: - result["detail"] = from_union([from_none, from_str], self.detail) - return result - - @dataclass class GitHubMcpToolConfig: "Per-session configuration for the built-in GitHub MCP server" @@ -6619,103 +6595,6 @@ def to_dict(self) -> dict: return result -@dataclass -class PermissionPromptRequestFactory: - "Factory run or authoring permission prompt" - approval_key: str - can_persist_approval: bool - description: str - kind: ClassVar[str] = "factory" - name: str - operation: FactoryPermissionOperation - phases: list[FactoryPermissionPhase] - # Experimental: this field is part of an experimental API and may change or be removed. - assisted_approval: PermissionAssistedApproval | None = None - declared_max_ai_credits: float | None = None - declared_max_concurrent_subagents: int | None = None - declared_max_total_subagents: int | None = None - declared_timeout_seconds: float | None = None - managed_approval_required: bool | None = None - max_ai_credits: float | None = None - max_concurrent_subagents: int | None = None - max_total_subagents: int | None = None - timeout_seconds: float | None = None - tool_call_id: str | None = None - - @staticmethod - def from_dict(obj: Any) -> "PermissionPromptRequestFactory": - assert isinstance(obj, dict) - approval_key = from_str(obj.get("approvalKey")) - can_persist_approval = from_bool(obj.get("canPersistApproval")) - description = from_str(obj.get("description")) - name = from_str(obj.get("name")) - operation = parse_enum(FactoryPermissionOperation, obj.get("operation")) - phases = from_list(FactoryPermissionPhase.from_dict, obj.get("phases")) - assisted_approval = from_union([from_none, PermissionAssistedApproval.from_dict], obj.get("assistedApproval")) - declared_max_ai_credits = from_union([from_none, from_float], obj.get("declaredMaxAiCredits")) - declared_max_concurrent_subagents = from_union([from_none, from_int], obj.get("declaredMaxConcurrentSubagents")) - declared_max_total_subagents = from_union([from_none, from_int], obj.get("declaredMaxTotalSubagents")) - declared_timeout_seconds = from_union([from_none, from_float], obj.get("declaredTimeoutSeconds")) - managed_approval_required = from_union([from_none, from_bool], obj.get("managedApprovalRequired")) - max_ai_credits = from_union([from_none, from_float], obj.get("maxAiCredits")) - max_concurrent_subagents = from_union([from_none, from_int], obj.get("maxConcurrentSubagents")) - max_total_subagents = from_union([from_none, from_int], obj.get("maxTotalSubagents")) - timeout_seconds = from_union([from_none, from_float], obj.get("timeoutSeconds")) - tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) - return PermissionPromptRequestFactory( - approval_key=approval_key, - can_persist_approval=can_persist_approval, - description=description, - name=name, - operation=operation, - phases=phases, - assisted_approval=assisted_approval, - declared_max_ai_credits=declared_max_ai_credits, - declared_max_concurrent_subagents=declared_max_concurrent_subagents, - declared_max_total_subagents=declared_max_total_subagents, - declared_timeout_seconds=declared_timeout_seconds, - managed_approval_required=managed_approval_required, - max_ai_credits=max_ai_credits, - max_concurrent_subagents=max_concurrent_subagents, - max_total_subagents=max_total_subagents, - timeout_seconds=timeout_seconds, - tool_call_id=tool_call_id, - ) - - def to_dict(self) -> dict: - result: dict = {} - result["approvalKey"] = from_str(self.approval_key) - result["canPersistApproval"] = from_bool(self.can_persist_approval) - result["description"] = from_str(self.description) - result["kind"] = self.kind - result["name"] = from_str(self.name) - result["operation"] = to_enum(FactoryPermissionOperation, self.operation) - result["phases"] = from_list(lambda x: to_class(FactoryPermissionPhase, x), self.phases) - if self.assisted_approval is not None: - result["assistedApproval"] = from_union([from_none, lambda x: to_class(PermissionAssistedApproval, x)], self.assisted_approval) - if self.declared_max_ai_credits is not None: - result["declaredMaxAiCredits"] = from_union([from_none, to_float], self.declared_max_ai_credits) - if self.declared_max_concurrent_subagents is not None: - result["declaredMaxConcurrentSubagents"] = from_union([from_none, to_int], self.declared_max_concurrent_subagents) - if self.declared_max_total_subagents is not None: - result["declaredMaxTotalSubagents"] = from_union([from_none, to_int], self.declared_max_total_subagents) - if self.declared_timeout_seconds is not None: - result["declaredTimeoutSeconds"] = from_union([from_none, to_float], self.declared_timeout_seconds) - if self.managed_approval_required is not None: - result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) - if self.max_ai_credits is not None: - result["maxAiCredits"] = from_union([from_none, to_float], self.max_ai_credits) - if self.max_concurrent_subagents is not None: - result["maxConcurrentSubagents"] = from_union([from_none, to_int], self.max_concurrent_subagents) - if self.max_total_subagents is not None: - result["maxTotalSubagents"] = from_union([from_none, to_int], self.max_total_subagents) - if self.timeout_seconds is not None: - result["timeoutSeconds"] = from_union([from_none, to_float], self.timeout_seconds) - if self.tool_call_id is not None: - result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) - return result - - @dataclass class PermissionPromptRequestHook: "Hook confirmation permission prompt" @@ -7010,6 +6889,103 @@ def to_dict(self) -> dict: return result +@dataclass +class PermissionPromptRequestWorkflow: + "Workflow run or authoring permission prompt" + approval_key: str + can_persist_approval: bool + description: str + kind: ClassVar[str] = "workflow" + name: str + operation: WorkflowPermissionOperation + phases: list[WorkflowPermissionPhase] + # Experimental: this field is part of an experimental API and may change or be removed. + assisted_approval: PermissionAssistedApproval | None = None + declared_max_ai_credits: float | None = None + declared_max_concurrent_subagents: int | None = None + declared_max_total_subagents: int | None = None + declared_timeout_seconds: float | None = None + managed_approval_required: bool | None = None + max_ai_credits: float | None = None + max_concurrent_subagents: int | None = None + max_total_subagents: int | None = None + timeout_seconds: float | None = None + tool_call_id: str | None = None + + @staticmethod + def from_dict(obj: Any) -> "PermissionPromptRequestWorkflow": + assert isinstance(obj, dict) + approval_key = from_str(obj.get("approvalKey")) + can_persist_approval = from_bool(obj.get("canPersistApproval")) + description = from_str(obj.get("description")) + name = from_str(obj.get("name")) + operation = parse_enum(WorkflowPermissionOperation, obj.get("operation")) + phases = from_list(WorkflowPermissionPhase.from_dict, obj.get("phases")) + assisted_approval = from_union([from_none, PermissionAssistedApproval.from_dict], obj.get("assistedApproval")) + declared_max_ai_credits = from_union([from_none, from_float], obj.get("declaredMaxAiCredits")) + declared_max_concurrent_subagents = from_union([from_none, from_int], obj.get("declaredMaxConcurrentSubagents")) + declared_max_total_subagents = from_union([from_none, from_int], obj.get("declaredMaxTotalSubagents")) + declared_timeout_seconds = from_union([from_none, from_float], obj.get("declaredTimeoutSeconds")) + managed_approval_required = from_union([from_none, from_bool], obj.get("managedApprovalRequired")) + max_ai_credits = from_union([from_none, from_float], obj.get("maxAiCredits")) + max_concurrent_subagents = from_union([from_none, from_int], obj.get("maxConcurrentSubagents")) + max_total_subagents = from_union([from_none, from_int], obj.get("maxTotalSubagents")) + timeout_seconds = from_union([from_none, from_float], obj.get("timeoutSeconds")) + tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) + return PermissionPromptRequestWorkflow( + approval_key=approval_key, + can_persist_approval=can_persist_approval, + description=description, + name=name, + operation=operation, + phases=phases, + assisted_approval=assisted_approval, + declared_max_ai_credits=declared_max_ai_credits, + declared_max_concurrent_subagents=declared_max_concurrent_subagents, + declared_max_total_subagents=declared_max_total_subagents, + declared_timeout_seconds=declared_timeout_seconds, + managed_approval_required=managed_approval_required, + max_ai_credits=max_ai_credits, + max_concurrent_subagents=max_concurrent_subagents, + max_total_subagents=max_total_subagents, + timeout_seconds=timeout_seconds, + tool_call_id=tool_call_id, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["approvalKey"] = from_str(self.approval_key) + result["canPersistApproval"] = from_bool(self.can_persist_approval) + result["description"] = from_str(self.description) + result["kind"] = self.kind + result["name"] = from_str(self.name) + result["operation"] = to_enum(WorkflowPermissionOperation, self.operation) + result["phases"] = from_list(lambda x: to_class(WorkflowPermissionPhase, x), self.phases) + if self.assisted_approval is not None: + result["assistedApproval"] = from_union([from_none, lambda x: to_class(PermissionAssistedApproval, x)], self.assisted_approval) + if self.declared_max_ai_credits is not None: + result["declaredMaxAiCredits"] = from_union([from_none, to_float], self.declared_max_ai_credits) + if self.declared_max_concurrent_subagents is not None: + result["declaredMaxConcurrentSubagents"] = from_union([from_none, to_int], self.declared_max_concurrent_subagents) + if self.declared_max_total_subagents is not None: + result["declaredMaxTotalSubagents"] = from_union([from_none, to_int], self.declared_max_total_subagents) + if self.declared_timeout_seconds is not None: + result["declaredTimeoutSeconds"] = from_union([from_none, to_float], self.declared_timeout_seconds) + if self.managed_approval_required is not None: + result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) + if self.max_ai_credits is not None: + result["maxAiCredits"] = from_union([from_none, to_float], self.max_ai_credits) + if self.max_concurrent_subagents is not None: + result["maxConcurrentSubagents"] = from_union([from_none, to_int], self.max_concurrent_subagents) + if self.max_total_subagents is not None: + result["maxTotalSubagents"] = from_union([from_none, to_int], self.max_total_subagents) + if self.timeout_seconds is not None: + result["timeoutSeconds"] = from_union([from_none, to_float], self.timeout_seconds) + if self.tool_call_id is not None: + result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) + return result + + @dataclass class PermissionPromptRequestWrite: "File write permission prompt" @@ -7307,97 +7283,6 @@ def to_dict(self) -> dict: return result -@dataclass -class PermissionRequestFactory: - "Factory run or authoring permission request" - approval_key: str - can_persist_approval: bool - description: str - kind: ClassVar[str] = "factory" - name: str - operation: FactoryPermissionOperation - phases: list[FactoryPermissionPhase] - declared_max_ai_credits: float | None = None - declared_max_concurrent_subagents: int | None = None - declared_max_total_subagents: int | None = None - declared_timeout_seconds: float | None = None - max_ai_credits: float | None = None - max_concurrent_subagents: int | None = None - max_total_subagents: int | None = None - timeout_seconds: float | None = None - tool_call_id: str | None = None - managed_approval_required: bool | None = None - - @staticmethod - def from_dict(obj: Any) -> "PermissionRequestFactory": - assert isinstance(obj, dict) - approval_key = from_str(obj.get("approvalKey")) - can_persist_approval = from_bool(obj.get("canPersistApproval")) - description = from_str(obj.get("description")) - name = from_str(obj.get("name")) - operation = parse_enum(FactoryPermissionOperation, obj.get("operation")) - phases = from_list(FactoryPermissionPhase.from_dict, obj.get("phases")) - declared_max_ai_credits = from_union([from_none, from_float], obj.get("declaredMaxAiCredits")) - declared_max_concurrent_subagents = from_union([from_none, from_int], obj.get("declaredMaxConcurrentSubagents")) - declared_max_total_subagents = from_union([from_none, from_int], obj.get("declaredMaxTotalSubagents")) - declared_timeout_seconds = from_union([from_none, from_float], obj.get("declaredTimeoutSeconds")) - max_ai_credits = from_union([from_none, from_float], obj.get("maxAiCredits")) - max_concurrent_subagents = from_union([from_none, from_int], obj.get("maxConcurrentSubagents")) - max_total_subagents = from_union([from_none, from_int], obj.get("maxTotalSubagents")) - timeout_seconds = from_union([from_none, from_float], obj.get("timeoutSeconds")) - tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) - managed_approval_required = from_union([from_none, from_bool], obj.get("managedApprovalRequired")) - return PermissionRequestFactory( - approval_key=approval_key, - can_persist_approval=can_persist_approval, - description=description, - name=name, - operation=operation, - phases=phases, - declared_max_ai_credits=declared_max_ai_credits, - declared_max_concurrent_subagents=declared_max_concurrent_subagents, - declared_max_total_subagents=declared_max_total_subagents, - declared_timeout_seconds=declared_timeout_seconds, - max_ai_credits=max_ai_credits, - max_concurrent_subagents=max_concurrent_subagents, - max_total_subagents=max_total_subagents, - timeout_seconds=timeout_seconds, - tool_call_id=tool_call_id, - managed_approval_required=managed_approval_required, - ) - - def to_dict(self) -> dict: - result: dict = {} - result["approvalKey"] = from_str(self.approval_key) - result["canPersistApproval"] = from_bool(self.can_persist_approval) - result["description"] = from_str(self.description) - result["kind"] = self.kind - result["name"] = from_str(self.name) - result["operation"] = to_enum(FactoryPermissionOperation, self.operation) - result["phases"] = from_list(lambda x: to_class(FactoryPermissionPhase, x), self.phases) - if self.declared_max_ai_credits is not None: - result["declaredMaxAiCredits"] = from_union([from_none, to_float], self.declared_max_ai_credits) - if self.declared_max_concurrent_subagents is not None: - result["declaredMaxConcurrentSubagents"] = from_union([from_none, to_int], self.declared_max_concurrent_subagents) - if self.declared_max_total_subagents is not None: - result["declaredMaxTotalSubagents"] = from_union([from_none, to_int], self.declared_max_total_subagents) - if self.declared_timeout_seconds is not None: - result["declaredTimeoutSeconds"] = from_union([from_none, to_float], self.declared_timeout_seconds) - if self.max_ai_credits is not None: - result["maxAiCredits"] = from_union([from_none, to_float], self.max_ai_credits) - if self.max_concurrent_subagents is not None: - result["maxConcurrentSubagents"] = from_union([from_none, to_int], self.max_concurrent_subagents) - if self.max_total_subagents is not None: - result["maxTotalSubagents"] = from_union([from_none, to_int], self.max_total_subagents) - if self.timeout_seconds is not None: - result["timeoutSeconds"] = from_union([from_none, to_float], self.timeout_seconds) - if self.tool_call_id is not None: - result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) - if self.managed_approval_required is not None: - result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) - return result - - @dataclass class PermissionRequestHook: "Hook confirmation permission request" @@ -7807,17 +7692,108 @@ def from_dict(obj: Any) -> "PermissionRequestUrl": def to_dict(self) -> dict: result: dict = {} - result["intention"] = from_str(self.intention) + result["intention"] = from_str(self.intention) + result["kind"] = self.kind + result["url"] = from_str(self.url) + if self.managed_approval_required is not None: + result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) + if self.redirected_from is not None: + result["redirectedFrom"] = from_union([from_none, from_str], self.redirected_from) + if self.request_sandbox_bypass is not None: + result["requestSandboxBypass"] = from_union([from_none, from_bool], self.request_sandbox_bypass) + if self.request_sandbox_bypass_reason is not None: + result["requestSandboxBypassReason"] = from_union([from_none, from_str], self.request_sandbox_bypass_reason) + if self.tool_call_id is not None: + result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) + return result + + +@dataclass +class PermissionRequestWorkflow: + "Workflow run or authoring permission request" + approval_key: str + can_persist_approval: bool + description: str + kind: ClassVar[str] = "workflow" + name: str + operation: WorkflowPermissionOperation + phases: list[WorkflowPermissionPhase] + declared_max_ai_credits: float | None = None + declared_max_concurrent_subagents: int | None = None + declared_max_total_subagents: int | None = None + declared_timeout_seconds: float | None = None + managed_approval_required: bool | None = None + max_ai_credits: float | None = None + max_concurrent_subagents: int | None = None + max_total_subagents: int | None = None + timeout_seconds: float | None = None + tool_call_id: str | None = None + + @staticmethod + def from_dict(obj: Any) -> "PermissionRequestWorkflow": + assert isinstance(obj, dict) + approval_key = from_str(obj.get("approvalKey")) + can_persist_approval = from_bool(obj.get("canPersistApproval")) + description = from_str(obj.get("description")) + name = from_str(obj.get("name")) + operation = parse_enum(WorkflowPermissionOperation, obj.get("operation")) + phases = from_list(WorkflowPermissionPhase.from_dict, obj.get("phases")) + declared_max_ai_credits = from_union([from_none, from_float], obj.get("declaredMaxAiCredits")) + declared_max_concurrent_subagents = from_union([from_none, from_int], obj.get("declaredMaxConcurrentSubagents")) + declared_max_total_subagents = from_union([from_none, from_int], obj.get("declaredMaxTotalSubagents")) + declared_timeout_seconds = from_union([from_none, from_float], obj.get("declaredTimeoutSeconds")) + managed_approval_required = from_union([from_none, from_bool], obj.get("managedApprovalRequired")) + max_ai_credits = from_union([from_none, from_float], obj.get("maxAiCredits")) + max_concurrent_subagents = from_union([from_none, from_int], obj.get("maxConcurrentSubagents")) + max_total_subagents = from_union([from_none, from_int], obj.get("maxTotalSubagents")) + timeout_seconds = from_union([from_none, from_float], obj.get("timeoutSeconds")) + tool_call_id = from_union([from_none, from_str], obj.get("toolCallId")) + return PermissionRequestWorkflow( + approval_key=approval_key, + can_persist_approval=can_persist_approval, + description=description, + name=name, + operation=operation, + phases=phases, + declared_max_ai_credits=declared_max_ai_credits, + declared_max_concurrent_subagents=declared_max_concurrent_subagents, + declared_max_total_subagents=declared_max_total_subagents, + declared_timeout_seconds=declared_timeout_seconds, + managed_approval_required=managed_approval_required, + max_ai_credits=max_ai_credits, + max_concurrent_subagents=max_concurrent_subagents, + max_total_subagents=max_total_subagents, + timeout_seconds=timeout_seconds, + tool_call_id=tool_call_id, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["approvalKey"] = from_str(self.approval_key) + result["canPersistApproval"] = from_bool(self.can_persist_approval) + result["description"] = from_str(self.description) result["kind"] = self.kind - result["url"] = from_str(self.url) + result["name"] = from_str(self.name) + result["operation"] = to_enum(WorkflowPermissionOperation, self.operation) + result["phases"] = from_list(lambda x: to_class(WorkflowPermissionPhase, x), self.phases) + if self.declared_max_ai_credits is not None: + result["declaredMaxAiCredits"] = from_union([from_none, to_float], self.declared_max_ai_credits) + if self.declared_max_concurrent_subagents is not None: + result["declaredMaxConcurrentSubagents"] = from_union([from_none, to_int], self.declared_max_concurrent_subagents) + if self.declared_max_total_subagents is not None: + result["declaredMaxTotalSubagents"] = from_union([from_none, to_int], self.declared_max_total_subagents) + if self.declared_timeout_seconds is not None: + result["declaredTimeoutSeconds"] = from_union([from_none, to_float], self.declared_timeout_seconds) if self.managed_approval_required is not None: result["managedApprovalRequired"] = from_union([from_none, from_bool], self.managed_approval_required) - if self.redirected_from is not None: - result["redirectedFrom"] = from_union([from_none, from_str], self.redirected_from) - if self.request_sandbox_bypass is not None: - result["requestSandboxBypass"] = from_union([from_none, from_bool], self.request_sandbox_bypass) - if self.request_sandbox_bypass_reason is not None: - result["requestSandboxBypassReason"] = from_union([from_none, from_str], self.request_sandbox_bypass_reason) + if self.max_ai_credits is not None: + result["maxAiCredits"] = from_union([from_none, to_float], self.max_ai_credits) + if self.max_concurrent_subagents is not None: + result["maxConcurrentSubagents"] = from_union([from_none, to_int], self.max_concurrent_subagents) + if self.max_total_subagents is not None: + result["maxTotalSubagents"] = from_union([from_none, to_int], self.max_total_subagents) + if self.timeout_seconds is not None: + result["timeoutSeconds"] = from_union([from_none, to_float], self.timeout_seconds) if self.tool_call_id is not None: result["toolCallId"] = from_union([from_none, from_str], self.tool_call_id) return result @@ -8516,6 +8492,8 @@ class SessionCompactionCompleteData: success: bool # Internal: this field is an internal SDK API and is not part of the public surface. _active_factory_summary: str | None = None + # Internal: this field is an internal SDK API and is not part of the public surface. + _active_workflow_summary: str | None = None behavior_model_id: str | None = None checkpoint_number: int | None = None checkpoint_path: str | None = None @@ -8543,6 +8521,7 @@ def from_dict(obj: Any) -> "SessionCompactionCompleteData": assert isinstance(obj, dict) success = from_bool(obj.get("success")) _active_factory_summary = from_union([from_none, from_str], obj.get("activeFactorySummary")) + _active_workflow_summary = from_union([from_none, from_str], obj.get("activeWorkflowSummary")) behavior_model_id = from_union([from_none, from_str], obj.get("behaviorModelId")) checkpoint_number = from_union([from_none, from_int], obj.get("checkpointNumber")) checkpoint_path = from_union([from_none, from_str], obj.get("checkpointPath")) @@ -8567,6 +8546,7 @@ def from_dict(obj: Any) -> "SessionCompactionCompleteData": return SessionCompactionCompleteData( success=success, _active_factory_summary=_active_factory_summary, + _active_workflow_summary=_active_workflow_summary, behavior_model_id=behavior_model_id, checkpoint_number=checkpoint_number, checkpoint_path=checkpoint_path, @@ -8595,6 +8575,8 @@ def to_dict(self) -> dict: result["success"] = from_bool(self.success) if self._active_factory_summary is not None: result["activeFactorySummary"] = from_union([from_none, from_str], self._active_factory_summary) + if self._active_workflow_summary is not None: + result["activeWorkflowSummary"] = from_union([from_none, from_str], self._active_workflow_summary) if self.behavior_model_id is not None: result["behaviorModelId"] = from_union([from_none, from_str], self.behavior_model_id) if self.checkpoint_number is not None: @@ -11019,6 +11001,7 @@ class SubagentStartedData: parent_id: str | None = None resumable: bool | None = None task_model_source: SubagentTaskModelSource | None = None + workflow_run_id: str | None = None @staticmethod def from_dict(obj: Any) -> "SubagentStartedData": @@ -11035,6 +11018,7 @@ def from_dict(obj: Any) -> "SubagentStartedData": parent_id = from_union([from_none, from_str], obj.get("parentId")) resumable = from_union([from_none, from_bool], obj.get("resumable")) task_model_source = from_union([from_none, lambda x: parse_enum(SubagentTaskModelSource, x)], obj.get("taskModelSource")) + workflow_run_id = from_union([from_none, from_str], obj.get("workflowRunId")) return SubagentStartedData( agent_description=agent_description, agent_display_name=agent_display_name, @@ -11048,6 +11032,7 @@ def from_dict(obj: Any) -> "SubagentStartedData": parent_id=parent_id, resumable=resumable, task_model_source=task_model_source, + workflow_run_id=workflow_run_id, ) def to_dict(self) -> dict: @@ -11072,6 +11057,8 @@ def to_dict(self) -> dict: result["resumable"] = from_union([from_none, from_bool], self.resumable) if self.task_model_source is not None: result["taskModelSource"] = from_union([from_none, lambda x: to_enum(SubagentTaskModelSource, x)], self.task_model_source) + if self.workflow_run_id is not None: + result["workflowRunId"] = from_union([from_none, from_str], self.workflow_run_id) return result @@ -11279,95 +11266,6 @@ def to_dict(self) -> dict: return result -@dataclass -class SystemNotificationFactoryCompleted: - "System notification metadata for a factory execution attempt that reached a terminal state." - attempt: int - consumed_nano_aiu: int - consumed_subagents: int - elapsed_ms: int - factory_name: str - run_id: str - status: SystemNotificationFactoryCompletedStatus - type: ClassVar[str] = "factory_completed" - failure: Any = None - pause_info: SystemNotificationFactoryPauseInfo | None = None - result_preview: str | None = None - retry_guidance: str | None = None - - @staticmethod - def from_dict(obj: Any) -> "SystemNotificationFactoryCompleted": - assert isinstance(obj, dict) - attempt = from_int(obj.get("attempt")) - consumed_nano_aiu = from_int(obj.get("consumedNanoAiu")) - consumed_subagents = from_int(obj.get("consumedSubagents")) - elapsed_ms = from_int(obj.get("elapsedMs")) - factory_name = from_str(obj.get("factoryName")) - run_id = from_str(obj.get("runId")) - status = parse_enum(SystemNotificationFactoryCompletedStatus, obj.get("status")) - failure = obj.get("failure") - pause_info = from_union([from_none, SystemNotificationFactoryPauseInfo.from_dict], obj.get("pauseInfo")) - result_preview = from_union([from_none, from_str], obj.get("resultPreview")) - retry_guidance = from_union([from_none, from_str], obj.get("retryGuidance")) - return SystemNotificationFactoryCompleted( - attempt=attempt, - consumed_nano_aiu=consumed_nano_aiu, - consumed_subagents=consumed_subagents, - elapsed_ms=elapsed_ms, - factory_name=factory_name, - run_id=run_id, - status=status, - failure=failure, - pause_info=pause_info, - result_preview=result_preview, - retry_guidance=retry_guidance, - ) - - def to_dict(self) -> dict: - result: dict = {} - result["attempt"] = to_int(self.attempt) - result["consumedNanoAiu"] = to_int(self.consumed_nano_aiu) - result["consumedSubagents"] = to_int(self.consumed_subagents) - result["elapsedMs"] = to_int(self.elapsed_ms) - result["factoryName"] = from_str(self.factory_name) - result["runId"] = from_str(self.run_id) - result["status"] = to_enum(SystemNotificationFactoryCompletedStatus, self.status) - result["type"] = self.type - if self.failure is not None: - result["failure"] = self.failure - if self.pause_info is not None: - result["pauseInfo"] = from_union([from_none, lambda x: to_class(SystemNotificationFactoryPauseInfo, x)], self.pause_info) - if self.result_preview is not None: - result["resultPreview"] = from_union([from_none, from_str], self.result_preview) - if self.retry_guidance is not None: - result["retryGuidance"] = from_union([from_none, from_str], self.retry_guidance) - return result - - -@dataclass -class SystemNotificationFactoryPauseInfo: - "Durable metadata describing who initiated a factory pause." - type: SystemNotificationFactoryPauseInfoType - key: str | None = None - - @staticmethod - def from_dict(obj: Any) -> "SystemNotificationFactoryPauseInfo": - assert isinstance(obj, dict) - type = parse_enum(SystemNotificationFactoryPauseInfoType, obj.get("type")) - key = from_union([from_none, from_str], obj.get("key")) - return SystemNotificationFactoryPauseInfo( - type=type, - key=key, - ) - - def to_dict(self) -> dict: - result: dict = {} - result["type"] = to_enum(SystemNotificationFactoryPauseInfoType, self.type) - if self.key is not None: - result["key"] = from_union([from_none, from_str], self.key) - return result - - @dataclass class SystemNotificationInstructionDiscovered: "System notification metadata for an instruction file discovered during tool access, including source, trigger file, and tool." @@ -11514,6 +11412,95 @@ def to_dict(self) -> dict: return result +@dataclass +class SystemNotificationWorkflowCompleted: + "System notification metadata for a workflow execution attempt that reached a terminal state." + attempt: int + consumed_nano_aiu: int + consumed_subagents: int + elapsed_ms: int + run_id: str + status: SystemNotificationWorkflowCompletedStatus + type: ClassVar[str] = "workflow_completed" + workflow_name: str + failure: Any = None + pause_info: SystemNotificationWorkflowPauseInfo | None = None + result_preview: str | None = None + retry_guidance: str | None = None + + @staticmethod + def from_dict(obj: Any) -> "SystemNotificationWorkflowCompleted": + assert isinstance(obj, dict) + attempt = from_int(obj.get("attempt")) + consumed_nano_aiu = from_int(obj.get("consumedNanoAiu")) + consumed_subagents = from_int(obj.get("consumedSubagents")) + elapsed_ms = from_int(obj.get("elapsedMs")) + run_id = from_str(obj.get("runId")) + status = parse_enum(SystemNotificationWorkflowCompletedStatus, obj.get("status")) + workflow_name = from_str(obj.get("workflowName")) + failure = obj.get("failure") + pause_info = from_union([from_none, SystemNotificationWorkflowPauseInfo.from_dict], obj.get("pauseInfo")) + result_preview = from_union([from_none, from_str], obj.get("resultPreview")) + retry_guidance = from_union([from_none, from_str], obj.get("retryGuidance")) + return SystemNotificationWorkflowCompleted( + attempt=attempt, + consumed_nano_aiu=consumed_nano_aiu, + consumed_subagents=consumed_subagents, + elapsed_ms=elapsed_ms, + run_id=run_id, + status=status, + workflow_name=workflow_name, + failure=failure, + pause_info=pause_info, + result_preview=result_preview, + retry_guidance=retry_guidance, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["attempt"] = to_int(self.attempt) + result["consumedNanoAiu"] = to_int(self.consumed_nano_aiu) + result["consumedSubagents"] = to_int(self.consumed_subagents) + result["elapsedMs"] = to_int(self.elapsed_ms) + result["runId"] = from_str(self.run_id) + result["status"] = to_enum(SystemNotificationWorkflowCompletedStatus, self.status) + result["type"] = self.type + result["workflowName"] = from_str(self.workflow_name) + if self.failure is not None: + result["failure"] = self.failure + if self.pause_info is not None: + result["pauseInfo"] = from_union([from_none, lambda x: to_class(SystemNotificationWorkflowPauseInfo, x)], self.pause_info) + if self.result_preview is not None: + result["resultPreview"] = from_union([from_none, from_str], self.result_preview) + if self.retry_guidance is not None: + result["retryGuidance"] = from_union([from_none, from_str], self.retry_guidance) + return result + + +@dataclass +class SystemNotificationWorkflowPauseInfo: + "Durable metadata describing who initiated a workflow pause." + type: SystemNotificationWorkflowPauseInfoType + key: str | None = None + + @staticmethod + def from_dict(obj: Any) -> "SystemNotificationWorkflowPauseInfo": + assert isinstance(obj, dict) + type = parse_enum(SystemNotificationWorkflowPauseInfoType, obj.get("type")) + key = from_union([from_none, from_str], obj.get("key")) + return SystemNotificationWorkflowPauseInfo( + type=type, + key=key, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["type"] = to_enum(SystemNotificationWorkflowPauseInfoType, self.type) + if self.key is not None: + result["key"] = from_union([from_none, from_str], self.key) + return result + + @dataclass class ToolExecutionCompleteContentAudio: "Audio content block with base64-encoded data" @@ -12792,28 +12779,6 @@ def to_dict(self) -> dict: return result -@dataclass -class UserToolSessionApprovalFactory: - "Session-scoped factory approval, optionally narrowed by approval key." - kind: ClassVar[str] = "factory" - approval_key: str | None = None - - @staticmethod - def from_dict(obj: Any) -> "UserToolSessionApprovalFactory": - assert isinstance(obj, dict) - approval_key = from_union([from_none, from_str], obj.get("approvalKey")) - return UserToolSessionApprovalFactory( - approval_key=approval_key, - ) - - def to_dict(self) -> dict: - result: dict = {} - result["kind"] = self.kind - if self.approval_key is not None: - result["approvalKey"] = from_union([from_none, from_str], self.approval_key) - return result - - @dataclass class UserToolSessionApprovalMcp: "Session-scoped tool-approval rule for an MCP server tool, or all tools on the server when `toolName` is null." @@ -12873,6 +12838,28 @@ def to_dict(self) -> dict: return result +@dataclass +class UserToolSessionApprovalWorkflow: + "Session-scoped workflow approval, optionally narrowed by approval key." + kind: ClassVar[str] = "workflow" + approval_key: str | None = None + + @staticmethod + def from_dict(obj: Any) -> "UserToolSessionApprovalWorkflow": + assert isinstance(obj, dict) + approval_key = from_union([from_none, from_str], obj.get("approvalKey")) + return UserToolSessionApprovalWorkflow( + approval_key=approval_key, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["kind"] = self.kind + if self.approval_key is not None: + result["approvalKey"] = from_union([from_none, from_str], self.approval_key) + return result + + @dataclass class UserToolSessionApprovalWrite: "Session-scoped tool-approval rule for filesystem write operations." @@ -12890,6 +12877,30 @@ def to_dict(self) -> dict: return result +@dataclass +class WorkflowPermissionPhase: + "A declared phase shown in a workflow permission prompt." + title: str + detail: str | None = None + + @staticmethod + def from_dict(obj: Any) -> "WorkflowPermissionPhase": + assert isinstance(obj, dict) + title = from_str(obj.get("title")) + detail = from_union([from_none, from_str], obj.get("detail")) + return WorkflowPermissionPhase( + title=title, + detail=detail, + ) + + def to_dict(self) -> dict: + result: dict = {} + result["title"] = from_str(self.title) + if self.detail is not None: + result["detail"] = from_union([from_none, from_str], self.detail) + return result + + @dataclass class WorkingDirectoryContext: "Working directory and git context at session start" @@ -12995,7 +13006,7 @@ def _load_PermissionPromptRequest(obj: Any) -> "PermissionPromptRequest": case "path": return PermissionPromptRequestPath.from_dict(obj) case "hook": return PermissionPromptRequestHook.from_dict(obj) case "extension-management": return PermissionPromptRequestExtensionManagement.from_dict(obj) - case "factory": return PermissionPromptRequestFactory.from_dict(obj) + case "workflow": return PermissionPromptRequestWorkflow.from_dict(obj) case "extension-permission-access": return PermissionPromptRequestExtensionPermissionAccess.from_dict(obj) case "extension-env-access": return PermissionPromptRequestExtensionEnvAccess.from_dict(obj) case _: raise ValueError(f"Unknown PermissionPromptRequest kind: {kind!r}") @@ -13014,7 +13025,7 @@ def _load_PermissionRequest(obj: Any) -> "PermissionRequest": case "custom-tool": return PermissionRequestCustomTool.from_dict(obj) case "hook": return PermissionRequestHook.from_dict(obj) case "extension-management": return PermissionRequestExtensionManagement.from_dict(obj) - case "factory": return PermissionRequestFactory.from_dict(obj) + case "workflow": return PermissionRequestWorkflow.from_dict(obj) case "extension-permission-access": return PermissionRequestExtensionPermissionAccess.from_dict(obj) case "extension-env-access": return PermissionRequestExtensionEnvAccess.from_dict(obj) case _: raise ValueError(f"Unknown PermissionRequest kind: {kind!r}") @@ -13046,7 +13057,7 @@ def _load_SystemNotification(obj: Any) -> "SystemNotification": case "shell_completed": return SystemNotificationShellCompleted.from_dict(obj) case "shell_detached_completed": return SystemNotificationShellDetachedCompleted.from_dict(obj) case "instruction_discovered": return SystemNotificationInstructionDiscovered.from_dict(obj) - case "factory_completed": return SystemNotificationFactoryCompleted.from_dict(obj) + case "workflow_completed": return SystemNotificationWorkflowCompleted.from_dict(obj) case "unclassified": return SystemNotificationUnclassified.from_dict(obj) case _: raise ValueError(f"Unknown SystemNotification type: {kind!r}") @@ -13076,7 +13087,7 @@ def _load_UserToolSessionApproval(obj: Any) -> "UserToolSessionApproval": case "memory": return UserToolSessionApprovalMemory.from_dict(obj) case "custom-tool": return UserToolSessionApprovalCustomTool.from_dict(obj) case "extension-management": return UserToolSessionApprovalExtensionManagement.from_dict(obj) - case "factory": return UserToolSessionApprovalFactory.from_dict(obj) + case "workflow": return UserToolSessionApprovalWorkflow.from_dict(obj) case "extension-permission-access": return UserToolSessionApprovalExtensionPermissionAccess.from_dict(obj) case "extension-env-access": return UserToolSessionApprovalExtensionEnvAccess.from_dict(obj) case _: raise ValueError(f"Unknown UserToolSessionApproval kind: {kind!r}") @@ -13095,11 +13106,11 @@ def _load_UserToolSessionApproval(obj: Any) -> "UserToolSessionApproval": # Derived user-facing permission prompt details for UI consumers -PermissionPromptRequest = PermissionPromptRequestCommands | PermissionPromptRequestWrite | PermissionPromptRequestRead | PermissionPromptRequestMcp | PermissionPromptRequestUrl | PermissionPromptRequestMemory | PermissionPromptRequestCustomTool | PermissionPromptRequestPath | PermissionPromptRequestHook | PermissionPromptRequestExtensionManagement | PermissionPromptRequestFactory | PermissionPromptRequestExtensionPermissionAccess | PermissionPromptRequestExtensionEnvAccess +PermissionPromptRequest = PermissionPromptRequestCommands | PermissionPromptRequestWrite | PermissionPromptRequestRead | PermissionPromptRequestMcp | PermissionPromptRequestUrl | PermissionPromptRequestMemory | PermissionPromptRequestCustomTool | PermissionPromptRequestPath | PermissionPromptRequestHook | PermissionPromptRequestExtensionManagement | PermissionPromptRequestWorkflow | PermissionPromptRequestExtensionPermissionAccess | PermissionPromptRequestExtensionEnvAccess # Details of the permission being requested -PermissionRequest = PermissionRequestShell | PermissionRequestWrite | PermissionRequestRead | PermissionRequestMcp | PermissionRequestUrl | PermissionRequestMemory | PermissionRequestCustomTool | PermissionRequestHook | PermissionRequestExtensionManagement | PermissionRequestFactory | PermissionRequestExtensionPermissionAccess | PermissionRequestExtensionEnvAccess +PermissionRequest = PermissionRequestShell | PermissionRequestWrite | PermissionRequestRead | PermissionRequestMcp | PermissionRequestUrl | PermissionRequestMemory | PermissionRequestCustomTool | PermissionRequestHook | PermissionRequestExtensionManagement | PermissionRequestWorkflow | PermissionRequestExtensionPermissionAccess | PermissionRequestExtensionEnvAccess # Location within a cited source (character, page, or content-block range) that supports a span. @@ -13107,11 +13118,11 @@ def _load_UserToolSessionApproval(obj: Any) -> "UserToolSessionApproval": # Structured metadata identifying what triggered this notification -SystemNotification = SystemNotificationAgentCompleted | SystemNotificationAgentIdle | SystemNotificationNewInboxMessage | SystemNotificationShellCompleted | SystemNotificationShellDetachedCompleted | SystemNotificationInstructionDiscovered | SystemNotificationFactoryCompleted | SystemNotificationUnclassified +SystemNotification = SystemNotificationAgentCompleted | SystemNotificationAgentIdle | SystemNotificationNewInboxMessage | SystemNotificationShellCompleted | SystemNotificationShellDetachedCompleted | SystemNotificationInstructionDiscovered | SystemNotificationWorkflowCompleted | SystemNotificationUnclassified # The approval to add as a session-scoped rule -UserToolSessionApproval = UserToolSessionApprovalCommands | UserToolSessionApprovalRead | UserToolSessionApprovalWrite | UserToolSessionApprovalMcp | UserToolSessionApprovalMemory | UserToolSessionApprovalCustomTool | UserToolSessionApprovalExtensionManagement | UserToolSessionApprovalFactory | UserToolSessionApprovalExtensionPermissionAccess | UserToolSessionApprovalExtensionEnvAccess +UserToolSessionApproval = UserToolSessionApprovalCommands | UserToolSessionApprovalRead | UserToolSessionApprovalWrite | UserToolSessionApprovalMcp | UserToolSessionApprovalMemory | UserToolSessionApprovalCustomTool | UserToolSessionApprovalExtensionManagement | UserToolSessionApprovalWorkflow | UserToolSessionApprovalExtensionPermissionAccess | UserToolSessionApprovalExtensionEnvAccess # The embedded resource contents, either text or base64-encoded binary @@ -13253,10 +13264,10 @@ class FusionTurnKind(Enum): # Experimental: this enum is part of an experimental API and may change or be removed. class PermissionMessageAuthorizationPolarity(Enum): - "Which direction a message-backed authorization claim moves authority in." - # The human's words authorized an effect. + "Direction stored in a historical extractor claim. Current runtimes do not apply it." + # Historical claim recorded as a grant. GRANT = "grant" - # The human's words refused an effect. + # Historical claim recorded as a denial. DENIAL = "denial" @@ -13558,28 +13569,6 @@ class ExtensionsLoadedExtensionStatus(Enum): STARTING = "starting" -class FactoryPermissionOperation(Enum): - "Operation gated by a factory permission request." - # Running a registered factory, which spends subagents, active time, and AI credits under the approved limits. - RUN = "run" - # Authoring a factory, which writes JavaScript into a session-scoped extension and loads it. - AUTHOR = "author" - - -class FactoryRunSettledStatus(Enum): - "Terminal status a factory run committed. A settled run is never `pending` or `running`, so those two members of the run-status domain are deliberately absent." - # The factory body resolved and its result was committed. - COMPLETED = "completed" - # The run was stopped by a limit, an approval refusal or another policy decision. - HALTED = "halted" - # The attempt paused intentionally while preserving resumable run state. - PAUSED = "paused" - # The run was cancelled by its caller or by session disposal. - CANCELLED = "cancelled" - # The run failed, with `failureType` carrying the class when it has one. - ERROR = "error" - - class HandoffSourceType(Enum): "Origin type of the session being handed off" # The handoff originated from a remote session. @@ -13854,6 +13843,8 @@ class ModelChangeSource(Enum): CHANGEBOARDING_SHORTCUT = "changeboarding_shortcut" # An SDK or RPC caller selected the model. SDK = "sdk" + # The user accepted a CAPI-issued Auto tier recommendation. + AUTO_TIER_RECOMMENDATION = "auto_tier_recommendation" class ModelDeselectedReason(Enum): @@ -13974,7 +13965,7 @@ class PermissionDecisionSource(Enum): HOST_POLICY = "host_policy" # The host denied the request because no interactive user response was available. UNATTENDED_FALLBACK = "unattended_fallback" - # A live authorization record from an earlier human decision in this session contained the proposal, so it ran without another prompt. This is not a new human decision and never mints authority of its own. + # Historical compatibility value for sessions created while authorization carry-forward was executable. Current runtimes do not produce this source. AUTHORIZATION_CARRY_FORWARD = "authorization_carry_forward" @@ -14447,22 +14438,22 @@ class SystemNotificationAgentCompletedStatus(Enum): FAILED = "failed" -class SystemNotificationFactoryCompletedStatus(Enum): - "Terminal status reached by a factory execution attempt." - # The factory completed successfully. +class SystemNotificationWorkflowCompletedStatus(Enum): + "Terminal status reached by a workflow execution attempt." + # The workflow completed successfully. COMPLETED = "completed" - # The factory was halted. + # The workflow was halted. HALTED = "halted" - # The factory attempt paused intentionally. + # The workflow attempt paused intentionally. PAUSED = "paused" - # The factory was cancelled. + # The workflow was cancelled. CANCELLED = "cancelled" - # The factory failed. + # The workflow failed. ERROR = "error" -class SystemNotificationFactoryPauseInfoType(Enum): - "Durable metadata describing who initiated a factory pause. discriminator" +class SystemNotificationWorkflowPauseInfoType(Enum): + "Durable metadata describing who initiated a workflow pause. discriminator" USER = "user" CHECKPOINT = "checkpoint" @@ -14539,6 +14530,28 @@ class Verbosity(Enum): HIGH = "high" +class WorkflowPermissionOperation(Enum): + "Operation gated by a workflow permission request." + # Running a registered workflow, which spends subagents, active time, and AI credits under the approved limits. + RUN = "run" + # Authoring a workflow, which writes JavaScript into a session-scoped extension and loads it. + AUTHOR = "author" + + +class WorkflowRunSettledStatus(Enum): + "Terminal status a workflow run committed. A settled run is never `pending` or `running`, so those two members of the run-status domain are deliberately absent." + # The workflow body resolved and its result was committed. + COMPLETED = "completed" + # The run was stopped by a limit, an approval refusal or another policy decision. + HALTED = "halted" + # The attempt paused intentionally while preserving resumable run state. + PAUSED = "paused" + # The run was cancelled by its caller or by session disposal. + CANCELLED = "cancelled" + # The run failed, with `failureType` carrying the class when it has one. + ERROR = "error" + + class WorkingDirectoryContextHostType(Enum): "Hosting platform type of the repository (github or ado)" # Repository is hosted on GitHub. @@ -14555,7 +14568,7 @@ class WorkspaceFileChangedOperation(Enum): UPDATE = "update" -SessionEventData = SessionStartData | SessionResumeData | SessionRemoteSteerableChangedData | SessionErrorData | SessionIdleData | SessionTitleChangedData | SessionScheduleCreatedData | SessionScheduleCancelledData | SessionScheduleRearmedData | SessionAutopilotObjectiveChangedData | SessionInfoData | SessionIndexedSearchData | SessionWarningData | SessionModelChangeData | SessionModelDeselectedData | SessionAutoTierRecommendationData | SessionAutoTierSwitchFailedData | SessionModeChangedData | SessionModeNoticeDeliveredData | SessionSessionLimitsChangedData | SessionPermissionsChangedData | SessionPlanChangedData | SessionTodosChangedData | SessionWorkspaceFileChangedData | SessionHandoffData | SessionTruncationData | SessionSnapshotRewindData | SessionShutdownData | SessionUsageCheckpointData | SessionContextChangedData | SessionUsageInfoData | SessionContextClearedData | SessionCompactionStartData | SessionCompactionCompleteData | SessionTaskCompleteData | SessionCompletionReceiptData | SessionFusionRouteStartedData | SessionFusionRouteFailedData | SessionFusionResolvedData | SessionFusionCompletedData | SessionPermissionRecoveryData | UserMessageData | PendingMessagesModifiedData | AssistantTurnStartData | AssistantTurnRetryData | AgentInterruptedData | AssistantIntentData | AssistantFusionPhaseStartedData | AssistantFusionPhaseActivityData | AssistantFusionPhaseCompletedData | AssistantFusionPhaseFailedData | AssistantServerToolProgressData | AssistantReasoningData | AssistantReasoningDeltaData | AssistantToolCallDeltaData | AssistantStreamingDeltaData | AssistantMessageData | AssistantMessageStartData | AssistantMessageDeltaData | AssistantTurnEndData | AssistantIdleData | AssistantUsageData | PromptCacheBreakData | ModelCallFailureData | ModelCallFinishedData | ModelCallStartData | AbortData | ToolUserRequestedData | ToolExecutionStartData | ToolExecutionPartialResultData | ToolExecutionProgressData | ToolExecutionCompleteData | ToolSearchActivatedData | SkillInvokedData | SkillInvokedRefData | SkillContextDeliveredData | SkillContextDeliveredRefData | SandboxDecisionData | SubagentStartedData | SubagentConfiguredData | SubagentCompletedData | SubagentFailedData | SubagentSelectedData | SubagentDeselectedData | HookStartData | HookEndData | HookProgressData | SessionBinaryAssetData | SystemMessageData | SystemNotificationData | PermissionRequestedData | PermissionCompletedData | PermissionCarriedForwardData | PermissionMessageAuthorizationData | PermissionMessageAuthorizationReadData | PermissionMessageAuthorizationDegradedData | PermissionAssentDetectedData | PermissionContextualAuthorizationData | UserInputRequestedData | UserInputCompletedData | ElicitationRequestedData | ElicitationCompletedData | SamplingRequestedData | SamplingCompletedData | McpOauthRequiredData | McpOauthCompletedData | McpHeadersRefreshRequiredData | McpHeadersRefreshCompletedData | SessionCustomNotificationData | UiEphemeralQueryData | ExternalToolRequestedData | ExternalToolCompletedData | CommandQueuedData | CommandExecuteData | CommandCompletedData | AutoModeSwitchRequestedData | AutoModeSwitchCompletedData | SessionLimitsExhaustedRequestedData | SessionLimitsExhaustedCompletedData | SessionAutoModeResolvedData | SessionManagedSettingsResolvedData | SessionManagedSettingsEnforcedData | CommandsChangedData | CapabilitiesChangedData | ExitPlanModeRequestedData | ExitPlanModeCompletedData | SessionToolsUpdatedData | SessionBackgroundTasksChangedData | FactoryRunUpdatedData | FactoryRunStartedData | FactoryRunSettledData | SessionSkillsLoadedData | SessionCustomAgentsUpdatedData | SessionMcpServersLoadedData | SessionMcpServerStatusChangedData | SessionMcpServerRemovedData | SessionMcpServerNeedsReconnectData | McpToolsListChangedData | McpResourcesListChangedData | McpPromptsListChangedData | SessionExtensionsLoadedData | SessionCanvasOpenedData | SessionCanvasRegistryChangedData | SessionCanvasClosedData | SessionCanvasUnavailableData | SessionCanvasRecordedData | SessionCanvasRemovedData | SessionExtensionsAttachmentsPushedData | McpAppToolCallCompleteData | RawSessionEventData | Data +SessionEventData = SessionStartData | SessionResumeData | SessionRemoteSteerableChangedData | SessionErrorData | SessionIdleData | SessionTitleChangedData | SessionScheduleCreatedData | SessionScheduleCancelledData | SessionScheduleRearmedData | SessionAutopilotObjectiveChangedData | SessionInfoData | SessionIndexedSearchData | SessionWarningData | SessionModelChangeData | SessionModelDeselectedData | SessionAutoTierRecommendationData | SessionAutoTierSwitchFailedData | SessionModeChangedData | SessionModeNoticeDeliveredData | SessionSessionLimitsChangedData | SessionPermissionsChangedData | SessionPlanChangedData | SessionTodosChangedData | SessionWorkspaceFileChangedData | SessionHandoffData | SessionTruncationData | SessionSnapshotRewindData | SessionShutdownData | SessionUsageCheckpointData | SessionContextChangedData | SessionUsageInfoData | SessionContextClearedData | SessionCompactionStartData | SessionCompactionCompleteData | SessionTaskCompleteData | SessionCompletionReceiptData | SessionFusionRouteStartedData | SessionFusionRouteFailedData | SessionFusionResolvedData | SessionFusionCompletedData | SessionPermissionRecoveryData | UserMessageData | PendingMessagesModifiedData | AssistantTurnStartData | AssistantTurnRetryData | AgentInterruptedData | AssistantIntentData | AssistantFusionPhaseStartedData | AssistantFusionPhaseActivityData | AssistantFusionPhaseCompletedData | AssistantFusionPhaseFailedData | AssistantServerToolProgressData | AssistantReasoningData | AssistantReasoningDeltaData | AssistantToolCallDeltaData | AssistantStreamingDeltaData | AssistantMessageData | AssistantMessageStartData | AssistantMessageDeltaData | AssistantTurnEndData | AssistantIdleData | AssistantUsageData | PromptCacheBreakData | ModelCallFailureData | ModelCallFinishedData | ModelCallStartData | AbortData | ToolUserRequestedData | ToolExecutionStartData | ToolExecutionPartialResultData | ToolExecutionProgressData | ToolExecutionCompleteData | ToolSearchActivatedData | SkillInvokedData | SkillInvokedRefData | SkillContextDeliveredData | SkillContextDeliveredRefData | SandboxDecisionData | SubagentStartedData | SubagentConfiguredData | SubagentCompletedData | SubagentFailedData | SubagentSelectedData | SubagentDeselectedData | HookStartData | HookEndData | HookProgressData | SessionBinaryAssetData | SystemMessageData | SystemNotificationData | PermissionRequestedData | PermissionCompletedData | PermissionCarriedForwardData | PermissionMessageAuthorizationData | PermissionMessageAuthorizationReadData | PermissionMessageAuthorizationDegradedData | PermissionAssentDetectedData | PermissionContextualAuthorizationData | UserInputRequestedData | UserInputCompletedData | ElicitationRequestedData | ElicitationCompletedData | SamplingRequestedData | SamplingCompletedData | McpOauthRequiredData | McpOauthCompletedData | McpHeadersRefreshRequiredData | McpHeadersRefreshCompletedData | SessionCustomNotificationData | UiEphemeralQueryData | ExternalToolRequestedData | ExternalToolCompletedData | CommandQueuedData | CommandExecuteData | CommandCompletedData | AutoModeSwitchRequestedData | AutoModeSwitchCompletedData | SessionLimitsExhaustedRequestedData | SessionLimitsExhaustedCompletedData | SessionAutoModeResolvedData | SessionManagedSettingsResolvedData | SessionManagedSettingsEnforcedData | CommandsChangedData | CapabilitiesChangedData | ExitPlanModeRequestedData | ExitPlanModeCompletedData | SessionToolsUpdatedData | SessionBackgroundTasksChangedData | WorkflowRunUpdatedData | WorkflowRunStartedData | WorkflowRunSettledData | SessionSkillsLoadedData | SessionCustomAgentsUpdatedData | SessionMcpServersLoadedData | SessionMcpServerStatusChangedData | SessionMcpServerRemovedData | SessionMcpServerNeedsReconnectData | McpToolsListChangedData | McpResourcesListChangedData | McpPromptsListChangedData | SessionExtensionsLoadedData | SessionCanvasOpenedData | SessionCanvasRegistryChangedData | SessionCanvasClosedData | SessionCanvasUnavailableData | SessionCanvasRecordedData | SessionCanvasRemovedData | SessionExtensionsAttachmentsPushedData | McpAppToolCallCompleteData | RawSessionEventData | Data @dataclass @@ -14709,9 +14722,9 @@ def from_dict(obj: Any) -> "SessionEvent": case SessionEventType.EXIT_PLAN_MODE_COMPLETED: data = ExitPlanModeCompletedData.from_dict(data_obj) case SessionEventType.SESSION_TOOLS_UPDATED: data = SessionToolsUpdatedData.from_dict(data_obj) case SessionEventType.SESSION_BACKGROUND_TASKS_CHANGED: data = SessionBackgroundTasksChangedData.from_dict(data_obj) - case SessionEventType.FACTORY_RUN_UPDATED: data = FactoryRunUpdatedData.from_dict(data_obj) - case SessionEventType.FACTORY_RUN_STARTED: data = FactoryRunStartedData.from_dict(data_obj) - case SessionEventType.FACTORY_RUN_SETTLED: data = FactoryRunSettledData.from_dict(data_obj) + case SessionEventType.WORKFLOW_RUN_UPDATED: data = WorkflowRunUpdatedData.from_dict(data_obj) + case SessionEventType.WORKFLOW_RUN_STARTED: data = WorkflowRunStartedData.from_dict(data_obj) + case SessionEventType.WORKFLOW_RUN_SETTLED: data = WorkflowRunSettledData.from_dict(data_obj) case SessionEventType.SESSION_SKILLS_LOADED: data = SessionSkillsLoadedData.from_dict(data_obj) case SessionEventType.SESSION_CUSTOM_AGENTS_UPDATED: data = SessionCustomAgentsUpdatedData.from_dict(data_obj) case SessionEventType.SESSION_MCP_SERVERS_LOADED: data = SessionMcpServersLoadedData.from_dict(data_obj) @@ -14878,12 +14891,6 @@ def session_event_to_dict(x: SessionEvent) -> Any: "ExtensionsLoadedExtensionStatus", "ExternalToolCompletedData", "ExternalToolRequestedData", - "FactoryPermissionOperation", - "FactoryPermissionPhase", - "FactoryRunSettledData", - "FactoryRunSettledStatus", - "FactoryRunStartedData", - "FactoryRunUpdatedData", "FusionAttribution", "FusionConversationScope", "FusionFollowUpAction", @@ -14981,7 +14988,6 @@ def session_event_to_dict(x: SessionEvent) -> Any: "PermissionPromptRequestExtensionEnvAccess", "PermissionPromptRequestExtensionManagement", "PermissionPromptRequestExtensionPermissionAccess", - "PermissionPromptRequestFactory", "PermissionPromptRequestHook", "PermissionPromptRequestMcp", "PermissionPromptRequestMemory", @@ -14989,6 +14995,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "PermissionPromptRequestPathAccessKind", "PermissionPromptRequestRead", "PermissionPromptRequestUrl", + "PermissionPromptRequestWorkflow", "PermissionPromptRequestWrite", "PermissionRecommendation", "PermissionRecoveryAttempt", @@ -15004,7 +15011,6 @@ def session_event_to_dict(x: SessionEvent) -> Any: "PermissionRequestExtensionEnvAccess", "PermissionRequestExtensionManagement", "PermissionRequestExtensionPermissionAccess", - "PermissionRequestFactory", "PermissionRequestHook", "PermissionRequestMcp", "PermissionRequestMemory", @@ -15017,6 +15023,7 @@ def session_event_to_dict(x: SessionEvent) -> Any: "PermissionRequestShellCommandSegment", "PermissionRequestShellPossibleUrl", "PermissionRequestUrl", + "PermissionRequestWorkflow", "PermissionRequestWrite", "PermissionRequestedData", "PermissionResult", @@ -15153,15 +15160,15 @@ def session_event_to_dict(x: SessionEvent) -> Any: "SystemNotificationAgentCompletedStatus", "SystemNotificationAgentIdle", "SystemNotificationData", - "SystemNotificationFactoryCompleted", - "SystemNotificationFactoryCompletedStatus", - "SystemNotificationFactoryPauseInfo", - "SystemNotificationFactoryPauseInfoType", "SystemNotificationInstructionDiscovered", "SystemNotificationNewInboxMessage", "SystemNotificationShellCompleted", "SystemNotificationShellDetachedCompleted", "SystemNotificationUnclassified", + "SystemNotificationWorkflowCompleted", + "SystemNotificationWorkflowCompletedStatus", + "SystemNotificationWorkflowPauseInfo", + "SystemNotificationWorkflowPauseInfoType", "TaskBlocker", "TaskBlockerKind", "TaskCompletionOutcome", @@ -15216,12 +15223,18 @@ def session_event_to_dict(x: SessionEvent) -> Any: "UserToolSessionApprovalExtensionEnvAccess", "UserToolSessionApprovalExtensionManagement", "UserToolSessionApprovalExtensionPermissionAccess", - "UserToolSessionApprovalFactory", "UserToolSessionApprovalMcp", "UserToolSessionApprovalMemory", "UserToolSessionApprovalRead", + "UserToolSessionApprovalWorkflow", "UserToolSessionApprovalWrite", "Verbosity", + "WorkflowPermissionOperation", + "WorkflowPermissionPhase", + "WorkflowRunSettledData", + "WorkflowRunSettledStatus", + "WorkflowRunStartedData", + "WorkflowRunUpdatedData", "WorkingDirectoryContext", "WorkingDirectoryContextHostType", "WorkspaceFileChangedOperation", diff --git a/python/e2e/test_rpc_generated_surface_e2e.py b/python/e2e/test_rpc_generated_surface_e2e.py index bc5d0ae52c..3e3f9290fd 100644 --- a/python/e2e/test_rpc_generated_surface_e2e.py +++ b/python/e2e/test_rpc_generated_surface_e2e.py @@ -58,18 +58,18 @@ "session.sandbox.getEnforcementStatus": rpc.SandboxApi.get_enforcement_status, "session.sandbox.disableForSession": rpc.SandboxApi.disable_for_session, "session.debug.collectLogs": rpc.DebugApi.collect_logs, - "session.factory.run": rpc.FactoryApi.run, - "session.factory.resume": rpc.FactoryApi.resume, - "session.factory.getRun": rpc.FactoryApi.get_run, - "session.factory.listRuns": rpc.FactoryApi.list_runs, - "session.factory.getRunDetail": rpc.FactoryApi.get_run_detail, - "session.factory.getRunProgress": rpc.FactoryApi.get_run_progress, - "session.factory.cancel": rpc.FactoryApi.cancel, - "session.factory.pause": rpc.FactoryApi.pause, - "session.factory.log": rpc.FactoryApi.log, - "session.factory.agent": rpc.FactoryApi.agent, - "session.factory.journal.get": rpc.FactoryJournalApi.get, - "session.factory.journal.put": rpc.FactoryJournalApi.put, + "session.workflow.run": rpc.WorkflowApi.run, + "session.workflow.resume": rpc.WorkflowApi.resume, + "session.workflow.getRun": rpc.WorkflowApi.get_run, + "session.workflow.listRuns": rpc.WorkflowApi.list_runs, + "session.workflow.getRunDetail": rpc.WorkflowApi.get_run_detail, + "session.workflow.getRunProgress": rpc.WorkflowApi.get_run_progress, + "session.workflow.cancel": rpc.WorkflowApi.cancel, + "session.workflow.pause": rpc.WorkflowApi.pause, + "session.workflow.log": rpc.WorkflowApi.log, + "session.workflow.agent": rpc.WorkflowApi.agent, + "session.workflow.journal.get": rpc.WorkflowJournalApi.get, + "session.workflow.journal.put": rpc.WorkflowJournalApi.put, "session.model.switchAutoTier": rpc.ModelApi.switch_auto_tier, "session.model.setAllowedModels": rpc.ModelApi.set_allowed_models, "session.workspaces.updateMetadata": rpc.WorkspacesApi.update_metadata, @@ -491,41 +491,41 @@ async def test_generated_rpc_gap_methods_round_trip_over_fake_cli( _request_for(rpc.DebugApi.collect_logs) ) - results["session.factory.run"] = await session.rpc.factory.run( - _request_for(rpc.FactoryApi.run) + results["session.workflow.run"] = await session.rpc.workflow.run( + _request_for(rpc.WorkflowApi.run) ) - results["session.factory.resume"] = await session.rpc.factory.resume( - _request_for(rpc.FactoryApi.resume) + results["session.workflow.resume"] = await session.rpc.workflow.resume( + _request_for(rpc.WorkflowApi.resume) ) - results["session.factory.getRun"] = await session.rpc.factory.get_run( - _request_for(rpc.FactoryApi.get_run) + results["session.workflow.getRun"] = await session.rpc.workflow.get_run( + _request_for(rpc.WorkflowApi.get_run) ) - results["session.factory.listRuns"] = await session.rpc.factory.list_runs( - _request_for(rpc.FactoryApi.list_runs) + results["session.workflow.listRuns"] = await session.rpc.workflow.list_runs( + _request_for(rpc.WorkflowApi.list_runs) ) - results["session.factory.getRunDetail"] = await session.rpc.factory.get_run_detail( - _request_for(rpc.FactoryApi.get_run_detail) + results["session.workflow.getRunDetail"] = await session.rpc.workflow.get_run_detail( + _request_for(rpc.WorkflowApi.get_run_detail) ) - results["session.factory.getRunProgress"] = await session.rpc.factory.get_run_progress( - _request_for(rpc.FactoryApi.get_run_progress) + results["session.workflow.getRunProgress"] = await session.rpc.workflow.get_run_progress( + _request_for(rpc.WorkflowApi.get_run_progress) ) - results["session.factory.cancel"] = await session.rpc.factory.cancel( - _request_for(rpc.FactoryApi.cancel) + results["session.workflow.cancel"] = await session.rpc.workflow.cancel( + _request_for(rpc.WorkflowApi.cancel) ) - results["session.factory.pause"] = await session.rpc.factory.pause( - _request_for(rpc.FactoryApi.pause) + results["session.workflow.pause"] = await session.rpc.workflow.pause( + _request_for(rpc.WorkflowApi.pause) ) - results["session.factory.log"] = await session.rpc.factory.log( - _request_for(rpc.FactoryApi.log) + results["session.workflow.log"] = await session.rpc.workflow.log( + _request_for(rpc.WorkflowApi.log) ) - results["session.factory.agent"] = await session.rpc.factory.agent( - _request_for(rpc.FactoryApi.agent) + results["session.workflow.agent"] = await session.rpc.workflow.agent( + _request_for(rpc.WorkflowApi.agent) ) - results["session.factory.journal.get"] = await session.rpc.factory.journal.get( - _request_for(rpc.FactoryJournalApi.get) + results["session.workflow.journal.get"] = await session.rpc.workflow.journal.get( + _request_for(rpc.WorkflowJournalApi.get) ) - results["session.factory.journal.put"] = await session.rpc.factory.journal.put( - _request_for(rpc.FactoryJournalApi.put) + results["session.workflow.journal.put"] = await session.rpc.workflow.journal.put( + _request_for(rpc.WorkflowJournalApi.put) ) results["session.model.switchAutoTier"] = await session.rpc.model.switch_auto_tier( @@ -814,10 +814,10 @@ async def test_generated_rpc_gap_methods_round_trip_over_fake_cli( assert catalog.candidates[0].installability.value assert catalog.candidates[0].provenance.authority == "sample-value" - factory_detail = results["session.factory.getRunDetail"] - assert factory_detail.consumed.active_ms == 7 - assert factory_detail.agents[0].agent_id == "sample-value" - assert factory_detail.progress.records[0].seq == 7 + workflow_detail = results["session.workflow.getRunDetail"] + assert workflow_detail.consumed.active_ms == 7 + assert workflow_detail.agents[0].agent_id == "sample-value" + assert workflow_detail.progress.records[0].seq == 7 permission_requests = results["session.permissions.pendingRequests"] assert len(permission_requests.items) == 1 diff --git a/rust/src/generated/api_types.rs b/rust/src/generated/api_types.rs index 7a4d3bde2b..ecfa797f59 100644 --- a/rust/src/generated/api_types.rs +++ b/rust/src/generated/api_types.rs @@ -249,6 +249,18 @@ pub mod rpc_methods { pub const SESSION_GITHUBAUTH_LOGOUTUSER: &str = "session.gitHubAuth.logoutUser"; /// `session.gitHubAuth.lastAuthErrors` pub const SESSION_GITHUBAUTH_LASTAUTHERRORS: &str = "session.gitHubAuth.lastAuthErrors"; + /// `session.accounts.enumerate` + pub const SESSION_ACCOUNTS_ENUMERATE: &str = "session.accounts.enumerate"; + /// `session.accounts.get` + pub const SESSION_ACCOUNTS_GET: &str = "session.accounts.get"; + /// `session.accounts.set` + pub const SESSION_ACCOUNTS_SET: &str = "session.accounts.set"; + /// `session.accounts.login.begin` + pub const SESSION_ACCOUNTS_LOGIN_BEGIN: &str = "session.accounts.login.begin"; + /// `session.accounts.login.advance` + pub const SESSION_ACCOUNTS_LOGIN_ADVANCE: &str = "session.accounts.login.advance"; + /// `session.accounts.login.cancel` + pub const SESSION_ACCOUNTS_LOGIN_CANCEL: &str = "session.accounts.login.cancel"; /// `session.debug.collectLogs` pub const SESSION_DEBUG_COLLECTLOGS: &str = "session.debug.collectLogs"; /// `session.canvas.list` @@ -265,36 +277,6 @@ pub mod rpc_methods { pub const SESSION_CANVAS_PROVIDER_REGISTER: &str = "session.canvas.provider.register"; /// `session.canvas.provider.unregister` pub const SESSION_CANVAS_PROVIDER_UNREGISTER: &str = "session.canvas.provider.unregister"; - /// `session.factory.run` - pub const SESSION_FACTORY_RUN: &str = "session.factory.run"; - /// `session.factory.resume` - pub const SESSION_FACTORY_RESUME: &str = "session.factory.resume"; - /// `session.factory.runFromTool` - pub const SESSION_FACTORY_RUNFROMTOOL: &str = "session.factory.runFromTool"; - /// `session.factory.resumeFromTool` - pub const SESSION_FACTORY_RESUMEFROMTOOL: &str = "session.factory.resumeFromTool"; - /// `session.factory.getRun` - pub const SESSION_FACTORY_GETRUN: &str = "session.factory.getRun"; - /// `session.factory.listRuns` - pub const SESSION_FACTORY_LISTRUNS: &str = "session.factory.listRuns"; - /// `session.factory.getRunDetail` - pub const SESSION_FACTORY_GETRUNDETAIL: &str = "session.factory.getRunDetail"; - /// `session.factory.getRunProgress` - pub const SESSION_FACTORY_GETRUNPROGRESS: &str = "session.factory.getRunProgress"; - /// `session.factory.cancel` - pub const SESSION_FACTORY_CANCEL: &str = "session.factory.cancel"; - /// `session.factory.pause` - pub const SESSION_FACTORY_PAUSE: &str = "session.factory.pause"; - /// `session.factory.pauseAtCheckpoint` - pub const SESSION_FACTORY_PAUSEATCHECKPOINT: &str = "session.factory.pauseAtCheckpoint"; - /// `session.factory.log` - pub const SESSION_FACTORY_LOG: &str = "session.factory.log"; - /// `session.factory.agent` - pub const SESSION_FACTORY_AGENT: &str = "session.factory.agent"; - /// `session.factory.journal.get` - pub const SESSION_FACTORY_JOURNAL_GET: &str = "session.factory.journal.get"; - /// `session.factory.journal.put` - pub const SESSION_FACTORY_JOURNAL_PUT: &str = "session.factory.journal.put"; /// `session.workflow.run` pub const SESSION_WORKFLOW_RUN: &str = "session.workflow.run"; /// `session.workflow.resume` @@ -871,10 +853,6 @@ pub mod rpc_methods { pub const SKILLPROVIDER_READ: &str = "skillProvider.read"; /// `providerToken.getToken` pub const PROVIDERTOKEN_GETTOKEN: &str = "providerToken.getToken"; - /// `factory.execute` - pub const FACTORY_EXECUTE: &str = "factory.execute"; - /// `factory.abort` - pub const FACTORY_ABORT: &str = "factory.abort"; /// `workflow.execute` pub const WORKFLOW_EXECUTE: &str = "workflow.execute"; /// `workflow.abort` @@ -1740,6 +1718,147 @@ pub struct AccountLogoutResult { pub has_more_users: bool, } +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthEnumerateQueryAccounts { + /// Account-collection query variant discriminator. + pub kind: AuthEnumerateQueryAccountsKind, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthEnumerateQueryProviders { + /// Whether an interactive Entra broker is available on the host; gates Entra availability in the returned list. + #[serde(skip_serializing_if = "Option::is_none")] + pub broker_available: Option, + /// Account-collection query variant discriminator. + pub kind: AuthEnumerateQueryProvidersKind, +} + +/// Enumerate request carrying the typed collection query. +/// +///

+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AccountsEnumerateRequest { + /// Which typed accounts collection to enumerate. + pub query: AuthEnumerateQuery, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthReadQueryActiveAccount { + /// Account read-datum query variant discriminator. + pub kind: AuthReadQueryActiveAccountKind, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthReadQueryStatus { + /// Account read-datum query variant discriminator. + pub kind: AuthReadQueryStatusKind, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthReadQueryLastErrors { + /// Account read-datum query variant discriminator. + pub kind: AuthReadQueryLastErrorsKind, +} + +/// Read request carrying the typed datum query. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AccountsGetRequest { + /// Which typed accounts datum to read. + pub query: AuthReadQuery, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthWriteSwitchActive { + /// Account mutation command variant discriminator. + pub kind: AuthWriteSwitchActiveKind, + /// Opaque selection id of the account to make active. + pub selection_id: String, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthWriteLogout { + /// Account mutation command variant discriminator. + pub kind: AuthWriteLogoutKind, + /// Opaque selection id of the account to log out; absent logs out the active account. + #[serde(skip_serializing_if = "Option::is_none")] + pub selection_id: Option, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthWriteSetCredentials { + /// Authentication host URL. + pub host: String, + /// Account mutation command variant discriminator. + pub kind: AuthWriteSetCredentialsKind, + /// Login/username for the credential. + pub login: String, + /// GitHub authentication token to install. + pub token: String, +} + +/// Mutation request carrying the typed write command. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AccountsSetRequest { + /// The non-interactive mutation command to apply. + pub command: AuthWrite, +} + +/// One signed-in account in the roster forest. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AccountStatus { + /// Whether this is the active account. + pub active: bool, + /// Opaque id of the account this one was derived from (e.g. an EMU account's base Entra identity); absent for a root account. Matches the base identity account's selectionId, forming the derivation edge. + #[serde(skip_serializing_if = "Option::is_none")] + pub derived_from: Option, + /// Authentication host URL. + pub host: String, + /// The provider kind of this account. + pub kind: AccountKind, + /// Authenticated login/username. + pub login: String, + /// Opaque selection id used to switch to, or log out, this account. + pub selection_id: String, +} + /// Canonical directory where custom agents can be discovered or created, with scope, preference, and optional project path. /// ///
@@ -2693,6 +2812,43 @@ pub struct AttachmentSelection { pub r#type: AttachmentSelectionType, } +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthEnumerateValueAccounts { + /// The signed-in account forest; empty when not logged in. + pub items: Vec, + /// Enumerated account-collection variant discriminator. + pub kind: AuthEnumerateValueAccountsKind, +} + +/// A provider offered for interactive login. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ProviderDescriptor { + /// Whether this provider is currently available to sign in with. + pub available: bool, + /// The neutral provider kind. + pub kind: LoginProviderKind, + /// Human-readable menu label, owned by the runtime so every consumer renders identical text. + pub label: String, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthEnumerateValueProviders { + /// The providers offered for interactive login. + pub items: Vec, + /// Enumerated account-collection variant discriminator. + pub kind: AuthEnumerateValueProvidersKind, +} + /// Credential-free authentication identity safe to expose to hosts and user interfaces. /// ///
@@ -2722,6 +2878,243 @@ pub struct AuthIdentity { pub r#type: AuthInfoType, } +/// Advance an in-flight login flow, optionally fulfilling an input-required step. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthLoginAdvanceRequest { + /// Opaque flow id from begin. + pub flow_id: String, + /// Neutral input fulfilling a preceding input-required step (e.g. a GHEC host); ignored otherwise. + #[serde(skip_serializing_if = "Option::is_none")] + pub input: Option, +} + +/// Begin an interactive login flow for a provider kind. Dispatch is kind-only. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthLoginBeginRequest { + /// The provider kind to sign in with. + pub kind: LoginProviderKind, +} + +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthLoginStepOpenUrl { + /// Login flow step variant discriminator. + pub kind: AuthLoginStepOpenUrlKind, + /// Authorize URL the consumer should open in a browser (consumer-driven browser-open). + pub url: String, +} + +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthLoginStepInputRequired { + /// Login flow step variant discriminator. + pub kind: AuthLoginStepInputRequiredKind, + /// Prompt for the value the provider needs; the consumer supplies it as advance input (e.g. a GitHub Enterprise Cloud host, *.ghe.com). + pub prompt: String, +} + +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthLoginStepAwaiting { + /// Login flow step variant discriminator. + pub kind: AuthLoginStepAwaitingKind, +} + +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthLoginStepNeedsInteraction { + /// Login flow step variant discriminator. + pub kind: AuthLoginStepNeedsInteractionKind, +} + +/// Terminal result of an interactive login flow. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthLoginResultDto { + /// Host that was signed in, when completed. + #[serde(skip_serializing_if = "Option::is_none")] + pub host: Option, + /// Login that was signed in, when completed. + #[serde(skip_serializing_if = "Option::is_none")] + pub login: Option, + /// Terminal disposition of the login. + pub status: AuthLoginResultStatus, +} + +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthLoginStepCompleted { + /// Login flow step variant discriminator. + pub kind: AuthLoginStepCompletedKind, + /// The terminal login result. + pub result: AuthLoginResultDto, +} + +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthLoginStepError { + /// Login flow step variant discriminator. + pub kind: AuthLoginStepErrorKind, + /// Human-readable failure message. + pub message: String, +} + +/// A started login flow: its opaque id and first step. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthLoginBegun { + /// Opaque flow id used to advance or cancel this login. + pub flow_id: String, + /// The first step of the flow. + pub step: AuthLoginStep, +} + +/// Cancel an in-flight login flow. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthLoginCancelRequest { + /// Opaque flow id from begin. + pub flow_id: String, +} + +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthReadValueActiveAccount { + /// The active account, or absent when not logged in. + #[serde(skip_serializing_if = "Option::is_none")] + pub account: Option, + /// Account read-datum variant discriminator. + pub kind: AuthReadValueActiveAccountKind, +} + +/// Neutral authentication status summary. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthStatusDto { + /// Number of signed-in accounts in the roster. + pub account_count: i64, + /// Active account host, if authenticated. + #[serde(skip_serializing_if = "Option::is_none")] + pub active_host: Option, + /// Active account login, if authenticated. + #[serde(skip_serializing_if = "Option::is_none")] + pub active_login: Option, + /// Copilot plan tier of the active account, if known. + #[serde(skip_serializing_if = "Option::is_none")] + pub copilot_plan: Option, + /// Whether the session has resolved authentication. + pub is_authenticated: bool, +} + +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthReadValueStatus { + /// Account read-datum variant discriminator. + pub kind: AuthReadValueStatusKind, + /// The neutral authentication status summary. + pub status: AuthStatusDto, +} + /// Validation error from an authentication attempt. /// ///
@@ -2740,6 +3133,40 @@ pub struct AuthValidationError { pub message: String, } +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthReadValueLastErrors { + /// Validation errors from the most recent authentication attempt. + pub errors: Vec, + /// Account read-datum variant discriminator. + pub kind: AuthReadValueLastErrorsKind, +} + +/// Result of a non-interactive accounts mutation. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthWriteResult { + /// For a logout, whether other signed-in accounts remain. + #[serde(skip_serializing_if = "Option::is_none")] + pub more_users: Option, + /// Whether the mutation was applied. + pub ok: bool, +} + /// Current per-window credit limit and consumption for an autopilot objective. /// ///
@@ -6592,946 +7019,6 @@ pub struct ExternalToolTextResultForLlmContentText { pub r#type: ExternalToolTextResultForLlmContentTextType, } -/// Parameters for cooperatively aborting a factory body. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryAbortRequest { - /// Target session identifier - pub session_id: SessionId, - /// Factory run identifier. - pub run_id: String, - /// Opaque token identifying the execution attempt to abort. - pub execution_token: String, -} - -/// Acknowledgement that a factory request was accepted. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryAckResult {} - -/// Options for one factory-scoped subagent call. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryAgentOptions { - /// Optional built-in or custom agent name whose definition configures the subagent. - #[serde(skip_serializing_if = "Option::is_none")] - pub agent: Option, - /// Optional context tier override for the subagent. - #[serde(skip_serializing_if = "Option::is_none")] - pub context_tier: Option, - /// Optional label distinguishing otherwise identical memoized agent calls. - #[serde(skip_serializing_if = "Option::is_none")] - pub label: Option, - /// Optional model identifier for the subagent. - #[serde(skip_serializing_if = "Option::is_none")] - pub model: Option, - /// Optional reasoning effort override for the subagent. - #[serde(skip_serializing_if = "Option::is_none")] - pub reasoning_effort: Option, - /// Optional JSON Schema for structured agent output. - #[serde(skip_serializing_if = "Option::is_none")] - pub schema: Option, -} - -/// Parameters for one factory-scoped subagent call. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryAgentRequest { - /// Opaque token identifying the current factory execution attempt. - pub execution_token: String, - /// Factory run identifier that owns the subagent. - pub factory_run_id: String, - /// Subagent execution options. - pub opts: FactoryAgentOptions, - /// Prompt to send to the subagent. - pub prompt: String, -} - -/// Result of one factory-scoped subagent call. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryAgentResult { - /// Agent result, omitted when the agent produced no result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, -} - -/// Prompt-safe durable identity and live status for a direct factory agent. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryAgentSummary { - /// Accumulated active agent time in milliseconds. - pub active_ms: i64, - /// Prompt-safe live activity text. - #[serde(skip_serializing_if = "Option::is_none")] - pub activity: Option, - /// Stable direct-agent identifier. - pub agent_id: String, - /// Registered agent type. - pub agent_type: String, - /// Epoch milliseconds when the agent completed. - #[serde(skip_serializing_if = "Option::is_none")] - pub completed_at: Option, - /// Friendly, non-unique name intended for display - #[serde(skip_serializing_if = "Option::is_none")] - pub display_name: Option, - /// Friendly, non-unique name intended for display - pub label: String, - /// Phase identifier active when the agent was launched, or null. - pub phase_id: Option, - /// Model requested when the agent was launched. - #[serde(skip_serializing_if = "Option::is_none")] - pub requested_model: Option, - /// Concrete model resolved for the agent. - #[serde(skip_serializing_if = "Option::is_none")] - pub resolved_model: Option, - /// Owning factory run identifier. - pub run_id: String, - /// Epoch milliseconds when the agent started. - #[serde(skip_serializing_if = "Option::is_none")] - pub started_at: Option, - /// Current durable or live agent status. - pub status: String, - /// Tool-call identifier that launched the agent. - pub tool_call_id: String, -} - -/// Parameters for cancelling a factory run. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryCancelRequest { - /// Factory run identifier. - pub run_id: String, -} - -/// Current factory phase identity. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryCurrentPhase { - /// Current phase identifier. - pub id: String, - /// Zero-based declared phase ordinal, or null for an undeclared phase. - pub ordinal: Option, -} - -/// Declared or approved factory resource ceilings. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryDeclaredLimits { - /// Maximum AI credits consumed by subagents and descendants. - #[serde(skip_serializing_if = "Option::is_none")] - pub max_ai_credits: Option, - /// Maximum concurrently active subagents. - #[serde(skip_serializing_if = "Option::is_none")] - pub max_concurrent_subagents: Option, - /// Maximum total subagents spawned by the run. - #[serde(skip_serializing_if = "Option::is_none")] - pub max_total_subagents: Option, - /// Maximum accumulated active execution time in seconds. - #[serde(skip_serializing_if = "Option::is_none")] - pub timeout_seconds: Option, -} - -/// Parameters sent to the owning extension to execute a factory closure. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryExecuteRequest { - /// Target session identifier - pub session_id: SessionId, - /// Registered factory name. - pub name: String, - /// Factory run identifier. - pub run_id: String, - /// Opaque token identifying this factory execution attempt. - pub execution_token: String, - /// Factory input value. - pub args: serde_json::Value, -} - -/// Result returned by an extension factory closure. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryExecuteResult { - /// Factory result value. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, -} - -/// Parameters for paging factory progress. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryGetRunProgressRequest { - /// Exclusive forward cursor. - #[serde(skip_serializing_if = "Option::is_none")] - pub after_seq: Option, - /// Exclusive backward cursor. - #[serde(skip_serializing_if = "Option::is_none")] - pub before_seq: Option, - /// Maximum records to return. Defaults to 200 and is capped at 500. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, - /// Optional phase identifier used to scope records and cursors. - #[serde(skip_serializing_if = "Option::is_none")] - pub phase_id: Option, - /// Factory run identifier. - pub run_id: String, -} - -/// Parameters for retrieving a factory run. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryGetRunRequest { - /// Factory run identifier. - pub run_id: String, -} - -/// Parameters for reading a factory journal entry. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryJournalGetRequest { - /// Opaque token identifying the current factory execution attempt. - pub execution_token: String, - /// Namespaced journal key. - pub key: String, - /// Factory run identifier. - pub run_id: String, -} - -/// Result of reading a factory journal entry. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryJournalGetResult { - /// Whether the journal contained the requested key. - pub hit: bool, - /// Cached JSON result. The hit field distinguishes a cached JSON null from a miss. - #[serde(skip_serializing_if = "Option::is_none")] - pub result_json: Option, -} - -/// Parameters for storing a factory journal entry. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryJournalPutRequest { - /// Opaque token identifying the current factory execution attempt. - pub execution_token: String, - /// Namespaced journal key. - pub key: String, - /// JSON result to memoize. - pub result_json: serde_json::Value, - /// Factory run identifier. - pub run_id: String, -} - -/// Parameters for paging factory runs. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryListRunsRequest { - /// Exclusive forward cursor. - #[serde(skip_serializing_if = "Option::is_none")] - pub after_seq: Option, - /// Exclusive backward cursor. - #[serde(skip_serializing_if = "Option::is_none")] - pub before_seq: Option, - /// Maximum terminal runs to return. Defaults to 200 and is capped at 500. - #[serde(skip_serializing_if = "Option::is_none")] - pub limit: Option, -} - -/// Durable factory resource consumption. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryRunConsumed { - /// Accumulated active execution time in milliseconds. - pub active_ms: i64, - /// AI usage consumed by the run in nano-AIU. - pub nano_aiu: i64, - /// Total subagents spawned by the run. - pub subagents: i64, -} - -/// Prompt-safe terminal factory outcome. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryRunTerminal { - /// Human-readable terminal error. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Machine-readable terminal failure. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure: Option, - /// Pause initiator metadata, or null when the run did not pause. - pub pause_info: Option, - /// Human-readable terminal reason. - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// Prompt-safe preview of the completed result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result_preview: Option, -} - -/// Durable factory run summary with read-time live overlays. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryRunSummary { - /// Epoch milliseconds when the current active segment started, or null while inactive. - pub active_segment_started_at: Option, - /// Approved effective resource ceilings, or null until approved. - pub approved: Option, - /// Whether the durable run state currently passes runtime resume eligibility checks. - pub can_resume: bool, - /// Epoch milliseconds when the run completed, or null while nonterminal. - pub completed_at: Option, - /// Durable resource consumption. - pub consumed: FactoryRunConsumed, - /// Epoch milliseconds when the run was created. - pub created_at: i64, - /// Current phase identity, or null before any phase is entered. - pub current_phase: Option, - /// Resource ceilings declared by the factory. - pub declared_limits: FactoryDeclaredLimits, - /// Number of phases declared by the factory. - pub declared_phase_count: i64, - /// Human-readable factory description. - pub description: String, - /// Registered factory name. - pub factory_name: String, - /// Number of direct factory agents currently live. - pub live_agent_count: i64, - /// Epoch milliseconds when this live-overlay snapshot was observed. - pub observed_at: i64, - /// Monotonic durable run revision. - pub revision: i64, - /// Factory run identifier. - pub run_id: String, - /// Epoch milliseconds when execution first started, or null before start. - pub started_at: Option, - /// Current factory run status. - pub status: FactoryRunStatus, - /// Terminal run outcome, or null while nonterminal. - pub terminal: Option, - /// Total direct factory agents spawned across all attempts. - pub total_spawned_agent_count: i64, - /// Epoch milliseconds when the durable run was last updated. - pub updated_at: i64, -} - -/// A page of factory runs in durable creation order. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryListRunsResult { - /// Whether terminal runs newer than this page exist. - #[serde(skip_serializing_if = "Option::is_none")] - pub has_more_newer: Option, - /// Newest terminal-run cursor in this page, or null when the terminal window is empty. - #[serde(skip_serializing_if = "Option::is_none")] - pub newest_seq: Option, - /// Oldest terminal-run cursor in this page, or null when the terminal window is empty. - #[serde(skip_serializing_if = "Option::is_none")] - pub oldest_seq: Option, - /// Number of terminal runs older than this page. - #[serde(skip_serializing_if = "Option::is_none")] - pub omitted_older: Option, - /// Factory run summaries in durable creation order. - pub runs: Vec, -} - -/// One ordered factory progress line. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryLogLine { - /// Progress line kind. - pub kind: FactoryLogLineKind, - /// Monotonic sequence number within the factory run. - pub seq: i64, - /// Progress text. - pub text: String, -} - -/// Parameters for recording factory progress. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryLogRequest { - /// Opaque token identifying the current factory execution attempt. - pub execution_token: String, - /// Ordered progress lines to append. - pub lines: Vec, - /// Factory run identifier. - pub run_id: String, -} - -/// Parameters for an owned durable pause checkpoint. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryPauseCheckpointRequest { - /// Opaque token identifying the execution attempt that reached the checkpoint. - pub execution_token: String, - /// Stable author-defined checkpoint key. - pub key: String, - /// Factory run identifier. - pub run_id: String, -} - -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryPauseCheckpointResult { - /// Whether this execution attempt must pause or may continue. - pub action: FactoryPauseCheckpointAction, -} - -/// Parameters for pausing a running factory. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryPauseRequest { - /// Factory run identifier. - pub run_id: String, -} - -/// Durable lifecycle and timing for one factory phase. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryPhaseObservation { - /// Completed active time accumulated by this phase in milliseconds. - pub accumulated_active_ms: i64, - /// Epoch milliseconds when this phase completed; for a skipped phase, the synthetic skip timestamp (equal to `startedAt`). - #[serde(skip_serializing_if = "Option::is_none")] - pub completed_at: Option, - /// Current live active time for this phase in milliseconds. - pub current_active_ms: i64, - /// Optional human-readable phase detail. - #[serde(skip_serializing_if = "Option::is_none")] - pub detail: Option, - /// Number of times execution entered this phase. - pub entry_count: i64, - /// Phase identifier. - pub id: String, - /// Most recent run attempt that entered this phase, or `0` if the phase has never been entered. - pub last_entered_run_attempt: i64, - /// Direct agents in this phase that are currently live. - pub live_agent_count: i64, - /// Zero-based declared phase ordinal, or null for an undeclared phase. - pub ordinal: Option, - /// Epoch milliseconds when this phase first started; for a skipped phase, the synthetic skip timestamp (equal to `completedAt`). - #[serde(skip_serializing_if = "Option::is_none")] - pub started_at: Option, - /// Derived lifecycle state of the phase. - pub status: FactoryPhaseStatus, - /// Human-readable phase title. - pub title: String, - /// Total direct agents associated with this phase. - pub total_agent_count: i64, -} - -/// One durable factory progress record. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryProgressLine { - /// Resume attempt that emitted this record. - pub attempt: i64, - /// Progress record kind. - pub kind: FactoryLogLineKind, - /// Phase active when the record was emitted, or null before any phase. - pub phase_id: Option, - /// Epoch milliseconds when the record was persisted. - pub recorded_at: i64, - /// Global monotonic sequence number within the run. - pub seq: i64, - /// Prompt-safe progress text. - pub text: String, -} - -/// A bidirectional page of factory progress. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryProgressPage { - /// Whether progress records newer than this page exist. - pub has_more_newer: bool, - /// Whether progress records older than this page exist. - pub has_more_older: bool, - /// Newest sequence number in this page, or null when empty. - pub newest_seq: Option, - /// Oldest sequence number in this page, or null when empty. - pub oldest_seq: Option, - /// Progress records in sequence order. - pub records: Vec, - /// Run revision reflected by this page. - pub revision: i64, -} - -/// Wire-only per-invocation factory resource ceiling overrides. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryRunLimits { - /// Maximum AI credits consumed by factory subagents and their descendants. The post-paid ceiling is soft: parallel turns can settle beyond it before the run stops. - #[serde(skip_serializing_if = "Option::is_none")] - pub max_ai_credits: Option, - /// Maximum number of factory subagents that may run concurrently. - #[serde(skip_serializing_if = "Option::is_none")] - pub max_concurrent_subagents: Option, - /// Maximum total number of factory subagents that may be admitted. - #[serde(skip_serializing_if = "Option::is_none")] - pub max_total_subagents: Option, - /// Maximum accumulated active-execution time in seconds. Active execution includes the entire extension body, subprocess waits, queued-agent waits, and sleeps; time between resumed attempts is not counted. - #[serde(skip_serializing_if = "Option::is_none")] - pub timeout_seconds: Option, -} - -/// Parameters for resuming a factory run from its persisted identity. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryResumeRequest { - /// Optional per-invocation resource ceiling overrides. - #[serde(skip_serializing_if = "Option::is_none")] - pub limits: Option, - /// Whether to emit factory phase names to the session transcript. - #[serde(skip_serializing_if = "Option::is_none")] - pub log_phase_names: Option, - /// Whether to notify the originating session when the factory completes. - #[serde(skip_serializing_if = "Option::is_none")] - pub notify_on_complete: Option, - /// Factory run identifier. - pub run_id: String, -} - -/// Complete current or terminal factory run envelope. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryRunResult { - /// One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. - #[serde(skip_serializing_if = "Option::is_none")] - pub attempt: Option, - /// Error message for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Machine-readable failure details for a halted or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure: Option, - /// Structured pause initiator metadata for a paused attempt. - #[serde(skip_serializing_if = "Option::is_none")] - pub pause_info: Option, - /// Reason for a halted or cancelled run. - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// Completed factory result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, - /// Factory run identifier. - pub run_id: String, - /// Partial journal and progress snapshot for a halted, cancelled, or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub snapshot: Option, - /// Current or terminal factory run status. - pub status: FactoryRunStatus, -} - -/// Resolved persisted factory identity and resumed run envelope. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryResumeResult { - /// Persisted factory name resolved for the resumed run. - pub factory_name: String, - /// Terminal resumed run envelope. - pub run: FactoryRunResult, -} - -/// Full factory run observability detail. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryRunDetail { - /// Epoch milliseconds when the current active segment started, or null while inactive. - pub active_segment_started_at: Option, - /// Durable identities and live statuses for direct factory agents. - pub agents: Vec, - /// Approved effective resource ceilings, or null until approved. - pub approved: Option, - /// Whether the durable run state currently passes runtime resume eligibility checks. - pub can_resume: bool, - /// Epoch milliseconds when the run completed, or null while nonterminal. - pub completed_at: Option, - /// Durable resource consumption. - pub consumed: FactoryRunConsumed, - /// Epoch milliseconds when the run was created. - pub created_at: i64, - /// Current phase identity, or null before any phase is entered. - pub current_phase: Option, - /// Resource ceilings declared by the factory. - pub declared_limits: FactoryDeclaredLimits, - /// Number of phases declared by the factory. - pub declared_phase_count: i64, - /// Human-readable factory description. - pub description: String, - /// Registered factory name. - pub factory_name: String, - /// Number of direct factory agents currently live. - pub live_agent_count: i64, - /// Epoch milliseconds when this live-overlay snapshot was observed. - pub observed_at: i64, - /// Lifecycle and timing observations for each factory phase. - pub phases: Vec, - /// Bidirectional page of durable factory progress. - pub progress: FactoryProgressPage, - /// Monotonic durable run revision. - pub revision: i64, - /// Factory run identifier. - pub run_id: String, - /// Epoch milliseconds when execution first started, or null before start. - pub started_at: Option, - /// Current factory run status. - pub status: FactoryRunStatus, - /// Terminal run outcome, or null while nonterminal. - pub terminal: Option, - /// Total direct factory agents spawned across all attempts. - pub total_spawned_agent_count: i64, - /// Epoch milliseconds when the durable run was last updated. - pub updated_at: i64, -} - -/// Options controlling factory invocation. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct RunOptions { - /// Per-invocation resource ceiling overrides. - #[serde(skip_serializing_if = "Option::is_none")] - pub limits: Option, - /// Whether to emit factory phase names to the session transcript. - #[serde(skip_serializing_if = "Option::is_none")] - pub log_phase_names: Option, - /// Whether to notify the originating session when the factory completes. - #[serde(skip_serializing_if = "Option::is_none")] - pub notify_on_complete: Option, - /// Run identifier whose journal and progress should seed this resumed run. - #[serde(skip_serializing_if = "Option::is_none")] - pub resume_from_run_id: Option, -} - -/// Parameters for invoking a registered factory. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryRunRequest { - /// Factory input value. - pub args: serde_json::Value, - /// Registered factory name. - pub name: String, - /// Factory invocation options. - #[serde(skip_serializing_if = "Option::is_none")] - pub options: Option, -} - -/// Internal parameters for resuming a factory run from a tool. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct FactoryToolResumeRequest { - /// Optional per-invocation resource ceiling overrides. - #[serde(skip_serializing_if = "Option::is_none")] - pub limits: Option, - /// Factory run identifier. - pub run_id: String, - /// Opaque identifier of the originating tool call. - #[serde(skip_serializing_if = "Option::is_none")] - pub tool_call_id: Option, -} - -/// Options for an internal tool-originated factory invocation. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct FactoryToolRunOptions { - /// Per-invocation resource ceiling overrides. - #[serde(skip_serializing_if = "Option::is_none")] - pub limits: Option, - /// Run identifier whose journal and progress should seed this resumed run. - #[serde(skip_serializing_if = "Option::is_none")] - pub resume_from_run_id: Option, -} - -/// Internal parameters for invoking a registered factory from a tool. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub(crate) struct FactoryToolRunRequest { - /// Factory input value. - pub args: serde_json::Value, - /// Registered factory name. - pub name: String, - /// Tool-originated factory invocation options. - #[doc(hidden)] - #[serde(skip_serializing_if = "Option::is_none")] - pub(crate) options: Option, - /// Opaque identifier of the originating tool call. - #[serde(skip_serializing_if = "Option::is_none")] - pub tool_call_id: Option, -} - /// Parameters for starting fleet orchestration: an optional user prompt combined with the fleet instructions, plus the send options forwarded to the resulting turn. /// ///
@@ -12291,6 +11778,12 @@ pub struct ModelApplyStartupOverlayRequest { /// Model required by device-managed policy, when configured. #[serde(skip_serializing_if = "Option::is_none")] pub device_managed_model: Option, + /// Context tier paired with the effective organization-managed model. Applies only when that concrete managed model is selected; it is ignored for Auto and for CLI, resume, or user overrides. + #[serde(skip_serializing_if = "Option::is_none")] + pub managed_context_tier: Option, + /// Reasoning effort paired with the effective organization-managed model. Applies only when that concrete managed model is selected; it is ignored for Auto and for CLI, resume, or user overrides. + #[serde(skip_serializing_if = "Option::is_none")] + pub managed_reasoning_effort: Option, /// Startup default model from the enterprise policy helper, when configured. Weakest of the managed sources: it applies only when neither device nor server policy names a model, and an explicit user selection still wins. #[serde(skip_serializing_if = "Option::is_none")] pub policy_helper_model: Option, @@ -13199,7 +12692,7 @@ pub struct PermissionDecisionApproveForSessionApprovalExtensionManagement { pub operation: Option, } -/// Session-scoped factory approval, optionally narrowed by approval key. +/// Session-scoped workflow approval, optionally narrowed by approval key. /// ///
/// @@ -13209,12 +12702,12 @@ pub struct PermissionDecisionApproveForSessionApprovalExtensionManagement { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PermissionDecisionApproveForSessionApprovalFactory { - /// Optional factory operation name or canonical approval key; when omitted, the approval covers all factory operations. +pub struct PermissionDecisionApproveForSessionApprovalWorkflow { + /// Optional workflow operation name or canonical approval key; when omitted, the approval covers all workflow operations. #[serde(skip_serializing_if = "Option::is_none")] pub approval_key: Option, - /// Approval covering factory operations. - pub kind: PermissionDecisionApproveForSessionApprovalFactoryKind, + /// Approval covering workflow operations. + pub kind: PermissionDecisionApproveForSessionApprovalWorkflowKind, } /// Session-scoped approval details for an extension's permission-gated capability access, keyed by extension name. @@ -13407,7 +12900,7 @@ pub struct PermissionDecisionApproveForLocationApprovalExtensionManagement { pub operation: Option, } -/// Location-scoped factory approval, optionally narrowed by approval key. +/// Location-scoped workflow approval, optionally narrowed by approval key. /// ///
/// @@ -13417,12 +12910,12 @@ pub struct PermissionDecisionApproveForLocationApprovalExtensionManagement { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PermissionDecisionApproveForLocationApprovalFactory { - /// Optional factory operation name or canonical approval key; when omitted, the approval covers all factory operations. +pub struct PermissionDecisionApproveForLocationApprovalWorkflow { + /// Optional workflow operation name or canonical approval key; when omitted, the approval covers all workflow operations. #[serde(skip_serializing_if = "Option::is_none")] pub approval_key: Option, - /// Approval covering factory operations. - pub kind: PermissionDecisionApproveForLocationApprovalFactoryKind, + /// Approval covering workflow operations. + pub kind: PermissionDecisionApproveForLocationApprovalWorkflowKind, } /// Location-scoped approval details for an extension's permission-gated capability access, keyed by extension name. @@ -13867,7 +13360,7 @@ pub struct PermissionsLocationsAddToolApprovalDetailsExtensionManagement { pub operation: Option, } -/// Location-persisted factory approval, optionally narrowed by approval key. +/// Location-persisted workflow approval, optionally narrowed by approval key. /// ///
/// @@ -13877,12 +13370,12 @@ pub struct PermissionsLocationsAddToolApprovalDetailsExtensionManagement { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PermissionsLocationsAddToolApprovalDetailsFactory { - /// Optional factory operation name or canonical approval key; when omitted, the approval covers all factory operations. +pub struct PermissionsLocationsAddToolApprovalDetailsWorkflow { + /// Optional workflow operation name or canonical approval key; when omitted, the approval covers all workflow operations. #[serde(skip_serializing_if = "Option::is_none")] pub approval_key: Option, - /// Approval covering factory operations. - pub kind: PermissionsLocationsAddToolApprovalDetailsFactoryKind, + /// Approval covering workflow operations. + pub kind: PermissionsLocationsAddToolApprovalDetailsWorkflowKind, } /// Location-persisted tool approval details for an extension's permission-gated capability access, keyed by extension name. @@ -21687,6 +21180,9 @@ pub struct SlashCommandShowDialogResult { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SlashCommandSetModelResult { + /// Auto routing profile selected by the command, when the model is Auto. + #[serde(skip_serializing_if = "Option::is_none")] + pub auto_tier: Option, /// Discriminator for a set-model result. pub kind: SlashCommandSetModelResultKind, /// Model selected by the command. @@ -26396,6 +25892,41 @@ pub struct SessionGitHubAuthLastAuthErrorsParams { pub session_id: SessionId, } +/// Result of a non-interactive accounts mutation. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionAccountsSetResult { + /// For a logout, whether other signed-in accounts remain. + #[serde(skip_serializing_if = "Option::is_none")] + pub more_users: Option, + /// Whether the mutation was applied. + pub ok: bool, +} + +/// A started login flow: its opaque id and first step. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SessionAccountsLoginBeginResult { + /// Opaque flow id used to advance or cancel this login. + pub flow_id: String, + /// The first step of the flow. + pub step: AuthLoginStep, +} + /// Result of collecting a session debug bundle. /// ///
@@ -26531,413 +26062,6 @@ pub struct SessionCanvasActionInvokeResult { pub result: Option, } -/// Complete current or terminal factory run envelope. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryRunResult { - /// One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. - #[serde(skip_serializing_if = "Option::is_none")] - pub attempt: Option, - /// Error message for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Machine-readable failure details for a halted or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure: Option, - /// Structured pause initiator metadata for a paused attempt. - #[serde(skip_serializing_if = "Option::is_none")] - pub pause_info: Option, - /// Reason for a halted or cancelled run. - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// Completed factory result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, - /// Factory run identifier. - pub run_id: String, - /// Partial journal and progress snapshot for a halted, cancelled, or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub snapshot: Option, - /// Current or terminal factory run status. - pub status: FactoryRunStatus, -} - -/// Resolved persisted factory identity and resumed run envelope. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryResumeResult { - /// Persisted factory name resolved for the resumed run. - pub factory_name: String, - /// Terminal resumed run envelope. - pub run: FactoryRunResult, -} - -/// Complete current or terminal factory run envelope. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryRunFromToolResult { - /// One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. - #[serde(skip_serializing_if = "Option::is_none")] - pub attempt: Option, - /// Error message for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Machine-readable failure details for a halted or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure: Option, - /// Structured pause initiator metadata for a paused attempt. - #[serde(skip_serializing_if = "Option::is_none")] - pub pause_info: Option, - /// Reason for a halted or cancelled run. - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// Completed factory result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, - /// Factory run identifier. - pub run_id: String, - /// Partial journal and progress snapshot for a halted, cancelled, or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub snapshot: Option, - /// Current or terminal factory run status. - pub status: FactoryRunStatus, -} - -/// Resolved persisted factory identity and resumed run envelope. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryResumeFromToolResult { - /// Persisted factory name resolved for the resumed run. - pub factory_name: String, - /// Terminal resumed run envelope. - pub run: FactoryRunResult, -} - -/// Complete current or terminal factory run envelope. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryGetRunResult { - /// One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. - #[serde(skip_serializing_if = "Option::is_none")] - pub attempt: Option, - /// Error message for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Machine-readable failure details for a halted or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure: Option, - /// Structured pause initiator metadata for a paused attempt. - #[serde(skip_serializing_if = "Option::is_none")] - pub pause_info: Option, - /// Reason for a halted or cancelled run. - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// Completed factory result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, - /// Factory run identifier. - pub run_id: String, - /// Partial journal and progress snapshot for a halted, cancelled, or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub snapshot: Option, - /// Current or terminal factory run status. - pub status: FactoryRunStatus, -} - -/// A page of factory runs in durable creation order. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryListRunsResult { - /// Whether terminal runs newer than this page exist. - #[serde(skip_serializing_if = "Option::is_none")] - pub has_more_newer: Option, - /// Newest terminal-run cursor in this page, or null when the terminal window is empty. - #[serde(skip_serializing_if = "Option::is_none")] - pub newest_seq: Option, - /// Oldest terminal-run cursor in this page, or null when the terminal window is empty. - #[serde(skip_serializing_if = "Option::is_none")] - pub oldest_seq: Option, - /// Number of terminal runs older than this page. - #[serde(skip_serializing_if = "Option::is_none")] - pub omitted_older: Option, - /// Factory run summaries in durable creation order. - pub runs: Vec, -} - -/// Full factory run observability detail. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryGetRunDetailResult { - /// Epoch milliseconds when the current active segment started, or null while inactive. - pub active_segment_started_at: Option, - /// Durable identities and live statuses for direct factory agents. - pub agents: Vec, - /// Approved effective resource ceilings, or null until approved. - pub approved: Option, - /// Whether the durable run state currently passes runtime resume eligibility checks. - pub can_resume: bool, - /// Epoch milliseconds when the run completed, or null while nonterminal. - pub completed_at: Option, - /// Durable resource consumption. - pub consumed: FactoryRunConsumed, - /// Epoch milliseconds when the run was created. - pub created_at: i64, - /// Current phase identity, or null before any phase is entered. - pub current_phase: Option, - /// Resource ceilings declared by the factory. - pub declared_limits: FactoryDeclaredLimits, - /// Number of phases declared by the factory. - pub declared_phase_count: i64, - /// Human-readable factory description. - pub description: String, - /// Registered factory name. - pub factory_name: String, - /// Number of direct factory agents currently live. - pub live_agent_count: i64, - /// Epoch milliseconds when this live-overlay snapshot was observed. - pub observed_at: i64, - /// Lifecycle and timing observations for each factory phase. - pub phases: Vec, - /// Bidirectional page of durable factory progress. - pub progress: FactoryProgressPage, - /// Monotonic durable run revision. - pub revision: i64, - /// Factory run identifier. - pub run_id: String, - /// Epoch milliseconds when execution first started, or null before start. - pub started_at: Option, - /// Current factory run status. - pub status: FactoryRunStatus, - /// Terminal run outcome, or null while nonterminal. - pub terminal: Option, - /// Total direct factory agents spawned across all attempts. - pub total_spawned_agent_count: i64, - /// Epoch milliseconds when the durable run was last updated. - pub updated_at: i64, -} - -/// A bidirectional page of factory progress. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryGetRunProgressResult { - /// Whether progress records newer than this page exist. - pub has_more_newer: bool, - /// Whether progress records older than this page exist. - pub has_more_older: bool, - /// Newest sequence number in this page, or null when empty. - pub newest_seq: Option, - /// Oldest sequence number in this page, or null when empty. - pub oldest_seq: Option, - /// Progress records in sequence order. - pub records: Vec, - /// Run revision reflected by this page. - pub revision: i64, -} - -/// Complete current or terminal factory run envelope. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryCancelResult { - /// One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. - #[serde(skip_serializing_if = "Option::is_none")] - pub attempt: Option, - /// Error message for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Machine-readable failure details for a halted or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure: Option, - /// Structured pause initiator metadata for a paused attempt. - #[serde(skip_serializing_if = "Option::is_none")] - pub pause_info: Option, - /// Reason for a halted or cancelled run. - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// Completed factory result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, - /// Factory run identifier. - pub run_id: String, - /// Partial journal and progress snapshot for a halted, cancelled, or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub snapshot: Option, - /// Current or terminal factory run status. - pub status: FactoryRunStatus, -} - -/// Complete current or terminal factory run envelope. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryPauseResult { - /// One-based execution attempt represented by this envelope. Absent before the first attempt starts or when returned by an older runtime. - #[serde(skip_serializing_if = "Option::is_none")] - pub attempt: Option, - /// Error message for an errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub error: Option, - /// Machine-readable failure details for a halted or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub failure: Option, - /// Structured pause initiator metadata for a paused attempt. - #[serde(skip_serializing_if = "Option::is_none")] - pub pause_info: Option, - /// Reason for a halted or cancelled run. - #[serde(skip_serializing_if = "Option::is_none")] - pub reason: Option, - /// Completed factory result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, - /// Factory run identifier. - pub run_id: String, - /// Partial journal and progress snapshot for a halted, cancelled, or errored run. - #[serde(skip_serializing_if = "Option::is_none")] - pub snapshot: Option, - /// Current or terminal factory run status. - pub status: FactoryRunStatus, -} - -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryPauseAtCheckpointResult { - /// Whether this execution attempt must pause or may continue. - pub action: FactoryPauseCheckpointAction, -} - -/// Acknowledgement that a factory request was accepted. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryLogResult {} - -/// Result of one factory-scoped subagent call. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryAgentResult { - /// Agent result, omitted when the agent produced no result. - #[serde(skip_serializing_if = "Option::is_none")] - pub result: Option, -} - -/// Result of reading a factory journal entry. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryJournalGetResult { - /// Whether the journal contained the requested key. - pub hit: bool, - /// Cached JSON result. The hit field distinguishes a cached JSON null from a miss. - #[serde(skip_serializing_if = "Option::is_none")] - pub result_json: Option, -} - -/// Acknowledgement that a factory request was accepted. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct SessionFactoryJournalPutResult {} - /// Complete current or terminal workflow run envelope. /// ///
@@ -32467,18 +31591,6 @@ pub struct ProviderTokenGetTokenResult { pub token: String, } -/// Acknowledgement that a factory request was accepted. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FactoryAbortResult {} - /// Acknowledgement that a workflow request was accepted. /// ///
@@ -32854,6 +31966,148 @@ pub enum AuthInfo { ApiKey(ApiKeyAuthInfo), } +/// The provider kind stamped on a signed-in account. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AccountKind { + /// An OAuth github.com account. + #[serde(rename = "githubDotCom")] + GitHubDotCom, + /// A GitHub Enterprise Cloud account — a GitHub account on a non-github.com host, e.g. *.ghe.com. + #[serde(rename = "proxima")] + Proxima, + /// A GitHub (EMU) account derived from a base Entra identity. + #[serde(rename = "entraEmu")] + EntraEmu, + /// A base Microsoft Entra identity. + #[serde(rename = "entra")] + Entra, + /// A Microsoft 365 Copilot (Loki) inference account derived from the same base Entra identity as an EMU account; its bearer is a Loki-scoped inference token consumed through the model-provider path, not the GitHub switcher. + #[serde(rename = "loki")] + Loki, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Account-collection query variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthEnumerateQueryAccountsKind { + #[serde(rename = "accounts")] + #[default] + Accounts, +} + +/// Account-collection query variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthEnumerateQueryProvidersKind { + #[serde(rename = "providers")] + #[default] + Providers, +} + +/// Selects which accounts collection to enumerate. A no-arg selector is the empty-payload variant. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AuthEnumerateQuery { + Accounts(AuthEnumerateQueryAccounts), + Providers(AuthEnumerateQueryProviders), +} + +/// Account read-datum query variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthReadQueryActiveAccountKind { + #[serde(rename = "activeAccount")] + #[default] + ActiveAccount, +} + +/// Account read-datum query variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthReadQueryStatusKind { + #[serde(rename = "status")] + #[default] + Status, +} + +/// Account read-datum query variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthReadQueryLastErrorsKind { + #[serde(rename = "lastErrors")] + #[default] + LastErrors, +} + +/// Selects which typed accounts datum to read. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AuthReadQuery { + ActiveAccount(AuthReadQueryActiveAccount), + Status(AuthReadQueryStatus), + LastErrors(AuthReadQueryLastErrors), +} + +/// Account mutation command variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthWriteSwitchActiveKind { + #[serde(rename = "switchActive")] + #[default] + SwitchActive, +} + +/// Account mutation command variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthWriteLogoutKind { + #[serde(rename = "logout")] + #[default] + Logout, +} + +/// Account mutation command variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthWriteSetCredentialsKind { + #[serde(rename = "setCredentials")] + #[default] + SetCredentials, +} + +/// One non-interactive accounts mutation command (the selector is fused with its typed args). +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AuthWrite { + SwitchActive(AuthWriteSwitchActive), + Logout(AuthWriteLogout), + SetCredentials(AuthWriteSetCredentials), +} + /// Resolved Anthropic adaptive-thinking capability for a model. /// ///
@@ -33339,6 +32593,62 @@ pub enum AttachmentSelectionType { Selection, } +/// Enumerated account-collection variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthEnumerateValueAccountsKind { + #[serde(rename = "accounts")] + #[default] + Accounts, +} + +/// A provider a consumer may interactively sign in with. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum LoginProviderKind { + /// OAuth github.com sign-in via the browser (web loopback + PKCE). + #[serde(rename = "githubDotCom")] + GitHubDotCom, + /// A GitHub Enterprise Cloud account — a GitHub account on a non-github.com host, e.g. *.ghe.com; the host is supplied interactively through the neutral input-required step. + #[serde(rename = "proxima")] + Proxima, + /// Microsoft Entra sign-in that derives a GitHub (EMU) credential. + #[serde(rename = "entra")] + Entra, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Enumerated account-collection variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthEnumerateValueProvidersKind { + #[serde(rename = "providers")] + #[default] + Providers, +} + +/// The enumerated collection, keyed by the same selector as the query. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AuthEnumerateValue { + Accounts(AuthEnumerateValueAccounts), + Providers(AuthEnumerateValueProviders), +} + /// Authentication type /// ///
@@ -33379,6 +32689,138 @@ pub enum AuthInfoType { Unknown, } +/// Login flow step variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthLoginStepOpenUrlKind { + #[serde(rename = "open-url")] + #[default] + OpenUrl, +} + +/// Login flow step variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthLoginStepInputRequiredKind { + #[serde(rename = "input-required")] + #[default] + InputRequired, +} + +/// Login flow step variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthLoginStepAwaitingKind { + #[serde(rename = "awaiting")] + #[default] + Awaiting, +} + +/// Login flow step variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthLoginStepNeedsInteractionKind { + #[serde(rename = "needs-interaction")] + #[default] + NeedsInteraction, +} + +/// Login flow step variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthLoginStepCompletedKind { + #[serde(rename = "completed")] + #[default] + Completed, +} + +/// Terminal disposition of a login persistence attempt. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthLoginResultStatus { + /// The credential was persisted and the account is signed in. + #[serde(rename = "completed")] + Completed, + /// Persistence needs explicit consent to store the token in plaintext. + #[serde(rename = "needs-plaintext-consent")] + NeedsPlaintextConsent, + /// The user declined plaintext persistence. + #[serde(rename = "declined")] + Declined, + /// Unknown variant for forward compatibility. + #[default] + #[serde(other)] + Unknown, +} + +/// Login flow step variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthLoginStepErrorKind { + #[serde(rename = "error")] + #[default] + Error, +} + +/// One step in an interactive login flow. The consumer acts on the step and calls advance to proceed. Browser-open is encoded as two distinct steps by design: `open-url` is CONSUMER-driven (the provider surfaces the authorize URL and the consumer opens it — github.com/GHEC web), while `needs-interaction` is PROVIDER-driven (the provider opens the browser or broker UI itself and does not surface a URL — Entra). +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AuthLoginStep { + OpenUrl(AuthLoginStepOpenUrl), + InputRequired(AuthLoginStepInputRequired), + Awaiting(AuthLoginStepAwaiting), + NeedsInteraction(AuthLoginStepNeedsInteraction), + Completed(AuthLoginStepCompleted), + Error(AuthLoginStepError), +} + +/// Account read-datum variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthReadValueActiveAccountKind { + #[serde(rename = "activeAccount")] + #[default] + ActiveAccount, +} + +/// Account read-datum variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthReadValueStatusKind { + #[serde(rename = "status")] + #[default] + Status, +} + +/// Account read-datum variant discriminator. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthReadValueLastErrorsKind { + #[serde(rename = "lastErrors")] + #[default] + LastErrors, +} + +/// The read result, keyed by the same selector as the query. +/// +///
+/// +/// **Experimental.** This type is part of an experimental wire-protocol surface +/// and may change or be removed in future SDK or CLI releases. +/// +///
+#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(untagged)] +pub enum AuthReadValue { + ActiveAccount(AuthReadValueActiveAccount), + Status(AuthReadValueStatus), + LastErrors(AuthReadValueLastErrors), +} + /// Current normalized autopilot objective lifecycle status. /// ///
@@ -35723,189 +35165,6 @@ pub enum ExternalToolTextResultForLlmContentTextType { Text, } -/// Execution-critical factory storage operation. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum FactoryDurableOperation { - /// Creating the durable run and declared phases. - #[serde(rename = "createRun")] - CreateRun, - /// Persisting the transition to running. - #[serde(rename = "markRunStarted")] - MarkRunStarted, - /// Persisting the terminal run envelope. - #[serde(rename = "finishRun")] - FinishRun, - /// Persisting subagent admission accounting. - #[serde(rename = "reserveAgent")] - ReserveAgent, - /// Rolling back an uncommitted subagent admission. - #[serde(rename = "releaseAgent")] - ReleaseAgent, - /// Persisting an idempotent model-usage charge. - #[serde(rename = "chargeCredit")] - ChargeCredit, - /// Persisting active execution time. - #[serde(rename = "addElapsed")] - AddElapsed, - /// Reading the authoritative AI-credit total. - #[serde(rename = "reconcileCreditTotal")] - ReconcileCreditTotal, - /// Reading a journal entry without treating storage failure as a cache miss. - #[serde(rename = "journalGet")] - JournalGet, - /// Persisting a journal entry before reporting success. - #[serde(rename = "journalPut")] - JournalPut, - /// Renewing the durable owner lease that proves this process still owns the run. - #[serde(rename = "refreshLease")] - RefreshLease, - /// Unknown variant for forward compatibility. - #[default] - #[serde(other)] - Unknown, -} - -/// Current or terminal state of a factory run. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum FactoryRunStatus { - /// The run was minted and is awaiting approval. - #[serde(rename = "pending")] - Pending, - /// The run is executing. - #[serde(rename = "running")] - Running, - /// The run completed successfully. - #[serde(rename = "completed")] - Completed, - /// The run was interrupted while resource budget remained. - #[serde(rename = "halted")] - Halted, - /// The current attempt stopped intentionally and the run may be resumed. - #[serde(rename = "paused")] - Paused, - /// The run was cancelled before completion. - #[serde(rename = "cancelled")] - Cancelled, - /// The factory body failed or reached a cumulative resource ceiling. - #[serde(rename = "error")] - Error, - /// Unknown variant for forward compatibility. - #[default] - #[serde(other)] - Unknown, -} - -/// Kind of factory progress line. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum FactoryLogLineKind { - /// A narrator log line. - #[serde(rename = "log")] - Log, - /// A named factory phase marker. - #[serde(rename = "phase")] - Phase, - /// Unknown variant for forward compatibility. - #[default] - #[serde(other)] - Unknown, -} - -/// Action the runtime selected for a durable factory pause checkpoint. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum FactoryPauseCheckpointAction { - /// The checkpoint was committed by a prior paused attempt, so execution may continue. - #[serde(rename = "continue")] - Continue, - /// This attempt claimed the checkpoint and must cooperatively stop. - #[serde(rename = "pause")] - Pause, - /// Unknown variant for forward compatibility. - #[default] - #[serde(other)] - Unknown, -} - -/// Derived lifecycle state of a factory phase. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum FactoryPhaseStatus { - /// The phase has not been entered yet. - #[serde(rename = "pending")] - Pending, - /// The phase is currently entered and accumulating active time. - #[serde(rename = "active")] - Active, - /// The phase was entered and has since been closed. - #[serde(rename = "completed")] - Completed, - /// The phase was never entered because a later phase was entered or the run reached a terminal state. - #[serde(rename = "skipped")] - Skipped, - /// Unknown variant for forward compatibility. - #[default] - #[serde(other)] - Unknown, -} - -/// Cumulative resource ceiling that stopped a factory run. -/// -///
-/// -/// **Experimental.** This type is part of an experimental wire-protocol surface -/// and may change or be removed in future SDK or CLI releases. -/// -///
-#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum FactoryRunFailureKind { - /// The run admitted the approved maximum total number of subagents. - #[serde(rename = "maxTotalSubagents")] - MaxTotalSubagents, - /// The run reached the approved accumulated active-execution time in seconds. - #[serde(rename = "timeoutSeconds")] - TimeoutSeconds, - /// The run's settled subagent model usage exceeded the approved AI-credit ceiling, or no headroom remained for another subagent. - #[serde(rename = "maxAiCredits")] - MaxAiCredits, - /// Unknown variant for forward compatibility. - #[default] - #[serde(other)] - Unknown, -} - /// Why the runtime is requesting a GitHub credential. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum GitHubTokenAcquireReason { @@ -37701,12 +36960,12 @@ pub enum PermissionDecisionApproveForSessionApprovalExtensionManagementKind { ExtensionManagement, } -/// Approval covering factory operations. +/// Approval covering workflow operations. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum PermissionDecisionApproveForSessionApprovalFactoryKind { - #[serde(rename = "factory")] +pub enum PermissionDecisionApproveForSessionApprovalWorkflowKind { + #[serde(rename = "workflow")] #[default] - Factory, + Workflow, } /// Approval covering an extension's request to access a permission-gated capability. @@ -37744,7 +37003,7 @@ pub enum PermissionDecisionApproveForSessionApproval { Memory(PermissionDecisionApproveForSessionApprovalMemory), CustomTool(PermissionDecisionApproveForSessionApprovalCustomTool), ExtensionManagement(PermissionDecisionApproveForSessionApprovalExtensionManagement), - Factory(PermissionDecisionApproveForSessionApprovalFactory), + Workflow(PermissionDecisionApproveForSessionApprovalWorkflow), ExtensionPermissionAccess(PermissionDecisionApproveForSessionApprovalExtensionPermissionAccess), ExtensionEnvAccess(PermissionDecisionApproveForSessionApprovalExtensionEnvAccess), } @@ -37821,12 +37080,12 @@ pub enum PermissionDecisionApproveForLocationApprovalExtensionManagementKind { ExtensionManagement, } -/// Approval covering factory operations. +/// Approval covering workflow operations. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum PermissionDecisionApproveForLocationApprovalFactoryKind { - #[serde(rename = "factory")] +pub enum PermissionDecisionApproveForLocationApprovalWorkflowKind { + #[serde(rename = "workflow")] #[default] - Factory, + Workflow, } /// Approval covering an extension's request to access a permission-gated capability. @@ -37864,7 +37123,7 @@ pub enum PermissionDecisionApproveForLocationApproval { Memory(PermissionDecisionApproveForLocationApprovalMemory), CustomTool(PermissionDecisionApproveForLocationApprovalCustomTool), ExtensionManagement(PermissionDecisionApproveForLocationApprovalExtensionManagement), - Factory(PermissionDecisionApproveForLocationApprovalFactory), + Workflow(PermissionDecisionApproveForLocationApprovalWorkflow), ExtensionPermissionAccess( PermissionDecisionApproveForLocationApprovalExtensionPermissionAccess, ), @@ -38150,12 +37409,12 @@ pub enum PermissionsLocationsAddToolApprovalDetailsExtensionManagementKind { ExtensionManagement, } -/// Approval covering factory operations. +/// Approval covering workflow operations. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum PermissionsLocationsAddToolApprovalDetailsFactoryKind { - #[serde(rename = "factory")] +pub enum PermissionsLocationsAddToolApprovalDetailsWorkflowKind { + #[serde(rename = "workflow")] #[default] - Factory, + Workflow, } /// Approval covering an extension's request to access a permission-gated capability. @@ -38193,7 +37452,7 @@ pub enum PermissionsLocationsAddToolApprovalDetails { Memory(PermissionsLocationsAddToolApprovalDetailsMemory), CustomTool(PermissionsLocationsAddToolApprovalDetailsCustomTool), ExtensionManagement(PermissionsLocationsAddToolApprovalDetailsExtensionManagement), - Factory(PermissionsLocationsAddToolApprovalDetailsFactory), + Workflow(PermissionsLocationsAddToolApprovalDetailsWorkflow), ExtensionPermissionAccess(PermissionsLocationsAddToolApprovalDetailsExtensionPermissionAccess), ExtensionEnvAccess(PermissionsLocationsAddToolApprovalDetailsExtensionEnvAccess), } @@ -38242,7 +37501,7 @@ pub enum PermissionModeSource { /// The mode was set at startup by the `defaultPermissionMode` user setting. #[serde(rename = "user_setting")] UserSetting, - /// The mode was set at startup by authenticated organization targeting. + /// Historical compatibility value for runtimes that selected Assisted mode through organization targeting. Current runtimes do not produce this source. #[serde(rename = "organization_targeting")] OrganizationTargeting, /// The mode was set through an RPC caller. diff --git a/rust/src/generated/rpc.rs b/rust/src/generated/rpc.rs index 5f9e03c499..df0de533ed 100644 --- a/rust/src/generated/rpc.rs +++ b/rust/src/generated/rpc.rs @@ -3160,6 +3160,13 @@ pub struct SessionRpc<'a> { } impl<'a> SessionRpc<'a> { + /// `session.accounts.*` sub-namespace. + pub fn accounts(&self) -> SessionRpcAccounts<'a> { + SessionRpcAccounts { + session: self.session, + } + } + /// `session.agent.*` sub-namespace. pub fn agent(&self) -> SessionRpcAgent<'a> { SessionRpcAgent { @@ -3244,13 +3251,6 @@ impl<'a> SessionRpc<'a> { } } - /// `session.factory.*` sub-namespace. - pub fn factory(&self) -> SessionRpcFactory<'a> { - SessionRpcFactory { - session: self.session, - } - } - /// `session.fleet.*` sub-namespace. pub fn fleet(&self) -> SessionRpcFleet<'a> { SessionRpcFleet { @@ -3741,6 +3741,214 @@ impl<'a> SessionRpc<'a> { } } +/// `session.accounts.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcAccounts<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcAccounts<'a> { + /// `session.accounts.login.*` sub-namespace. + pub fn login(&self) -> SessionRpcAccountsLogin<'a> { + SessionRpcAccountsLogin { + session: self.session, + } + } + + /// Enumerate a typed accounts collection: the signed-in accounts, or the providers offered for interactive login. + /// + /// Wire method: `session.accounts.enumerate`. + /// + /// # Parameters + /// + /// * `params` - Enumerate request carrying the typed collection query. + /// + /// # Returns + /// + /// The enumerated collection, keyed by the same selector as the query. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn enumerate( + &self, + params: AccountsEnumerateRequest, + ) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_ACCOUNTS_ENUMERATE, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Read one typed accounts datum: the active account, a neutral status summary, or the last authentication errors. + /// + /// Wire method: `session.accounts.get`. + /// + /// # Parameters + /// + /// * `params` - Read request carrying the typed datum query. + /// + /// # Returns + /// + /// The read result, keyed by the same selector as the query. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn get(&self, params: AccountsGetRequest) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_ACCOUNTS_GET, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Apply one non-interactive accounts mutation: switch the active account, log an account out, or set credentials from a token. + /// + /// Wire method: `session.accounts.set`. + /// + /// # Parameters + /// + /// * `params` - Mutation request carrying the typed write command. + /// + /// # Returns + /// + /// Result of a non-interactive accounts mutation. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn set(&self, params: AccountsSetRequest) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_ACCOUNTS_SET, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } +} + +/// `session.accounts.login.*` RPCs. +#[derive(Clone, Copy)] +pub struct SessionRpcAccountsLogin<'a> { + pub(crate) session: &'a Session, +} + +impl<'a> SessionRpcAccountsLogin<'a> { + /// Begin an interactive login flow for a provider kind (dispatch is kind-only) and return its opaque flow id and first step. + /// + /// Wire method: `session.accounts.login.begin`. + /// + /// # Parameters + /// + /// * `params` - Begin an interactive login flow for a provider kind. Dispatch is kind-only. + /// + /// # Returns + /// + /// A started login flow: its opaque id and first step. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn begin(&self, params: AuthLoginBeginRequest) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call(rpc_methods::SESSION_ACCOUNTS_LOGIN_BEGIN, Some(wire_params)) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Advance an in-flight login flow, optionally fulfilling an input-required step, and return the next step. + /// + /// Wire method: `session.accounts.login.advance`. + /// + /// # Parameters + /// + /// * `params` - Advance an in-flight login flow, optionally fulfilling an input-required step. + /// + /// # Returns + /// + /// One step in an interactive login flow. The consumer acts on the step and calls advance to proceed. Browser-open is encoded as two distinct steps by design: `open-url` is CONSUMER-driven (the provider surfaces the authorize URL and the consumer opens it — github.com/GHEC web), while `needs-interaction` is PROVIDER-driven (the provider opens the browser or broker UI itself and does not surface a URL — Entra). + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn advance(&self, params: AuthLoginAdvanceRequest) -> Result { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_ACCOUNTS_LOGIN_ADVANCE, + Some(wire_params), + ) + .await?; + Ok(serde_json::from_value(_value)?) + } + + /// Cancel an in-flight login flow and release its resources. + /// + /// Wire method: `session.accounts.login.cancel`. + /// + /// # Parameters + /// + /// * `params` - Cancel an in-flight login flow. + /// + ///
+ /// + /// **Experimental.** This API is part of an experimental wire-protocol surface + /// and may change or be removed in future SDK or CLI releases. Pin both the + /// SDK and CLI versions if your code depends on it. + /// + ///
+ pub async fn cancel(&self, params: AuthLoginCancelRequest) -> Result<(), Error> { + let mut wire_params = serde_json::to_value(params)?; + wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); + let _value = self + .session + .client() + .call( + rpc_methods::SESSION_ACCOUNTS_LOGIN_CANCEL, + Some(wire_params), + ) + .await?; + Ok(()) + } +} + /// `session.agent.*` RPCs. #[derive(Clone, Copy)] pub struct SessionRpcAgent<'a> { @@ -5385,505 +5593,6 @@ impl<'a> SessionRpcExtensions<'a> { } } -/// `session.factory.*` RPCs. -#[derive(Clone, Copy)] -pub struct SessionRpcFactory<'a> { - pub(crate) session: &'a Session, -} - -impl<'a> SessionRpcFactory<'a> { - /// `session.factory.journal.*` sub-namespace. - pub fn journal(&self) -> SessionRpcFactoryJournal<'a> { - SessionRpcFactoryJournal { - session: self.session, - } - } - - /// Runs a registered factory by name at the top level. - /// - /// Wire method: `session.factory.run`. - /// - /// # Parameters - /// - /// * `params` - Parameters for invoking a registered factory. - /// - /// # Returns - /// - /// Complete current or terminal factory run envelope. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn run(&self, params: FactoryRunRequest) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_FACTORY_RUN, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Resumes a factory run using its persisted name, arguments, journal, and accounting. - /// - /// Wire method: `session.factory.resume`. - /// - /// # Parameters - /// - /// * `params` - Parameters for resuming a factory run from its persisted identity. - /// - /// # Returns - /// - /// Resolved persisted factory identity and resumed run envelope. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn resume(&self, params: FactoryResumeRequest) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_FACTORY_RESUME, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Internal tool-originated factory invocation. - /// - /// Wire method: `session.factory.runFromTool`. - /// - /// # Parameters - /// - /// * `params` - Internal parameters for invoking a registered factory from a tool. - /// - /// # Returns - /// - /// Complete current or terminal factory run envelope. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub(crate) async fn run_from_tool( - &self, - params: FactoryToolRunRequest, - ) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_FACTORY_RUNFROMTOOL, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Internal tool-originated factory resume. - /// - /// Wire method: `session.factory.resumeFromTool`. - /// - /// # Parameters - /// - /// * `params` - Internal parameters for resuming a factory run from a tool. - /// - /// # Returns - /// - /// Resolved persisted factory identity and resumed run envelope. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub(crate) async fn resume_from_tool( - &self, - params: FactoryToolResumeRequest, - ) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call( - rpc_methods::SESSION_FACTORY_RESUMEFROMTOOL, - Some(wire_params), - ) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Gets the current or settled envelope for a factory run. - /// - /// Wire method: `session.factory.getRun`. - /// - /// # Parameters - /// - /// * `params` - Parameters for retrieving a factory run. - /// - /// # Returns - /// - /// Complete current or terminal factory run envelope. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn get_run(&self, params: FactoryGetRunRequest) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_FACTORY_GETRUN, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Lists durable factory runs for this session in creation order. - /// - /// Wire method: `session.factory.listRuns`. - /// - /// # Parameters - /// - /// * `params` - Parameters for paging factory runs. - /// - /// # Returns - /// - /// A page of factory runs in durable creation order. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn list_runs( - &self, - params: FactoryListRunsRequest, - ) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_FACTORY_LISTRUNS, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Gets durable and live observability detail for one factory run. - /// - /// Wire method: `session.factory.getRunDetail`. - /// - /// # Parameters - /// - /// * `params` - Parameters for retrieving a factory run. - /// - /// # Returns - /// - /// Full factory run observability detail. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn get_run_detail( - &self, - params: FactoryGetRunRequest, - ) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_FACTORY_GETRUNDETAIL, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Pages durable progress for one factory run. - /// - /// Wire method: `session.factory.getRunProgress`. - /// - /// # Parameters - /// - /// * `params` - Parameters for paging factory progress. - /// - /// # Returns - /// - /// A bidirectional page of factory progress. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn get_run_progress( - &self, - params: FactoryGetRunProgressRequest, - ) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call( - rpc_methods::SESSION_FACTORY_GETRUNPROGRESS, - Some(wire_params), - ) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Requests cancellation of a factory run and returns its run envelope. - /// - /// Wire method: `session.factory.cancel`. - /// - /// # Parameters - /// - /// * `params` - Parameters for cancelling a factory run. - /// - /// # Returns - /// - /// Complete current or terminal factory run envelope. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn cancel(&self, params: FactoryCancelRequest) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_FACTORY_CANCEL, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Pauses a running factory and returns its settled run envelope. - /// - /// Wire method: `session.factory.pause`. - /// - /// # Parameters - /// - /// * `params` - Parameters for pausing a running factory. - /// - /// # Returns - /// - /// Complete current or terminal factory run envelope. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn pause(&self, params: FactoryPauseRequest) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_FACTORY_PAUSE, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Atomically pauses an owned factory attempt at a durable checkpoint. - /// - /// Wire method: `session.factory.pauseAtCheckpoint`. - /// - /// # Parameters - /// - /// * `params` - Parameters for an owned durable pause checkpoint. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub(crate) async fn pause_at_checkpoint( - &self, - params: FactoryPauseCheckpointRequest, - ) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call( - rpc_methods::SESSION_FACTORY_PAUSEATCHECKPOINT, - Some(wire_params), - ) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Records a batch of ordered factory progress lines. - /// - /// Wire method: `session.factory.log`. - /// - /// # Parameters - /// - /// * `params` - Parameters for recording factory progress. - /// - /// # Returns - /// - /// Acknowledgement that a factory request was accepted. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn log(&self, params: FactoryLogRequest) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_FACTORY_LOG, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Runs one factory-scoped subagent and returns its result. - /// - /// Wire method: `session.factory.agent`. - /// - /// # Parameters - /// - /// * `params` - Parameters for one factory-scoped subagent call. - /// - /// # Returns - /// - /// Result of one factory-scoped subagent call. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn agent(&self, params: FactoryAgentRequest) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_FACTORY_AGENT, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } -} - -/// `session.factory.journal.*` RPCs. -#[derive(Clone, Copy)] -pub struct SessionRpcFactoryJournal<'a> { - pub(crate) session: &'a Session, -} - -impl<'a> SessionRpcFactoryJournal<'a> { - /// Reads a memoized factory journal entry. - /// - /// Wire method: `session.factory.journal.get`. - /// - /// # Parameters - /// - /// * `params` - Parameters for reading a factory journal entry. - /// - /// # Returns - /// - /// Result of reading a factory journal entry. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn get( - &self, - params: FactoryJournalGetRequest, - ) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_FACTORY_JOURNAL_GET, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } - - /// Stores a memoized factory journal entry. - /// - /// Wire method: `session.factory.journal.put`. - /// - /// # Parameters - /// - /// * `params` - Parameters for storing a factory journal entry. - /// - /// # Returns - /// - /// Acknowledgement that a factory request was accepted. - /// - ///
- /// - /// **Experimental.** This API is part of an experimental wire-protocol surface - /// and may change or be removed in future SDK or CLI releases. Pin both the - /// SDK and CLI versions if your code depends on it. - /// - ///
- pub async fn put(&self, params: FactoryJournalPutRequest) -> Result { - let mut wire_params = serde_json::to_value(params)?; - wire_params["sessionId"] = serde_json::Value::String(self.session.id().to_string()); - let _value = self - .session - .client() - .call(rpc_methods::SESSION_FACTORY_JOURNAL_PUT, Some(wire_params)) - .await?; - Ok(serde_json::from_value(_value)?) - } -} - /// `session.fleet.*` RPCs. #[derive(Clone, Copy)] pub struct SessionRpcFleet<'a> { diff --git a/rust/src/generated/session_events.rs b/rust/src/generated/session_events.rs index 6cc0534f8b..3959c75599 100644 --- a/rust/src/generated/session_events.rs +++ b/rust/src/generated/session_events.rs @@ -449,8 +449,8 @@ pub enum SessionEventType { /// and may change or be removed in future SDK or CLI releases. /// ///
- #[serde(rename = "factory.run_updated")] - FactoryRunUpdated, + #[serde(rename = "workflow.run_updated")] + WorkflowRunUpdated, /// ///
/// @@ -458,8 +458,8 @@ pub enum SessionEventType { /// and may change or be removed in future SDK or CLI releases. /// ///
- #[serde(rename = "factory.run_started")] - FactoryRunStarted, + #[serde(rename = "workflow.run_started")] + WorkflowRunStarted, /// ///
/// @@ -467,8 +467,8 @@ pub enum SessionEventType { /// and may change or be removed in future SDK or CLI releases. /// ///
- #[serde(rename = "factory.run_settled")] - FactoryRunSettled, + #[serde(rename = "workflow.run_settled")] + WorkflowRunSettled, #[serde(rename = "session.skills_loaded")] SessionSkillsLoaded, #[serde(rename = "session.custom_agents_updated")] @@ -969,8 +969,8 @@ pub enum SessionEventData { /// and may change or be removed in future SDK or CLI releases. /// ///
- #[serde(rename = "factory.run_updated")] - FactoryRunUpdated(FactoryRunUpdatedData), + #[serde(rename = "workflow.run_updated")] + WorkflowRunUpdated(WorkflowRunUpdatedData), /// ///
/// @@ -978,8 +978,8 @@ pub enum SessionEventData { /// and may change or be removed in future SDK or CLI releases. /// ///
- #[serde(rename = "factory.run_started")] - FactoryRunStarted(FactoryRunStartedData), + #[serde(rename = "workflow.run_started")] + WorkflowRunStarted(WorkflowRunStartedData), /// ///
/// @@ -987,8 +987,8 @@ pub enum SessionEventData { /// and may change or be removed in future SDK or CLI releases. /// ///
- #[serde(rename = "factory.run_settled")] - FactoryRunSettled(FactoryRunSettledData), + #[serde(rename = "workflow.run_settled")] + WorkflowRunSettled(WorkflowRunSettledData), #[serde(rename = "session.skills_loaded")] SessionSkillsLoaded(SessionSkillsLoadedData), #[serde(rename = "session.custom_agents_updated")] @@ -2121,10 +2121,14 @@ pub struct ResponsesReasoning { #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SessionCompactionCompleteData { - /// Authoritative active-factory reminder appended to the compacted context + /// Legacy active-workflow reminder retained for replay compatibility #[doc(hidden)] #[serde(skip_serializing_if = "Option::is_none")] pub(crate) active_factory_summary: Option, + /// Authoritative active-workflow reminder appended to the compacted context + #[doc(hidden)] + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) active_workflow_summary: Option, /// Canonical model identifier used for model-specific behavior when replaying compaction #[serde(skip_serializing_if = "Option::is_none")] pub behavior_model_id: Option, @@ -4904,7 +4908,7 @@ pub struct SubagentStartedData { /// Whether the sub-agent runs synchronously or in the background. #[serde(skip_serializing_if = "Option::is_none")] pub execution_mode: Option, - /// Root id of the factory run that spawned this sub-agent, when it was spawned by one. + /// Legacy root id of the workflow run that spawned this sub-agent. New consumers should use workflowRunId. #[serde(skip_serializing_if = "Option::is_none")] pub factory_run_id: Option, /// Model the sub-agent will run with, when known at start. @@ -4919,11 +4923,14 @@ pub struct SubagentStartedData { /// Whether this sub-agent can be resumed. Currently always false. #[serde(skip_serializing_if = "Option::is_none")] pub resumable: Option, - /// Where the model input for this sub-agent came from. Present when the task planner resolved the launch (the task tool and factory agents); absent for sub-agents created through other runtime paths. + /// Where the model input for this sub-agent came from. Present when the task planner resolved the launch (the task tool and workflow agents); absent for sub-agents created through other runtime paths. #[serde(skip_serializing_if = "Option::is_none")] pub task_model_source: Option, /// Tool call ID of the parent tool invocation that spawned this sub-agent pub tool_call_id: String, + /// Root id of the workflow run that spawned this sub-agent, when it was spawned by one. + #[serde(skip_serializing_if = "Option::is_none")] + pub workflow_run_id: Option, } /// Session event "subagent.configured". Resolved runtime configuration for a configured sub-agent @@ -5581,10 +5588,10 @@ pub struct PermissionRequestExtensionManagement { pub tool_call_id: Option, } -/// A declared phase shown in a factory permission prompt. +/// A declared phase shown in a workflow permission prompt. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FactoryPermissionPhase { +pub struct WorkflowPermissionPhase { /// Optional phase detail #[serde(skip_serializing_if = "Option::is_none")] pub detail: Option, @@ -5592,31 +5599,31 @@ pub struct FactoryPermissionPhase { pub title: String, } -/// Factory run or authoring permission request +/// Workflow run or authoring permission request #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PermissionRequestFactory { - /// Canonical key used for scoped factory approvals +pub struct PermissionRequestWorkflow { + /// Canonical key used for scoped workflow approvals pub approval_key: String, - /// Whether this factory is eligible for persistent approval + /// Whether this workflow is eligible for persistent approval pub can_persist_approval: bool, - /// Factory-declared AI-credit limit before any run/resume caller override is applied. + /// Workflow-declared AI-credit limit before any run/resume caller override is applied. #[serde(skip_serializing_if = "Option::is_none")] pub declared_max_ai_credits: Option, - /// Factory-declared concurrent-subagent limit before any run/resume caller override is applied. + /// Workflow-declared concurrent-subagent limit before any run/resume caller override is applied. #[serde(skip_serializing_if = "Option::is_none")] pub declared_max_concurrent_subagents: Option, - /// Factory-declared total-subagent limit before any run/resume caller override is applied. + /// Workflow-declared total-subagent limit before any run/resume caller override is applied. #[serde(skip_serializing_if = "Option::is_none")] pub declared_max_total_subagents: Option, - /// Factory-declared active-time limit in seconds before any run/resume caller override is applied. + /// Workflow-declared active-time limit in seconds before any run/resume caller override is applied. #[serde(skip_serializing_if = "Option::is_none")] pub declared_timeout_seconds: Option, - /// Factory description + /// Workflow description pub description: String, /// Permission kind discriminator - pub kind: PermissionRequestFactoryKind, - /// When true, managed policy requires an explicit user decision and automatic approval must be bypassed. + pub kind: PermissionRequestWorkflowKind, + /// Whether managed policy requires a human response and forbids host auto-approval #[serde(skip_serializing_if = "Option::is_none")] pub managed_approval_required: Option, /// Effective AI-credit limit; omitted means unlimited @@ -5628,12 +5635,12 @@ pub struct PermissionRequestFactory { /// Effective total-subagent limit; omitted means unlimited #[serde(skip_serializing_if = "Option::is_none")] pub max_total_subagents: Option, - /// Factory name + /// Workflow name pub name: String, - /// Factory operation, either run or author - pub operation: FactoryPermissionOperation, - /// Declared factory phases - pub phases: Vec, + /// Workflow operation, either run or author + pub operation: WorkflowPermissionOperation, + /// Declared workflow phases + pub phases: Vec, /// Effective active-time limit in seconds; omitted means unlimited #[serde(skip_serializing_if = "Option::is_none")] pub timeout_seconds: Option, @@ -6031,11 +6038,11 @@ pub struct PermissionPromptRequestExtensionManagement { pub tool_call_id: Option, } -/// Factory run or authoring permission prompt +/// Workflow run or authoring permission prompt #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct PermissionPromptRequestFactory { - /// Canonical key used for scoped factory approvals +pub struct PermissionPromptRequestWorkflow { + /// Canonical key used for scoped workflow approvals pub approval_key: String, /// Assisted-approval judge information for this request; present only in assisted mode. /// @@ -6047,24 +6054,24 @@ pub struct PermissionPromptRequestFactory { ///
#[serde(skip_serializing_if = "Option::is_none")] pub assisted_approval: Option, - /// Whether this factory is eligible for persistent approval + /// Whether this workflow is eligible for persistent approval pub can_persist_approval: bool, - /// Factory-declared AI-credit limit before any run/resume caller override is applied. + /// Workflow-declared AI-credit limit before any run/resume caller override is applied. #[serde(skip_serializing_if = "Option::is_none")] pub declared_max_ai_credits: Option, - /// Factory-declared concurrent-subagent limit before any run/resume caller override is applied. + /// Workflow-declared concurrent-subagent limit before any run/resume caller override is applied. #[serde(skip_serializing_if = "Option::is_none")] pub declared_max_concurrent_subagents: Option, - /// Factory-declared total-subagent limit before any run/resume caller override is applied. + /// Workflow-declared total-subagent limit before any run/resume caller override is applied. #[serde(skip_serializing_if = "Option::is_none")] pub declared_max_total_subagents: Option, - /// Factory-declared active-time limit in seconds before any run/resume caller override is applied. + /// Workflow-declared active-time limit in seconds before any run/resume caller override is applied. #[serde(skip_serializing_if = "Option::is_none")] pub declared_timeout_seconds: Option, - /// Factory description + /// Workflow description pub description: String, /// Prompt kind discriminator - pub kind: PermissionPromptRequestFactoryKind, + pub kind: PermissionPromptRequestWorkflowKind, /// Whether managed policy requires a human response and forbids host auto-approval #[serde(skip_serializing_if = "Option::is_none")] pub managed_approval_required: Option, @@ -6077,12 +6084,12 @@ pub struct PermissionPromptRequestFactory { /// Effective total-subagent limit; omitted means unlimited #[serde(skip_serializing_if = "Option::is_none")] pub max_total_subagents: Option, - /// Factory name + /// Workflow name pub name: String, - /// Factory operation, either run or author - pub operation: FactoryPermissionOperation, - /// Declared factory phases - pub phases: Vec, + /// Workflow operation, either run or author + pub operation: WorkflowPermissionOperation, + /// Declared workflow phases + pub phases: Vec, /// Effective active-time limit in seconds; omitted means unlimited #[serde(skip_serializing_if = "Option::is_none")] pub timeout_seconds: Option, @@ -6247,15 +6254,15 @@ pub struct UserToolSessionApprovalExtensionManagement { pub operation: Option, } -/// Session-scoped factory approval, optionally narrowed by approval key. +/// Session-scoped workflow approval, optionally narrowed by approval key. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct UserToolSessionApprovalFactory { - /// Optional factory operation name or canonical approval key +pub struct UserToolSessionApprovalWorkflow { + /// Optional workflow operation name or canonical approval key #[serde(skip_serializing_if = "Option::is_none")] pub approval_key: Option, - /// Factory approval kind - pub kind: UserToolSessionApprovalFactoryKind, + /// Workflow approval kind + pub kind: UserToolSessionApprovalWorkflowKind, } /// Session-scoped tool-approval rule for an extension's permission-gated capability access, keyed by extension name. @@ -6416,7 +6423,7 @@ pub struct PermissionCompletedData { pub tool_call_id: Option, } -/// Session event "permission.carriedForward". Records that a live authorization record from an earlier human decision in this session contained a permission proposal, so it ran without another prompt. This mints no authority: it accounts for one more effect against the prior grant, which is what lets a replayed session agree with the live one about how much of that grant is left. +/// Session event "permission.carriedForward". Historical decode-only receipt from the retired Assisted Permissions authorization extractor. Current runtimes ignore it for permission decisions. /// ///
/// @@ -6465,7 +6472,7 @@ pub struct PermissionCarriedForwardData { pub tool_call_id: String, } -/// Session event "permission.messageAuthorization". Freezes one blinded, verbatim-verified authorization claim the runtime minted from a human user message, so a resumed session re-establishes the same grant deterministically instead of re-running the extraction model. This mints no authority on its own: it records what a blinded proposer pointed at and the trusted discriminator the runtime established, and deterministic establishment runs on replay. Persisted so recorded authority survives compaction and process resume. +/// Session event "permission.messageAuthorization". Historical decode-only claim from the retired Assisted Permissions authorization extractor. Current runtimes preserve the payload but do not establish authority from it. /// ///
/// @@ -6562,7 +6569,7 @@ pub struct PermissionMessageAuthorizationData { pub world: Option, } -/// Session event "permission.messageAuthorizationRead". Records that one human turn has been read by the blinded authorization proposer, whether or not it minted anything, so a resumed session does not re-run the extraction model on a turn the live session already read. Also records whether that pass activates ongoing extraction; contextual-assent-only passes do not, so unrelated future messages remain outside extraction. +/// Session event "permission.messageAuthorizationRead". Historical decode-only extractor progress marker. Current runtimes do not run or resume extraction from it. /// ///
/// @@ -6594,7 +6601,7 @@ pub struct PermissionMessageAuthorizationReadData { pub turn_index: i64, } -/// Session event "permission.messageAuthorizationDegraded". Records that message-backed authorization could not safely represent one human turn before compaction. The runtime may compact the original message after this marker is durable, but message-derived carry-forward and assisted auto-approval remain disabled for the rest of the session so subsequent commands continue through the ordinary permission prompt. +/// Session event "permission.messageAuthorizationDegraded". Historical decode-only degradation marker from the retired extractor. Current runtimes ignore it for permission decisions. /// ///
/// @@ -6616,7 +6623,7 @@ pub struct PermissionMessageAuthorizationDegradedData { pub turn_index: i64, } -/// Session event "permission.assentDetected". Records that deterministic text recognition found likely assent in the human turn immediately following a root Autopilot permission request that was blocked because no interactive response was available. This event grants no authority; its model-facing projection only suggests retrying the unchanged operation. +/// Session event "permission.assentDetected". Historical decode-only contextual-assent marker. Current runtimes do not project it into the conversation or permission flow. /// ///
/// @@ -6647,7 +6654,7 @@ pub struct PermissionAssentDetectedData { pub turn_index: i64, } -/// Session event "permission.contextualAuthorization". Freezes a blinded contextual authorization proposal whose verbatim human span was deterministically bound to the immediately preceding blocked permission request. The event carries no action fields; replay re-derives the exact action from the earlier permission request and mints a one-shot message grant only when the binding and span still verify. +/// Session event "permission.contextualAuthorization". Historical decode-only contextual authorization claim. Current runtimes preserve the payload but do not establish authority from it. /// ///
/// @@ -7326,7 +7333,7 @@ pub struct SessionToolsUpdatedData { #[serde(rename_all = "camelCase")] pub struct SessionBackgroundTasksChangedData {} -/// Session event "factory.run_updated". Ephemeral invalidation signal for a changed factory run. +/// Session event "workflow.run_updated". Ephemeral invalidation signal for a changed workflow run. /// ///
/// @@ -7336,14 +7343,14 @@ pub struct SessionBackgroundTasksChangedData {} ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FactoryRunUpdatedData { +pub struct WorkflowRunUpdatedData { /// Monotonic revision now available for the run. pub revision: i64, - /// Factory run identifier. + /// Workflow run identifier. pub run_id: String, } -/// Session event "factory.run_started". Ephemeral signal that a factory run attempt began executing. +/// Session event "workflow.run_started". Ephemeral signal that a workflow run attempt began executing. /// ///
/// @@ -7353,16 +7360,16 @@ pub struct FactoryRunUpdatedData { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FactoryRunStartedData { +pub struct WorkflowRunStartedData { /// Attempt number this start committed; a resumed run increments it. pub attempt: i64, - /// Name of the factory this run executes. Low cardinality by construction. - pub factory_name: String, - /// Identifier of the factory run that started. + /// Identifier of the workflow run that started. pub run_id: String, + /// Name of the workflow this run executes. Low cardinality by construction. + pub workflow_name: String, } -/// Session event "factory.run_settled". Ephemeral signal that a factory run reached a terminal status. +/// Session event "workflow.run_settled". Ephemeral signal that a workflow run reached a terminal status. /// ///
/// @@ -7372,20 +7379,20 @@ pub struct FactoryRunStartedData { ///
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] -pub struct FactoryRunSettledData { +pub struct WorkflowRunSettledData { /// AI credits this run consumed, in nano-AIU. pub consumed_nano_aiu: i64, /// Subagents this run consumed against its limits. pub consumed_subagents: i64, /// Active milliseconds accumulated across every attempt of this run. pub elapsed_ms: i64, - /// Typed failure class recorded on the run, when it failed with one (e.g. `factory_limit_reached`). + /// Typed failure class recorded on the run, when it failed with one (e.g. `workflow_limit_reached`). #[serde(skip_serializing_if = "Option::is_none")] pub failure_type: Option, - /// Identifier of the factory run that settled. + /// Identifier of the workflow run that settled. pub run_id: String, /// Terminal status the run committed. - pub status: FactoryRunSettledStatus, + pub status: WorkflowRunSettledStatus, } /// A single resolved skill in `session.skills_loaded`, including source, invocability, enabled state, path, and argument hint. @@ -8225,6 +8232,9 @@ pub enum ModelChangeSource { /// An SDK or RPC caller selected the model. #[serde(rename = "sdk")] Sdk, + /// The user accepted a CAPI-issued Auto tier recommendation. + #[serde(rename = "auto_tier_recommendation")] + AutoTierRecommendation, /// Unknown variant for forward compatibility. #[default] #[serde(other)] @@ -10111,19 +10121,19 @@ pub enum PermissionRequestExtensionManagementKind { /// Permission kind discriminator #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum PermissionRequestFactoryKind { - #[serde(rename = "factory")] +pub enum PermissionRequestWorkflowKind { + #[serde(rename = "workflow")] #[default] - Factory, + Workflow, } -/// Operation gated by a factory permission request. +/// Operation gated by a workflow permission request. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum FactoryPermissionOperation { - /// Running a registered factory, which spends subagents, active time, and AI credits under the approved limits. +pub enum WorkflowPermissionOperation { + /// Running a registered workflow, which spends subagents, active time, and AI credits under the approved limits. #[serde(rename = "run")] Run, - /// Authoring a factory, which writes JavaScript into a session-scoped extension and loads it. + /// Authoring a workflow, which writes JavaScript into a session-scoped extension and loads it. #[serde(rename = "author")] Author, /// Unknown variant for forward compatibility. @@ -10161,7 +10171,7 @@ pub enum PermissionRequest { CustomTool(PermissionRequestCustomTool), Hook(PermissionRequestHook), ExtensionManagement(PermissionRequestExtensionManagement), - Factory(PermissionRequestFactory), + Workflow(PermissionRequestWorkflow), ExtensionPermissionAccess(PermissionRequestExtensionPermissionAccess), ExtensionEnvAccess(PermissionRequestExtensionEnvAccess), } @@ -10266,10 +10276,10 @@ pub enum PermissionPromptRequestExtensionManagementKind { /// Prompt kind discriminator #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum PermissionPromptRequestFactoryKind { - #[serde(rename = "factory")] +pub enum PermissionPromptRequestWorkflowKind { + #[serde(rename = "workflow")] #[default] - Factory, + Workflow, } /// Prompt kind discriminator @@ -10302,7 +10312,7 @@ pub enum PermissionPromptRequest { Path(PermissionPromptRequestPath), Hook(PermissionPromptRequestHook), ExtensionManagement(PermissionPromptRequestExtensionManagement), - Factory(PermissionPromptRequestFactory), + Workflow(PermissionPromptRequestWorkflow), ExtensionPermissionAccess(PermissionPromptRequestExtensionPermissionAccess), ExtensionEnvAccess(PermissionPromptRequestExtensionEnvAccess), } @@ -10322,7 +10332,7 @@ pub enum PermissionDecisionSource { /// The host denied the request because no interactive user response was available. #[serde(rename = "unattended_fallback")] UnattendedFallback, - /// A live authorization record from an earlier human decision in this session contained the proposal, so it ran without another prompt. This is not a new human decision and never mints authority of its own. + /// Historical compatibility value for sessions created while authorization carry-forward was executable. Current runtimes do not produce this source. #[serde(rename = "authorization_carry_forward")] AuthorizationCarryForward, /// Unknown variant for forward compatibility. @@ -10395,12 +10405,12 @@ pub enum UserToolSessionApprovalExtensionManagementKind { ExtensionManagement, } -/// Factory approval kind +/// Workflow approval kind #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum UserToolSessionApprovalFactoryKind { - #[serde(rename = "factory")] +pub enum UserToolSessionApprovalWorkflowKind { + #[serde(rename = "workflow")] #[default] - Factory, + Workflow, } /// Extension permission access approval kind @@ -10430,7 +10440,7 @@ pub enum UserToolSessionApproval { Memory(UserToolSessionApprovalMemory), CustomTool(UserToolSessionApprovalCustomTool), ExtensionManagement(UserToolSessionApprovalExtensionManagement), - Factory(UserToolSessionApprovalFactory), + Workflow(UserToolSessionApprovalWorkflow), ExtensionPermissionAccess(UserToolSessionApprovalExtensionPermissionAccess), ExtensionEnvAccess(UserToolSessionApprovalExtensionEnvAccess), } @@ -10516,7 +10526,7 @@ pub enum PermissionResult { DeniedByPermissionRequestHook(PermissionDeniedByPermissionRequestHook), } -/// Which direction a message-backed authorization claim moves authority in. +/// Direction stored in a historical extractor claim. Current runtimes do not apply it. /// ///
/// @@ -10526,10 +10536,10 @@ pub enum PermissionResult { ///
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub enum PermissionMessageAuthorizationPolarity { - /// The human's words authorized an effect. + /// Historical claim recorded as a grant. #[serde(rename = "grant")] Grant, - /// The human's words refused an effect. + /// Historical claim recorded as a denial. #[serde(rename = "denial")] Denial, /// Unknown variant for forward compatibility. @@ -10837,10 +10847,10 @@ pub enum ExitPlanModeAction { Unknown, } -/// Terminal status a factory run committed. A settled run is never `pending` or `running`, so those two members of the run-status domain are deliberately absent. +/// Terminal status a workflow run committed. A settled run is never `pending` or `running`, so those two members of the run-status domain are deliberately absent. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] -pub enum FactoryRunSettledStatus { - /// The factory body resolved and its result was committed. +pub enum WorkflowRunSettledStatus { + /// The workflow body resolved and its result was committed. #[serde(rename = "completed")] Completed, /// The run was stopped by a limit, an approval refusal or another policy decision. diff --git a/rust/tests/e2e/rpc_surface_coverage.rs b/rust/tests/e2e/rpc_surface_coverage.rs index 20a56e6882..11e0e2d764 100644 --- a/rust/tests/e2e/rpc_surface_coverage.rs +++ b/rust/tests/e2e/rpc_surface_coverage.rs @@ -218,7 +218,7 @@ async fn client_rpc_surface_uses_typed_namespaces_and_round_trips_results() { } #[tokio::test] -async fn session_lifecycle_factory_and_history_rpc_surface_is_typed() { +async fn session_lifecycle_workflow_and_history_rpc_surface_is_typed() { let mut results = ResponseMap::default(); results.insert_default::("session.sendMessages"); results.insert_default::("session.abort"); @@ -237,34 +237,34 @@ async fn session_lifecycle_factory_and_history_rpc_surface_is_typed() { results .insert_default::("session.contentExclusion.checkPaths"); results.insert( - "session.factory.run", - FactoryRunResult { + "session.workflow.run", + WorkflowRunResult { attempt: Some(2), - result: Some(json!({"artifact": "factory-output"})), + result: Some(json!({"artifact": "workflow-output"})), run_id: "run-123".to_string(), ..Default::default() }, ); results.insert( - "session.factory.resume", - FactoryResumeResult { - factory_name: "coverage-factory".to_string(), - run: FactoryRunResult { + "session.workflow.resume", + WorkflowResumeResult { + workflow_name: "coverage-workflow".to_string(), + run: WorkflowRunResult { run_id: "run-123".to_string(), ..Default::default() }, }, ); - results.insert_default::("session.factory.getRun"); - results.insert_default::("session.factory.listRuns"); - results.insert_default::("session.factory.getRunDetail"); - results.insert_default::("session.factory.getRunProgress"); - results.insert_default::("session.factory.cancel"); - results.insert_default::("session.factory.pause"); - results.insert_default::("session.factory.log"); - results.insert_default::("session.factory.agent"); - results.insert_default::("session.factory.journal.get"); - results.insert_default::("session.factory.journal.put"); + results.insert_default::("session.workflow.getRun"); + results.insert_default::("session.workflow.listRuns"); + results.insert_default::("session.workflow.getRunDetail"); + results.insert_default::("session.workflow.getRunProgress"); + results.insert_default::("session.workflow.cancel"); + results.insert_default::("session.workflow.pause"); + results.insert_default::("session.workflow.log"); + results.insert_default::("session.workflow.agent"); + results.insert_default::("session.workflow.journal.get"); + results.insert_default::("session.workflow.journal.put"); results.insert_default::("session.fleet.start"); results.insert( "session.history.compact", @@ -331,77 +331,77 @@ async fn session_lifecycle_factory_and_history_rpc_surface_is_typed() { }) ); - let run = rpc_ok!(session.rpc().factory().run(FactoryRunRequest { + let run = rpc_ok!(session.rpc().workflow().run(WorkflowRunRequest { args: json!({"mode": "offline", "count": 2}), - name: "coverage-factory".to_string(), + name: "coverage-workflow".to_string(), options: None, })); assert_eq!(run.run_id, "run-123"); assert_eq!(run.attempt, Some(2)); - assert_eq!(run.result, Some(json!({"artifact": "factory-output"}))); - let resumed = rpc_ok!(session.rpc().factory().resume(FactoryResumeRequest { + assert_eq!(run.result, Some(json!({"artifact": "workflow-output"}))); + let resumed = rpc_ok!(session.rpc().workflow().resume(WorkflowResumeRequest { run_id: "run-123".to_string(), notify_on_complete: Some(false), ..Default::default() })); - assert_eq!(resumed.factory_name, "coverage-factory"); + assert_eq!(resumed.workflow_name, "coverage-workflow"); assert_eq!(resumed.run.run_id, "run-123"); rpc_ok!( session .rpc() - .factory() - .get_run(FactoryGetRunRequest::default()) + .workflow() + .get_run(WorkflowGetRunRequest::default()) ); rpc_ok!( session .rpc() - .factory() - .list_runs(FactoryListRunsRequest::default()) + .workflow() + .list_runs(WorkflowListRunsRequest::default()) ); rpc_ok!( session .rpc() - .factory() - .get_run_detail(FactoryGetRunRequest::default()) + .workflow() + .get_run_detail(WorkflowGetRunRequest::default()) ); rpc_ok!( session .rpc() - .factory() - .get_run_progress(FactoryGetRunProgressRequest::default()) + .workflow() + .get_run_progress(WorkflowGetRunProgressRequest::default()) ); rpc_ok!( session .rpc() - .factory() - .cancel(FactoryCancelRequest::default()) + .workflow() + .cancel(WorkflowCancelRequest::default()) ); rpc_ok!( session .rpc() - .factory() - .pause(FactoryPauseRequest::default()) + .workflow() + .pause(WorkflowPauseRequest::default()) ); - rpc_ok!(session.rpc().factory().log(FactoryLogRequest::default())); + rpc_ok!(session.rpc().workflow().log(WorkflowLogRequest::default())); rpc_ok!( session .rpc() - .factory() - .agent(FactoryAgentRequest::default()) + .workflow() + .agent(WorkflowAgentRequest::default()) ); rpc_ok!( session .rpc() - .factory() + .workflow() .journal() - .get(FactoryJournalGetRequest::default()) + .get(WorkflowJournalGetRequest::default()) ); rpc_ok!( session .rpc() - .factory() + .workflow() .journal() - .put(FactoryJournalPutRequest::default()) + .put(WorkflowJournalPutRequest::default()) ); rpc_ok!(session.rpc().fleet().start(FleetStartRequest::default())); @@ -458,18 +458,18 @@ async fn session_lifecycle_factory_and_history_rpc_surface_is_typed() { "session.autopilotObjective.getState", "session.completions.getTriggerCharacters", "session.contentExclusion.checkPaths", - "session.factory.run", - "session.factory.resume", - "session.factory.getRun", - "session.factory.listRuns", - "session.factory.getRunDetail", - "session.factory.getRunProgress", - "session.factory.cancel", - "session.factory.pause", - "session.factory.log", - "session.factory.agent", - "session.factory.journal.get", - "session.factory.journal.put", + "session.workflow.run", + "session.workflow.resume", + "session.workflow.getRun", + "session.workflow.listRuns", + "session.workflow.getRunDetail", + "session.workflow.getRunProgress", + "session.workflow.cancel", + "session.workflow.pause", + "session.workflow.log", + "session.workflow.agent", + "session.workflow.journal.get", + "session.workflow.journal.put", "session.fleet.start", "session.history.compact", "session.history.compact", @@ -478,12 +478,12 @@ async fn session_lifecycle_factory_and_history_rpc_surface_is_typed() { "session.limitPrediction.predict", ]); fake.assert_params( - "session.factory.run", + "session.workflow.run", 0, json!({ "sessionId": "rpc-surface-session", "args": {"mode": "offline", "count": 2}, - "name": "coverage-factory" + "name": "coverage-workflow" }), ); fake.assert_params( diff --git a/rust/tests/session_test.rs b/rust/tests/session_test.rs index bca042b634..7862a6161b 100644 --- a/rust/tests/session_test.rs +++ b/rust/tests/session_test.rs @@ -1466,8 +1466,8 @@ async fn create_session_forwards_refresh_custom_instructions_only_when_set() { if let Some(refresh) = refresh { config = config.with_refresh_custom_instructions(refresh); } - let create = client.create_session(config); - let server = async { + let create = Box::pin(client.create_session(config)); + let server = Box::pin(async { let request = read_framed(&mut server_read).await; assert_eq!(request["method"], "session.create"); assert_eq!( @@ -1482,7 +1482,7 @@ async fn create_session_forwards_refresh_custom_instructions_only_when_set() { "result": { "sessionId": session_id }, }); write_framed(&mut server_write, &serde_json::to_vec(&response).unwrap()).await; - }; + }); let (session, ()) = timeout(TIMEOUT, async { tokio::join!(create, server) }) .await