Skip to content

Extract the CLI's Webex API logic into a Go SDK in pkg/ - #31

Merged
edumansky merged 19 commits into
mainfrom
go-sdk
Nov 18, 2026
Merged

edumansky merged 19 commits into
mainfrom
go-sdk

Conversation

@edumansky

@edumansky edumansky commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

The CLI's Webex API logic is now a Go SDK in pkg/, and the CLI runs on it. The CLI's commands, flags and requests don't change: the golden files from #30 pass unchanged. A few edge cases now fail safely instead (see "CLI changes" below).

This is PR 2 of the SDK plan. It covers only the logic the CLI already had, so another program, such as Webex Admin Studio, can call Webex the way the CLI does and build its own model on top. Studio's catalog, guard and change sets are not here.

The SDK

Package What it holds
pkg/webexapi Client.Send: the bearer token, one refresh after a 401, waits for a 429's Retry-After within limits, and nothing else retried. A redirect is never followed: a 3xx returns RedirectError. APIError, with the response's redacted body; RateLimitError, WrongRegionError (451) and RedirectError all unwrap to it. Fail-closed paging (Visit, All, Paging). HostsFor, which refuses an unknown Contact Center data center. Org ID conversion. Multipart bodies.
pkg/webexops The operation table, generated from the collections: 2,124 CLI *Operations with route, host, parameters, body fields, paging and CLI names, plus Call and All. Each is named by its area, method and path (CcGetOrganizationByOrgidV2Team), so a name always means the same request; 1,972 are exported. A route listed more than once is exported once: on its first listing when all listings send the same request, or else as an operation combining every listing's parameters, which is not a CLI command (4 routes today). Request and List refuse a parameter the operation lacks, a value for a fixed parameter, and a missing path value. codegen/operation_names.json records each exported name's route, so a name is never given to another route in a later refresh. The handwritten upload, download and search commands are not in the table.
pkg/aiagent BotToken and RedactSecrets for AI Agent Studio. Call and All hide Studio's tokens in its responses, as the CLI already did.
  • No hidden state: none of these packages has process-wide state, and every call takes a context.
  • Hooks: BeforeSend, AfterResponse and OnRetry let a program log or stop requests.
  • Import rule: pkg/imports_test.go fails if pkg/ imports anything but the standard library and itself. So it can never pull in internal/, cobra or the keyring.

The CLI on top

  • internal/client.API builds the CLI's webexapi.Client:

    • its token and refresh, and --max-retry;
    • --debug, --dry-run and read-only mode as hooks;
    • the "Rate limited" line, and the 451 message with its --region advice.

    client.Request, which the handwritten commands use, now sends through it.

  • internal/apicmd builds each webex <area> <group> <command> from the table:

    • flags, help and required flags;
    • --last, --body/--body-file and --paginate;
    • the agent token lookup;
    • redaction and the private-API notice.
  • codegen/generate_cli.py writes pkg/webexops/zz_*.go instead of cobra files. Each area package keeps its handwritten commands and gains a commands.go.

    • Every parameter whose name looks like an org ID is classified in one table, ORG_ID_FORMS, as taking either the UUID or the base64 Webex ID. Codegen stops on one it can't classify. The table reproduces today's marks exactly; the generated files are unchanged.
  • Removed: the 202 generated cobra files. The binary is about 4 MB smaller.

CLI changes

These are intended, and are the only ones. None appears in the golden files:

  • A redirect is an error, not followed. A read-only probe of 413 GET operations on a test tenant met no redirect.
  • DecodeOrgID converts only organization IDs. The base64 ID of a person or another object is no longer taken for an org UUID.

Commits

  1. The transport moves to pkg/webexapi and pkg/aiagent, with internal/client and internal/config on top. This commit builds and passes every test, golden files included, on its own.

  2. The operation table and internal/apicmd replace the generated commands.

  3. Docs:

    • AGENTS.md: the layout, the pkg/ rule and the key files;
    • a README section;
    • a site page, "Go SDK", with an example.
  4. Design review fixes, from a design review of the SDK:

    • no redirects;
    • one checked request builder;
    • the org ID table;
    • one name per route.

    Follow-ups the review found that this PR doesn't change are Decide paging from the route and response, not the CLI command name #32 to Add a timeout, a response size limit, and other safer HTTP defaults #37.

Checks

  • Golden files: go test -run Golden . passes with no update. All 6,196 recorded runs are unchanged, covering every command's flags, help, use line and request, uploads, downloads, searches, later pages and the 5 unreachable commands.
  • Test suites: go vet ./..., go test -p 1 ./... and the 90 codegen tests pass. make codegen is idempotent, and the docs site builds.
  • New SDK tests:
    • the 26 paging tests, moved to pkg/webexapi and run without the CLI;
    • Send: 401 refresh, 429 limits, 451, redaction, BeforeSend and headers;
    • redirects never followed for GET or DELETE, on the same origin or another, and a redirected list failing; - hosts and org IDs, including a person's ID that is not decoded;
    • the table's consistency, Call/All, request building and argument checks;
    • Call/All redacting AI Agent Studio responses;
    • BotToken;
    • the import rule.
  • New codegen tests: an unclassified org parameter stops codegen; webexapis.com org parameters are not converted; a route with differing listings gets one combined name; a parameter in two places, or two routes spelled alike, are not exported.
  • Live on a test tenant, main against this branch. Output was compared, not printed.
    • Reads, 13 commands in all six areas, including --paginate, CC, SCIM, identity-org get, a CDR read and cc ai-agent list, give identical output. The only differences are values Webex changes on every call: an org's created time, which differs between two main runs too, and AI Agent Studio's transaction_id.
    • Errors match apart from Webex's tracking IDs.
    • --dry-run writes print the same request on both builds: a body from flags, a raw body, a path-only DELETE, a SCIM write on the identity host, a multipart upload, and an AI agent call that looks up its token first. Nothing was sent.
  • The docs example, built as its own module outside the repo, depends only on pkg/webexapi, pkg/webexops and pkg/aiagent. It lists the same 8 CC teams as webex cc team list --paginate.

Not in this PR

  • Anything only Studio needs: catalog, resource types, guard, change sets, fake API and Terraform naming.
  • New behaviour, such as Contact Center pacing.
  • Auth, output, the config file and MCP, which stay CLI concerns.

🤖 Generated with Claude Code

edumansky and others added 3 commits November 17, 2026 15:17
pkg/webexapi sends requests the way the CLI did: the bearer token, one refresh
after a 401, waits for a 429's Retry-After within limits, errors that carry the
failed response, fail-closed list paging, the hosts of each data region and
Contact Center data center, org ID conversion and multipart bodies. It holds no
process-wide state and takes a context on every call. pkg/aiagent looks up an
AI agent's runtime token and redacts Studio credentials.

internal/client now builds a webexapi.Client from the command line: --debug,
--dry-run, read-only mode and the rate-limit message are its hooks, and a 451
keeps its CLI advice. The paging tests move with the pager. pkg/imports_test.go
keeps pkg/ free of CLI code. The golden files are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
codegen now writes pkg/webexops: one exported *Operation per API call, with its
route, host, parameters, body fields, paging and CLI names, and Call and All to
send it through a webexapi.Client. internal/apicmd builds the same commands
from the table that the generated cobra files declared, so those 202 files are
gone. Every command keeps its flags, help and request: the golden files are
unchanged. The read-only check finds query POSTs in the table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@edumansky edumansky left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex review (gpt-6.2-astra, reasoning effort: high)

The CLI golden tests and all 78 Python tests passed, but they do not cover the new SDK's host validation, redaction, error types, or operation-name stability. The full Go suite could not complete because the sandbox denied loopback listeners.

Comment thread pkg/webexapi/hosts.go Outdated
func CCHost(ccRegion string) string { return "https://api.wxcc-" + ccRegion + ".cisco.com" }

// AIAgentHost is AI Agent Studio's base URL in a Contact Center data center.
func AIAgentHost(ccRegion string) string { return "https://studio.aiagent-" + ccRegion + ".cisco.com" }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Validate the Contact Center region before building SDK hosts

The CLI checks the region against its supported data centers, but SDK callers go directly through HostsFor, CCHost, or AIAgentHost. If a region read from configuration contains URL delimiters, concatenation can produce a host outside cisco.com; the client then sends its bearer token there. Check the region against a fixed allowlist before constructing either host, and fail closed for invalid input. This keeps the SDK's regional host selection safe without relying on CLI validation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9140b4d. HostsFor now returns (Hosts, error) and refuses a Contact Center data center that is not in CCRegions. The exported CCHost/AIAgentHost helpers are gone, so no SDK path puts the region into a host unchecked. internal/config takes its hosts from HostsFor. Test: TestHostsForRefusesAnUnknownContactCenterRegion, with us1.example.com/#, xx9 and US1.

Comment thread pkg/webexapi/errors.go
shown := e.shown
if shown == nil {
shown = e.Body
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Honor a redactor that suppresses the entire error body

If a caller's Request.Redact returns nil to suppress a sensitive response, APIError.Error() falls back to the original body and logs up to 500 bytes of it. attempt already sets shown to the original body when no redactor is configured, so distinguish that case from an intentionally empty result. A test should verify that a nil-returning redactor leaves no response content in the error string.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9140b4d. APIError records whether the request had a redactor, and Error() shows exactly what the redactor returned, an empty result included. Without a redactor it shows the body. Test: TestARedactorThatReturnsNothingHidesTheWholeBody.

Comment thread codegen/generate_cli.py Outdated
base, n = op_id, 2
while op_id in used_ids:
op_id, n = f'{base}_{n}', n + 1
used_ids.add(op_id)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Bind colliding SDK identifiers to stable routes

The numeric suffix depends on collection order. Today CallingCallSettingsForMeUpdateSequentialRingUser2 addresses the criteria-by-ID PUT, while its _2 sibling addresses the settings PUT. If a refresh reorders or removes the first entry, existing Go code can still compile but update settings instead of a criterion. Pin the identifiers for these collisions by method and route, following the project's route-based naming convention, and test that reordering the endpoints preserves the mapping.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9140b4d. The collections list some routes twice under different commands; for example, GET …/priorityAlert is both get-priority-alert and get-priority-alert-2. So the pinned names in OPERATION_IDS (codegen/naming_overrides.py) are keyed by method, path and CLI command. The five criteria operations are pinned, such as CallingCallSettingsForMeGetPriorityAlertCriterion, and their duplicates keep their own names. Codegen now stops on any collision that is not pinned, instead of adding _2. Tests: OperationIDTest.test_colliding_operations_are_named_by_route_in_any_order, which runs both orders, and test_a_collision_without_route_names_stops_generation.

Comment thread pkg/webexapi/client.go
}
if c.MaxRetryWait > 0 && waited+wait > c.MaxRetryWait {
return resp, fmt.Errorf("rate limited (429): retry wait of %s would exceed max-retry-timer of %s — try again after %s",
(waited + wait).Round(time.Second), c.MaxRetryWait.Round(time.Second), wait.Round(time.Second))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve the typed API error when 429 retries stop

Both retry-limit exits replace the *APIError from attempt with a plain formatted error. With the zero-value client this happens on the first 429. In particular, All returns only the error, so an SDK consumer cannot use errors.As to distinguish rate limiting from other failures or inspect the failed response. Keep the retry diagnostic while making the underlying SDK APIError available through unwrapping.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9140b4d. Both retry-limit exits return a RateLimitError with the same message, and it unwraps to the 429's *APIError, so errors.As works through All too. Test: TestAnExhaustedRateLimitStillUnwrapsToTheAPIError, which checks both the unwrap and the unchanged message.

Comment thread codegen/generate_cli.py Outdated
lines.append(f'{indent3}req.PathParam("{p["name"]}", {var})')

# Query params
'orgUUID': p['name'] == 'orgId' and path.startswith(('/identity/scim/', '/identity/organizations/')),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Mark UUID organization parameters in the SDK table

CcTeamList and AdminOrgContactsList both require UUIDs, but their generated orgid parameters have OrgUUID unset. Passing a base64 Webex organization ID therefore sends it unchanged, unlike the same CLI call, where the root command decodes it. Set the metadata for the UUID parameters already identified by needs_uuid_orgid, and apply conversion to query parameters where appropriate, so consumers get the same request behavior as the CLI.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9140b4d. Codegen marks OrgUUID on the path and query orgid parameters of every route that takes the UUID (needs_uuid_orgid), and Request converts query parameters too. CcTeamList and AdminOrgContactsList are now marked. The CLI already sends the UUID, so the golden files are unchanged. Tests: TestOrgParametersThatTakeTheUUIDAreMarked, which checks every CC operation and the contacts list and converts a base64 ID in path and query, plus the codegen FlagTest.

Comment thread pkg/webexops/operation.go Outdated
func Groups(areaName string) []Group { return areas[areaName].groups }

// Operations lists an area's operations, in collection order.
func Operations(areaName string) []*Operation { return areas[areaName].operations }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Return independent slices when listing groups and operations

Groups and Operations expose the registry's backing slices. A consumer that sorts the returned operations for display changes the collection order seen by every later caller; filtering in place can overwrite entries altogether. Return copies of the slices and document whether the pointed-to descriptors are read-only. This matters for the SDK's no process-wide state guarantee, even when callers never modify an Operation itself.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9140b4d. Groups and Operations return slices.Clone copies, and their docs say the operations they point to are shared and must not be changed. Test: TestListingsAreCopies.

Comment thread pkg/webexapi/client.go Outdated
if r.Redact != nil {
shown = r.Redact(data)
}
return resp, &APIError{Status: resp.Status, Body: data, shown: shown}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep in-place redaction from changing the returned response

Response.Body and the slice passed to Redact share storage. An SDK redactor that masks credentials in place also changes the response returned to its caller, despite Request.Redact promising that the response keeps the body as received. Give the callback a separate buffer and test with a redactor that edits its argument.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9140b4d. Redact now gets bytes.Clone(data), so an in-place redactor can't change Response.Body. Test: TestARedactorThatEditsItsArgumentLeavesTheResponse.

Comment thread pkg/webexapi/multipart.go Outdated
if strings.ContainsAny(name, "\r\n") {
return Multipart{}, fmt.Errorf("attachment filename must not contain newlines")
}
data, err := io.ReadAll(io.LimitReader(f, limit+1))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Avoid silently encoding an empty file at the maximum size limit

MultipartFile now accepts a caller-supplied int64 limit. If a caller passes math.MaxInt64 to allow any regular file, limit+1 overflows, LimitReader immediately returns EOF, and a nonempty attachment is encoded as a zero-byte file without error. Handle that limit without adding one, or reject it explicitly before reading.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9140b4d. When the limit is math.MaxInt64, MultipartFile reads the file without a LimitReader. Any other limit still reads one byte past it, to catch a file that grew after Stat. Test: TestMultipartFileWithTheLargestLimitKeepsTheFile.

Comment thread internal/client/request.go Outdated
return webexapi.Request{
Method: r.method,
URL: webexapi.WithQuery(r.url(), r.query()),
Body: []byte(r.bodyRaw),

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Avoid copying large multipart bodies back into bytes

Handwritten uploads convert the SDK's encoded bytes to a string in setMultipart, then sdkRequest copies that string back into a byte slice. For a supported 100 MiB message attachment, this allocates another roughly 100 MiB merely to send an already encoded body; the previous strings.Reader sent it without that copy. Retain the SDK multipart bytes through dispatch and keep the diagnostic summary separate.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9140b4d. client.Request keeps the SDK's encoded multipart bytes in bodyBytes and sends them without a string round trip; the summary stays separate for diagnostics. SetBodyRaw clears them. Test: TestMultipartBodyIsSentWithoutCopying, which checks that two sends share the same backing array. The multipart tests that read the body now read the bytes that are sent.

Comment thread site/src/content/docs/sdk.mdx Outdated
| Package | What it does |
|---|---|
| `pkg/webexapi` | Sends requests: the bearer token, one refresh after a 401, waits for a 429's `Retry-After`, and errors that carry the failed response. Reads lists to their end, and fails rather than return part of a list. Names the hosts for each data region and Contact Center data center, and converts organization IDs. |
| `pkg/webexops` | Every operation the CLI has, generated from Cisco's Postman collections. Each is an exported `*Operation` with its route, host, parameters, body fields and paging. `Call` sends one; `All` reads a list to its end. |

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Document which CLI operations the SDK table excludes

The table does not contain every CLI operation: the generator explicitly skips messaging messages create, Contact Center search, and several Calling uploads. Someone following this page to send a message will not find the advertised exported operation. Qualify the coverage here and in the README, identifying the handwritten command exceptions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9140b4d. The SDK page no longer says "every operation". It lists the handwritten commands that are not in the table: message create, the Calling and CC uploads, the downloads, and cc search. It also points to EncodeMultipart/MultipartFile for building those requests. The README says the same in short.

- HostsFor refuses a Contact Center data center that is not in CCRegions, since it
  becomes part of the host the token is sent to.
- APIError shows exactly what Redact returned, an empty body included, and
  Redact gets a copy, so the Response keeps the body as received.
- A 429 that is not retried further returns a RateLimitError that unwraps to the
  APIError, with the same message.
- Contact Center and contacts orgid parameters are marked OrgUUID, and Call
  converts query parameters too.
- Operations whose CLI names collide are named by route and command in
  OPERATION_IDS; codegen stops on any other collision.
- Groups and Operations return copies.
- MultipartFile reads a file whole when the limit is MaxInt64.
- Handwritten uploads send the encoded multipart bytes without another copy.
- The SDK page and README name the handwritten commands the table leaves out.

The golden files are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@edumansky

Copy link
Copy Markdown
Contributor Author

Codex review: outcome

Codex (gpt-6.2-astra, reasoning effort: high) reviewed 1be4ddc and made ten points. I checked each one against the code and confirmed it was real. All ten are fixed in 9140b4d.

# Finding Outcome Test
1 [P1] CC region not validated before building hosts Fixed: HostsFor returns an error for a data center not in CCRegions, and the host-building helpers are no longer exported TestHostsForRefusesAnUnknownContactCenterRegion
2 [P1] A redactor returning nil exposes the body Fixed: APIError shows exactly the redactor's result TestARedactorThatReturnsNothingHidesTheWholeBody
3 [P2] Colliding operation names depend on collection order Fixed: named by method, path and CLI command in OPERATION_IDS. Codegen stops on any other collision. OperationIDTest
4 [P2] The 429 limit error drops the typed APIError Fixed: RateLimitError, with the same message, unwraps to it TestAnExhaustedRateLimitStillUnwrapsToTheAPIError
5 [P2] UUID org parameters not marked Fixed: path and query orgid parameters are marked OrgUUID, and both are converted TestOrgParametersThatTakeTheUUIDAreMarked, codegen FlagTest
6 [P2] Groups/Operations share the backing slices Fixed: they return copies TestListingsAreCopies
7 [P2] An in-place redactor changes the response Fixed: the redactor gets a copy TestARedactorThatEditsItsArgumentLeavesTheResponse
8 [P2] A MaxInt64 limit encodes an empty file Fixed: no LimitReader at that limit TestMultipartFileWithTheLargestLimitKeepsTheFile
9 [P2] Multipart bodies copied again before sending Fixed: the encoded bytes are sent as they are TestMultipartBodyIsSentWithoutCopying
10 [P3] Docs say the table has every CLI operation Fixed: the SDK page and README list the handwritten commands it leaves out —

Each test was written first and failed before its fix. The pinned names showed one more thing: the collections list many routes twice under different commands. So a route alone doesn't identify an operation, and the pins are keyed by route and command.

Checks after the fix:

  • go test -run Golden . passes with no update. OrgUUID conversion is a no-op for the CLI, which already sends the UUID.
  • go vet ./..., go test -p 1 ./..., the 80 codegen tests and the docs site build pass. make codegen is idempotent.
  • The docs example, updated for the new HostsFor signature, still lists the same 8 CC teams live.

Environmental: Codex couldn't finish the full Go suite in its sandbox, because the sandbox denies loopback listeners. The suite passes locally and in CI.

🤖 Generated with Claude Code

@edumansky edumansky left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex review, round 2 (gpt-6.2-astra, reasoning effort: high)

The CLI golden tests passed, but the new public SDK cannot express some documented requests and can discard redaction or cancellation information on error paths. The full Go suite could not complete because the sandbox prohibited local test servers from binding ports.

Comment thread codegen/generate_cli.py Outdated
@@ -366,307 +264,213 @@ def generate_command(ep, group_var, base_url_expr, is_calling, redact=False, pri
p['name'] = 'orgid'

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve API parameter names in generated SDK operations

AdminOrgContactsGet documents orgId as its URI parameter, but the generator renames it to orgid. An SDK caller following the API documentation and passing Args.Params["orgId"] therefore sends a literal {orgid} path segment instead of the organization ID. Keep the API name for lookup and retain orgid separately as the CLI flag name; make the correction in the generator rather than the generated table, per AGENTS.md:20.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 42c9232. The generator no longer rewrites {orgId} to {orgid} in the path, and it records the parameter under its API name, orgId. Only the CLI flag is still --orgid. So AdminOrgContactsGet takes Args.Params["orgId"]. Paths whose collection itself writes {orgid} keep it. The read-only list of query POSTs follows the template (/v1/{orgId}/functions/{id}:export), and TestQueryPOSTPathsMatchRequests checks the list against the table. Tests: TestParametersHaveTheirAPINames, plus the codegen FlagTest and AiAgentStudioTest. The golden files are unchanged.

Comment thread pkg/webexops/operation.go
case InPath:
path[p.Name] = v
case InQuery:
query.Set(p.Name, v)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Allow SDK calls to send repeated query parameters

The Admin collection specifies eventCategories twice in the List Admin Audit Events request, but Args.Params holds only one string per name and query.Set replaces any previous value. Consequently, webexops.Call and All cannot express the documented two-category filter. Allow multiple query values in SDK arguments while preserving the CLI's existing single-value request, which is pinned by the golden tests.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 42c9232. Args.Query (url.Values) gives a query parameter its values when it is sent more than once, in place of its value in Params. The CLI doesn't use it, so its single-value requests are unchanged. Test: TestAQueryParameterCanBeSentMoreThanOnce, which sends eventCategories twice.

Comment thread pkg/webexapi/client.go Outdated
}

if resp != nil && resp.Status == http.StatusUnavailableForLegalReasons {
return resp, newWrongRegionError(resp.Body)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Extract the 451 endpoint from the redacted response

On a 451, attempt applies Request.Redact, but Send discards that error and extracts the endpoint from the original response body. Even a redactor that returns an empty body can therefore have a hostname it removed printed by WrongRegionError.Error(). Use the redacted view for the displayed endpoint and keep the original bytes on Response for callers that need them.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 42c9232. Send now takes a 451's endpoint from what the request's Redact left (APIError.shownBody). WrongRegionError.Body and the Response keep the body as received. Test: TestA451NamesOnlyWhatTheRedactorLeaves.

Comment thread pkg/webexapi/client.go Outdated
apiErr, _ := err.(*APIError)
if retries >= c.MaxRetries {
return resp, &RateLimitError{err: apiErr, msg: fmt.Sprintf("rate limited (429): retry limit reached after %d attempts — try again after %s",
retries, wait.Round(time.Second))}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve body-read errors when handling a 429

If the request context expires after the 429 headers arrive but before the body finishes, attempt returns a response and a wrapped read error, not an *APIError. With the default MaxRetries == 0, this unchecked assertion replaces that error with a RateLimitError whose Unwrap returns nil. Callers lose both the cancellation cause and the promised typed API error. Check the error type before applying the retry policy and preserve the read error when the response was incomplete.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 42c9232. At either retry limit, a 429 whose error is not an *APIError (its body could not be read) now returns that error unchanged, and so does a 451. Below the limit a 429 is still retried, as before. Test: TestA429WhoseBodyCannotBeReadKeepsTheReadError, where the server declares 100 bytes and sends 5.

Comment thread pkg/webexapi/hosts.go Outdated
ccRegion = DefaultCCRegion
}
if !slices.Contains(CCRegions, ccRegion) {
return Hosts{}, fmt.Errorf("unknown Contact Center data center %q; use one of %s", ccRegion, strings.Join(CCRegions, ", "))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep the host-validation allowlist private

HostsFor validates against the exported, writable CCRegions slice. An SDK consumer filtering that slice in place for a region picker can change which data centers every other client accepts, or make the default us1 fail validation. Keep validation backed by a private list and return a copy for display, consistent with the SDK's no process-wide state rule.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 42c9232. HostsFor checks a private ccRegions. The exported CCRegions is a copy for display. Test: TestChangingCCRegionsDoesNotChangeWhatHostsForAccepts, which changes CCRegions[0]: the default us1 is still accepted, and the changed value is not.

Comment thread pkg/webexops/operation.go Outdated
}

// Groups lists an area's groups, in collection order. The list is a copy.
func Groups(areaName string) []Group { return slices.Clone(areas[areaName].groups) }

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Clone group aliases when returning group metadata

Groups copies each Group but not its Aliases backing array. A caller editing the returned alias for the CC flow group changes what subsequent callers see, despite the copy guarantee and the SDK's state-isolation rule. Clone each group's aliases as well, and extend TestListingsAreCopies to mutate an alias rather than only replacing a whole group.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 42c9232. Groups clones each group's Aliases. TestListingsAreCopies now changes the CC flow group's alias and checks that the next listing still says flows.

- Org parameters keep their API name (orgId) and path template in the table;
  only the CLI flag is --orgid. The read-only query list follows the template.
- Args.Query sends a query parameter more than once.
- A 451 names only an endpoint the request's Redact leaves, and keeps the
  response body as received.
- A 429 or 451 whose body could not be read returns the read error.
- HostsFor checks a private list, so changing CCRegions cannot change it.
- Groups clones each group's aliases.

The golden files are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@edumansky

Copy link
Copy Markdown
Contributor Author

Codex review, round 2: outcome

Codex (gpt-6.2-astra, reasoning effort: high) reviewed 9140b4d and made six points. I checked each one against the code and confirmed it was real. All six are fixed in 42c9232.

# Finding Outcome Test
1 [P2] SDK parameters lose their API names Fixed: the table keeps orgId and its path template, and only the CLI flag is --orgid. The read-only query list follows the template. TestParametersHaveTheirAPINames, codegen FlagTest/AiAgentStudioTest, TestQueryPOSTPathsMatchRequests
2 [P2] A query parameter can't be sent twice Fixed: Args.Query TestAQueryParameterCanBeSentMoreThanOnce
3 [P2] A 451 takes its endpoint from the unredacted body Fixed: it takes the endpoint from what Redact leaves, and keeps the raw body on the response TestA451NamesOnlyWhatTheRedactorLeaves
4 [P2] A 429 read error is lost at the retry limit Fixed: the read error is returned; the same goes for a 451 TestA429WhoseBodyCannotBeReadKeepsTheReadError
5 [P2] Host validation uses the writable CCRegions Fixed: it uses a private list, and CCRegions is a display copy TestChangingCCRegionsDoesNotChangeWhatHostsForAccepts
6 [P3] Group aliases are shared Fixed: aliases are cloned TestListingsAreCopies

Each test failed before its fix.

Checks after the fix:

  • go test -run Golden . passes with no update, so the CLI's requests are unchanged.
  • go vet ./..., go test -p 1 ./... and the 80 codegen tests pass, and make codegen is idempotent.
  • Live on a test tenant, main against this build:
    • Reads give identical output, apart from AI Agent Studio's per-request transaction_id and Webex's tracking ID in an error.
    • All six kinds of --dry-run write print the same request.

Environmental: Codex couldn't run the full Go suite in its sandbox, because the sandbox prohibits local listeners. It passes locally and in CI.

🤖 Generated with Claude Code

@edumansky edumansky left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex review, round 3 (gpt-6.2-astra, reasoning effort: high)

The command golden tests and Python codegen tests pass, but a collection reorder can silently redirect an existing SDK write to a different endpoint. The SDK also handles the same organization ID differently depending on which query input the caller uses.

Comment thread codegen/generate_cli.py Outdated
host_of = resolve_base_url(collection_name, ep['path'], host)
key = (ep['method'], ep['path'], ep['command'])
op = operation(ep, collection_name, host_of, is_calling, paging_overrides)
op_id = OPERATION_IDS.get(collection_name, {}).get(key) or go_identifier(area, group, ep['command'])

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Bind exported operation names to stable routes

A collection reorder can silently change which endpoint compiled SDK code calls. Reversing the committed Call Park collection entries switches CallingCallParkUpdate from PUT .../callParks/{callParkId} to PUT .../callParks/settings: extraction reassigns update and update-2, and both Go identifiers still compile. Pin SDK names for these collisions by method and route, independently of the CLI suffix, and test reordering before extraction rather than after names have been assigned. This follows the repository’s route-based naming convention.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b006aaa. You were right that pinning by route plus CLI command didn't go far enough, because extraction renumbers the commands themselves.

operation_ids in codegen/generate_cli.py now names every member of a numbered family (update, update-2, …) by the family's command plus the part of its own route after the family's common path. So PUT …/callParks/{callParkId} is CallingCallParkUpdateByCallParkId, and PUT …/callParks/settings is CallingCallParkUpdateSettings, whichever command number each one gets.

  • A route listed twice gets _2, which reaches the same endpoint either way.
  • Two different routes that would share a name stop generation.
  • OPERATION_IDS is removed.

That covers 184 operations in 86 families. Tests: OperationIDTest.test_names_stay_with_their_routes_when_extraction_renumbers_commands, which swaps the command names between the two Call Park routes as extraction would, plus tests for a repeated route and for a family on one path.

Comment thread pkg/webexops/operation.go
}
for k, vs := range args.Query {
query[k] = vs
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Normalize organization IDs supplied through Args.Query

CcSubscriptionsListV1 converts a base64 orgId to a UUID when supplied through Args.Params, but sends the same ID unchanged through Args.Query. The final query assignment bypasses Param.OrgUUID, so SDK callers using url.Values can send the wrong organization ID format to Contact Center. Apply the conversion to each overriding value for marked query parameters without mutating the caller’s slice. See the SDK org ID conversion contract.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b006aaa. Values in Args.Query for a query parameter marked OrgUUID are now converted on a clone, so the caller's url.Values is unchanged. TestOrgParametersThatTakeTheUUIDAreMarked now sends a base64 orgId through Args.Query, and checks both the UUID in the URL and the caller's unchanged value.

Comment thread internal/aiagent/aiagent.go Outdated
return a.Token, nil
}
return "", fmt.Errorf("AI agent %s not found in organization %s", agentID, orgID)
return aiagent.BotToken(context.Background(), client.API("/api/v2/organizations/{orgid}/agents/", ""), studioURL(), orgID, agentID)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Preserve region guidance when agent token lookup fails

If Studio returns 451 during the preliminary agent-token lookup, this wrapper now returns the SDK error directly. apicmd.NewCommand returns that lookup error before reaching its client.CLIError handling, so this path loses the CLI’s region guidance even though the main operation still gets it. Translate the wrapped WrongRegionError at the CLI adapter boundary and direct Studio users to --cc-region, which selects the Studio host.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b006aaa. internal/aiagent.BotToken passes its error through client.CLIError. That function now puts the CLI's 451 message in place of the SDK's wherever the error is wrapped, so the result reads "looking up AI agent a1: wrong data region (451)… rerun with --region …", as on main. I kept main's --region wording rather than switching to --cc-region, so this restores the old behaviour exactly. Test: TestBotTokenGivesTheCLIsAdviceForTheWrongRegion.

Comment thread site/src/content/docs/sdk.mdx Outdated

- **Retries:** only a 401 (once, after `Refresh`) and a 429 are retried. A 5xx or a broken connection may follow a write that was carried out, so it is returned, not repeated. A 429 that is not retried further returns a `RateLimitError`, which unwraps to the `APIError`.
- **Hosts:** `HostsFor` refuses a Contact Center data center that is not in `CCRegions`, since it becomes part of the host the token is sent to.
- **Paging:** each list's paging was derived from its collection and, where Webex differs, measured against a live organization. A list that can't be read to its end returns `webexapi.ErrIncompleteList`.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Clarify which paging failures match ErrIncompleteList

The SDK guide says a list that cannot be read to its end returns ErrIncompleteList, but if page two returns HTTP 500, All returns the APIError directly; cancellation likewise returns a context or transport error. A caller following this guidance would miss those failures with errors.Is(err, webexapi.ErrIncompleteList). Distinguish the fail-closed guarantee—All returns no partial items—from the sentinel, which identifies inconsistent paging responses.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b006aaa. The SDK page now says that All and Visit fail rather than return part of a list. A failed request returns its own error, such as an APIError or the context's error. Only responses that don't page as expected match ErrIncompleteList: for example, a missing item array or total, a repeated page, or a next link to another host.

- Commands that extraction numbers (update, update-2) can swap numbers when a
  collection is reordered, so their operations are now named by the family's
  command and the rest of their route, such as CallingCallParkUpdateByCallParkId
  and CallingCallParkUpdateSettings. A name can no longer move to another route;
  a route listed twice gets _2. OPERATION_IDS is no longer needed.
- Args.Query converts org IDs for parameters that take the UUID, without
  changing the caller's values.
- A 451 during the AI agent token lookup gives the CLI's region advice again,
  after its context.
- The SDK page says which paging failures match ErrIncompleteList.

The golden files are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@edumansky

Copy link
Copy Markdown
Contributor Author

Codex review, round 3: outcome

Codex (gpt-6.2-astra, reasoning effort: high) reviewed 42c9232 and made four points. I checked each one against the code and confirmed it was real. All four are fixed in b006aaa.

# Finding Where it came from Outcome Test
1 [P1] A collection reorder can move an operation's name to another route New SDK surface. The CLI's numbered command names have always moved this way. Fixed: numbered families (184 operations) are named by command and route remainder, and OPERATION_IDS is removed OperationIDTest (3 tests)
2 [P2] Args.Query skips org ID conversion New in round 2 Fixed: converted on a copy TestOrgParametersThatTakeTheUUIDAreMarked
3 [P3] The agent token lookup lost the CLI's 451 advice A regression from this PR; main gave it Fixed: CLIError puts the CLI message in place of the SDK's within any wrapping error, with main's wording TestBotTokenGivesTheCLIsAdviceForTheWrongRegion
4 [P3] The docs overstate ErrIncompleteList New docs Fixed: they separate fail-closed paging from the sentinel —

Each test failed before its fix.

Checks after the fix:

  • go test -run Golden . passes with no update.
  • go vet ./..., go test -p 1 ./... and the 81 codegen tests pass, make codegen is idempotent, and the site builds.
  • The docs example still builds and lists the same 8 CC teams live.

Environmental: Codex's sandbox can't run the Go tests that open local listeners. They pass locally and in CI.

🤖 Generated with Claude Code

@edumansky edumansky left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex review, round 4 (gpt-6.2-astra, reasoning effort: high)

The CLI golden tests passed, but collection refreshes can silently change the route or parameters behind an exported SDK name. The SDK also misses a documented UUID conversion and loses cancellation errors during token refresh.

Comment thread codegen/generate_cli.py
for base, members in families.items():
if len(members) == 1:
ids[members[0]] = go_identifier(area, group, endpoints[members[0]]['command'])
continue

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep exported operation names bound to routes when a family shrinks

MeetingsInviteesCreateMeeting currently sends POST /meetingInvitees. If a collection refresh removes that route but retains /meetingInvitees/bulkInsert, extraction names the remaining command create-meeting, and this singleton branch gives it the removed operation’s Go name. Existing SDK callers still compile but now send their single-invitee payload to the bulk endpoint. Bind published IDs to method and path independently of which sibling routes remain, and test removal as well as reordering in the weekly refresh workflow.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 57caaf9. Any name derived from the CLI's command names can move, so names are now recorded. codegen/operation_names.json holds every published Go name with the operation it names: group, method and path. operation_ids keeps a recorded operation's name, and never gives a new operation a name that was ever published, even one whose route is gone. In your example, the surviving bulk route keeps its own name, and MeetingsInviteesCreateMeeting is retired, so code that used it fails to build. Test: OperationIDTest.test_a_removed_routes_name_goes_to_no_other_route, which removes a route and runs again with the same record. Every current name is unchanged.

Comment thread codegen/generate_cli.py Outdated
raise SystemExit(f"{ep['method']} {ep['path']} and {routes[name][0]} {routes[name][1]} would both be "
f"named {name} in pkg/webexops; extend operation_ids in codegen/generate_cli.py.")
seen[name] = seen.get(name, 0) + 1
ids[i] = name if seen[name] == 1 else f'{name}_{seen[name]}'

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Distinguish same-route operations with different parameters

Collection order still determines the _2 suffix even when the two entries have different request contracts. For example, CallingWorkspacesGet_2 declares includeCapabilities, but CallingWorkspacesGet does not. Reversing those entries leaves callers compiling against _2 while Operation.list silently drops Args.Params["includeCapabilities"]. Give distinguishable variants stable IDs and test reordering two entries with different parameter sets, as those parameters are part of the published operation table.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 57caaf9. A route that a group lists more than once is now identified by its place among those listings, ordered by their parameter names, not by collection order. CallingWorkspacesGet_2 stays on the listing with includeCapabilities whichever way round the collection lists them. A later new parameter doesn't rename an operation, because a route listed once is identified by group, method and path alone. Tests: test_listings_of_one_route_keep_their_names_by_their_parameters, which swaps the command names and order, and test_a_new_parameter_keeps_the_name.

Comment thread codegen/generate_cli.py Outdated
params.append({
'name': p.get('_api_name', p['name']), 'in': 'InQuery',
'flag': flag_for(p['name'], camel_to_kebab(p['name'])), 'usage': p.get('description', ''),
'orgUUID': needs_uuid_orgid and p['name'] == 'orgid',

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Mark Slido’s sessionOrgId query parameter as a UUID

Both Meetings operations for GET /slido/compliance/events describe sessionOrgId as a “Webex organization UUID,” but this condition leaves OrgUUID false. An SDK caller supplying a base64 Webex org ID therefore sends it unchanged, whether using Args.Params or Args.Query. Mark this route’s parameter in the generator rather than the generated table and verify that both argument forms send the decoded UUID.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 57caaf9. The generator's new UUID_ORG_PARAMS table marks Meetings' sessionOrgId as OrgUUID on both /slido/compliance/events operations, the only two that have it. Request already converts a marked query parameter from Params and, since the last round, from Query. Test: FlagTest.test_slidos_session_org_takes_the_uuid.

Comment thread pkg/webexapi/client.go
resp, err := c.attempt(ctx, r)
if resp != nil && resp.Status == http.StatusUnauthorized && c.Refresh != nil {
if c.Refresh(ctx) != nil {
return resp, err

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve context cancellation during token refresh

If the caller’s deadline expires while Refresh(ctx) is running after a 401, Send discards the refresh error and returns only the earlier APIError. Callers cannot detect cancellation with errors.Is and may treat a timed-out request as an authentication failure. When the context is done, return its error alongside the received response; ordinary refresh failures can retain the existing 401 behavior. This matters for the SDK’s per-call context contract.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 57caaf9. When Refresh fails and the context is done, Send returns ctx.Err() with the 401 response. Any other refresh failure still returns the 401's APIError. Test: TestARefreshCutOffByTheContextReturnsTheContextError.

- codegen/operation_names.json records every published Go name with the
  operation it names: group, method, path, and for a route listed more than once
  its place among those listings ordered by parameters. A recorded operation
  keeps its name; a new one never takes a name that was published, so a name
  cannot move to another route when a family shrinks or listings swap. Adding a
  parameter keeps a name. Every current name is unchanged.
- Slido's sessionOrgId is marked as taking the org UUID.
- A refresh cut off by the caller's context returns the context's error.

The golden files are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@edumansky

Copy link
Copy Markdown
Contributor Author

Codex review, round 4: outcome

Codex (gpt-6.2-astra, reasoning effort: high) reviewed b006aaa and made four points. I checked each one against the code and confirmed it was real. All four are fixed in 57caaf9. All four are about the new SDK; none changes the CLI.

# Finding Outcome Test
1 [P2] A name can move to another route when a family shrinks Fixed: codegen/operation_names.json records each published name with its operation, and names are never reused test_a_removed_routes_name_goes_to_no_other_route
2 [P2] Listings of one route with different parameters swap with order Fixed: told apart by their parameters; a new parameter keeps a name test_listings_of_one_route_keep_their_names_by_their_parameters, test_a_new_parameter_keeps_the_name
3 [P2] Slido's sessionOrgId is not marked as taking the UUID Fixed: UUID_ORG_PARAMS test_slidos_session_org_takes_the_uuid
4 [P2] A refresh cut off by the context hides the context error Fixed TestARefreshCutOffByTheContextReturnsTheContextError

Each test failed before its fix. The record keeps every current name, so the only change to the generated table is the Slido OrgUUID mark. AGENTS.md and the SDK page say how the record works.

Checks after the fix:

  • go test -run Golden . passes with no update.
  • go vet ./..., go test -p 1 ./... and the 85 codegen tests pass, and the site builds.
  • make codegen is idempotent, record included.

Environmental: Codex's sandbox can't run the Go tests that open local listeners. They pass locally and in CI.

🤖 Generated with Claude Code

@edumansky edumansky left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex review, round 5 (gpt-6.2-astra, reasoning effort: high)

The CLI golden tests and Python codegen tests passed, but they do not cover duplicate-listing removal, credential exposure through typed errors, or missing path arguments in direct SDK calls.

Comment thread codegen/generate_cli.py Outdated
identities = [None] * len(endpoints)
for (method, path), listings in routes.items():
for n, i in enumerate(sorted(listings, key=lambda i: parameters(endpoints[i]))):
identities[i] = f'{group} {method} {path}' + (f' #{n + 1}' if n else '')

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep SDK names stable when a duplicate route listing disappears

The ordinal is recomputed from the surviving listings on every refresh. For the current GET /workspaces/{workspaceId} pair, removing the listing with includeCapabilities makes the remaining operation switch from CallingWorkspacesGet to CallingWorkspacesGet_2. Existing callers of _2 still compile, but their includeCapabilities parameter is now silently dropped. Persist a discriminator for each listing rather than just its rank, and test removal as well as reordering, to uphold the published-name guarantee.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c2ec2b6. The record no longer holds a rank. Each entry is the operation's group, method, path and sorted parameter names, numbered only among listings identical in all four, and operation_ids matches entries exactly. So when one listing of GET /workspaces/{workspaceId} is removed, the other keeps its own name. One fallback remains: when a route has a single listing whose parameters changed, and exactly one unclaimed name is recorded for that route, the listing keeps that name, so adding a parameter doesn't rename an operation. In any other case the operation gets a name never published before. Test: test_removing_one_listing_of_a_route_leaves_the_others_name, which removes each listing in turn, along with the existing reorder, swap and new-parameter tests. The record was rebuilt in this form, and every current name is unchanged.

Comment thread pkg/webexapi/client.go
if r.Redact != nil {
// A copy, so a redactor that edits its argument leaves the response as received.
apiErr.shown, apiErr.redacted = r.Redact(bytes.Clone(data)), true
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep Studio credentials out of exported error bodies

When a Studio request fails, Error() is redacted but APIError.Body still contains the credentials. A consumer that serializes the typed error or logs its Body therefore discloses the token; the 451 conversion likewise copies the raw body into WrongRegionError. Keep the original bytes on Response for callers that need them, but use the redacted bytes for exported error fields whenever Request.Redact is set. This preserves the SDK’s Studio credential-redaction responsibility.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c2ec2b6. When the request has a Redact, APIError.Body now holds the redacted body. So does WrongRegionError.Body, which also takes its endpoint from it. Only the Response keeps the body as received. This also simplified APIError, which no longer carries a second copy. Test: TestErrorsHoldOnlyTheRedactedBody, which covers both a 400 and a 451.

Comment thread pkg/webexops/operation.go
v = args.Params[p.Name]
}
if v == "" {
continue

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Reject missing path parameters before sending SDK requests

SDK callers do not pass through Cobra’s required-flag checks. For example, calling CcTeamList without orgid skips the path parameter here, so FillPath leaves {orgid} in place and the client sends an authenticated request to /organization/%7Borgid%7D/v2/team. Have Call and All report the missing path parameter before invoking the transport, so a missing argument produces an actionable local error rather than a misleading API response.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c2ec2b6. webexops.Call and All return an error naming each path parameter that has no value, before anything is sent. Test: TestCallAndAllRefuseAMissingPathParameter, which calls CcTeamList with no orgid and checks that the server sees no request.

The CLI builds its requests with op.Request/op.List and sends them through its client directly, so it still sends an empty path flag exactly as on main, and the golden files are unchanged. Refusing an empty path flag in the CLI too would be a small CLI behaviour change, so I left it as a possible follow-up.

- The names record holds each operation's parameter names with its route, and
  matches them exactly, so removing one listing of a route cannot give its name
  to another. A route's only listing whose parameters changed keeps the one name
  recorded for that route. Every current name is unchanged.
- APIError.Body and WrongRegionError.Body hold the body after the request's
  Redact; the Response keeps it as received.
- webexops.Call and All refuse a path parameter without a value before sending.
  The CLI keeps its requests unchanged by building them with Request and List.

The golden files are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@edumansky

Copy link
Copy Markdown
Contributor Author

Codex review, round 5: outcome

Codex (gpt-6.2-astra, reasoning effort: high) reviewed 57caaf9 and made three points. I checked each one against the code and confirmed it was real. All three are fixed in c2ec2b6, all in the SDK.

# Finding Outcome Test
1 [P2] Removing one listing of a route lets another take its name Fixed: the record holds parameter names with the route and matches them exactly test_removing_one_listing_of_a_route_leaves_the_others_name
2 [P2] APIError.Body keeps Studio credentials Fixed: error bodies are the redacted body, and only the Response keeps the raw one TestErrorsHoldOnlyTheRedactedBody
3 [P2] A missing path argument is sent as {name} Fixed in webexops.Call/All. The CLI keeps its requests as on main; changing that is a possible follow-up. TestCallAndAllRefuseAMissingPathParameter

Each test failed before its fix. The names record was rebuilt in its new form, and every operation name is unchanged.

Checks after the fix:

  • go test -run Golden . passes with no update.
  • go vet ./..., go test -p 1 ./... and the 86 codegen tests pass.
  • make codegen is idempotent, record included.

Environmental: Codex's sandbox can't run the Go tests that open local listeners. They pass locally and in CI.

🤖 Generated with Claude Code

ghost left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex review, round 6 (gpt-6.2-astra, reasoning effort: high)

The CLI golden tests and Python codegen tests passed, but they do not cover several failures in the new SDK: required upload bodies are discarded, redirects bypass the request guard, and a compatible collection update can remove a published Go name. The full Go suite could not be verified because the sandbox denied local test-server listeners.

Comment thread pkg/webexapi/client.go Outdated
if client == nil {
client = http.DefaultClient
}
httpResp, err := client.Do(httpReq)

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Apply the SDK request guard to redirects

BeforeSend runs before client.Do, but Go follows redirects inside Do without invoking the hook again. An SDK caller that uses the hook to allow only a particular origin can therefore send a request to an origin it never approved. This matters for Studio operations because Go does not strip the custom Bot-Access-Token header on cross-host redirects. Apply the guard to redirect requests as well, or reject cross-origin redirects carrying credentials, while preserving the caller's CheckRedirect policy. The CLI also relies on these hooks for request policy (AGENTS.md:50).

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8206fe4. Client now sends through a copy of its HTTP client whose CheckRedirect does three things:

  • runs BeforeSend on each redirect request, so an origin policy sees every request;
  • then defers to the caller's own CheckRedirect, or Go's 10-redirect limit when there isn't one;
  • drops Bot-Access-Token when the redirect goes to another host, since net/http strips Authorization but not custom headers.

An error from BeforeSend stops the redirect, and errors.Is finds it in the returned error. Test: TestRedirectsPassBeforeSendAndLoseTheAgentTokenOnAnotherHost. For the CLI, a redirect now also passes through its debug, read-only and dry-run checks. The old CLI had the same gap, and the golden files don't change.

Comment thread pkg/webexops/operation.go Outdated
}
if op.Body != nil {
l.Body, l.ContentType = args.Body, args.ContentType
}

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve multipart bodies for published upload operations

DeviceDeviceCallUploadBackgroundImage and its Calling counterpart have Body == nil because the collection has no raw JSON example, yet their descriptions explicitly require multipart form data. Even if an SDK caller builds the correct payload with webexapi.EncodeMultipart and supplies both Args.Body and ContentType, this condition silently drops both and sends an empty POST. Represent multipart body support separately from JSON flag availability so these exported operations can send their required payload. Make the metadata change in the generator rather than the generated table (AGENTS.md:20).

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8206fe4. Request/List now send any body given in Args. Operation.Body is now documented as the JSON body the collection gives (nil when it gives none), not as whether a body may be sent. So DeviceDeviceCallUploadBackgroundImage sends a multipart body built with EncodeMultipart. The CLI only sets a body for operations with Body, so its requests are unchanged. Test: TestRequestFillsTheOperation now sends a multipart body through that operation.

Comment thread codegen/generate_cli.py Outdated
if ftype == 'header':
lines.append(f'{indent2}cmd.Flags().StringVar(&{var}, "{flag_name}", "", "{desc_escaped}")')
recorded = [name for name, identity in names.items()
if identity.startswith(route + ' [') and name not in claimed]

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve SDK names when one duplicate listing gains a parameter

Adding an optional query parameter to just the second existing GET /workspaces/{workspaceId} listing changes DeviceWorkspacesGet_2 to DeviceWorkspacesGet_3, breaking downstream builds even though neither operation was removed or renumbered. The first listing matches exactly, but listings[route] > 1 skips reconciliation for the remaining listing. After exact matches, reconcile a single unambiguous unmatched pair rather than requiring the route to have only one listing in total. This preserves the published-name invariant without assigning names by collection order (AGENTS.md:48).

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8206fe4. The fallback in operation_ids now works per route after exact matches. When exactly one listing is left unmatched and exactly one name recorded for that route is left unclaimed, they are paired, whether the route has one listing or several. Test: test_one_of_two_listings_gaining_a_parameter_keeps_its_name, which adds a parameter to the second of two GET /workspaces/{workspaceId} listings and keeps both names.

Comment thread codegen/generate_cli.py
'orgUUID': (needs_uuid_orgid and p['name'] == 'orgid') or
p['name'] in UUID_ORG_PARAMS.get(collection_name, ()),
})
for h in ep.get('extra_headers', []):

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Mark UUID-valued Contact Center query and header parameters

The generated CcSkillProfileCreate converts a base64 organization ID in the orgid path parameter but sends that same ID unchanged in the organizationId query parameter. CcSearchMetadataGet likewise leaves X-ORGANIZATION-ID unconverted. The committed Contact Center collection shows UUID values for both, so callers using Webex organization IDs can send two different representations in one request or send the wrong identifier for delegated access. Mark the UUID-valued query and header parameters in the generator and test the resulting requests (AGENTS.md:20).

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8206fe4. UUID_ORG_PARAMS now marks Contact Center organizationId (query) and X-ORGANIZATION-ID (header) as taking the UUID, matching the UUID examples in the collection, and the generator now applies the table to headers too. That marks CcSkillProfileCreate, CcSearchMetadataGet and the other operations that have them. Request already converts any marked parameter. Test: FlagTest.test_contact_center_organization_id_and_header_take_the_uuid. A CLI user who passes a base64 ID to those flags now gets it converted as well.

Comment thread site/src/content/docs/sdk.mdx Outdated
The CLI is built on a Go SDK that other Go programs can import. It sends requests the way the CLI does: the same hosts, retries, paging and errors. It holds no process-wide state, and every call takes a context.

```bash
go get github.com/Cloverhound/webex-cli

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Install the SDK package instead of the CLI main package

In a fresh consumer module, the documented go get command adds the root CLI's dependency graph to go.mod, including Cobra and the OS keyring. Using go get github.com/Cloverhound/webex-cli/pkg/webexops for this example adds only the Webex module and supplies both packages the example imports. Point readers at the SDK package they need so installation preserves the dependency separation described in AGENTS.md:50.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8206fe4. The SDK page now says go get github.com/Cloverhound/webex-cli/pkg/webexops. It notes that this brings in pkg/webexapi, and that the module root is the CLI, which needs Cobra and the keyring.

- Redirects pass through BeforeSend, then the caller's CheckRedirect, and a
  redirect to another host drops AI Agent Studio's Bot-Access-Token.
- Request sends any body given in Args, so the upload operations the collection
  gives no JSON body for can send their multipart body. The CLI sends a body only
  for operations with one, as before.
- When one listing of a route stays unmatched and one name recorded for the route
  stays unclaimed, they are paired however many listings the route has, so one of
  two listings gaining a parameter keeps its name.
- Contact Center organizationId and X-ORGANIZATION-ID are marked as taking the
  org UUID.
- The SDK page installs pkg/webexops rather than the CLI's module root.

The golden files and every operation name are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@edumansky

ghost commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Codex review, round 6: outcome

Codex (gpt-6.2-astra, reasoning effort: high) reviewed c2ec2b6 and made five points. I checked each one against the code, and for the CC org parameters against the collection's examples, and confirmed it was real. All five are fixed in 8206fe4.

# Finding Outcome Test
1 [P2] Redirects skip BeforeSend Fixed: redirects pass through BeforeSend and then the caller's CheckRedirect, and Bot-Access-Token is dropped on another host TestRedirectsPassBeforeSendAndLoseTheAgentTokenOnAnotherHost
2 [P2] Upload operations drop their body Fixed: a body in Args is always sent TestRequestFillsTheOperation
3 [P2] One of two listings gaining a parameter is renamed Fixed: an unmatched listing and an unclaimed recorded name are paired per route test_one_of_two_listings_gaining_a_parameter_keeps_its_name
4 [P2] CC organizationId and X-ORGANIZATION-ID not marked Fixed in UUID_ORG_PARAMS, now applied to headers too test_contact_center_organization_id_and_header_take_the_uuid
5 [P3] Docs go get the CLI root Fixed —

Each test failed before its fix. Every operation name is unchanged.

Visible in the CLI only in cases the golden files don't cover:

  • A redirect now passes through the CLI's debug, read-only and dry-run checks.
  • A base64 org ID passed to a CC --organization-id or --x-organization-id flag is converted to the UUID.

Checks after the fix:

  • go test -run Golden . passes with no update.
  • go vet ./..., go test -p 1 ./... and the 88 codegen tests pass.
  • make codegen is idempotent, and the site builds.

Environmental: Codex's sandbox can't run the Go tests that open local listeners. They pass locally and in CI.

🤖 Generated with Claude Code

Each operation's Go name is now its area, method and path, such as
CcGetOrganizationByOrgidV2Team or CallingPostTelephonyCallsDial, never its CLI
command name, which the collection's order can change. A name therefore always
means the same request, and nothing has to be recorded to keep it so:
codegen/operation_names.json and its matching rules are gone.

A route the collection lists more than once is exported once when every listing
sends the same request (146 routes) and not at all when they differ (4 routes);
the other listings are unexported, for the CLI's commands. Two routes that would
share a name stop codegen.

The CLI is unchanged: it builds its commands from each entry's area, group and
command, not its Go name. The golden files are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@edumansky

ghost commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Operation names now come from the route

In cd59888, each SDK operation's Go name is built from its area, method and path, instead of its CLI command name.

Examples:

Before Now
CcTeamList CcGetOrganizationByOrgidV2Team
CallingCallParkUpdate CallingPutTelephonyConfigLocationsByLocationIdCallParksByCallParkId
CallingCallControlsDial CallingPostTelephonyCallsDial

Why:

  • Codex's reviews in rounds 1, 3, 4, 5 and 6 each found another way a command-derived name could silently move to a different request. The CLI numbers duplicate commands (update, update-2) in collection order, so the names moved whenever Cisco reordered, removed or changed a listing.
  • A name made from the route can only mean that route. So codegen/operation_names.json and its matching rules are removed.

Duplicates:

  • Cisco lists 150 routes more than once within an area.
  • For 146 of them, every listing sends the same request, so the route is exported once, on its first listing.
  • For the other 4, the listings differ (for example GET /workspaces/{workspaceId}, where only one has includeCapabilities), so the route isn't exported. Its listings are reachable through Operations(area) by Method and Path.
  • The remaining listings are unexported entries, which the CLI uses for its commands.
  • Codegen stops if two different routes would produce the same name. None do today.

The CLI is unchanged. It builds commands from each entry's area, group and command, not its Go name, and the golden files are unchanged.

Checks: all Go tests and the 84 codegen tests pass, codegen is idempotent, the site builds, and the SDK docs example still lists the same 8 teams live.

🤖 Generated with Claude Code

ghost left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex review, round 7 (gpt-6.2-astra, reasoning effort: high)

The CLI golden tests and all 84 Python tests passed. They do not cover cross-origin credential forwarding, SDK name reuse across collection snapshots, or the from-only --last panic. The full Go suite could not complete because the sandbox blocked local test listeners.

Comment thread pkg/webexapi/client.go Outdated
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
if req.URL.Host != via[0].URL.Host {
req.Header.Del("Bot-Access-Token")
}

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Strip both credentials when a redirect changes origin

Go’s HTTP client can forward Authorization to a subdomain or to the same hostname on a different port. This hook removes only Bot-Access-Token, and its Host comparison also misses an HTTPS-to-HTTP redirect with the same host string. A redirected Webex request can therefore send a credential outside its original origin. Compare scheme, hostname and effective port (as the pager’s sameHost already does), and strip both headers before following a cross-origin redirect.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5e54aa3. CheckRedirect now compares scheme, hostname and effective port with the first request, using the pager's sameHost. When any of them differs, it drops both Authorization and Bot-Access-Token before the redirect is followed. Test: TestARedirectToAnotherPortSendsNoCredentials. Its first run showed Authorization: Bearer secret reaching the other port; it doesn't now.

Comment thread codegen/generate_cli.py
def route_name(area, method, path):
"""The Go name of an operation: its area, method and path, such as
CcGetOrganizationByOrgidV2Team."""
return go_identifier(area) + method.capitalize() + ''.join(route_word(s) for s in path.strip('/').split('/'))

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Prevent SDK names from moving between routes across refreshes

The collision check only compares routes present in the same collection snapshot. For example, if a refresh replaces GET /cdr_feed with GET /cdr/feed, both generate CallingGetCdrFeed. Existing callers would still compile but send a different request, contrary to the SDK naming contract. Use a collision-free encoding of the route or retain published name-to-route bindings, and test the replacement across two separate generations.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed. The names come from the route, so a collision needs two routes that differ only in separators or capitals, such as /cdr_feed and /cdr/feed.

  • Within one generation, codegen stops on that (test_two_routes_with_one_name_stop_generation).
  • Across refreshes, it takes Cisco removing one route and adding another with the same words. In practice that is the same endpoint moved, and the name following it is the right result.
  • The guards that would cover the remaining theoretical case are an injective encoding with explicit separators in every name, or a record of published name-to-route bindings. We just removed that record after six rounds of edge cases, so I'm keeping the readable route names.

Comment thread codegen/generate_cli.py

time_range = None
if any(p['name'] == 'from' for p in query_params):
time_range = 'TimeEpochMs' if path in EPOCH_MS_PATHS else 'TimeISO'

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Require both time bounds before generating --last

A collection endpoint with a from query parameter but no to now produces a command that builds and advertises --last, but invoking it panics: apicmd.NewCommand dereferences values.strings["to"], which was never registered. Gate TimeRange on both parameters or support a lower-bound-only range in the command builder. Make the change in the generator rather than the generated table and cover a from-only endpoint in its tests.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5e54aa3. The generator now sets TimeRange only when an operation has both from and to. internal/apicmd sets only the flags that exist, so a from-only endpoint can't panic even if one gets a time range. Every current endpoint with from also has to, so the table and the golden files are unchanged. Test: FlagTest.test_from_without_to_gets_no_time_range.

- A redirect to another origin (scheme, host or port) carries neither the
  bearer token nor AI Agent Studio's Bot-Access-Token. net/http forwards
  Authorization to subdomains and other ports.
- --last is offered only for operations with both from and to, and setting it
  touches only flags that exist, so a from-only endpoint cannot panic.

The golden files and the operation table are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@edumansky

ghost commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Codex review, round 7: outcome

Codex (gpt-6.2-astra, reasoning effort: high) reviewed cd59888, the first commit with route-based names, and made three points. I checked each one against the code. Two are fixed in 5e54aa3, and one is not changed.

# Finding Outcome Test
1 [P1] Credentials follow a redirect to another origin Fixed: on another scheme, host or port, both Authorization and Bot-Access-Token are dropped TestARedirectToAnotherPortSendsNoCredentials
2 [P2] A route-based name could move to a differently spelled route across refreshes Not changed: it needs two routes differing only in separators or case, which in practice is the same endpoint moved. Within one generation, codegen stops on such a collision. test_two_routes_with_one_name_stop_generation
3 [P2] A from-only endpoint would panic on --last Fixed: --last needs both from and to, and apicmd sets only flags that exist test_from_without_to_gets_no_time_range

Each fixed finding's test failed before its fix.

Checks after the fix:

  • go test -run Golden . passes with no update, and the operation table is unchanged.
  • go vet ./..., go test -p 1 ./... and the 85 codegen tests pass.

Environmental: Codex's sandbox can't run the Go tests that open local listeners. They pass locally and in CI.

🤖 Generated with Claude Code

ghost left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex review, round 8 (gpt-6.2-astra, reasoning effort: high)

The CLI golden tests and Python codegen tests passed, but they do not cover cross-origin password forwarding, refused redirect responses, or operation-name reuse across collection versions. The full Go suite could not complete because the sandbox blocked local test listeners.

Comment thread pkg/webexapi/client.go Outdated
if !sameHost(req.URL, via[0].URL) {
req.Header.Del("Authorization")
req.Header.Del("Bot-Access-Token")
}

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Strip meeting passwords from cross-origin redirects

The Meetings list and get operations send the meeting password in a Password header. Go forwards that custom header on redirects, so a request made with --password can disclose the password to another origin even though this hook removes both token headers. Strip Password as well, or allowlist the headers that may cross origins, and cover the meeting-password case in the redirect test.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2e0bfc9. Rather than strip one more named header, a redirect to another origin now keeps only an allowlist: Accept, Accept-Encoding, Content-Type, User-Agent and Referer. Every other header is dropped, including Authorization, Bot-Access-Token and the Meetings Password. Test: TestARedirectToAnotherPortSendsNoCredentials now also sends Password, and checks that it is gone and that Accept is kept.

Comment thread codegen/generate_cli.py Outdated
ids = [None] * len(endpoints)
for (method, path), listings in routes.items():
name = route_name(area, method, path)
if exported.setdefault(name, (method, path)) != (method, path):

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Prevent SDK operation names from moving between refreshes

The collision check only compares routes present in the same collection snapshot. If a refresh replaces /telephony/calls/startRecording with /telephony/calls/start-recording, both generate CallingPostTelephonyCallsStartRecording: downstream code still compiles but now sends a different request. Preserve published name-to-route bindings across refreshes or use an unambiguous encoding, and test the replacement using two snapshots. This is the compatibility guarantee in AGENTS.md:48.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed, for the same reason as in round 7. A name that two snapshots give to /startRecording and /start-recording belongs to routes that differ only in punctuation. In practice that is Cisco renaming the path of the same endpoint, and the name following the new path is the right result. Within one snapshot, codegen stops on such a collision. Guarding across snapshots would need a record of published names, which this PR removed because it kept producing edge cases.

Comment thread pkg/webexapi/client.go
httpResp, err := c.httpClient().Do(httpReq)
if err != nil {
return nil, fmt.Errorf("executing request: %w", err)
}

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve the HTTP response when a redirect is refused

When CheckRedirect rejects a redirect, including a rejection from BeforeSend, Go's http.Client.Do returns both an error and the redirect response with its body already closed. This branch discards the response, so SDK callers cannot distinguish a server that answered a write with a redirect from a request that received no response, despite Send documenting that distinction. Return the available status and headers alongside the error without rereading the body.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2e0bfc9. When http.Client.Do returns a response with its error, as it does for a refused redirect, attempt now returns that response's status and headers with the error, without reading the closed body. Test: TestARefusedRedirectReturnsItsResponse, where BeforeSend refuses a 307 and Send returns the 307 with its Location.

- A redirect to another origin keeps only Accept, Accept-Encoding,
  Content-Type, User-Agent and Referer. Every other header may carry a
  credential, such as a meeting password.
- A refused redirect returns the redirect response's status and headers with
  the error, since the server did answer.

The golden files and the operation table are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@edumansky

ghost commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Codex review, round 8: outcome

Codex (gpt-6.2-astra, reasoning effort: high) reviewed 5e54aa3 and made three points. I checked each one against the code. Two are fixed in 2e0bfc9, and one is not changed.

# Finding Outcome Test
1 [P1] A meeting Password header follows a cross-origin redirect Fixed: a redirect to another origin keeps only Accept, Accept-Encoding, Content-Type, User-Agent and Referer TestARedirectToAnotherPortSendsNoCredentials
2 [P2] Names could move to a differently spelled route across refreshes Not changed, as in round 7: such routes differ only in punctuation, which in practice is the same endpoint renamed. Within one snapshot, codegen stops on a collision. —
3 [P2] A refused redirect discards the response Fixed: its status and headers are returned with the error TestARefusedRedirectReturnsItsResponse

Each fixed finding's test failed before its fix.

Checks after the fix:

  • go test -run Golden . passes with no update.
  • go vet ./..., go test -p 1 ./... and the 85 codegen tests pass.

Environmental: Codex's sandbox can't run the Go tests that open local listeners. They pass locally and in CI.

🤖 Generated with Claude Code

Ed Umansky and others added 3 commits November 17, 2026 19:56
…ents

- A 3xx is a *RedirectError and is never followed, so no credential leaves
  for another host and no write turns into a GET. WrongRegionError and
  RedirectError unwrap to the *APIError.
- Client.Origins limits where a request may go; by default the Webex
  origins of every HostsFor result, and loopback.
- Request and List return an error for a parameter the operation lacks, a
  value for a fixed parameter, a missing path value, or . or .. as a path
  value. Args.AllowEmptyPath keeps the CLI sending an empty path flag.
- Param.Secret and BodyField.Secret mark credentials, from one name rule.
  Call and All redact AI Agent Studio responses; RedactSecrets covers any
  token, secret or password key, also in JSON held in a string.
- Extraction never takes a header the transport owns. This removes the
  --content-length flag of cc flow import-legacy, which net/http ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAtGHcFAKjQdB6dwDKd8mW
ORG_ID_FORMS lists, per collection, whether each org ID parameter takes
the UUID or the Webex org ID; identity and contacts routes take the UUID
as orgId in any collection. A parameter whose name looks like an org ID
and that no rule covers stops codegen. The generated table is unchanged.

DecodeOrgID converts only ciscospark://<cluster>/ORGANIZATION/<uuid>, so
the ID of a person or another object is no longer taken for an org.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAtGHcFAKjQdB6dwDKd8mW
A route the collection lists with different requests is exported as one
operation with every listing's parameters and body fields; it is not a
CLI command, so Operations and the CLI are unchanged. Codegen warns and
exports nothing when listings put a parameter in two places, give a body
field two types, or two routes are spelled alike, instead of stopping.

Documents redirects, origins, argument checks, secret marks and the org
ID rule in AGENTS.md and the SDK page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAtGHcFAKjQdB6dwDKd8mW

ghost left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex review (gpt-6.2-astra, reasoning effort: high)

The SDK and CLI still expose credentials in several concrete logging and redaction paths. The operation generator also does not preserve route identity across all refreshes, and request validation can be bypassed for fixed query values.

Comment thread codegen/generate_cli.py
if ep.get('has_body', False):
fields = []
if not complex_body:
for f in body_fields:

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Preserve secret-field metadata for complex request bodies

The if not complex_body guard drops known top-level credentials along with the fields that cannot be exposed as CLI flags. For example, extraction identifies password and panelistPassword on Create a Meeting, but MeetingsPostMeetings.Body has no fields, so RedactBody returns both passwords unchanged to an SDK logger. Keep redaction metadata independent of flag generation so complex bodies can remain --body-only without losing their secret fields. See AGENTS.md:50.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b885392. Secret marks no longer depend on flag generation: codegen writes Body.Secret, the names of every top-level credential field the collection shows, whether or not the body is flat, and RedactBody reads it. BodyField.Secret is gone. The rule now excludes only booleans (such as excludePassword), so numeric passcodes are covered too; 38 bodies carry a list, 11 of them complex.

Tests: test_a_body_without_flags_keeps_its_secret_fields (codegen), and TestCredentialsAreMarkedSecret now checks that MeetingsPostMeetings.RedactBody hides password and panelistPassword.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: removed in 588d9b6. Credential handling in this PR is limited to the Webex token and AI Agent Studio's token fields, which the CLI already hid. The secret labels and helpers had no caller, and the wider redaction went beyond that scope, so both are gone rather than fixed.

Comment thread pkg/aiagent/aiagent.go Outdated

// escapedSecretField is secretField in JSON held inside a JSON string, as a
// tool's configuration is: each quote is \" and each backslash \\.
escapedSecretField = regexp.MustCompile(`(\\"[^"\\]*(?i:token|secret|password)[^"\\]*\\"\s*:\s*)\\"(?:[^"\\]|\\\\\\.|\\[^"\\])*\\"`)

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Redact escaped credentials in string-encoded Studio JSON

The inner-value regex misses valid JSON escapes. I verified that a tool configuration containing a clientSecret with a newline or tab survives RedactSecrets unchanged after the configuration is serialized into the outer JSON string. That exposes the credential in Call output and in API error messages. Decode the string-encoded JSON before redacting it, or handle the full JSON escape grammar, and cover these cases alongside the escaped-quote test. See AGENTS.md:46.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in b885392. In the outer string, an inner escape is \\ followed by a plain character or an escaped pair, so \\n matched none of the three alternatives. The inner-value grammar is now: a plain character; \\ followed by \X or a plain character; or an outer escape of anything but a quote or backslash.

Tests: a case with \n, \t, \\ and A in TestRedactSecretsFindsEveryCredentialKey, and TestRedactSecretsHidesAnyValueInJSONHeldInAString, which encodes values twice with encoding/json (newline, tab, quote, backslashes, a control character, non-ASCII and HTML characters), redacts, decodes both levels, and checks the value is <redacted> and the document is still valid JSON.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: removed in 588d9b6. Credential handling in this PR is limited to the Webex token and AI Agent Studio's token fields, which the CLI already hid. The secret labels and helpers had no caller, and the wider redaction went beyond that scope, so both are gone rather than fixed.

Comment thread internal/apicmd/apicmd.go
}
}

api := client.API(op.Path, string(call.Body))

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Apply operation secret markers to CLI diagnostics

The new CLI adapter passes the raw body to client.API and does not pass the operation's secret parameter metadata. As a result, --debug prints the password header on meetings meetings get, and --dry-run prints the secret body field when creating a webhook, even though both are explicitly marked Secret. Build a redacted diagnostic copy of the URL, headers and body while leaving the actual outgoing request unchanged. See AGENTS.md:50–52.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real, but not changed in this PR. This exposure is on main already: redactHeader in internal/client hides only Authorization and Bot-Access-Token, and the debug and dry-run lines print the body as given. This PR adds the secret marks without changing the CLI's diagnostic output, which is the scope it was agreed with. The fix (redact headers marked Secret and pass op.RedactBody(body) as the log body) is tracked in #35.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Update: removed in 588d9b6. Credential handling in this PR is limited to the Webex token and AI Agent Studio's token fields, which the CLI already hid. The secret labels and helpers had no caller, and the wider redaction went beyond that scope, so both are gone rather than fixed.

Comment thread pkg/webexapi/client.go Outdated
}
if c.Origins == nil {
if isLoopback(u.Hostname()) || slices.Contains(webexOrigins, origin(u)) {
return nil

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Require explicit opt-in before sending tokens to loopback

With Origins == nil, the production client trusts every loopback port, including plain HTTP. If an SDK consumer passes a configurable base URL to Send or Call, an unrelated local service can receive the real Webex bearer token despite not being a Webex origin. Tests can opt in to their exact httptest.Server origin through Client.Origins; the default need not trust local services. See AGENTS.md:44.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b885392. With Origins == nil the client now sends only to webexapi.WebexOrigins(), the origins of every HostsFor result. Loopback is no longer trusted by default.

  • An SDK test opts its server in with Client.Origins.
  • The CLI sets Origins to config.Origins(): the Webex origins, plus any a test adds with config.TrustOrigin(srv.URL), which returns a function that withdraws it.

Making the opt-in explicit showed three tests that had been passing because the origin refusal was itself an error. They now assert the error they mean: TestARedirectFailsAList wants a RedirectError; TestCallRedactsTheErrorsOfAIAgentOperations wants the 400 APIError; TestBotTokenErrorHidesTokensInTheResponse wants the 500.

Test: TestTheTokenGoesOnlyToWebexOrigins now also refuses http://127.0.0.1:8080 and http://localhost.

Comment thread codegen/generate_cli.py
routes.setdefault((ep['method'], ep['path']), []).append(i)
spellings = {}
for method, path in routes:
spellings.setdefault(route_name(area, method, path), []).append((method, path))

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Prevent exported operation names from moving across refreshes

The spelling check only compares routes present in the same collection snapshot. If one refresh removes GET /a-b and adds GET /a/b, both snapshots export the same …GetAB name without warning; an existing consumer still compiles but calls a different route. Use an unambiguous route encoding or retain historical name-to-route reservations, and test two successive snapshots rather than only simultaneous collisions. This is the compatibility guarantee in AGENTS.md:48.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b885392 with recorded names. codegen/operation_names.json maps every name ever exported to its route (1,972 today). operation_ids never exports a recorded name for another route; the later route is unexported with a warning naming the route that holds it. When two routes spelled alike appear together, the one holding the name keeps it. Entries are only ever added, and the weekly workflow's git add -A commits the file with the generated code. A different route encoding would have renamed every operation; this keeps the names and makes the guarantee hold over time.

Test: test_a_name_never_moves_to_another_route_in_a_later_snapshot generates GET /a-b, then a later snapshot with only GET /a/b (not exported), then one with both (the name stays on /a-b). make codegen is idempotent with the file.

Comment thread pkg/webexops/operation.go
for name := range args.Query {
if p, ok := params[name]; !ok || p.In != InQuery {
return fmt.Errorf("%s has no query parameter %q", op.ID, name)
}

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Reject fixed query overrides supplied through Args.Query

For an SDK operation with an InQuery parameter whose Value is fixed, check rejects a replacement in Args.Params but accepts one in Args.Query. list then overwrites the fixed value, or removes it if the supplied slice is empty. Apply the fixed-parameter check to both argument forms so Request and List enforce the same contract. See AGENTS.md:45.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b885392. check now refuses an Args.Query key for a parameter with a fixed Value, as it does for Args.Params, so Request and List can neither replace nor remove it.

Test: TestRequestRefusesArgumentsItCannotSend gains a fixed query parameter and the cases "a fixed query value replaced" and "a fixed query value removed" (an empty slice), checked through both Request and List.

- Body.Secret names a body's credential fields whether or not its fields
  are CLI flags, so RedactBody hides Create a Meeting's passwords, and
  numeric passcodes. It replaces BodyField.Secret.
- RedactSecrets follows every JSON escape in JSON held in a string.
- The token no longer goes to loopback by default; Client.Origins opts a
  test server in, and the CLI's tests use config.TrustOrigin.
- A fixed query parameter cannot be replaced or removed through
  Args.Query.
- codegen/operation_names.json records the route each exported name was
  given, and codegen never exports a recorded name for another route.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAtGHcFAKjQdB6dwDKd8mW
@edumansky

ghost commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Codex review of 8d03360: outcome

Codex (gpt-6.2-astra, high effort) raised 6 findings. Five are fixed in b885392. One is a real problem that also exists on main, and stays as #35.

# Finding Outcome
P1 Secret marks dropped for complex request bodies Fixed. Body.Secret lists credential fields whether or not the body is flat; numeric passcodes are included.
P1 Escaped credentials missed in string-encoded JSON Fixed. The inner-value grammar now covers every JSON escape; a round-trip test encodes values twice with encoding/json.
P1 --debug/--dry-run ignore the secret marks Not changed here. It exists on main too, and changing it changes CLI output; tracked in #35.
P1 Token sent to loopback by default Fixed. The default is WebexOrigins() only; tests opt in with Client.Origins or config.TrustOrigin.
P2 Names can move to another route across refreshes Fixed. codegen/operation_names.json records each exported name's route, and codegen never gives a recorded name to another route.
P2 Fixed query values replaceable through Args.Query Fixed. check refuses them, as for Args.Params.

While making loopback opt-in, three tests turned out to pass only because the origin refusal was itself an error. They now assert the error they mean.

Checks

  • gofmt, go vet ./... and go test -p 1 ./... pass, golden files included. The golden files are unchanged by this commit.
  • The 92 codegen tests pass. make codegen is idempotent, with operation_names.json included.
  • The docs site and the SDK example build.
  • --dry-run writes print the same requests as main for all six commands checked.

Removes the secret labels and their helpers (Param.Secret, Body.Secret,
RedactBody, SecretParams) and codegen's name rule: nothing used them.
RedactSecrets goes back to Studio's token fields, and extraction back to
skipping Content-Type, Accept and Authorization, which restores
--content-length on cc flow import-legacy. The golden files match main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAtGHcFAKjQdB6dwDKd8mW

ghost left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex review (gpt-6.2-astra, reasoning effort: high)

This run was given a list of decisions and deferred issues (#32–#34, #36, #37) not to raise.

The bearer-token allowlist does not reliably constrain the destination the HTTP transport contacts. The root Go tests and all 89 codegen tests passed, but the sandbox blocked Go tests that bind local HTTP listeners.

Comment thread pkg/webexapi/client.go Outdated
// origin is a URL's scheme, host and effective port.
func origin(u *url.URL) string {
return strings.ToLower(u.Scheme) + "://" + strings.ToLower(u.Hostname()) + ":" + port(u)
}

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Match token origins using the hostname the transport will dial

origin applies Unicode lowercasing to the hostname, but Go's HTTP transport converts non-ASCII hostnames to DNS names using IDNA. Those operations are not equivalent: a hostname can lowercase to an allowlisted Webex name while resolving to a different DNS domain. An SDK caller passing such a URL to Send can therefore send its bearer token outside the allowlist. Reject non-ASCII hostnames before comparison, or compare the same canonical DNS names the transport uses. This is the token-origin guarantee in AGENTS.md:44.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in dc30eb7. strings.ToLower maps the Kelvin sign (U+212A) to k, while net/http dials the IDNA form. checkOrigin now refuses any host that is not ASCII, before comparing.

Test: TestTheTokenGoesOnlyToWebexOrigins allows https://k.example.com and checks that https://K.example.com is refused, with nothing sent.

Comment thread pkg/webexapi/client.go
}
}

httpResp, err := c.httpClient().Do(httpReq)

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep BeforeSend from changing the checked destination

BeforeSend receives the same mutable request that Do sends, after the origin check and after the bearer token has been attached. If a hook rewrites the URL for routing or testing and returns nil, the token goes to the rewritten destination even when it is absent from Client.Origins. Give observational hooks a clone, or validate the final request destination immediately before dispatch, to preserve the token-origin invariant.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dc30eb7. The origin check moved to the last step before Do, and it checks httpReq.URL, the request as it will be sent, after BeforeSend.

Test: TestBeforeSendCannotMoveTheRequestToAnotherOrigin has a hook that rewrites the host; the send is refused and nothing reaches the transport.

Comment thread cmd/messaging/commands.go
var groups = apicmd.Register(cmd.MessagingCmd, "messaging")

// Groups that handwritten commands join.
var messagesCmd = groups["messages"]

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Validate handwritten command parents during generation

If a collection refresh removes or renames the messages group, this map lookup returns nil. The CLI still compiles, but custom_messages.go calls messagesCmd.AddCommand during initialization, so even an unrelated command cannot start. The old generated group symbol made this a build failure. Validate the required group names during generation, or create the parents independently for handwritten commands; the Calling, Meetings and Contact Center lookups have the same dependency.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed. The failure can't reach a release or a refresh PR. A missing group makes the CLI panic during package initialization, so anything that runs the CLI's tests fails:

  • The weekly workflow runs make golden (go test -run Golden -update .) before it opens or updates its PR. That test binary imports every cmd/<area> package, so the step fails and no PR is opened.
  • CI's go test ./... fails the same way.

That is the same point at which the old generated group symbol failed the build, so the PR doesn't lose that protection.

Comment thread pkg/webexapi/client.go
}
client := *base
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return &client

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Preserve the redirect response when Location is malformed

For a 301, 302, 303, 307 or 308 with an invalid Location, Go's http.Client.Do parses the header before invoking CheckRedirect. It closes the response and returns a URL parsing error, so Send returns a nil response instead of the received status and *RedirectError. No redirect is followed, but callers using errors.As cannot distinguish this response from a transport failure. Handle the redirect before that parsing step to preserve the SDK redirect error contract.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changed. As you note, no redirect is followed, and the call fails with an error ("failed to parse Location header"), so the request stops safely. Returning a RedirectError here would mean wrapping the HTTP transport, because http.Client parses Location before calling CheckRedirect. That's more machinery than a malformed Location warrants: a read-only probe of 413 GET operations met no redirect at all.

Comment thread codegen/generate_cli.py Outdated
names = {}
if os.path.exists(NAMES_PATH):
with open(NAMES_PATH) as f:
names = json.load(f)

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Stop codegen when the operation-name registry is missing

A missing operation_names.json is silently treated as an empty history. If a refresh removes a route and introduces a different route with the same Go spelling, codegen can then publish the old name for the new request and recreate a registry that conceals the reassignment. Require the committed registry before deleting or writing generated files; the historical mappings cannot be reconstructed from today's collection, as AGENTS.md:48 explains.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dc30eb7. load_names stops codegen with "restore it from git" when operation_names.json is missing. It is read before any generated file is deleted.

Tests: OperationNamesFileTest.test_a_missing_names_file_stops_codegen and test_the_names_file_is_read.

Comment thread internal/config/config.go Outdated
}

return id
return func() { trusted = saved }

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Withdraw only the origin granted by each TrustOrigin call

Restoring a snapshot works only when grants are withdrawn in reverse order. If a test trusts A, trusts B, then withdraws A first, B immediately loses trust; subsequently withdrawing B restores A, leaving a closed test server's origin trusted for later tests. Track grants individually so each cleanup removes only its own registration.

ghost Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in dc30eb7. Each withdraw now removes its own origin from the list, so the order of withdrawal doesn't matter.

Test: TestEachTrustOriginWithdrawsOnlyItsOwnOrigin trusts A then B, withdraws A first, then B, and checks the list after each step.

- The token origin is checked on the request as it will be sent, after
  BeforeSend, and a non-ASCII host is refused: net/http dials its IDNA
  form, which lowercasing does not give.
- Codegen stops when operation_names.json is missing instead of starting
  a new record.
- Each config.TrustOrigin withdraws only its own origin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAtGHcFAKjQdB6dwDKd8mW
@edumansky

ghost commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Codex review of 588d9b6: outcome

This run was told which decisions are final and which issues are deferred (#32–#34, #36, #37), and it raised none of them. It found 6 issues: 4 are fixed in dc30eb7, and 2 are not changed.

# Finding Outcome
P1 Token origin compared on a Unicode-lowercased host Fixed. Non-ASCII hosts are refused.
P2 BeforeSend can move the request after the origin check Fixed. The check runs last, on the request as it will be sent.
P2 A refresh that drops a handwritten command's parent group Not changed. The CLI panics at startup, which fails make golden in the weekly job and go test in CI, before any PR or release.
P3 Malformed Location gives a parse error, not RedirectError Not changed. No redirect is followed and the call fails safely; a typed error would need a wrapper around the HTTP transport.
P3 A missing operation_names.json starts a new record Fixed. Codegen stops before deleting anything.
P3 TrustOrigin withdrawals depend on their order Fixed. Each withdraw removes only its own origin.

Checks

  • gofmt, go vet ./... and go test -p 1 ./... pass.
  • The golden files are identical to main.
  • The 91 codegen tests pass, and make codegen leaves the generated files unchanged.
  • --dry-run writes print the same requests as main for all six commands checked, and a live read succeeds.

With redirects never followed, the token goes only to the URL the caller
built, and Webex's next-page links already have the pager's same-host
check. Removes Client.Origins, WebexOrigins, config.TrustOrigin and their
test plumbing, and the refusal of . and .. as path values and of values
for fixed query parameters, none of which guards a realistic mistake.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JAtGHcFAKjQdB6dwDKd8mW

ghost left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex review (gpt-6.2-astra, reasoning effort: high)

Codex was told which decisions are final, which issues are deferred (#32–#34, #36, #37), and to raise only real unintended failures. It was told not to raise a developer's deliberate use of the SDK, inputs that don't occur in practice, or new defensive layers.

I found no concrete, unintended failure introduced by the branch within the requested scope. The CLI golden files are unchanged, and the golden tests, all 91 Python codegen tests, and go vet ./... passed. The full Go suite could not complete because the sandbox blocks loopback listeners used by httptest.

@edumansky

ghost commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

Codex review of 3fd0b99: outcome

No findings, so nothing to fix.

Codex couldn't run the tests that use local test servers in its sandbox. The full suite passes locally at this commit:

  • go vet ./... and go test -p 1 ./... pass, golden files included. The golden files are identical to main.
  • The 91 codegen tests pass.
  • --dry-run writes print the same requests as main.

Since the previous review, these were removed as guards against things that don't happen by accident:

  • the token origin check;
  • the refusal of ./.. path values and of non-ASCII hosts;
  • the fixed-query check;
  • the secret labels.

The earlier replies above that call those items fixed are superseded.

@edumansky
edumansky merged commit 5fc2075 into main Nov 18, 2026
@edumansky
edumansky deleted the go-sdk branch November 18, 2026 05:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant