GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — feat: add Zero Anthropic provider by gnanam1990 · Pull Request #15 · Twigpine/zero Conversation
Collaborator
SummaryAdds the Zero Anthropic provider module for the M1 provider-runtime slice.
Drac Reference MapUsed the Drac reverse-engineered source as behavioral reference, then rewrote the module cleanly in TypeScript for Zero:
Validation
Reviewers@Vasanthdev2004 @anandh8x please review this provider module.
Sorry, something went wrong. Uh oh!
There was an error while loading. Please reload this page. All reactions
anandh8x
requested changes
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Code Review: PR #15 —
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| throw new Error('Zero anthropic provider requires an API key'); | ||
| } | ||
|
|
||
| return new AnthropicProvider({ |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Important — maxTokens is not threaded from the registry.
return new AnthropicProvider({ apiKey: runtime.apiKey, baseURL: runtime.baseURL, model: runtime.apiModel, });
The registry has claude-sonnet-4.5: maxOutputTokens: 64_000, claude-opus-4.1: maxOutputTokens: 32_000, claude-haiku-4.5: maxOutputTokens: 8_192. The provider's default is 4096, so every Claude registry model is silently truncated to 4k output unless the caller passes maxTokens explicitly — which the resolver never does.
Visible symptom: a claude-sonnet-4.5 user asks for a refactor of a 500-line file and gets a 2-3k-token response that stops mid-function with no error.
Ask: Pass maxTokens: runtime.model?.context.maxOutputTokens here (with a sane floor of 8192). For unknown models the 4k default is acceptable; for every registry-known Anthropic model the runtime should use its own ceiling.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
|
||
| const DEFAULT_ANTHROPIC_BASE_URL = 'https://api.anthropic.com'; | ||
| const DEFAULT_ANTHROPIC_VERSION = '2023-06-01'; | ||
| const DEFAULT_MAX_TOKENS = 4096; |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Important — 4096 default is well below every Anthropic model's maxOutputTokens in the registry.
This default is only correct for unknown models. Every Claude registry model has a much higher ceiling (Haiku 4.5: 8_192, Sonnet 4.5: 64_000, Opus 4.1: 32_000). The resolver's anthropic branch doesn't pass anything else (see src/zero-provider-runtime/resolver.ts:98-102), so this 4096 is what every Claude call uses.
Ask: The default here is fine for runtime.model === undefined (unknown model). For registry models the resolver should pass maxTokens: runtime.model.context.maxOutputTokens. This constant can stay as a fallback floor.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| })); | ||
| } | ||
|
|
||
| function parseToolArguments(argumentsJson: string): Record<string, unknown> { |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Important — the two non-object fallback paths will 400 against Anthropic's API.
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { return parsed as Record<string, unknown>; } return { input: parsed }; ... catch { return { input: argumentsJson }; }
{ input: parsed } (string inside an object) and { input: argumentsJson } (raw string) both send a string in Anthropic's tool_use.input, which the API requires to be a JSON object. The request will be rejected with a 400, and the user sees "Provider returned error" rather than a clear "model emitted non-object tool arguments."
Ask: Pick one of:
throw new Error(tool arguments for ${name} were not a JSON object: ${argumentsJson}). Surfaces the contract violation at the wire boundary.{} and let the tool's Zod schema fail downstream with "missing field" errors. Consistent with the rest of the slice's error model.I lean (a) since "model emitted a string where an object was expected" is a contract violation worth surfacing — not a recoverable case for the agent.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| while (true) { | ||
| const { value, done } = await reader.read(); | ||
| buffer += decoder.decode(value, { stream: !done }); | ||
| buffer = buffer.replace(/\r\n/g, '\n'); |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Suggestion — buffer.replace(/\r\n/g, '\n') runs on every chunk, on the entire accumulator.
For a long stream the buffer grows to several KB and the work compounds (O(n) per chunk, O(n²) over the stream). Anthropic's protocol is LF anyway, so this normalization isn't needed in the happy path. Move it into parseAnthropicSSEPayload (per-event, on the small rawEvent slice) so it only runs on the bytes that actually need parsing.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| } catch (err: any) { | ||
| console.error(`[zero] ${err?.message ?? String(err)}`); | ||
| if (runtime?.provider === 'anthropic' || runtime?.provider === 'google') { | ||
| if (runtime?.provider === 'google') { |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Suggestion — the not-implemented hint is now a hardcoded google check that will miss future pending providers.
if (runtime?.provider === 'google') { console.error(`[zero] ${runtime.provider} adapter is not yet implemented. ...`); }
When Anthropic moved to "implemented," the resolver's generic message (Zero ${runtime.provider} provider adapter is not implemented yet. The provider resolver can identify the model, but the streaming adapter lands in a later M1 slice.) still fires for google. The user sees both messages back-to-back. If a fourth provider (e.g., mistral) lands as pending, this hardcoded check silently misses it.
Ask: Have createZeroProvider throw a typed error (e.g., ZeroPendingProviderError) and let the CLI check err instanceof ZeroPendingProviderError rather than hardcoding a provider name. Or add runtime.pending: boolean to the resolved runtime and have the CLI check that. Either way, this hint should not be a string-equality on a provider name.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
95a9e7d to
b5938a2
Compare
|
@anandh8x @Vasanthdev2004 updated PR #15 for re-review. Fixed the two requested-change blockers:
Also addressed low-risk review suggestions while in the same module:
Validation after rebasing on latest
|
Sorry, something went wrong.
There was an error while loading. Please reload this page.
BlockersNone found. Non-Blocking
Looks Good
Verdict: Approve — the Anthropic adapter is now dispatch-safe enough for this M1 provider slice. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Approved — prior Anthropic correctness blockers are fixed, runtime wiring is safe, and local validation passed.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
feat: add Zero Anthropic provider (re-review, head b5938a20)Author: @gnanam1990 → feat/zero-anthropic-provider → main
Scope: 6 files, +909/-10. Same 5 files as v1 plus new src/zero-provider-runtime/index.ts barrel.
| v1 Issue | Status |
|---|---|
max_tokens: 4096 hardcode silently truncates Claude models |
FIXED — resolveAnthropicMaxTokens reads registry context.maxOutputTokens, floors at 8192, returns 4096 default only for unknown models |
parseToolArguments fallback sends string in tool_use.input → API 400 |
FIXED — throws on non-object tool args (chose option (a) from initial review) |
buffer.replace(/\r\n/g, '\n') per-chunk on the accumulator |
FIXED — findSSEBoundary checks both CRLF and LF natively; \r\n normalization moved to per-event parseAnthropicSSEPayload slice |
CLI hardcoded google not-implemented hint duplicates resolver error |
FIXED — ZeroPendingProviderError typed class thrown by resolver; CLI checks err instanceof ZeroPendingProviderError with generic hint. Also fixed latent v1 bug where CLI printed "anthropic adapter not implemented" for an actually-implemented provider. |
| No AbortController/signal support | NOT FIXED (non-blocking for M1 per initial review — type accepts AbortSignal via Parameters<typeof fetch> but never threaded) |
Missing test coverage (multi-tool, error SSE, 429, empty-messages guard, missing toolCallId) |
ALL 5 FIXED — new tests added. Also added: normalizeMaxTokens validation, non-JSON-object tool arguments rejection |
max_tokens not validated client-side |
FIXED — normalizeMaxTokens validates isFinite, isInteger, >= 1. Tested. |
| No retry on 5xx | NOT FIXED (optional, consistent with codebase) |
ZeroPendingProviderError — typed error carrying provider string. Clean instanceof check in CLI instead of fragile string matching.resolveAnthropicMaxTokens — Math.max(runtime.model.context.maxOutputTokens, MIN_REGISTRY_ANTHROPIC_MAX_TOKENS) where MIN_REGISTRY_ANTHROPIC_MAX_TOKENS = 8192 (matches Haiku 4.5's ceiling). Correctly handles both large (Sonnet 64k, Opus 32k) and small (Haiku 8k) models.normalizeMaxTokens — validates before construction. Catches configuration errors early.findSSEBoundary / parseAnthropicSSEPayload — clean separation of SSE frame parsing from event processing.getDetailedErrorMessage / getResponseErrorMessage — consistent, descriptive error messages from fetch failures, API errors, and stream errors. Recursion guard prevents "Provider returned error: Provider returned error: ..." nesting.appendUserBlocks — merges consecutive user content blocks (Anthropic requires strictly alternating user/assistant roles).createFetch, streamResponse, event, collectEvents keep tests clean.AbortController / AbortSignal for user-cancellable streams — FetchLike type now accepts signal via Parameters<typeof fetch>, but createStream never passes one. A Ctrl+C during a long Claude response cannot cancel the in-flight request. Worth adding for M2 agent-loop cancellation.ZERO_ANTHROPIC_VERSION env var — DEFAULT_ANTHROPIC_VERSION = '2023-06-01' hardcoded. If Anthropic ever ships a new version (unlikely but possible), users must modify source. Config-driven would be ideal.beta header not tested — anthropic-beta option exists but no test verifies it's sent. Low risk since the header is additive.toolBlocks cleanup — after message_stop, remaining tool blocks are yielded as tool-call-end. The message_stop for...of loop handles this, but no test explicitly asserts orphaned tool blocks get cleaned up on stream end.src/zero-provider-runtime/index.ts is new (barrel re-export). src/cli/index.ts now imports ZeroPendingProviderError from the barrel. No conflict with any open PR.feat/m2-update-check, anandh8x) also touches src/index.ts (adds update command). No overlap — #15 touches src/cli/index.ts (error handling in runHeadless), #16 touches src/index.ts (main program). Merge-safe.src/zero-provider-runtime/resolver.ts changes are additive (new anthropic branch, new helpers, new error class). No API contract changes to ZeroResolvedProviderRuntime or createZeroProvider's public signature.beta header transmission (forward-looking option; Anthropic's prompt caching beta)stream: false mode (M1 is streaming-only)content: [{ type: 'image', source: ... }]) — not needed for M1 agentmax_tokens override from the caller (always uses the provider-level setting)bun test --timeout 15000 (pass), bun run typecheck (pass), bun run build (pass) — all green per author.
Both real correctness issues from v1 are properly fixed. The ZeroPendingProviderError refactor is a nice design upgrade. Test coverage went from 4 to 11 cases, covering every error path discussed in v1. Clean M1 slice — ready to merge.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
|
||
| const DEFAULT_ANTHROPIC_BASE_URL = 'https://api.anthropic.com'; | ||
| const DEFAULT_ANTHROPIC_VERSION = '2023-06-01'; | ||
| const DEFAULT_MAX_TOKENS = 4096; |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Follow-up (not blocking): DEFAULT_ANTHROPIC_VERSION = '2023-06-01' is hardcoded. If Anthropic ships a new Messages API version, users must modify source. Consider making this configurable via env var / options. Same pattern applies to DEFAULT_ANTHROPIC_BASE_URL.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| @@ -168,6 +191,14 @@ function ensureOpenAICompatibleGatewayBaseURL(baseURL: string | undefined): asse | |||
| } | |||
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Clean fix. resolveAnthropicMaxTokens reads runtime.model.context.maxOutputTokens, floors at MIN_REGISTRY_ANTHROPIC_MAX_TOKENS = 8192 (matching Haiku 4.5's ceiling), and returns undefined for unknown models (falls through to constructor's 4096 default). Math.max ensures every registry model gets its own ceiling: 64k for Sonnet 4.5, 32k for Opus 4.x/4.1, 8k for Haiku. This is the exact fix requested in v1.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| } | ||
| } | ||
|
|
||
| function normalizeMaxTokens(maxTokens: number): number { |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Good addition: normalizeMaxTokens validates isFinite, isInteger, >= 1. Catches maxTokens: 0 or NaN before they reach the API. Tested at tests/anthropic-provider.test.ts:352-358.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| })); | ||
| } | ||
|
|
||
| function parseToolArguments(argumentsJson: string, toolName: string): Record<string, unknown> { |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Clean fix — chose option (a) from v1 review: throw at the wire boundary. Two distinct error messages for "parsed but not an object" vs "unparseable JSON." The catch's includes('JSON object') guard preserves the first error through the re-throw chain. Tested at tests/anthropic-provider.test.ts:332-350.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| console.error( | ||
| `[zero] ${runtime.provider} adapter is not yet implemented. ` + | ||
| 'Set provider: "openai-compatible" with a custom gateway or use an OpenAI model.' | ||
| '[zero] Use an implemented provider, or set provider: "openai-compatible" with a custom gateway.' |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Clean refactor. err instanceof ZeroPendingProviderError replaces the fragile runtime?.provider === 'anthropic' || runtime?.provider === 'google' string check. Also fixed a subtle bug from v1 where the CLI printed "anthropic adapter is not yet implemented" for an actually-implemented provider.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| yield* this.readStream(response); | ||
| } | ||
|
|
||
| private async createStream(body: Record<string, unknown>): Promise<Response> { |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Follow-up (not blocking): createStream never passes an AbortSignal. For M2 agent-loop cancellation (Ctrl+C during a long Claude response), thread a signal option from streamCompletion → createStream → fetchImpl. The FetchLike type already accepts it via Parameters<typeof fetch>.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
| } | ||
| } | ||
|
|
||
| async function* readAnthropicSSE( |
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Nice refactor from v1. findSSEBoundary handles both \n\n and \r\n\r\n natively at the buffer level. The \r\n → \n normalization is now inside parseAnthropicSSEPayload (line 310) — per-event slice, not per-chunk accumulator. Eliminates the O(n²) concern from v1's buffer.replace().
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
There was an error while loading. Please reload this page.