diff --git a/internal/cli/agent/intent_agent-run.go b/internal/cli/agent/intent_agent-run.go
index 0ff4a771..69e848a9 100644
--- a/internal/cli/agent/intent_agent-run.go
+++ b/internal/cli/agent/intent_agent-run.go
@@ -41,7 +41,8 @@ func InitIntentAgentRun(parent *cobra.Command) error {
"speakeasy_strict_body_keys": "true",
"speakeasy_help_defaults": "model gemini-4-hydrogen · stream true",
"speakeasy_help_escalate": "exact request JSON via --body @request.json (schema with --schema)",
- "speakeasy_outcome": "{\"statePointer\":\"/status\",\"streamStatePointer\":\"/data/interaction/status\",\"states\":{\"budget_exceeded\":\"success\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"success\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"pending\"},\"errorPointer\":\"/errors\",\"errorMessageField\":\"message\"}",
+ "speakeasy_outcome": "{\"statePointer\":\"/status\",\"streamStatePointers\":[\"/data/status\",\"/data/interaction/status\"],\"states\":{\"budget_exceeded\":\"success\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"success\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"continue\"},\"errorPointer\":\"/errors\",\"errorMessageField\":\"message\"}",
+ "speakeasy_continuation": "{\"bind\":[{\"pointer\":\"/continuation_token\",\"streamPointers\":[\"/data/continuation_token\",\"/data/interaction/continuation_token\"],\"to\":\"$.continuation_token\",\"toPath\":[\"continuation_token\"],\"streamAuthoritativeWhen\":{\"pointer\":\"/data/event_type\",\"equals\":\"interaction.completed\"},\"flag\":\"continuation-token\"},{\"pointer\":\"/id\",\"streamPointers\":[\"/data/interaction_id\",\"/data/interaction/id\"],\"to\":\"$.previous_interaction_id\",\"toPath\":[\"previous_interaction_id\"],\"optional\":true,\"unlessRequest\":{\"pointer\":\"/store\",\"equals\":false},\"flag\":\"previous-interaction-id\"}],\"omit\":[{\"name\":\"$.input\",\"path\":[\"input\"],\"unlessRequest\":{\"pointer\":\"/store\",\"equals\":false\x7d\x7d],\"unlessRequest\":[{\"pointer\":\"/background\",\"equals\":true},{\"pointer\":\"/agent\",\"exists\":true}],\"merge\":[\"/steps\"],\"mergeDropLeadingWhere\":[{\"pointer\":\"/steps\",\"field\":\"type\",\"equals\":\"user_input\"}],\"sum\":[\"/usage/total_input_tokens\",\"/usage/total_output_tokens\",\"/usage/total_thought_tokens\",\"/usage/total_tool_use_tokens\",\"/usage/total_cached_tokens\",\"/usage/total_tokens\"],\"keepFirst\":[{\"pointer\":\"/previous_interaction_id\"},{\"pointer\":\"/created\"},{\"pointer\":\"/input\"},{\"pointer\":\"/usage/initial_input_tokens\",\"fallback\":\"/usage/total_input_tokens\"}],\"collect\":[{\"to\":\"/continuation_ids\",\"from\":[\"/continuation_ids\",\"/id\"],\"unique\":true}],\"sumBy\":[{\"pointer\":\"/usage/input_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/output_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/cached_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/tool_use_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/grounding_tool_count\",\"key\":\"type\",\"value\":\"count\"}],\"maxHops\":10}",
"speakeasy_stream_select": "/data/delta/text",
"speakeasy_stream_metadata": "[{\"label\":\"Interaction ID\",\"pointers\":[\"/data/interaction/id\"]}]",
},
@@ -73,12 +74,21 @@ func InitIntentAgentRun(parent *cobra.Command) error {
BodySources: []string{"body"},
})
+ cmd.Flags().StringP("continuation-token", "", "", "Resume a cut-off interaction from its checkpoint token")
+ flagutil.MarkRequestInput(cmd, "continuation-token")
+ _ = flagutil.AnnotatePromptFlag(cmd, "continuation-token", flagutil.PromptFlagSpec{
+ Required: false,
+ Kind: "string",
+ Order: 2,
+
+ BodySources: []string{"body"},
+ })
cmd.Flags().StringP("model", "m", "", "Model to run (see \"gemini-api models\") (e.g. gemma-4-26b-a4b-it, gemma-4-31b-it, gemini-flash-latest, gemini-flash-lite-latest, ..., default: gemini-4-hydrogen)")
flagutil.MarkRequestInput(cmd, "model")
_ = flagutil.AnnotatePromptFlag(cmd, "model", flagutil.PromptFlagSpec{
Required: false,
Kind: "string",
- Order: 2,
+ Order: 3,
BodySources: []string{"body"},
})
@@ -89,7 +99,16 @@ func InitIntentAgentRun(parent *cobra.Command) error {
_ = flagutil.AnnotatePromptFlag(cmd, "previous-interaction-id", flagutil.PromptFlagSpec{
Required: false,
Kind: "string",
- Order: 3,
+ Order: 4,
+
+ BodySources: []string{"body"},
+ })
+ cmd.Flags().BoolP("store", "", false, "Store the interaction server-side for later retrieval or multi-turn continuation")
+ flagutil.MarkRequestInput(cmd, "store")
+ _ = flagutil.AnnotatePromptFlag(cmd, "store", flagutil.PromptFlagSpec{
+ Required: false,
+ Kind: "bool",
+ Order: 5,
BodySources: []string{"body"},
})
@@ -98,20 +117,22 @@ func InitIntentAgentRun(parent *cobra.Command) error {
_ = flagutil.AnnotatePromptFlag(cmd, "stream", flagutil.PromptFlagSpec{
Required: false,
Kind: "bool",
- Order: 4,
+ Order: 6,
BodySources: []string{"body"},
})
if err := interactive.Declare(cmd, interactive.CommandSpec{Args: []interactive.ArgSpec{
{
Name: "input", Summary: "Prompt or task to send",
- Required: true, Variadic: true,
+ Required: false, Variadic: true,
BodyKey: "input",
SatisfiedBy: []string{"body"},
},
}}); err != nil {
return fmt.Errorf("declare interactive arguments for intent agent-run: %w", err)
}
+ cmd.Flags().Bool("auto-continue", true, "Keep sending the request while the response asks to continue, and combine the responses")
+ cmd.Flags().Int("max-continuations", 10, "Maximum number of responses to request when continuing automatically")
for _, sibling := range parent.Commands() {
if sibling.Name() == cmd.Name() || sibling.HasAlias(cmd.Name()) {
return fmt.Errorf("intent command %q collides with the name or alias of an existing %q command; rename the declared command", "agent-run", sibling.Name())
@@ -154,7 +175,7 @@ var intentAgentRunDispatch = flagutil.DispatchTable{
Name: "input", BodyKey: "input",
Kind: flagutil.FlagKindString, Positional: true,
RouteIDs: []string{"agent", "model"},
- RequiredRouteIDs: []string{"agent", "model"},
+ RequiredRouteIDs: []string{},
},
{
Name: "agent", BodyKey: "agent",
@@ -168,6 +189,12 @@ var intentAgentRunDispatch = flagutil.DispatchTable{
RouteIDs: []string{"agent", "model"},
RequiredRouteIDs: []string{},
},
+ {
+ Name: "continuation-token", BodyKey: "continuation_token",
+ Kind: flagutil.FlagKindString, Positional: false,
+ RouteIDs: []string{"agent", "model"},
+ RequiredRouteIDs: []string{},
+ },
{
Name: "model", BodyKey: "model",
Kind: flagutil.FlagKindString, Positional: false,
@@ -180,6 +207,12 @@ var intentAgentRunDispatch = flagutil.DispatchTable{
RouteIDs: []string{"agent", "model"},
RequiredRouteIDs: []string{},
},
+ {
+ Name: "store", BodyKey: "store",
+ Kind: flagutil.FlagKindBool, Positional: false,
+ RouteIDs: []string{"agent", "model"},
+ RequiredRouteIDs: []string{},
+ },
{
Name: "stream", BodyKey: "stream",
Kind: flagutil.FlagKindBool, Positional: false,
@@ -303,15 +336,6 @@ func runIntentAgentRunCmd(cmd *cobra.Command, args []string) error {
if requested, _ := cmd.Flags().GetBool("schema"); requested {
return usage.EmitBodySchema(cmd.OutOrStdout(), "CreateInteraction")
}
- if len(args) == 0 && !flagutil.FlagChanged(cmd, "agent") && !flagutil.FlagChanged(cmd, "background") && !flagutil.FlagChanged(cmd, "model") && !flagutil.FlagChanged(cmd, "previous-interaction-id") && !flagutil.FlagChanged(cmd, "stream") {
- bodySupplied, err := flagutil.PrimeDispatchBody(cmd, "body")
- if err != nil {
- return err
- }
- if !bodySupplied {
- return output.UsageHelpError(cmd, fmt.Errorf("%s", "missing required argument (or pass a full request with --body)"))
- }
- }
if hint := flagutil.SpacedBoolValueHint(cmd, args); hint != "" && !client.IsJSONDryRun(cmd) && !output.IsMachineMode(cmd) {
fmt.Fprintln(cmd.ErrOrStderr(), hint)
}
diff --git a/internal/cli/agent/intent_generate.go b/internal/cli/agent/intent_generate.go
index 31bc7c7d..b133204b 100644
--- a/internal/cli/agent/intent_generate.go
+++ b/internal/cli/agent/intent_generate.go
@@ -33,7 +33,7 @@ func InitIntentGenerate(parent *cobra.Command) error {
cmd := &cobra.Command{
Use: "generate [prompt]",
Short: "Text & multimodal generation (gemini-4-hydrogen)",
- Long: "Send a prompt to a Gemini model and print the reply as it is\ngenerated; text deltas are streamed directly to stdout. Uses the\nschema's default model (gemini-4-hydrogen) unless --model or a full\n--body names one. --stream=false returns one complete interaction;\n--output-format json shows the raw NDJSON event stream. Thinking\nmodels such as gemini-4-hydrogen may emit their deltas in a burst\nafter thinking; gemini-flash-lite-latest streams visibly. Full request\ncontrol: \"gemini-api agent run\".\n\nArguments:\n Prompt to send to the model",
+ Long: "Send a prompt to a Gemini model and stream text deltas to stdout. Uses the\nschema's default model (gemini-4-hydrogen) unless --model or --body names one\n(--stream=false returns one complete interaction; --output-format json shows\nthe raw NDJSON event stream). Full request control: \"gemini-api agent run\".\n\nArguments:\n Prompt to send to the model",
Example: " gemini-api generate \"Write a haiku about APIs\" --model gemini-pro-latest\n gemini-api generate \"Explain concurrency in one sentence\"",
Args: cobra.ArbitraryArgs,
RunE: runIntentGenerateCmd,
@@ -44,7 +44,8 @@ func InitIntentGenerate(parent *cobra.Command) error {
"speakeasy_help_defaults": "model gemini-4-hydrogen · streams the reply (--stream=false for one result)",
"speakeasy_help_learn": "https://aistudio.google.com/docs/text-generation",
"speakeasy_help_escalate": "full request control via gemini-api agent run",
- "speakeasy_outcome": "{\"statePointer\":\"/status\",\"streamStatePointer\":\"/data/interaction/status\",\"states\":{\"budget_exceeded\":\"success\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"success\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"pending\"},\"errorPointer\":\"/errors\",\"errorMessageField\":\"message\"}",
+ "speakeasy_outcome": "{\"statePointer\":\"/status\",\"streamStatePointers\":[\"/data/status\",\"/data/interaction/status\"],\"states\":{\"budget_exceeded\":\"success\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"success\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"continue\"},\"errorPointer\":\"/errors\",\"errorMessageField\":\"message\"}",
+ "speakeasy_continuation": "{\"bind\":[{\"pointer\":\"/continuation_token\",\"streamPointers\":[\"/data/continuation_token\",\"/data/interaction/continuation_token\"],\"to\":\"$.continuation_token\",\"toPath\":[\"continuation_token\"],\"streamAuthoritativeWhen\":{\"pointer\":\"/data/event_type\",\"equals\":\"interaction.completed\"},\"flag\":\"continuation-token\"},{\"pointer\":\"/id\",\"streamPointers\":[\"/data/interaction_id\",\"/data/interaction/id\"],\"to\":\"$.previous_interaction_id\",\"toPath\":[\"previous_interaction_id\"],\"optional\":true,\"unlessRequest\":{\"pointer\":\"/store\",\"equals\":false},\"flag\":\"previous-interaction-id\"}],\"omit\":[{\"name\":\"$.input\",\"path\":[\"input\"],\"unlessRequest\":{\"pointer\":\"/store\",\"equals\":false\x7d\x7d],\"unlessRequest\":[{\"pointer\":\"/background\",\"equals\":true},{\"pointer\":\"/agent\",\"exists\":true}],\"merge\":[\"/steps\"],\"mergeDropLeadingWhere\":[{\"pointer\":\"/steps\",\"field\":\"type\",\"equals\":\"user_input\"}],\"sum\":[\"/usage/total_input_tokens\",\"/usage/total_output_tokens\",\"/usage/total_thought_tokens\",\"/usage/total_tool_use_tokens\",\"/usage/total_cached_tokens\",\"/usage/total_tokens\"],\"keepFirst\":[{\"pointer\":\"/previous_interaction_id\"},{\"pointer\":\"/created\"},{\"pointer\":\"/input\"},{\"pointer\":\"/usage/initial_input_tokens\",\"fallback\":\"/usage/total_input_tokens\"}],\"collect\":[{\"to\":\"/continuation_ids\",\"from\":[\"/continuation_ids\",\"/id\"],\"unique\":true}],\"sumBy\":[{\"pointer\":\"/usage/input_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/output_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/cached_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/tool_use_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/grounding_tool_count\",\"key\":\"type\",\"value\":\"count\"}],\"maxHops\":10}",
"speakeasy_stream_select": "/data/delta/text",
"speakeasy_stream_metadata": "[{\"label\":\"Interaction ID\",\"pointers\":[\"/data/interaction/id\"]}]",
},
@@ -56,12 +57,21 @@ func InitIntentGenerate(parent *cobra.Command) error {
_ = flagutil.AnnotatePromptFlag(cmd, "body", flagutil.PromptFlagSpec{Kind: "json", BodyFlag: true})
cmd.Flags().Bool("schema", false, "Print the exact JSON Schema of the request body and exit")
_ = flagutil.AnnotatePromptFlag(cmd, "schema", flagutil.PromptFlagSpec{Kind: "bool", DocSurface: true})
+ cmd.Flags().StringP("continuation-token", "", "", "Resume a cut-off interaction from its checkpoint token")
+ flagutil.MarkRequestInput(cmd, "continuation-token")
+ _ = flagutil.AnnotatePromptFlag(cmd, "continuation-token", flagutil.PromptFlagSpec{
+ Required: false,
+ Kind: "string",
+ Order: 0,
+
+ BodySources: []string{"body"},
+ })
cmd.Flags().StringP("model", "m", "", "Model to use (see \"gemini-api models\") (e.g. gemma-4-26b-a4b-it, gemma-4-31b-it, gemini-flash-latest, gemini-flash-lite-latest, ..., default: gemini-4-hydrogen)")
flagutil.MarkRequestInput(cmd, "model")
_ = flagutil.AnnotatePromptFlag(cmd, "model", flagutil.PromptFlagSpec{
Required: false,
Kind: "string",
- Order: 0,
+ Order: 1,
BodySources: []string{"body"},
})
@@ -70,7 +80,16 @@ func InitIntentGenerate(parent *cobra.Command) error {
_ = flagutil.AnnotatePromptFlag(cmd, "previous-interaction-id", flagutil.PromptFlagSpec{
Required: false,
Kind: "string",
- Order: 1,
+ Order: 2,
+
+ BodySources: []string{"body"},
+ })
+ cmd.Flags().BoolP("store", "", false, "Store the interaction server-side for later retrieval or multi-turn continuation")
+ flagutil.MarkRequestInput(cmd, "store")
+ _ = flagutil.AnnotatePromptFlag(cmd, "store", flagutil.PromptFlagSpec{
+ Required: false,
+ Kind: "bool",
+ Order: 3,
BodySources: []string{"body"},
})
@@ -79,7 +98,7 @@ func InitIntentGenerate(parent *cobra.Command) error {
_ = flagutil.AnnotatePromptFlag(cmd, "stream", flagutil.PromptFlagSpec{
Required: false,
Kind: "bool",
- Order: 2,
+ Order: 4,
BodySources: []string{"body"},
})
@@ -88,20 +107,22 @@ func InitIntentGenerate(parent *cobra.Command) error {
_ = flagutil.AnnotatePromptFlag(cmd, "system", flagutil.PromptFlagSpec{
Required: false,
Kind: "string",
- Order: 3,
+ Order: 5,
BodySources: []string{"body"},
})
if err := interactive.Declare(cmd, interactive.CommandSpec{Args: []interactive.ArgSpec{
{
Name: "prompt", Summary: "Prompt to send to the model",
- Required: true, Variadic: true,
+ Required: false, Variadic: true,
BodyKey: "input",
SatisfiedBy: []string{"body"},
},
}}); err != nil {
return fmt.Errorf("declare interactive arguments for intent generate: %w", err)
}
+ cmd.Flags().Bool("auto-continue", true, "Keep sending the request while the response asks to continue, and combine the responses")
+ cmd.Flags().Int("max-continuations", 10, "Maximum number of responses to request when continuing automatically")
for _, sibling := range parent.Commands() {
if sibling.Name() == cmd.Name() || sibling.HasAlias(cmd.Name()) {
return fmt.Errorf("intent command %q collides with the name or alias of an existing %q command; rename the declared command", "generate", sibling.Name())
@@ -161,6 +182,12 @@ func runIntentGenerateCmd(cmd *cobra.Command, args []string) error {
return flagutil.WithCLIValidation(err)
}
}
+ if flagutil.FlagChanged(cmd, "continuation-token") {
+ v, _ := flagutil.GetStringFlag(cmd, "continuation-token")
+ if err := flagutil.MergeInputIntoBody(cmd, suppliedBodyFlag, "continuation_token", "--continuation-token", v); err != nil {
+ return flagutil.WithCLIValidation(err)
+ }
+ }
if flagutil.FlagChanged(cmd, "model") {
v, _ := flagutil.GetStringFlag(cmd, "model")
if err := flagutil.MergeInputIntoBody(cmd, suppliedBodyFlag, "model", "--model", v); err != nil {
@@ -173,6 +200,12 @@ func runIntentGenerateCmd(cmd *cobra.Command, args []string) error {
return flagutil.WithCLIValidation(err)
}
}
+ if flagutil.FlagChanged(cmd, "store") {
+ v, _ := cmd.Flags().GetBool("store")
+ if err := flagutil.MergeInputIntoBody(cmd, suppliedBodyFlag, "store", "--store", v); err != nil {
+ return flagutil.WithCLIValidation(err)
+ }
+ }
if flagutil.FlagChanged(cmd, "stream") {
v, _ := cmd.Flags().GetBool("stream")
if err := flagutil.MergeInputIntoBody(cmd, suppliedBodyFlag, "stream", "--stream", v); err != nil {
@@ -186,20 +219,18 @@ func runIntentGenerateCmd(cmd *cobra.Command, args []string) error {
}
}
}
- if len(args) == 0 && !bodySupplied && !flagutil.FlagChanged(cmd, "body") && !flagutil.FlagChanged(cmd, "model") && !flagutil.FlagChanged(cmd, "previous-interaction-id") && !flagutil.FlagChanged(cmd, "stream") && !flagutil.FlagChanged(cmd, "system") {
- return output.UsageHelpError(cmd, fmt.Errorf("%s", "missing required argument (or pass a full request with --body)"))
- }
if !bodySupplied {
body := map[string]any{}
if err := json.Unmarshal([]byte(intentGeneratePreset.Preset), &body); err != nil {
return err
}
- if len(args) == 0 {
- return flagutil.WithCLIValidation(fmt.Errorf("missing required argument (or pass a full request with --body)"))
- }
if len(args) > 0 {
body["input"] = strings.Join(args, " ")
}
+ if flagutil.FlagChanged(cmd, "continuation-token") {
+ v, _ := flagutil.GetStringFlag(cmd, "continuation-token")
+ body["continuation_token"] = v
+ }
if flagutil.FlagChanged(cmd, "model") {
v, _ := flagutil.GetStringFlag(cmd, "model")
body["model"] = v
@@ -208,6 +239,10 @@ func runIntentGenerateCmd(cmd *cobra.Command, args []string) error {
v, _ := flagutil.GetStringFlag(cmd, "previous-interaction-id")
body["previous_interaction_id"] = v
}
+ if flagutil.FlagChanged(cmd, "store") {
+ v, _ := cmd.Flags().GetBool("store")
+ body["store"] = v
+ }
if flagutil.FlagChanged(cmd, "stream") {
v, _ := cmd.Flags().GetBool("stream")
body["stream"] = v
@@ -246,12 +281,5 @@ func runIntentGenerateCmd(cmd *cobra.Command, args []string) error {
}
}
}
- if bodySupplied {
- if err := flagutil.RequireBodyInputs(cmd, suppliedBodyFlag, []flagutil.RequiredBodyInput{
- {Path: []string{"input"}, Source: "the argument"},
- }); err != nil {
- return err
- }
- }
return runRunCmd(cmd, nil)
}
diff --git a/internal/cli/agent/intent_image.go b/internal/cli/agent/intent_image.go
index a97ece70..55e52b57 100644
--- a/internal/cli/agent/intent_image.go
+++ b/internal/cli/agent/intent_image.go
@@ -33,7 +33,7 @@ func InitIntentImage(parent *cobra.Command) error {
cmd := &cobra.Command{
Use: "image [prompt]",
Short: "Generate or edit images (gemini-nano-banana-2.1)",
- Long: "Generate an image from a text prompt via the Interactions API (image\nresponse modality) and write it to a file; stdout carries the file path.\nUse --out to choose the file (or directory), or --raw-response for the API\nresponse. To edit an image conversationally, pass the interaction ID of\nthe prior turn (--out --jq .response_id, or --raw-response --jq .id)\nas --previous-interaction-id.\n\nArguments:\n Image prompt",
+ Long: "Generate an image from a text prompt via the Interactions API (image response\nmodality) and write it to a file; stdout carries the file path (--out to choose\nthe file or directory; --raw-response for the API response). To edit an image\nconversationally, pass the prior turn's ID as --previous-interaction-id.\n\nArguments:\n Image prompt",
Example: " gemini-api image \"make the sky stormy\" --previous-interaction-id v1_ChdPU0F4YWFtNkFwS2kxZThQZ05lbXdROBIXT1NBeGFhbTZBcEtpMWU4UGdOZW13UTg\n gemini-api image \"a lighthouse at sunset\"\n gemini-api image \"product shot, white bg\" --aspect-ratio 16:9 --image-size 2K --out shots/hero.jpg",
Args: cobra.ArbitraryArgs,
RunE: runIntentImageCmd,
@@ -45,7 +45,8 @@ func InitIntentImage(parent *cobra.Command) error {
"speakeasy_help_learn": "https://aistudio.google.com/docs/image-generation",
"speakeasy_help_escalate": "full request control via gemini-api agent run",
"speakeasy_artifact": "{\"pointer\":[{\"field\":\"steps\"},{\"wild\":true},{\"field\":\"content\"},{\"wild\":true}],\"kind\":\"image\",\"defaultPath\":\"gemini-image-{timestamp}-{rand}.{ext}\"}",
- "speakeasy_outcome": "{\"statePointer\":\"/status\",\"streamStatePointer\":\"/data/interaction/status\",\"states\":{\"budget_exceeded\":\"success\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"success\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"pending\"},\"errorPointer\":\"/errors\",\"errorMessageField\":\"message\"}",
+ "speakeasy_outcome": "{\"statePointer\":\"/status\",\"streamStatePointers\":[\"/data/status\",\"/data/interaction/status\"],\"states\":{\"budget_exceeded\":\"success\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"success\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"continue\"},\"errorPointer\":\"/errors\",\"errorMessageField\":\"message\"}",
+ "speakeasy_continuation": "{\"bind\":[{\"pointer\":\"/continuation_token\",\"streamPointers\":[\"/data/continuation_token\",\"/data/interaction/continuation_token\"],\"to\":\"$.continuation_token\",\"toPath\":[\"continuation_token\"],\"streamAuthoritativeWhen\":{\"pointer\":\"/data/event_type\",\"equals\":\"interaction.completed\"\x7d\x7d,{\"pointer\":\"/id\",\"streamPointers\":[\"/data/interaction_id\",\"/data/interaction/id\"],\"to\":\"$.previous_interaction_id\",\"toPath\":[\"previous_interaction_id\"],\"optional\":true,\"unlessRequest\":{\"pointer\":\"/store\",\"equals\":false},\"flag\":\"previous-interaction-id\"}],\"omit\":[{\"name\":\"$.input\",\"path\":[\"input\"],\"unlessRequest\":{\"pointer\":\"/store\",\"equals\":false\x7d\x7d],\"unlessRequest\":[{\"pointer\":\"/background\",\"equals\":true},{\"pointer\":\"/agent\",\"exists\":true}],\"merge\":[\"/steps\"],\"mergeDropLeadingWhere\":[{\"pointer\":\"/steps\",\"field\":\"type\",\"equals\":\"user_input\"}],\"sum\":[\"/usage/total_input_tokens\",\"/usage/total_output_tokens\",\"/usage/total_thought_tokens\",\"/usage/total_tool_use_tokens\",\"/usage/total_cached_tokens\",\"/usage/total_tokens\"],\"keepFirst\":[{\"pointer\":\"/previous_interaction_id\"},{\"pointer\":\"/created\"},{\"pointer\":\"/input\"},{\"pointer\":\"/usage/initial_input_tokens\",\"fallback\":\"/usage/total_input_tokens\"}],\"collect\":[{\"to\":\"/continuation_ids\",\"from\":[\"/continuation_ids\",\"/id\"],\"unique\":true}],\"sumBy\":[{\"pointer\":\"/usage/input_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/output_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/cached_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/tool_use_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/grounding_tool_count\",\"key\":\"type\",\"value\":\"count\"}],\"maxHops\":10}",
},
}
intentMeta := flagutil.NonBodyMeta(runCmdMeta, "Body")
@@ -117,6 +118,8 @@ func InitIntentImage(parent *cobra.Command) error {
Kind: "string",
})
cmd.Flags().Bool("raw-response", false, "Print the raw API response instead of writing the image to a file")
+ cmd.Flags().Bool("auto-continue", true, "Keep sending the request while the response asks to continue, and combine the responses")
+ cmd.Flags().Int("max-continuations", 10, "Maximum number of responses to request when continuing automatically")
for _, sibling := range parent.Commands() {
if sibling.Name() == cmd.Name() || sibling.HasAlias(cmd.Name()) {
return fmt.Errorf("intent command %q collides with the name or alias of an existing %q command; rename the declared command", "image", sibling.Name())
diff --git a/internal/cli/agent/intent_music.go b/internal/cli/agent/intent_music.go
index b7cca459..9731894a 100644
--- a/internal/cli/agent/intent_music.go
+++ b/internal/cli/agent/intent_music.go
@@ -45,7 +45,8 @@ func InitIntentMusic(parent *cobra.Command) error {
"speakeasy_help_learn": "https://aistudio.google.com/docs/music-generation",
"speakeasy_help_escalate": "full request control via gemini-api agent run",
"speakeasy_artifact": "{\"pointer\":[{\"field\":\"steps\"},{\"wild\":true},{\"field\":\"content\"},{\"wild\":true}],\"kind\":\"audio\",\"defaultPath\":\"gemini-music-{timestamp}-{rand}.{ext}\"}",
- "speakeasy_outcome": "{\"statePointer\":\"/status\",\"streamStatePointer\":\"/data/interaction/status\",\"states\":{\"budget_exceeded\":\"success\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"success\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"pending\"},\"errorPointer\":\"/errors\",\"errorMessageField\":\"message\"}",
+ "speakeasy_outcome": "{\"statePointer\":\"/status\",\"streamStatePointers\":[\"/data/status\",\"/data/interaction/status\"],\"states\":{\"budget_exceeded\":\"success\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"success\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"continue\"},\"errorPointer\":\"/errors\",\"errorMessageField\":\"message\"}",
+ "speakeasy_continuation": "{\"bind\":[{\"pointer\":\"/continuation_token\",\"streamPointers\":[\"/data/continuation_token\",\"/data/interaction/continuation_token\"],\"to\":\"$.continuation_token\",\"toPath\":[\"continuation_token\"],\"streamAuthoritativeWhen\":{\"pointer\":\"/data/event_type\",\"equals\":\"interaction.completed\"\x7d\x7d,{\"pointer\":\"/id\",\"streamPointers\":[\"/data/interaction_id\",\"/data/interaction/id\"],\"to\":\"$.previous_interaction_id\",\"toPath\":[\"previous_interaction_id\"],\"optional\":true,\"unlessRequest\":{\"pointer\":\"/store\",\"equals\":false\x7d\x7d],\"omit\":[{\"name\":\"$.input\",\"path\":[\"input\"],\"unlessRequest\":{\"pointer\":\"/store\",\"equals\":false\x7d\x7d],\"unlessRequest\":[{\"pointer\":\"/background\",\"equals\":true},{\"pointer\":\"/agent\",\"exists\":true}],\"merge\":[\"/steps\"],\"mergeDropLeadingWhere\":[{\"pointer\":\"/steps\",\"field\":\"type\",\"equals\":\"user_input\"}],\"sum\":[\"/usage/total_input_tokens\",\"/usage/total_output_tokens\",\"/usage/total_thought_tokens\",\"/usage/total_tool_use_tokens\",\"/usage/total_cached_tokens\",\"/usage/total_tokens\"],\"keepFirst\":[{\"pointer\":\"/previous_interaction_id\"},{\"pointer\":\"/created\"},{\"pointer\":\"/input\"},{\"pointer\":\"/usage/initial_input_tokens\",\"fallback\":\"/usage/total_input_tokens\"}],\"collect\":[{\"to\":\"/continuation_ids\",\"from\":[\"/continuation_ids\",\"/id\"],\"unique\":true}],\"sumBy\":[{\"pointer\":\"/usage/input_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/output_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/cached_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/tool_use_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/grounding_tool_count\",\"key\":\"type\",\"value\":\"count\"}],\"maxHops\":10}",
},
}
intentMeta := flagutil.NonBodyMeta(runCmdMeta, "Body")
@@ -81,6 +82,8 @@ func InitIntentMusic(parent *cobra.Command) error {
Kind: "string",
})
cmd.Flags().Bool("raw-response", false, "Print the raw API response instead of writing the audio to a file")
+ cmd.Flags().Bool("auto-continue", true, "Keep sending the request while the response asks to continue, and combine the responses")
+ cmd.Flags().Int("max-continuations", 10, "Maximum number of responses to request when continuing automatically")
for _, sibling := range parent.Commands() {
if sibling.Name() == cmd.Name() || sibling.HasAlias(cmd.Name()) {
return fmt.Errorf("intent command %q collides with the name or alias of an existing %q command; rename the declared command", "music", sibling.Name())
diff --git a/internal/cli/agent/intent_video.go b/internal/cli/agent/intent_video.go
index 5218c0a8..ebe27158 100644
--- a/internal/cli/agent/intent_video.go
+++ b/internal/cli/agent/intent_video.go
@@ -47,7 +47,7 @@ func InitIntentVideo(parent *cobra.Command) error {
"speakeasy_help_learn": "https://aistudio.google.com/docs/video",
"speakeasy_help_escalate": "full request control via gemini-api agent run",
"speakeasy_artifact": "{\"pointer\":[{\"field\":\"steps\"},{\"wild\":true},{\"field\":\"content\"},{\"wild\":true}],\"kind\":\"video\",\"defaultPath\":\"gemini-video-{timestamp}-{rand}.{ext}\"}",
- "speakeasy_async": "{\"idPointer\":\"/id\",\"statePointer\":\"/status\",\"states\":{\"budget_exceeded\":\"failure\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"failure\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"pending\"},\"interval\":\"5s\",\"backoff\":1.5,\"maxInterval\":\"30s\",\"timeout\":\"15m\",\"command\":\"video\",\"resume\":\"gemini-api video --resume\",\"parameterIn\":\"path\",\"parameterName\":\"interactionsId\",\"params\":[{\"in\":\"query\",\"name\":\"stream\",\"value\":false}]}",
+ "speakeasy_async": "{\"idPointer\":\"/id\",\"statePointer\":\"/status\",\"states\":{\"budget_exceeded\":\"failure\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"failure\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"handoff\"},\"interval\":\"5s\",\"backoff\":1.5,\"maxInterval\":\"30s\",\"timeout\":\"15m\",\"command\":\"video\",\"resume\":\"gemini-api video --resume\",\"parameterIn\":\"path\",\"parameterName\":\"interactionsId\",\"params\":[{\"in\":\"query\",\"name\":\"stream\",\"value\":false}]}",
},
}
intentMeta := flagutil.NonBodyMeta(runCmdMeta, "Body")
diff --git a/internal/cli/agent/run.go b/internal/cli/agent/run.go
index cb7012de..cf34f5d4 100644
--- a/internal/cli/agent/run.go
+++ b/internal/cli/agent/run.go
@@ -44,7 +44,8 @@ func initRunCmd(parent *cobra.Command) error {
"speakeasy_operation": "CreateInteraction",
"speakeasy_stream_select": "/data/delta/text",
"speakeasy_stream_metadata": "[{\"label\":\"Interaction ID\",\"pointers\":[\"/data/interaction/id\"]}]",
- "speakeasy_outcome": "{\"statePointer\":\"/status\",\"streamStatePointer\":\"/data/interaction/status\",\"states\":{\"budget_exceeded\":\"success\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"success\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"pending\"},\"errorPointer\":\"/errors\",\"errorMessageField\":\"message\"}",
+ "speakeasy_outcome": "{\"statePointer\":\"/status\",\"streamStatePointers\":[\"/data/status\",\"/data/interaction/status\"],\"states\":{\"budget_exceeded\":\"success\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"success\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"continue\"},\"errorPointer\":\"/errors\",\"errorMessageField\":\"message\"}",
+ "speakeasy_continuation": "{\"bind\":[{\"pointer\":\"/continuation_token\",\"streamPointers\":[\"/data/continuation_token\",\"/data/interaction/continuation_token\"],\"to\":\"$.continuation_token\",\"toPath\":[\"continuation_token\"],\"streamAuthoritativeWhen\":{\"pointer\":\"/data/event_type\",\"equals\":\"interaction.completed\"},\"flag\":\"continuation-token\"},{\"pointer\":\"/id\",\"streamPointers\":[\"/data/interaction_id\",\"/data/interaction/id\"],\"to\":\"$.previous_interaction_id\",\"toPath\":[\"previous_interaction_id\"],\"optional\":true,\"unlessRequest\":{\"pointer\":\"/store\",\"equals\":false},\"flag\":\"previous-interaction-id\"}],\"omit\":[{\"name\":\"$.input\",\"path\":[\"input\"],\"unlessRequest\":{\"pointer\":\"/store\",\"equals\":false\x7d\x7d],\"unlessRequest\":[{\"pointer\":\"/background\",\"equals\":true},{\"pointer\":\"/agent\",\"exists\":true}],\"merge\":[\"/steps\"],\"mergeDropLeadingWhere\":[{\"pointer\":\"/steps\",\"field\":\"type\",\"equals\":\"user_input\"}],\"sum\":[\"/usage/total_input_tokens\",\"/usage/total_output_tokens\",\"/usage/total_thought_tokens\",\"/usage/total_tool_use_tokens\",\"/usage/total_cached_tokens\",\"/usage/total_tokens\"],\"keepFirst\":[{\"pointer\":\"/previous_interaction_id\"},{\"pointer\":\"/created\"},{\"pointer\":\"/input\"},{\"pointer\":\"/usage/initial_input_tokens\",\"fallback\":\"/usage/total_input_tokens\"}],\"collect\":[{\"to\":\"/continuation_ids\",\"from\":[\"/continuation_ids\",\"/id\"],\"unique\":true}],\"sumBy\":[{\"pointer\":\"/usage/input_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/output_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/cached_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/tool_use_tokens_by_modality\",\"key\":\"modality\",\"value\":\"tokens\"},{\"pointer\":\"/usage/grounding_tool_count\",\"key\":\"type\",\"value\":\"count\"}],\"maxHops\":10}",
},
}
flagutil.RegisterFlags(cmd, runCmdMeta)
@@ -59,6 +60,38 @@ func initRunCmd(parent *cobra.Command) error {
}
cmd.Flags().Bool("schema", false, "Print the exact JSON Schema of the request body and exit")
_ = flagutil.AnnotatePromptFlag(cmd, "schema", flagutil.PromptFlagSpec{Kind: "bool", DocSurface: true})
+ cmd.Flags().Bool("auto-continue", true, "Keep sending the request while the response asks to continue, and combine the responses")
+ cmd.Flags().Int("max-continuations", 10, "Maximum number of responses to request when continuing automatically")
+ cmd.Flags().StringP("continuation-token", "", "", "Resume a cut-off interaction from its checkpoint token")
+ if err := cmd.Flags().SetAnnotation("continuation-token", flagutil.AnnotationOpDeclaredInput, []string{"continuation_token"}); err != nil {
+ return err
+ }
+ flagutil.MarkRequestInput(cmd, "continuation-token")
+ _ = flagutil.AnnotatePromptFlag(cmd, "continuation-token", flagutil.PromptFlagSpec{
+ PromptOptional: true,
+ Kind: "string",
+ DefaultResolves: false,
+ })
+ cmd.Flags().StringP("previous-interaction-id", "", "", "Continue from an earlier interaction by passing its interaction ID")
+ if err := cmd.Flags().SetAnnotation("previous-interaction-id", flagutil.AnnotationOpDeclaredInput, []string{"previous_interaction_id"}); err != nil {
+ return err
+ }
+ flagutil.MarkRequestInput(cmd, "previous-interaction-id")
+ _ = flagutil.AnnotatePromptFlag(cmd, "previous-interaction-id", flagutil.PromptFlagSpec{
+ PromptOptional: true,
+ Kind: "string",
+ DefaultResolves: false,
+ })
+ cmd.Flags().BoolP("store", "", false, "Store the interaction server-side for later retrieval or multi-turn continuation")
+ if err := cmd.Flags().SetAnnotation("store", flagutil.AnnotationOpDeclaredInput, []string{"store"}); err != nil {
+ return err
+ }
+ flagutil.MarkRequestInput(cmd, "store")
+ _ = flagutil.AnnotatePromptFlag(cmd, "store", flagutil.PromptFlagSpec{
+ PromptOptional: true,
+ Kind: "bool",
+ DefaultResolves: false,
+ })
cmd.Flags().BoolP("stream", "", true, "Stream the reply as it is generated; use --stream=false for one complete interaction")
if err := cmd.Flags().SetAnnotation("stream", flagutil.AnnotationOpDeclaredInput, []string{"stream"}); err != nil {
return err
@@ -126,6 +159,21 @@ func executeRunCmd(cmd *cobra.Command, args []string, asyncIntent bool) (*operat
if asyncIntent || output.WantsRawJSON(cmd) {
sdkOpts = append(sdkOpts, operations.WithSkipDeserialization())
}
+ if !asyncIntent && output.ContinuationActive(cmd) {
+ hop := func() (interface{}, error) {
+ stopProgress := output.StartRequestProgress(cmd)
+ defer stopProgress()
+ res, err := s.Agent.Run(cmd.Context(), *req, sdkOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return res, nil
+ }
+ if !client.IsDryRun(cmd) {
+ return nil, output.ContinuationStream(cmd, &req, hop, "InteractionSSEStreamEvent")
+ }
+ return nil, output.ContinuationResult(cmd, &req, hop)
+ }
if !client.IsDryRun(cmd) && !asyncIntent {
stopProgress := output.StartRequestProgress(cmd)
res, err := s.Agent.Run(cmd.Context(), *req, sdkOpts...)
diff --git a/internal/cli/agent/status.go b/internal/cli/agent/status.go
index b29aa0b4..6aa0f71e 100644
--- a/internal/cli/agent/status.go
+++ b/internal/cli/agent/status.go
@@ -48,7 +48,7 @@ func initStatusCmd(parent *cobra.Command) error {
"speakeasy_operation": "getInteractionById",
"speakeasy_stream_select": "/data/delta/text",
"speakeasy_stream_metadata": "[{\"label\":\"Interaction ID\",\"pointers\":[\"/data/interaction/id\"]}]",
- "speakeasy_outcome": "{\"statePointer\":\"/status\",\"streamStatePointer\":\"/data/interaction/status\",\"states\":{\"budget_exceeded\":\"success\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"success\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"pending\"},\"errorPointer\":\"/errors\",\"errorMessageField\":\"message\"}",
+ "speakeasy_outcome": "{\"statePointer\":\"/status\",\"streamStatePointers\":[\"/data/status\",\"/data/interaction/status\"],\"states\":{\"budget_exceeded\":\"success\",\"cancelled\":\"failure\",\"completed\":\"success\",\"failed\":\"failure\",\"in_progress\":\"pending\",\"incomplete\":\"success\",\"queued\":\"pending\",\"requires_action\":\"handoff\",\"requires_continuation\":\"handoff\"},\"errorPointer\":\"/errors\",\"errorMessageField\":\"message\"}",
},
}
flagutil.RegisterFlags(cmd, statusCmdMeta)
diff --git a/internal/cli/custom/custom_test.go b/internal/cli/custom/custom_test.go
index c3c40c52..a6bc0418 100644
--- a/internal/cli/custom/custom_test.go
+++ b/internal/cli/custom/custom_test.go
@@ -2180,6 +2180,30 @@ func TestAttachInteractionInputsAndNormalizeFilesURIs(t *testing.T) {
})
}
+func TestAttachInteractionInputsRejectsDriftedAgentRunLong(t *testing.T) {
+ noop := func(*cobra.Command, []string) error { return nil }
+ root := &cobra.Command{Use: "gemini-api"}
+ for _, name := range []string{"generate", "image", "video", "music"} {
+ cmd := &cobra.Command{Use: name, RunE: noop}
+ cmd.Flags().String("body", "", "")
+ root.AddCommand(cmd)
+ }
+ agentGroup := &cobra.Command{Use: "agent"}
+ runCmd := &cobra.Command{
+ Use: "run [input]",
+ Long: "Some unexpected generated Long help text.",
+ RunE: noop,
+ }
+ runCmd.Flags().String("body", "", "")
+ agentGroup.AddCommand(runCmd)
+ root.AddCommand(agentGroup)
+
+ err := attachInteractionInputs(root)
+ if err == nil || !strings.Contains(err.Error(), "generated Long help text changed") {
+ t.Fatalf("attachInteractionInputs(drifted Long) = %v, want generated Long help text drift error", err)
+ }
+}
+
func TestResolveEnvUploadAndDownloadArgsCoverage(t *testing.T) {
if _, _, extra := resolveEnvUploadArgs([]string{"extra"}, "env1", "file1"); !extra {
t.Error("resolveEnvUploadArgs with both flags and positional arg: want extra=true")
diff --git a/internal/cli/custom/media.go b/internal/cli/custom/media.go
index 804163f5..c699edd7 100644
--- a/internal/cli/custom/media.go
+++ b/internal/cli/custom/media.go
@@ -43,6 +43,7 @@ import (
"github.com/google-gemini/gemini-api-cli/internal/sdk/sdkinternal/hooks"
"github.com/google-gemini/gemini-api-cli/internal/usage"
"github.com/spf13/cobra"
+ "github.com/spf13/pflag"
)
// maxInlineRequestBytes is the CLI's conservative budget for one interaction
@@ -675,6 +676,10 @@ type intentInputs struct {
// file is -f/--file, a text content block read from a file; only for
// commands without media inputs, where -i already takes text files.
file bool
+ // continuationResume allows omitting the positional prompt/input when
+ // manually resuming a stored continuation checkpoint via continuation_token,
+ // while still enforcing input for all other invocations.
+ continuationResume bool
}
// attachInteractionInputs wires -i/--input, --mime-type, --stdin, -f/--file,
@@ -687,7 +692,7 @@ func attachInteractionInputs(root *cobra.Command) error {
promptDesc string
inputs intentInputs
}{
- {"generate", "prompt", "Prompt to send to the model", intentInputs{media: true, stdin: true}},
+ {"generate", "prompt", "Prompt to send to the model", intentInputs{media: true, stdin: true, continuationResume: true}},
{"image", "prompt", "Description of the image to generate", intentInputs{media: true, stdin: true}},
{"video", "prompt", "Scene description for the video to generate", intentInputs{media: true, stdin: true}},
{"music", "prompt", "Music prompt", intentInputs{stdin: true, file: true}},
@@ -709,15 +714,20 @@ func attachInteractionInputs(root *cobra.Command) error {
agentRunCmd := findChild(agentGroup, "run")
// agent run keeps piped stdin as the request body: it is the full-control
// surface, so it takes media inputs but no --stdin/--file text.
- if err := attachIntentInputs(agentRunCmd, "input", "Prompt or task to send", intentInputs{media: true}); err != nil {
+ hadGeneratedLong := agentRunCmd != nil && agentRunCmd.Long != ""
+ if err := attachIntentInputs(agentRunCmd, "input", "Prompt or task to send", intentInputs{media: true, continuationResume: true}); err != nil {
return fmt.Errorf("agent run: %w", err)
}
- agentRunCmd.Long = strings.Replace(
- agentRunCmd.Long,
- "Run one interaction with a Gemini model (--model, the default) or a\nmanaged agent (--agent); the two flag sets are mutually exclusive.\nStreams text as it arrives; --stream=false returns one complete\ninteraction. --body takes the exact request JSON (\"model\"/\"agent\" picks the variant).",
- "Run one interaction with a Gemini model (--model, default) or a managed agent (--agent).\nStreams text as it arrives (--stream=false or --background for one interaction unless --stream is passed); --body takes exact request JSON.",
- 1,
- )
+ if hadGeneratedLong {
+ const (
+ generatedAgentRunLong = "Run one interaction with a Gemini model (--model, the default) or a\nmanaged agent (--agent); the two flag sets are mutually exclusive.\nStreams text as it arrives; --stream=false returns one complete\ninteraction. --body takes the exact request JSON (\"model\"/\"agent\" picks the variant).\n\nArguments:\n Prompt or task to send\n\nRequest variants: Agent (--agent), Model (--model; default).\nVariant-specific flags cannot be combined."
+ compactAgentRunLong = "Run one interaction with a Gemini model (--model, default) or a managed agent (--agent); streams text as it arrives (--stream=false or --background for one interaction unless --stream is passed; --body takes exact request JSON).\nArguments: Prompt or task to send\nRequest variants: Agent (--agent), Model (--model; default). Variant-specific flags cannot be combined."
+ )
+ if !strings.Contains(agentRunCmd.Long, generatedAgentRunLong) {
+ return fmt.Errorf("agent run: generated Long help text changed; update compactAgentRunLong in attachInteractionInputs")
+ }
+ agentRunCmd.Long = strings.Replace(agentRunCmd.Long, generatedAgentRunLong, compactAgentRunLong, 1)
+ }
return nil
}
@@ -767,6 +777,9 @@ func attachIntentInputs(cmd *cobra.Command, argName, promptDesc string, in inten
flagutil.MarkRequestInput(cmd, "stdin")
satisfiedBy = append(satisfiedBy, "stdin")
}
+ if in.continuationResume && cmd.Flags().Lookup("continuation-token") != nil {
+ satisfiedBy = append(satisfiedBy, "continuation-token")
+ }
declareInteractive(cmd, interactive.CommandSpec{Args: []interactive.ArgSpec{
{
Name: argName,
@@ -860,6 +873,11 @@ func attachIntentInputs(cmd *cobra.Command, argName, promptDesc string, in inten
text = ""
}
if len(inputs) == 0 && text == "" && suppliedBodyFlag == "" && !stdinAttached {
+ if in.continuationResume {
+ if err := validateContinuationInput(c, args, argName, false, nil, "", false); err != nil {
+ return err
+ }
+ }
return original(c, args)
}
@@ -875,6 +893,14 @@ func attachIntentInputs(cmd *cobra.Command, argName, promptDesc string, in inten
c.SetIn(bytes.NewReader(rawBody))
bodySource = "stdin"
}
+ if len(bytes.TrimSpace(rawBody)) == 0 {
+ if in.continuationResume {
+ if err := validateContinuationInput(c, args, argName, len(inputs) > 0 || text != "", map[string]any{}, suppliedBodyFlag, stdinAttached); err != nil {
+ return err
+ }
+ }
+ return original(c, args)
+ }
if err := decodeBodyJSON(rawBody, &bodyMap); err != nil || bodyMap == nil {
if err != nil && stdinAttached && in.stdin {
return usageError(fmt.Sprintf("failed to parse stdin as JSON: %v", err),
@@ -894,6 +920,11 @@ func attachIntentInputs(cmd *cobra.Command, argName, promptDesc string, in inten
return usageError(fmt.Sprintf("cannot combine positional <%s> with \"input\" in %s", argName, bodySource))
}
}
+ if in.continuationResume {
+ if err := validateContinuationInput(c, args, argName, len(inputs) > 0 || text != "", bodyMap, suppliedBodyFlag, stdinAttached); err != nil {
+ return err
+ }
+ }
var s *sdk.GeminiAPI
var mediaBlocks []any
@@ -964,6 +995,115 @@ func attachIntentInputs(cmd *cobra.Command, argName, promptDesc string, in inten
return nil
}
+// validateContinuationInput enforces a prompt/input on commands whose generated
+// spec leaves $.input optional so manual stored-mode continuation resumes can
+// follow resumeHint ("--continuation-token ... --previous-interaction-id ...,
+// leaving $.input out of the request body"). Omitting input is allowed only
+// when a non-empty continuation_token is provided in stored model mode (not
+// --store=false, --agent, or --background).
+func validateContinuationInput(c *cobra.Command, args []string, argName string, hasMediaOrText bool, bodyMap map[string]any, suppliedBodyFlag string, stdinAttached bool) error {
+ if len(args) > 0 || hasMediaOrText || (bodyMap != nil && bodyMap["input"] != nil) {
+ return nil
+ }
+ if shouldDeferAgentRunDispatchError(c, bodyMap) {
+ return nil
+ }
+
+ hasToken := false
+ if c.Flags().Lookup("continuation-token") != nil && flagutil.FlagChanged(c, "continuation-token") {
+ if v, ok := flagutil.GetStringFlag(c, "continuation-token"); ok && strings.TrimSpace(v) != "" {
+ hasToken = true
+ }
+ }
+ if bodyMap != nil {
+ if s, ok := bodyMap["continuation_token"].(string); ok && strings.TrimSpace(s) != "" {
+ hasToken = true
+ }
+ }
+
+ storeFlagChanged := c.Flags().Lookup("store") != nil && flagutil.FlagChanged(c, "store")
+ _, bodyHasStore := bodyMap["store"]
+ if hasToken && storeFlagChanged && bodyHasStore {
+ // Let the generated command report the duplicate --store / body key error.
+ return nil
+ }
+
+ stateless := false
+ if storeFlagChanged {
+ if v, err := c.Flags().GetBool("store"); err == nil && !v {
+ stateless = true
+ }
+ }
+ if bodyMap != nil {
+ if b, ok := bodyMap["store"].(bool); ok && !b {
+ stateless = true
+ }
+ }
+
+ agentSet := (c.Flags().Lookup("agent") != nil && flagutil.FlagChanged(c, "agent")) ||
+ (bodyMap != nil && bodyMap["agent"] != nil)
+ backgroundTrue := false
+ if c.Flags().Lookup("background") != nil && flagutil.FlagChanged(c, "background") {
+ if v, err := c.Flags().GetBool("background"); err == nil && v {
+ backgroundTrue = true
+ }
+ }
+ if bodyMap != nil {
+ if b, ok := bodyMap["background"].(bool); ok && b {
+ backgroundTrue = true
+ }
+ }
+
+ if hasToken && !stateless && !agentSet && !backgroundTrue {
+ return nil
+ }
+
+ if suppliedBodyFlag == "" && !stdinAttached && !hasRequestInputFlagChanged(c) {
+ return output.UsageHelpError(c, fmt.Errorf("missing required argument <%s> (or pass a full request with --body)", argName))
+ }
+ if hasToken && stateless {
+ return flagutil.WithCLIValidation(fmt.Errorf("stateless continuation (store=false) requires <%s> (or \"input\" in --body)", argName))
+ }
+ if suppliedBodyFlag != "" || stdinAttached {
+ source := "stdin"
+ if suppliedBodyFlag != "" {
+ source = "--" + suppliedBodyFlag
+ }
+ return flagutil.WithCLIValidation(fmt.Errorf("the request body from %s has no \"input\": pass the <%s> argument, set \"input\" in the body, or pass --continuation-token to resume", source, argName))
+ }
+ return flagutil.WithCLIValidation(fmt.Errorf("missing required argument <%s> (or pass --continuation-token to resume, or a full request with --body)", argName))
+}
+
+func hasRequestInputFlagChanged(c *cobra.Command) bool {
+ changed := false
+ c.LocalFlags().VisitAll(func(f *pflag.Flag) {
+ if f.Changed && len(f.Annotations[flagutil.AnnotationRequestInput]) > 0 {
+ changed = true
+ }
+ })
+ return changed
+}
+
+// shouldDeferAgentRunDispatchError returns true when agent run has a route
+// selection conflict or missing --agent selector so flagutil.Select reports
+// the specific route error rather than a generic missing-input error.
+func shouldDeferAgentRunDispatchError(c *cobra.Command, bodyMap map[string]any) bool {
+ if c.Name() != "run" {
+ return false
+ }
+ hasModel := (c.Flags().Lookup("model") != nil && flagutil.FlagChanged(c, "model")) ||
+ (bodyMap != nil && bodyMap["model"] != nil)
+ hasAgent := (c.Flags().Lookup("agent") != nil && flagutil.FlagChanged(c, "agent")) ||
+ (bodyMap != nil && bodyMap["agent"] != nil)
+ if hasModel && hasAgent {
+ return true
+ }
+ if bodyMap != nil && bodyMap["agent_config"] != nil && !hasAgent {
+ return true
+ }
+ return false
+}
+
func decodeBodyJSON(raw []byte, dst *map[string]any) error {
dec := json.NewDecoder(bytes.NewReader(raw))
dec.UseNumber()
diff --git a/internal/output/continuation.go b/internal/output/continuation.go
new file mode 100644
index 00000000..59a8acf9
--- /dev/null
+++ b/internal/output/continuation.go
@@ -0,0 +1,1150 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
+
+package output
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "math/big"
+ "net/http"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+
+ "github.com/google-gemini/gemini-api-cli/internal/flagutil"
+ "github.com/spf13/cobra"
+)
+
+const continuationAnnotation = "speakeasy_continuation"
+
+type continuationBinding struct {
+ Pointer string `json:"pointer"`
+ StreamPointers []string `json:"streamPointers"`
+ To string `json:"to"`
+ ToPath []string `json:"toPath"`
+ Optional bool `json:"optional"`
+ Flag string `json:"flag"`
+ UnlessRequest *continuationRequestCondition `json:"unlessRequest"`
+ StreamAuthoritativeWhen *continuationRequestCondition `json:"streamAuthoritativeWhen"`
+}
+
+// continuationRequestCondition with Exists set treats a null value as absent.
+type continuationRequestCondition struct {
+ Pointer string `json:"pointer"`
+ Equals interface{} `json:"equals"`
+ Exists *bool `json:"exists"`
+}
+
+func (c *continuationRequestCondition) matches(root interface{}) bool {
+ value, ok := outcomePointer(root, c.Pointer)
+ if c.Exists != nil {
+ return (ok && value != nil) == *c.Exists
+ }
+ return ok && continuationValuesEqual(value, c.Equals)
+}
+
+type continuationOmit struct {
+ Name string `json:"name"`
+ Path []string `json:"path"`
+ UnlessRequest *continuationRequestCondition `json:"unlessRequest"`
+}
+
+type continuationMergeDrop struct {
+ Pointer string `json:"pointer"`
+ Field string `json:"field"`
+ Equals interface{} `json:"equals"`
+}
+
+type continuationKeepFirst struct {
+ Pointer string `json:"pointer"`
+ Fallback string `json:"fallback"`
+}
+
+type continuationCollect struct {
+ To string `json:"to"`
+ From []string `json:"from"`
+ Unique bool `json:"unique"`
+}
+
+type continuationSumBy struct {
+ Pointer string `json:"pointer"`
+ Key string `json:"key"`
+ Value string `json:"value"`
+}
+
+type continuationConfig struct {
+ Bind []continuationBinding `json:"bind"`
+ Omit []continuationOmit `json:"omit"`
+ UnlessRequest []continuationRequestCondition `json:"unlessRequest"`
+ Merge []string `json:"merge"`
+ MergeDropLeadingWhere []continuationMergeDrop `json:"mergeDropLeadingWhere"`
+ Sum []string `json:"sum"`
+ KeepFirst []continuationKeepFirst `json:"keepFirst"`
+ Collect []continuationCollect `json:"collect"`
+ SumBy []continuationSumBy `json:"sumBy"`
+ MaxHops int `json:"maxHops"`
+}
+
+// ContinuationHop sends the command's request once more. The request the
+// driver mutates between hops is the one the closure sends.
+type ContinuationHop func() (interface{}, error)
+
+func activeContinuation(cmd *cobra.Command) *continuationConfig {
+ if cmd == nil || cmd.Annotations == nil {
+ return nil
+ }
+ raw := cmd.Annotations[continuationAnnotation]
+ if raw == "" {
+ return nil
+ }
+ var cfg continuationConfig
+ if err := json.Unmarshal([]byte(raw), &cfg); err != nil || len(cfg.Bind) == 0 {
+ return nil
+ }
+ return &cfg
+}
+
+// ContinuationActive reports whether the command declares a continuation
+// recipe the runtime can drive.
+func ContinuationActive(cmd *cobra.Command) bool {
+ return activeContinuation(cmd) != nil && activeOutcome(cmd) != nil
+}
+
+type continuationRun struct {
+ cmd *cobra.Command
+ cfg *continuationConfig
+ outcome *outcomeConfig
+ request interface{}
+ original interface{}
+ hop ContinuationHop
+ auto bool
+ limit int
+ skipped bool
+
+ hops int
+ state string
+ values map[string]string
+ sentValues map[string]string
+ fallback map[string]string
+ fallbackValid bool
+ limited bool
+ stalled bool
+ missing []string
+}
+
+func newContinuationRun(cmd *cobra.Command, request interface{}, hop ContinuationHop) (*continuationRun, error) {
+ run := &continuationRun{cmd: cmd, cfg: activeContinuation(cmd), outcome: activeOutcome(cmd), request: request, original: continuationRequestPayload(request), hop: hop, values: map[string]string{}, sentValues: map[string]string{}}
+ for i := range run.cfg.UnlessRequest {
+ if run.cfg.UnlessRequest[i].matches(run.original) {
+ run.skipped = true
+ break
+ }
+ }
+ for _, binding := range run.cfg.Bind {
+ if binding.Optional || !run.bindingEnabled(binding) {
+ continue
+ }
+ if value := continuationPathString(run.original, binding.ToPath); value != "" {
+ run.sentValues[binding.To] = value
+ }
+ }
+ run.auto, _ = flagutil.GetBoolFlag(cmd, "auto-continue")
+ run.limit = run.cfg.MaxHops
+ if flagutil.FlagChanged(cmd, "max-continuations") {
+ limit, _ := flagutil.GetIntFlag(cmd, "max-continuations")
+ if limit < 1 {
+ return nil, flagutil.WithCLIValidation(fmt.Errorf("--max-continuations must be at least 1, got %d", limit))
+ }
+ run.limit = limit
+ }
+ if run.limit < 1 {
+ run.limit = 1
+ }
+ return run, nil
+}
+
+func (r *continuationRun) beginHop() {
+ r.state = ""
+ r.values = map[string]string{}
+}
+
+func (r *continuationRun) bindingEnabled(binding continuationBinding) bool {
+ return binding.UnlessRequest == nil || !binding.UnlessRequest.matches(r.original)
+}
+
+func (r *continuationRun) omitEnabled(omit continuationOmit) bool {
+ return len(omit.Path) > 0 && (omit.UnlessRequest == nil || !omit.UnlessRequest.matches(r.original))
+}
+
+func continuationPathString(root interface{}, path []string) string {
+ current := root
+ for _, key := range path {
+ object, ok := current.(map[string]interface{})
+ if !ok {
+ return ""
+ }
+ current = object[key]
+ }
+ text, _ := current.(string)
+ return text
+}
+
+func continuationValuesEqual(left, right interface{}) bool {
+ if reflect.DeepEqual(left, right) {
+ return true
+ }
+ leftNumber, leftOK := continuationNumber(left)
+ rightNumber, rightOK := continuationNumber(right)
+ return leftOK && rightOK && leftNumber.Cmp(rightNumber) == 0
+}
+
+func continuationNumber(value interface{}) (*big.Rat, bool) {
+ var text string
+ switch number := value.(type) {
+ case json.Number:
+ text = number.String()
+ case float64:
+ text = strconv.FormatFloat(number, 'g', -1, 64)
+ case float32:
+ text = strconv.FormatFloat(float64(number), 'g', -1, 32)
+ case int:
+ text = strconv.Itoa(number)
+ case int64:
+ text = strconv.FormatInt(number, 10)
+ case uint64:
+ text = strconv.FormatUint(number, 10)
+ default:
+ return nil, false
+ }
+ return parseBoundedRat(text)
+}
+
+func (r *continuationRun) capture(payload interface{}, stream bool) {
+ for _, binding := range r.cfg.Bind {
+ if !r.bindingEnabled(binding) {
+ continue
+ }
+ pointers := []string{binding.Pointer}
+ if stream {
+ pointers = binding.StreamPointers
+ }
+ found := ""
+ for _, pointer := range pointers {
+ if pointer == "" {
+ continue
+ }
+ if value, ok := outcomePointer(payload, pointer); ok {
+ if text, isString := value.(string); isString && text != "" {
+ found = text
+ }
+ }
+ }
+ switch {
+ case found != "":
+ r.values[binding.To] = found
+ case stream && binding.StreamAuthoritativeWhen != nil && binding.StreamAuthoritativeWhen.matches(payload):
+ delete(r.values, binding.To)
+ }
+ }
+ pointers := []string{r.outcome.StatePointer}
+ if stream {
+ pointers = r.outcome.streamStatePointers()
+ }
+ for _, pointer := range pointers {
+ if pointer == "" {
+ continue
+ }
+ if value, ok := outcomePointer(payload, pointer); ok {
+ if text, isString := value.(string); isString && text != "" {
+ r.state = text
+ break
+ }
+ }
+ }
+}
+
+// advance reports whether another hop should be sent and, when it should,
+// writes the resume values into the request.
+func (r *continuationRun) advance() (bool, error) {
+ if r.outcome.States[r.state] != "continue" {
+ return false, nil
+ }
+ r.missing = nil
+ for _, binding := range r.cfg.Bind {
+ if !r.bindingEnabled(binding) {
+ continue
+ }
+ if !binding.Optional && r.values[binding.To] == "" {
+ r.missing = append(r.missing, binding.To)
+ }
+ }
+ if len(r.missing) == 0 {
+ r.fallback = cloneContinuationValues(r.values)
+ r.fallbackValid = true
+ }
+ if len(r.missing) > 0 || !r.auto {
+ return false, nil
+ }
+ if r.repeated() {
+ r.stalled = true
+ return false, nil
+ }
+ if r.hops >= r.limit {
+ r.limited = true
+ return false, nil
+ }
+ var sets []continuationBodySet
+ for _, binding := range r.cfg.Bind {
+ if !r.bindingEnabled(binding) {
+ continue
+ }
+ if value, ok := r.values[binding.To]; ok {
+ sets = append(sets, continuationBodySet{to: binding.To, path: binding.ToPath, value: value})
+ }
+ }
+ var omits [][]string
+ for _, omit := range r.cfg.Omit {
+ if r.omitEnabled(omit) {
+ omits = append(omits, omit.Path)
+ }
+ }
+ if err := updateContinuationBody(r.request, sets, omits); err != nil {
+ return false, r.wrap(WithCLIReason(fmt.Errorf("cannot prepare the next request: %w", err), ReasonCLIRuntime))
+ }
+ if r.sentValues == nil {
+ r.sentValues = map[string]string{}
+ }
+ for _, set := range sets {
+ r.sentValues[set.to] = set.value
+ }
+ return true, nil
+}
+
+func (r *continuationRun) repeated() bool {
+ compared := false
+ for _, binding := range r.cfg.Bind {
+ if binding.Optional || !r.bindingEnabled(binding) {
+ continue
+ }
+ sent := r.sentValues[binding.To]
+ if sent == "" || r.values[binding.To] != sent {
+ return false
+ }
+ compared = true
+ }
+ return compared
+}
+
+func (r *continuationRun) send() (interface{}, error) {
+ res, err := r.hop()
+ if err != nil {
+ if r.hops == 0 {
+ return nil, err
+ }
+ return nil, r.wrap(err)
+ }
+ r.hops++
+ return res, nil
+}
+
+func (r *continuationRun) resumeFields() map[string]interface{} {
+ values := r.resumeValues()
+ if len(values) == 0 || !r.hasCompleteRequiredBindings(values) {
+ return nil
+ }
+ fields := map[string]interface{}{}
+ for to, value := range values {
+ fields[to] = value
+ }
+ return fields
+}
+
+func (r *continuationRun) resumable() bool {
+ values := r.resumeValues()
+ if len(values) == 0 || !r.hasCompleteRequiredBindings(values) {
+ return false
+ }
+ for _, binding := range r.cfg.Bind {
+ if r.bindingEnabled(binding) && values[binding.To] != "" {
+ return true
+ }
+ }
+ return false
+}
+
+func (r *continuationRun) hasCompleteRequiredBindings(values map[string]string) bool {
+ for _, binding := range r.cfg.Bind {
+ if r.bindingEnabled(binding) && !binding.Optional && values[binding.To] == "" {
+ return false
+ }
+ }
+ return true
+}
+
+func (r *continuationRun) resumeValues() map[string]string {
+ if r.outcome.States[r.state] == "success" || r.outcome.States[r.state] == "handoff" {
+ return nil
+ }
+ if r.outcome.States[r.state] == "failure" || len(r.values) == 0 || !r.hasCompleteRequiredBindings(r.values) || (r.repeated() && r.fallbackValid) {
+ if r.fallbackValid {
+ return r.fallback
+ }
+ return nil
+ }
+ return r.values
+}
+
+func cloneContinuationValues(values map[string]string) map[string]string {
+ cloned := make(map[string]string, len(values))
+ for key, value := range values {
+ cloned[key] = value
+ }
+ return cloned
+}
+
+// resumeHint names the command's own flags for each resume value; values
+// without a declared flag are named by their request-body path.
+func (r *continuationRun) resumeHint() string {
+ if !r.resumable() {
+ return ""
+ }
+ var flags, paths []string
+ values := r.resumeValues()
+ for _, binding := range r.cfg.Bind {
+ if !r.bindingEnabled(binding) {
+ continue
+ }
+ value, ok := values[binding.To]
+ if !ok {
+ continue
+ }
+ if binding.Flag != "" {
+ flags = append(flags, fmt.Sprintf("--%s %s", binding.Flag, strconv.Quote(value)))
+ } else {
+ paths = append(paths, fmt.Sprintf("%s=%s", binding.To, strconv.Quote(value)))
+ }
+ }
+ var parts []string
+ if len(flags) > 0 {
+ parts = append(parts, "re-run the same command with "+strings.Join(flags, " "))
+ }
+ if len(paths) > 0 {
+ parts = append(parts, "set "+strings.Join(paths, ", ")+" in the request body")
+ }
+ hint := "To continue, " + strings.Join(parts, " and ")
+ var omitted []string
+ for _, omit := range r.cfg.Omit {
+ if r.omitEnabled(omit) && omit.Name != "" {
+ omitted = append(omitted, omit.Name)
+ }
+ }
+ if len(omitted) > 0 {
+ hint += ", leaving " + strings.Join(omitted, ", ") + " out of the request body"
+ }
+ return hint
+}
+
+func (r *continuationRun) wrap(err error) error {
+ if err == nil {
+ return nil
+ }
+ return &continuationError{err: err, hops: r.hops, resume: r.resumeFields(), hint: r.resumeHint()}
+}
+
+// finish reports what the loop stopped on once the result is rendered.
+func (r *continuationRun) finish() error {
+ if r.limited {
+ return Error(r.cmd, &continuationLimitError{hops: r.hops, resume: r.resumeFields(), hint: r.resumeHint()})
+ }
+ if len(r.missing) > 0 {
+ sort.Strings(r.missing)
+ return Error(r.cmd, r.wrap(WithCLIReason(fmt.Errorf("the response reported state %q but carried no %s to continue with; the output is incomplete", r.state, strings.Join(r.missing, ", ")), ReasonCLIProtocol)))
+ }
+ if IsMachineMode(r.cmd) || r.cmd.Context().Err() != nil {
+ return nil
+ }
+ stderr := r.cmd.ErrOrStderr()
+ if r.hops > 1 {
+ fmt.Fprintf(stderr, "Continued across %d responses.\n", r.hops)
+ }
+ if r.stalled {
+ fmt.Fprintln(stderr, "Stopped continuing: the response returned the resume value it was sent with.")
+ }
+ if r.outcome.States[r.state] == "continue" && !r.auto {
+ if hint := r.resumeHint(); hint != "" {
+ fmt.Fprintln(stderr, hint+".")
+ }
+ }
+ return nil
+}
+
+type continuationError struct {
+ err error
+ hops int
+ resume map[string]interface{}
+ hint string
+}
+
+func (e *continuationError) Error() string { return e.err.Error() }
+
+func (e *continuationError) Unwrap() error { return e.err }
+
+func (e *continuationError) MachineErrorFields() map[string]interface{} {
+ fields := map[string]interface{}{}
+ var inner interface{ MachineErrorFields() map[string]interface{} }
+ if errors.As(e.err, &inner) {
+ for key, value := range inner.MachineErrorFields() {
+ fields[key] = value
+ }
+ }
+ fields["hops"] = e.hops
+ if len(e.resume) > 0 {
+ fields["continuation"] = e.resume
+ }
+ return fields
+}
+
+func (e *continuationError) CLIHints() []string {
+ var hints []string
+ var inner interface{ CLIHints() []string }
+ if errors.As(e.err, &inner) {
+ hints = append(hints, inner.CLIHints()...)
+ }
+ if e.hint != "" {
+ hints = append(hints, e.hint)
+ }
+ return hints
+}
+
+type continuationLimitError struct {
+ hops int
+ resume map[string]interface{}
+ hint string
+}
+
+func (e *continuationLimitError) Error() string {
+ return fmt.Sprintf("stopped after %d responses; the response still asks to continue (raise --max-continuations to allow more)", e.hops)
+}
+
+func (e *continuationLimitError) CLIReason() string { return ReasonCLIContinuationLimit }
+
+func (e *continuationLimitError) MachineErrorFields() map[string]interface{} {
+ fields := map[string]interface{}{"hops": e.hops}
+ if len(e.resume) > 0 {
+ fields["continuation"] = e.resume
+ }
+ return fields
+}
+
+func (e *continuationLimitError) CLIHints() []string {
+ if e.hint == "" {
+ return nil
+ }
+ return []string{e.hint}
+}
+
+// ContinuationResult sends the request, then re-sends it with the resume
+// values from each response while the response's state classifies as
+// continue, and renders one result.
+func ContinuationResult(cmd *cobra.Command, request interface{}, hop ContinuationHop) error {
+ run, err := newContinuationRun(cmd, request, hop)
+ if err != nil {
+ return err
+ }
+ res, err := run.send()
+ if err != nil {
+ return Error(cmd, err)
+ }
+ if run.skipped {
+ return Result(cmd, res)
+ }
+ return run.discrete(res)
+}
+
+// discrete continues from an already-sent response whose body is a single
+// JSON document.
+func (r *continuationRun) discrete(res interface{}) error {
+ cmd, run := r.cmd, r
+ var (
+ last interface{}
+ payloads []interface{}
+ )
+ for {
+ if len(payloads) > 0 {
+ var err error
+ if res, err = run.send(); err != nil {
+ return Error(cmd, err)
+ }
+ }
+ if flagutil.DidDryRunRequest(cmd) {
+ return Result(cmd, res)
+ }
+ payload, ok := outcomeResultPayload(res)
+ if !ok {
+ return Result(cmd, res)
+ }
+ last = res
+ payloads = append(payloads, payload)
+ run.beginHop()
+ run.capture(payload, false)
+ more, err := run.advance()
+ if err != nil {
+ return Error(cmd, err)
+ }
+ if !more {
+ break
+ }
+ }
+
+ target := last
+ if run.combines(len(payloads)) {
+ target = mergedContinuationResult(last, mergeContinuationPayloads(run.cfg, payloads))
+ }
+ if failure := outcomeResultFailure(cmd, target); failure != nil {
+ if activeArtifact(cmd) != nil {
+ return Error(cmd, run.wrap(failure))
+ }
+ if err := renderResult(cmd, target, true); err != nil {
+ return err
+ }
+ return Error(cmd, run.wrap(failure))
+ }
+ if err := Result(cmd, target); err != nil {
+ return err
+ }
+ return run.finish()
+}
+
+// combines leaves a single auto-continued response as sent unless the recipe
+// adds fields to it, so one-hop results match multi-hop ones.
+func (r *continuationRun) combines(hops int) bool {
+ cfg := r.cfg
+ if !r.auto || hops == 0 {
+ return false
+ }
+ if len(cfg.Collect) > 0 {
+ return true
+ }
+ for _, kept := range cfg.KeepFirst {
+ if kept.Fallback != "" {
+ return true
+ }
+ }
+ return hops > 1 && (len(cfg.Merge) > 0 || len(cfg.Sum) > 0 || len(cfg.KeepFirst) > 0 || len(cfg.SumBy) > 0)
+}
+
+func mergeContinuationPayloads(cfg *continuationConfig, payloads []interface{}) interface{} {
+ first := payloads[0]
+ merged := cloneContinuationJSON(payloads[len(payloads)-1])
+ for _, pointer := range cfg.Merge {
+ var drop *continuationMergeDrop
+ for i := range cfg.MergeDropLeadingWhere {
+ if cfg.MergeDropLeadingWhere[i].Pointer == pointer {
+ drop = &cfg.MergeDropLeadingWhere[i]
+ }
+ }
+ var items []interface{}
+ found := false
+ for i, payload := range payloads {
+ if value, ok := outcomePointer(payload, pointer); ok {
+ if list, isList := value.([]interface{}); isList {
+ if i > 0 && drop != nil {
+ list = dropContinuationLeading(list, drop)
+ }
+ items = append(items, cloneContinuationJSON(list).([]interface{})...)
+ found = true
+ }
+ }
+ }
+ if found {
+ if items == nil {
+ items = []interface{}{}
+ }
+ merged = setContinuationPointer(merged, pointer, items)
+ }
+ }
+ for _, kept := range cfg.KeepFirst {
+ value, ok := outcomePointer(first, kept.Pointer)
+ if (!ok || value == nil) && kept.Fallback != "" {
+ if fallback, found := outcomePointer(first, kept.Fallback); found && fallback != nil {
+ value, ok = fallback, true
+ }
+ }
+ switch {
+ case ok && value != nil:
+ parent := continuationParentPointer(kept.Pointer)
+ _, firstHasParent := continuationObjectAt(first, parent)
+ _, mergedHasParent := continuationObjectAt(merged, parent)
+ if firstHasParent || mergedHasParent {
+ merged = setContinuationPointer(merged, kept.Pointer, cloneContinuationJSON(value))
+ }
+ case len(payloads) > 1:
+ deleteContinuationPointer(merged, kept.Pointer)
+ }
+ }
+ for _, collect := range cfg.Collect {
+ if values := collectContinuationStrings(payloads, collect); len(values) > 0 {
+ merged = setContinuationPointer(merged, collect.To, values)
+ }
+ }
+ for _, pointer := range cfg.Sum {
+ if total, ok := sumContinuationValues(payloads, pointer); ok {
+ merged = setContinuationPointer(merged, pointer, total)
+ }
+ }
+ for _, rule := range cfg.SumBy {
+ if items, ok := sumContinuationGroups(payloads, rule); ok {
+ merged = setContinuationPointer(merged, rule.Pointer, items)
+ }
+ }
+ return merged
+}
+
+func dropContinuationLeading(items []interface{}, drop *continuationMergeDrop) []interface{} {
+ for len(items) > 0 {
+ object, ok := items[0].(map[string]interface{})
+ if !ok {
+ break
+ }
+ value, present := object[drop.Field]
+ if !present || !continuationValuesEqual(value, drop.Equals) {
+ break
+ }
+ items = items[1:]
+ }
+ return items
+}
+
+func collectContinuationStrings(payloads []interface{}, collect continuationCollect) []interface{} {
+ var values []interface{}
+ seen := map[string]bool{}
+ add := func(value interface{}) {
+ text, ok := value.(string)
+ if !ok || text == "" || (collect.Unique && seen[text]) {
+ return
+ }
+ seen[text] = true
+ values = append(values, text)
+ }
+ for _, payload := range payloads {
+ for _, pointer := range collect.From {
+ value, ok := outcomePointer(payload, pointer)
+ if !ok {
+ continue
+ }
+ if list, isList := value.([]interface{}); isList {
+ for _, item := range list {
+ add(item)
+ }
+ continue
+ }
+ add(value)
+ }
+ }
+ return values
+}
+
+type continuationGroup struct {
+ item map[string]interface{}
+ total *big.Rat
+ summed bool
+ unsummable bool
+}
+
+// sumContinuationGroups keeps items that are not objects with a scalar key
+// as they are.
+func sumContinuationGroups(payloads []interface{}, rule continuationSumBy) ([]interface{}, bool) {
+ var entries []interface{}
+ groups := map[string]*continuationGroup{}
+ found := false
+ for _, payload := range payloads {
+ value, ok := outcomePointer(payload, rule.Pointer)
+ list, isList := value.([]interface{})
+ if !ok || !isList {
+ continue
+ }
+ found = true
+ for _, element := range list {
+ object, isObject := element.(map[string]interface{})
+ var key interface{}
+ if isObject {
+ key = object[rule.Key]
+ }
+ id, groupable := continuationGroupKey(key)
+ if !groupable {
+ entries = append(entries, cloneContinuationJSON(element))
+ continue
+ }
+ group := groups[id]
+ if group == nil {
+ group = &continuationGroup{item: cloneContinuationJSON(object).(map[string]interface{}), total: new(big.Rat)}
+ groups[id] = group
+ entries = append(entries, group)
+ }
+ if number, ok := continuationNumber(object[rule.Value]); ok {
+ group.total.Add(group.total, number)
+ group.summed = true
+ } else if _, isNumber := object[rule.Value].(json.Number); isNumber {
+ group.unsummable = true
+ }
+ }
+ }
+ if !found {
+ return nil, false
+ }
+ items := make([]interface{}, 0, len(entries))
+ for _, entry := range entries {
+ group, isGroup := entry.(*continuationGroup)
+ if !isGroup {
+ items = append(items, entry)
+ continue
+ }
+ if group.summed && !group.unsummable {
+ group.item[rule.Value] = continuationTotal(group.total)
+ }
+ items = append(items, group.item)
+ }
+ return items, true
+}
+
+func continuationGroupKey(key interface{}) (string, bool) {
+ switch typed := key.(type) {
+ case string:
+ return "s" + typed, true
+ case bool:
+ return "b" + strconv.FormatBool(typed), true
+ }
+ if number, ok := continuationNumber(key); ok {
+ return "n" + number.RatString(), true
+ }
+ return "", false
+}
+
+func sumContinuationValues(payloads []interface{}, pointer string) (json.Number, bool) {
+ total := new(big.Rat)
+ found := false
+ for _, payload := range payloads {
+ value, ok := outcomePointer(payload, pointer)
+ if !ok {
+ continue
+ }
+ number, isNumber := value.(json.Number)
+ if !isNumber {
+ continue
+ }
+ term, ok := continuationNumber(number)
+ if !ok {
+ return "", false
+ }
+ total.Add(total, term)
+ found = true
+ }
+ if !found {
+ return "", false
+ }
+ return continuationTotal(total), true
+}
+
+func continuationTotal(total *big.Rat) json.Number {
+ if total.IsInt() {
+ return json.Number(total.Num().String())
+ }
+ approx, _ := total.Float64()
+ return json.Number(strconv.FormatFloat(approx, 'g', -1, 64))
+}
+
+func cloneContinuationJSON(value interface{}) interface{} {
+ switch typed := value.(type) {
+ case map[string]interface{}:
+ cloned := make(map[string]interface{}, len(typed))
+ for key, child := range typed {
+ cloned[key] = cloneContinuationJSON(child)
+ }
+ return cloned
+ case []interface{}:
+ cloned := make([]interface{}, len(typed))
+ for i, child := range typed {
+ cloned[i] = cloneContinuationJSON(child)
+ }
+ return cloned
+ default:
+ return value
+ }
+}
+
+func continuationPointerTokens(pointer string) []string {
+ if !strings.HasPrefix(pointer, "/") {
+ return nil
+ }
+ var tokens []string
+ for _, raw := range strings.Split(strings.TrimPrefix(pointer, "/"), "/") {
+ tokens = append(tokens, strings.ReplaceAll(strings.ReplaceAll(raw, "~1", "/"), "~0", "~"))
+ }
+ return tokens
+}
+
+func continuationParentPointer(pointer string) string {
+ if index := strings.LastIndex(pointer, "/"); index > 0 {
+ return pointer[:index]
+ }
+ return ""
+}
+
+func continuationObjectAt(root interface{}, pointer string) (map[string]interface{}, bool) {
+ value, ok := outcomePointer(root, pointer)
+ object, isObject := value.(map[string]interface{})
+ return object, ok && isObject
+}
+
+func setContinuationPointer(root interface{}, pointer string, value interface{}) interface{} {
+ tokens := continuationPointerTokens(pointer)
+ object, ok := root.(map[string]interface{})
+ if len(tokens) == 0 || !ok {
+ return root
+ }
+ current := object
+ for _, token := range tokens[:len(tokens)-1] {
+ child, ok := current[token].(map[string]interface{})
+ if !ok {
+ child = map[string]interface{}{}
+ current[token] = child
+ }
+ current = child
+ }
+ current[tokens[len(tokens)-1]] = value
+ return object
+}
+
+func deleteContinuationPointer(root interface{}, pointer string) {
+ tokens := continuationPointerTokens(pointer)
+ if len(tokens) == 0 {
+ return
+ }
+ parent, ok := continuationObjectAt(root, continuationParentPointer(pointer))
+ if ok {
+ delete(parent, tokens[len(tokens)-1])
+ }
+}
+
+type continuationHTTPMeta struct {
+ Response *http.Response
+}
+
+type continuationResultEnvelope struct {
+ HTTPMeta continuationHTTPMeta
+ Result interface{}
+}
+
+func mergedContinuationResult(last interface{}, merged interface{}) interface{} {
+ raw, err := json.Marshal(merged)
+ if err != nil {
+ return last
+ }
+ var resp http.Response
+ if lastResp := extractHTTPResponse(last); lastResp != nil {
+ resp = *lastResp
+ resp.Header = lastResp.Header.Clone()
+ }
+ resp.Body = io.NopCloser(bytes.NewReader(raw))
+ resp.ContentLength = int64(len(raw))
+ return &continuationResultEnvelope{
+ HTTPMeta: continuationHTTPMeta{Response: &resp},
+ Result: merged,
+ }
+}
+
+func continuationRequestPayload(request interface{}) interface{} {
+ target, err := continuationBodyTarget(request)
+ if err != nil {
+ return nil
+ }
+ encoded, err := json.Marshal(target.Interface())
+ if err != nil {
+ return nil
+ }
+ payload, err := decodeWithNumbers(encoded)
+ if err != nil {
+ return nil
+ }
+ return payload
+}
+
+type continuationBodySet struct {
+ to string
+ path []string
+ value string
+}
+
+// updateContinuationBody edits the request field tagged as the media-type
+// body, or the request itself when the body is the whole request. The body
+// round-trips through JSON so nested paths and union bodies are written the
+// way the API receives them.
+func updateContinuationBody(request interface{}, sets []continuationBodySet, omits [][]string) error {
+ if len(sets) == 0 && len(omits) == 0 {
+ return nil
+ }
+ target, err := continuationBodyTarget(request)
+ if err != nil {
+ return err
+ }
+ if target.Kind() == reflect.Ptr && target.IsNil() {
+ target.Set(reflect.New(target.Type().Elem()))
+ }
+ encoded, err := json.Marshal(target.Interface())
+ if err != nil {
+ return err
+ }
+ decoded, err := decodeWithNumbers(encoded)
+ if err != nil {
+ return err
+ }
+ body, ok := decoded.(map[string]interface{})
+ if !ok {
+ return errors.New("the request body is not a JSON object")
+ }
+ for _, set := range sets {
+ flagutil.SetBodyPath(body, set.path, set.value)
+ }
+ for _, path := range omits {
+ deleteContinuationBodyPath(body, path)
+ }
+ encoded, err = json.Marshal(body)
+ if err != nil {
+ return err
+ }
+ fresh := reflect.New(target.Type())
+ if err := json.Unmarshal(encoded, fresh.Interface()); err != nil {
+ return err
+ }
+ target.Set(fresh.Elem())
+ return nil
+}
+
+func deleteContinuationBodyPath(body map[string]interface{}, path []string) {
+ if len(path) == 0 {
+ return
+ }
+ current := body
+ for _, key := range path[:len(path)-1] {
+ child, ok := current[key].(map[string]interface{})
+ if !ok {
+ return
+ }
+ current = child
+ }
+ delete(current, path[len(path)-1])
+}
+
+func continuationBodyTarget(request interface{}) (reflect.Value, error) {
+ v := reflect.ValueOf(request)
+ if v.Kind() != reflect.Ptr || v.IsNil() {
+ return reflect.Value{}, errors.New("the request must be passed by pointer")
+ }
+ v = v.Elem()
+ s := v
+ for s.Kind() == reflect.Ptr && !s.IsNil() {
+ s = s.Elem()
+ }
+ if s.Kind() == reflect.Struct {
+ for i := 0; i < s.NumField(); i++ {
+ if strings.HasPrefix(s.Type().Field(i).Tag.Get("request"), "mediaType=") && s.Field(i).CanSet() {
+ return s.Field(i), nil
+ }
+ }
+ }
+ return v, nil
+}
+
+// ContinuationStream streams the response, then opens the next hop's stream
+// with the resume values seen in the events while the last reported state
+// classifies as continue. Every hop's events go to one output sequence.
+func ContinuationStream(cmd *cobra.Command, request interface{}, hop ContinuationHop, streamFieldName string) error {
+ run, err := newContinuationRun(cmd, request, hop)
+ if err != nil {
+ return err
+ }
+ if run.skipped || len(run.outcome.streamStatePointers()) == 0 {
+ res, err := run.send()
+ if err != nil {
+ return Error(cmd, err)
+ }
+ return StreamResult(cmd, res, streamFieldName)
+ }
+ res, err := run.send()
+ if err != nil {
+ return Error(cmd, err)
+ }
+ run.beginHop()
+ hops := &streamContinuation{run: run}
+ if err := streamResult(cmd, res, streamFieldName, hops, nil); err != nil || hops.finished {
+ return err
+ }
+ return run.finish()
+}
+
+type streamContinuation struct {
+ run *continuationRun
+ finished bool
+}
+
+func (s *streamContinuation) discrete(res interface{}) error {
+ s.finished = true
+ return s.run.discrete(res)
+}
+
+func (s *streamContinuation) observe(frame map[string]interface{}) {
+ if frame != nil {
+ s.run.capture(frame, true)
+ }
+}
+
+// abort discards the values captured in a stream the server ended with an
+// error event, so a resume points at the last hop that completed.
+func (s *streamContinuation) abort() {
+ s.run.state = ""
+ s.run.values = map[string]string{}
+}
+
+func (s *streamContinuation) wrap(err error) error { return s.run.wrap(err) }
+
+func (s *streamContinuation) next() (interface{}, bool, error) {
+ switch s.run.outcome.States[s.run.state] {
+ case "continue", "success", "failure", "handoff":
+ default:
+ if s.run.resumable() {
+ message := "the stream ended before reporting a final state"
+ if s.run.state != "" {
+ message = fmt.Sprintf("the stream ended while the response was still %q", s.run.state)
+ }
+ return nil, false, s.run.wrap(WithCLIReason(errors.New(message), ReasonCLIConnection))
+ }
+ }
+ more, err := s.run.advance()
+ if err != nil || !more {
+ return nil, false, err
+ }
+ res, err := s.run.send()
+ if err != nil {
+ return nil, false, err
+ }
+ s.run.beginHop()
+ return res, true, nil
+}
diff --git a/internal/output/output_test.go b/internal/output/output_test.go
index 3b5c7207..da3e04cd 100644
--- a/internal/output/output_test.go
+++ b/internal/output/output_test.go
@@ -24,6 +24,8 @@ import (
"fmt"
"io"
"net/http"
+ "net/http/httptest"
+ "path/filepath"
"reflect"
"strings"
"testing"
@@ -1096,6 +1098,647 @@ func TestOutcomeStreamStatePointerOrder(t *testing.T) {
})
}
}
+func TestContinuationBindingPointerOrder(t *testing.T) {
+ run := &continuationRun{
+ cfg: &continuationConfig{Bind: []continuationBinding{
+ {StreamPointers: []string{"/first", "/last"}, To: "token"},
+ }},
+ outcome: &outcomeConfig{}, values: map[string]string{},
+ }
+ run.capture(map[string]interface{}{"first": "older", "last": "newer"}, true)
+ if got := run.values["token"]; got != "newer" {
+ t.Fatalf("token = %q, want last present binding value", got)
+ }
+}
+
+func TestContinuationRequestCondition(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ body map[string]interface{}
+ equals interface{}
+ wantEnabled bool
+ }{
+ {"false matches", map[string]interface{}{"retain": false}, false, false},
+ {"true differs", map[string]interface{}{"retain": true}, false, true},
+ {"missing differs", map[string]interface{}{}, false, true},
+ {"null differs from false", map[string]interface{}{"retain": nil}, false, true},
+ {"null matches null", map[string]interface{}{"retain": nil}, nil, false},
+ {"missing differs from null", map[string]interface{}{}, nil, true},
+ {"string differs from boolean", map[string]interface{}{"retain": "false"}, false, true},
+ {"numbers compare by value", map[string]interface{}{"retain": json.Number("1.0")}, float64(1), false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ run := &continuationRun{original: tc.body}
+ binding := continuationBinding{UnlessRequest: &continuationRequestCondition{Pointer: "/retain", Equals: tc.equals}}
+ if got := run.bindingEnabled(binding); got != tc.wantEnabled {
+ t.Fatalf("enabled = %v, want %v", got, tc.wantEnabled)
+ }
+ })
+ }
+}
+
+func TestContinuationCheckpointSnapshots(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ payload map[string]interface{}
+ want map[string]interface{}
+ }{
+ {"empty new hop", map[string]interface{}{}, map[string]interface{}{"$.resumeToken": "token-1", "$.previousId": "w1"}},
+ {"new id without token", map[string]interface{}{"id": "w2"}, map[string]interface{}{"$.resumeToken": "token-1", "$.previousId": "w1"}},
+ {"new checkpoint", map[string]interface{}{"resumeToken": "token-2", "id": "w2"}, map[string]interface{}{"$.resumeToken": "token-2", "$.previousId": "w2"}},
+ {"new token without optional id", map[string]interface{}{"resumeToken": "token-2"}, map[string]interface{}{"$.resumeToken": "token-2"}},
+ {"failure token ignored", map[string]interface{}{"status": "failed", "resumeToken": "bad-token", "id": "w2"}, map[string]interface{}{"$.resumeToken": "token-1", "$.previousId": "w1"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ request := map[string]interface{}{}
+ run := &continuationRun{
+ cfg: &continuationConfig{Bind: []continuationBinding{
+ {Pointer: "/resumeToken", To: "$.resumeToken", ToPath: []string{"resumeToken"}},
+ {Pointer: "/id", To: "$.previousId", ToPath: []string{"previousId"}, Optional: true},
+ }},
+ outcome: &outcomeConfig{StatePointer: "/status", States: map[string]string{"more": "continue", "failed": "failure"}},
+ request: &request, auto: true, limit: 3, hops: 1, values: map[string]string{},
+ }
+ run.capture(map[string]interface{}{"status": "more", "resumeToken": "token-1", "id": "w1"}, false)
+ if more, err := run.advance(); err != nil || !more {
+ t.Fatalf("advance = %v, %v", more, err)
+ }
+ run.beginHop()
+ run.capture(tc.payload, false)
+ if got := run.resumeFields(); !reflect.DeepEqual(got, tc.want) {
+ t.Fatalf("resume = %#v, want %#v", got, tc.want)
+ }
+ })
+ }
+}
+
+func continuationTestPayloads(t *testing.T, raws ...string) []interface{} {
+ t.Helper()
+ payloads := make([]interface{}, 0, len(raws))
+ for _, raw := range raws {
+ payload, err := decodeWithNumbers([]byte(raw))
+ if err != nil {
+ t.Fatalf("decode %s: %v", raw, err)
+ }
+ payloads = append(payloads, payload)
+ }
+ return payloads
+}
+
+func continuationTestJSON(t *testing.T, value interface{}) string {
+ t.Helper()
+ raw, err := json.Marshal(value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(raw)
+}
+
+func continuationTaskConfig() *continuationConfig {
+ return &continuationConfig{
+ Merge: []string{"/steps"},
+ MergeDropLeadingWhere: []continuationMergeDrop{{Pointer: "/steps", Field: "type", Equals: "prompt_echo"}},
+ KeepFirst: []continuationKeepFirst{
+ {Pointer: "/previous_id"},
+ {Pointer: "/started_at"},
+ {Pointer: "/usage/first_units", Fallback: "/usage/units"},
+ },
+ Collect: []continuationCollect{{To: "/run_ids", From: []string{"/run_ids", "/id"}, Unique: true}},
+ Sum: []string{"/usage/units"},
+ SumBy: []continuationSumBy{
+ {Pointer: "/usage/units_by_kind", Key: "kind", Value: "count"},
+ {Pointer: "/usage/tool_calls", Key: "type", Value: "count"},
+ },
+ }
+}
+
+func TestMergeContinuationPayloads(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ payloads []string
+ want string
+ }{
+ {
+ name: "three hops",
+ payloads: []string{
+ `{"id":"i1","started_at":"c1","steps":[{"type":"prompt_echo","text":"hi"},{"type":"output","text":"a"}],"usage":{"units":10,"units_by_kind":[{"kind":"alpha","count":10}],"tool_calls":[{"type":"search","count":1}]}}`,
+ `{"id":"i2","previous_id":"i1","run_ids":["i1"],"started_at":"c2","steps":[{"type":"prompt_echo","text":"hi"},{"type":"prompt_echo","text":"again"},{"type":"output","text":"b"},{"type":"prompt_echo","text":"kept"}],"usage":{"units":4,"units_by_kind":[{"kind":"beta","count":2},{"kind":"alpha","count":3}]}}`,
+ `{"id":"i3","previous_id":"i2","started_at":"c3","steps":[{"type":"output","text":"c"}],"usage":{"units":1,"units_by_kind":[{"kind":"alpha","count":9223372036854775807}],"tool_calls":[{"type":"search","count":2,"note":"last"}]}}`,
+ },
+ want: `{"id":"i3","run_ids":["i1","i2","i3"],"started_at":"c1","steps":[{"text":"hi","type":"prompt_echo"},{"text":"a","type":"output"},{"text":"b","type":"output"},{"text":"kept","type":"prompt_echo"},{"text":"c","type":"output"}],"usage":{"first_units":10,"tool_calls":[{"count":3,"type":"search"}],"units":15,"units_by_kind":[{"count":9223372036854775820,"kind":"alpha"},{"count":2,"kind":"beta"}]}}`,
+ },
+ {
+ name: "first hop values win and absent ones are removed",
+ payloads: []string{
+ `{"id":"i1","previous_id":"i0","usage":{"units":3,"first_units":2}}`,
+ `{"id":"i2","previous_id":"i1","started_at":"c2","usage":{"units":4}}`,
+ },
+ want: `{"id":"i2","previous_id":"i0","run_ids":["i1","i2"],"usage":{"first_units":2,"units":7}}`,
+ },
+ {
+ name: "single hop gains collected ids and the initial fallback",
+ payloads: []string{`{"id":"i1","usage":{"units":5}}`},
+ want: `{"id":"i1","run_ids":["i1"],"usage":{"first_units":5,"units":5}}`,
+ },
+ {
+ name: "an explicit first-hop null counts as absent",
+ payloads: []string{
+ `{"id":"i1","previous_id":null,"usage":{"first_units":null}}`,
+ `{"id":"i2","previous_id":"i1","usage":{"first_units":4}}`,
+ },
+ want: `{"id":"i2","run_ids":["i1","i2"],"usage":{}}`,
+ },
+ {
+ name: "a response without usage gains no usage",
+ payloads: []string{`{"id":"i1"}`, `{"id":"i2"}`},
+ want: `{"id":"i2","run_ids":["i1","i2"]}`,
+ },
+ {
+ name: "only the first hop keeps leading items",
+ payloads: []string{`{"id":"i1","steps":[{"type":"prompt_echo"}]}`, `{"id":"i2","steps":[{"type":"prompt_echo"}]}`},
+ want: `{"id":"i2","run_ids":["i1","i2"],"steps":[{"type":"prompt_echo"}]}`,
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ payloads := continuationTestPayloads(t, tc.payloads...)
+ last := continuationTestJSON(t, payloads[len(payloads)-1])
+ got := continuationTestJSON(t, mergeContinuationPayloads(continuationTaskConfig(), payloads))
+ if got != tc.want {
+ t.Fatalf("merged =\n%s\nwant\n%s", got, tc.want)
+ }
+ if after := continuationTestJSON(t, payloads[len(payloads)-1]); after != last {
+ t.Fatalf("the last payload changed: %s", after)
+ }
+ })
+ }
+}
+
+func TestMergeContinuationCollectKeepsDuplicates(t *testing.T) {
+ cfg := &continuationConfig{Collect: []continuationCollect{{To: "/ids", From: []string{"/ids", "/id"}}}}
+ payloads := continuationTestPayloads(t, `{"id":"a","ids":["a",""]}`, `{"id":"a"}`)
+ if got := continuationTestJSON(t, mergeContinuationPayloads(cfg, payloads)); got != `{"id":"a","ids":["a","a","a"]}` {
+ t.Fatalf("merged = %s", got)
+ }
+}
+
+func TestMergeContinuationSumByNumericKeys(t *testing.T) {
+ cfg := &continuationConfig{SumBy: []continuationSumBy{
+ {Pointer: "/counts", Key: "id", Value: "n"},
+ }}
+ payloads := continuationTestPayloads(t, `{"counts":[{"id":1,"n":1},{"id":-0,"n":1}]}`, `{"counts":[{"id":1.0,"n":2},{"id":"1","n":4},{"id":0,"n":1},{"n":8}]}`)
+ want := `{"counts":[{"id":1,"n":3},{"id":-0,"n":2},{"id":"1","n":4},{"n":8}]}`
+ if got := continuationTestJSON(t, mergeContinuationPayloads(cfg, payloads)); got != want {
+ t.Fatalf("merged = %s, want %s", got, want)
+ }
+}
+
+func TestContinuationCombines(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ cfg *continuationConfig
+ auto bool
+ hops int
+ want bool
+ }{
+ {"collect on one hop", &continuationConfig{Collect: []continuationCollect{{To: "/ids"}}}, true, 1, true},
+ {"keepFirst fallback on one hop", &continuationConfig{KeepFirst: []continuationKeepFirst{{Pointer: "/a", Fallback: "/b"}}}, true, 1, true},
+ {"merge and sum on one hop", &continuationConfig{Merge: []string{"/steps"}, Sum: []string{"/n"}}, true, 1, false},
+ {"merge on two hops", &continuationConfig{Merge: []string{"/steps"}}, true, 2, true},
+ {"keepFirst on two hops", &continuationConfig{KeepFirst: []continuationKeepFirst{{Pointer: "/a"}}}, true, 2, true},
+ {"auto-continue disabled", &continuationConfig{Collect: []continuationCollect{{To: "/ids"}}}, false, 1, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ run := &continuationRun{cfg: tc.cfg, auto: tc.auto}
+ if got := run.combines(tc.hops); got != tc.want {
+ t.Fatalf("combines = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestContinuationExistsCondition(t *testing.T) {
+ present, absent := true, false
+ for _, tc := range []struct {
+ name string
+ body map[string]interface{}
+ exists bool
+ want bool
+ }{
+ {"object present", map[string]interface{}{"runner": map[string]interface{}{}}, true, true},
+ {"missing", map[string]interface{}{}, true, false},
+ {"null counts as absent", map[string]interface{}{"runner": nil}, true, false},
+ {"absent matches exists false", map[string]interface{}{}, false, true},
+ {"present fails exists false", map[string]interface{}{"runner": "a"}, false, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ exists := &absent
+ if tc.exists {
+ exists = &present
+ }
+ condition := &continuationRequestCondition{Pointer: "/runner", Exists: exists}
+ if got := condition.matches(tc.body); got != tc.want {
+ t.Fatalf("matches = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestContinuationRecipeUnlessRequestSkips(t *testing.T) {
+ cmd := &cobra.Command{Use: "run"}
+ present := true
+ recipe, _ := json.Marshal(continuationConfig{
+ Bind: []continuationBinding{{Pointer: "/token", To: "$.token", ToPath: []string{"token"}}},
+ UnlessRequest: []continuationRequestCondition{{Pointer: "/detached", Equals: true}, {Pointer: "/runner", Exists: &present}},
+ })
+ cmd.Annotations = map[string]string{continuationAnnotation: string(recipe)}
+ for _, tc := range []struct {
+ name string
+ body map[string]interface{}
+ want bool
+ }{
+ {"attached engine request", map[string]interface{}{"engine": "e"}, false},
+ {"detached request", map[string]interface{}{"engine": "e", "detached": true}, true},
+ {"runner request", map[string]interface{}{"runner": "r"}, true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ body := tc.body
+ run, err := newContinuationRun(cmd, &body, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if run.skipped != tc.want {
+ t.Fatalf("skipped = %v, want %v", run.skipped, tc.want)
+ }
+ })
+ }
+}
+
+func TestContinuationRepeatedTokenStops(t *testing.T) {
+ newRun := func(sent string) *continuationRun {
+ request := map[string]interface{}{"token": sent}
+ return &continuationRun{
+ cfg: &continuationConfig{Bind: []continuationBinding{
+ {Pointer: "/token", To: "$.token", ToPath: []string{"token"}},
+ {Pointer: "/id", To: "$.previous", ToPath: []string{"previous"}, Optional: true},
+ }},
+ outcome: &outcomeConfig{StatePointer: "/status", States: map[string]string{"more": "continue"}},
+ request: &request,
+ auto: true,
+ limit: 1,
+ hops: 1,
+ values: map[string]string{},
+ sentValues: map[string]string{"$.token": sent},
+ }
+ }
+
+ run := newRun("t1")
+ run.capture(map[string]interface{}{"status": "more", "token": "t1", "id": "new-id"}, false)
+ if more, err := run.advance(); more || err != nil || !run.stalled || run.limited {
+ t.Fatalf("advance = %v, %v; stalled %v, limited %v", more, err, run.stalled, run.limited)
+ }
+
+ run = newRun("")
+ run.limit = 3
+ run.capture(map[string]interface{}{"status": "more", "token": "t1"}, false)
+ if more, err := run.advance(); !more || err != nil {
+ t.Fatalf("a first token must continue: %v, %v", more, err)
+ }
+ if run.sentValues["$.token"] != "t1" {
+ t.Fatalf("sent values = %#v", run.sentValues)
+ }
+ run.beginHop()
+ run.capture(map[string]interface{}{"status": "more", "token": "t1"}, true)
+ run.capture(map[string]interface{}{"status": "more", "token": "t1"}, false)
+ if more, _ := run.advance(); more || !run.stalled {
+ t.Fatalf("the repeated token must stop the loop")
+ }
+}
+
+func TestContinuationAuthoritativeStreamFrame(t *testing.T) {
+ run := &continuationRun{
+ cfg: &continuationConfig{Bind: []continuationBinding{
+ {
+ StreamPointers: []string{"/data/token", "/data/task/token"},
+ To: "$.token",
+ StreamAuthoritativeWhen: &continuationRequestCondition{Pointer: "/data/event_type", Equals: "completed"},
+ },
+ }},
+ outcome: &outcomeConfig{}, values: map[string]string{},
+ }
+ run.capture(map[string]interface{}{"data": map[string]interface{}{"event_type": "progress", "token": "mid"}}, true)
+ run.capture(map[string]interface{}{"data": map[string]interface{}{"event_type": "progress"}}, true)
+ if run.values["$.token"] != "mid" {
+ t.Fatalf("a progress event without a token keeps the checkpoint, got %#v", run.values)
+ }
+ run.capture(map[string]interface{}{"data": map[string]interface{}{"event_type": "completed", "task": map[string]interface{}{"token": ""}}}, true)
+ if _, ok := run.values["$.token"]; ok {
+ t.Fatalf("a completion without a token must clear the checkpoint, got %#v", run.values)
+ }
+ run.capture(map[string]interface{}{"data": map[string]interface{}{"event_type": "completed", "task": map[string]interface{}{"token": "final"}}}, true)
+ if run.values["$.token"] != "final" {
+ t.Fatalf("token = %#v", run.values)
+ }
+}
+
+func TestStreamContinuationAbortDiscardsHopValues(t *testing.T) {
+ newRun := func() *continuationRun {
+ request := map[string]interface{}{"prompt": "hi"}
+ return &continuationRun{
+ cfg: &continuationConfig{Bind: []continuationBinding{
+ {StreamPointers: []string{"/data/token"}, To: "$.token", ToPath: []string{"token"}},
+ {StreamPointers: []string{"/data/id"}, To: "$.previous", ToPath: []string{"previous"}, Optional: true},
+ }},
+ outcome: &outcomeConfig{StreamStatePointers: []string{"/data/status"}, States: map[string]string{"in_progress": "pending", "more": "continue"}},
+ request: &request,
+ auto: true,
+ limit: 3,
+ values: map[string]string{},
+ sentValues: map[string]string{},
+ }
+ }
+ progress := func(token, id string) map[string]interface{} {
+ return map[string]interface{}{"data": map[string]interface{}{"status": "in_progress", "token": token, "id": id}}
+ }
+
+ run := newRun()
+ run.hops = 1
+ run.capture(progress("mid1", "r1"), true)
+ hops := &streamContinuation{run: run}
+ hops.abort()
+ if fields := run.resumeFields(); fields != nil {
+ t.Fatalf("a first stream that ended in an error event has no resume point, got %#v", fields)
+ }
+ if hint := run.resumeHint(); hint != "" {
+ t.Fatalf("hint = %q", hint)
+ }
+
+ run = newRun()
+ run.hops = 1
+ run.capture(map[string]interface{}{"data": map[string]interface{}{"status": "more", "token": "t1", "id": "r1"}}, true)
+ if more, err := run.advance(); !more || err != nil {
+ t.Fatalf("advance = %v, %v", more, err)
+ }
+ run.hops = 2
+ run.beginHop()
+ run.capture(progress("mid2", "r2"), true)
+ hops = &streamContinuation{run: run}
+ hops.abort()
+ want := map[string]interface{}{"$.token": "t1", "$.previous": "r1"}
+ if fields := run.resumeFields(); !reflect.DeepEqual(fields, want) {
+ t.Fatalf("resume = %#v, want the last completed hop %#v", fields, want)
+ }
+
+ run.outcome.States["done"] = "success"
+ run.beginHop()
+ run.capture(map[string]interface{}{"data": map[string]interface{}{"status": "done", "id": "r2"}}, true)
+ hops.abort()
+ if fields := run.resumeFields(); !reflect.DeepEqual(fields, want) {
+ t.Fatalf("an error after a success frame keeps the last checkpoint: got %#v, want %#v", fields, want)
+ }
+}
+
+func TestContinuationOptionalOnlyHopFallsBack(t *testing.T) {
+ request := map[string]interface{}{"persist": false}
+ run := &continuationRun{
+ cfg: &continuationConfig{Bind: []continuationBinding{
+ {Pointer: "/token", To: "$.token", ToPath: []string{"token"}, UnlessRequest: &continuationRequestCondition{Pointer: "/persist", Equals: false}},
+ {Pointer: "/id", To: "$.previous", ToPath: []string{"previous"}, Optional: true},
+ }},
+ outcome: &outcomeConfig{StatePointer: "/status", States: map[string]string{"in_progress": "pending", "more": "continue"}},
+ request: &request,
+ original: map[string]interface{}{"persist": false},
+ auto: true,
+ limit: 3,
+ hops: 1,
+ values: map[string]string{},
+ sentValues: map[string]string{},
+ }
+ run.capture(map[string]interface{}{"status": "more", "id": "r1"}, false)
+ if more, err := run.advance(); !more || err != nil {
+ t.Fatalf("advance = %v, %v", more, err)
+ }
+ run.hops = 2
+ run.beginHop()
+ want := map[string]interface{}{"$.previous": "r1"}
+ if got := run.resumeFields(); !reflect.DeepEqual(got, want) {
+ t.Fatalf("a failed send keeps the last checkpoint: got %#v, want %#v", got, want)
+ }
+ run.capture(map[string]interface{}{"status": "in_progress"}, false)
+ if got := run.resumeFields(); !reflect.DeepEqual(got, want) {
+ t.Fatalf("a pending hop without values keeps the last checkpoint: got %#v, want %#v", got, want)
+ }
+ if !run.resumable() {
+ t.Fatal("the last checkpoint must stay resumable")
+ }
+}
+
+func TestContinuationRepeatedTokenDropKeepsIssuingOwner(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ frame map[string]interface{}
+ }{
+ {"echoed token without an id", map[string]interface{}{"data": map[string]interface{}{"status": "in_progress", "token": "t1"}}},
+ {"echoed token with a new id", map[string]interface{}{"data": map[string]interface{}{"status": "in_progress", "token": "t1", "id": "i2"}}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ request := map[string]interface{}{"prompt": "hi"}
+ run := &continuationRun{
+ cfg: &continuationConfig{Bind: []continuationBinding{
+ {StreamPointers: []string{"/data/token"}, To: "$.token", ToPath: []string{"token"}},
+ {StreamPointers: []string{"/data/id"}, To: "$.previous", ToPath: []string{"previous"}, Optional: true},
+ }},
+ outcome: &outcomeConfig{StreamStatePointers: []string{"/data/status"}, States: map[string]string{"in_progress": "pending", "more": "continue"}},
+ request: &request,
+ auto: true,
+ limit: 3,
+ hops: 1,
+ values: map[string]string{},
+ sentValues: map[string]string{},
+ }
+ run.capture(map[string]interface{}{"data": map[string]interface{}{"status": "more", "token": "t1", "id": "i1"}}, true)
+ if more, err := run.advance(); !more || err != nil {
+ t.Fatalf("advance = %v, %v", more, err)
+ }
+ run.hops = 2
+ run.beginHop()
+ run.capture(tc.frame, true)
+
+ var wrapped *continuationError
+ if !errors.As(run.wrap(errors.New("stream dropped")), &wrapped) {
+ t.Fatal("expected a continuation error")
+ }
+ want := map[string]interface{}{"$.token": "t1", "$.previous": "i1"}
+ if got := wrapped.MachineErrorFields()["continuation"]; !reflect.DeepEqual(got, want) {
+ t.Fatalf("continuation = %#v, want %#v", got, want)
+ }
+ })
+ }
+}
+
+func TestMergedContinuationResultKeepsResponseMetadata(t *testing.T) {
+ apiRequest, err := http.NewRequest(http.MethodPost, "http://127.0.0.1:8080/v1/widgets", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ apiRequest.Header.Set("Authorization", "Bearer secret")
+ lastResponse := &http.Response{
+ Status: "201 Created",
+ StatusCode: http.StatusCreated,
+ Proto: "HTTP/1.1",
+ Header: http.Header{"X-Request-Id": []string{"r1"}},
+ Body: io.NopCloser(strings.NewReader(`{"id":"i1"}`)),
+ Request: apiRequest,
+ }
+ last := &continuationResultEnvelope{HTTPMeta: continuationHTTPMeta{Response: lastResponse}}
+ merged := map[string]interface{}{"id": "i1", "ids": []interface{}{"i1"}}
+
+ got := extractHTTPResponse(mergedContinuationResult(last, merged))
+ if got == nil || got == lastResponse {
+ t.Fatalf("expected a fresh response, got %#v", got)
+ }
+ if got.Request != apiRequest || got.StatusCode != http.StatusCreated || got.Status != "201 Created" || got.Proto != "HTTP/1.1" {
+ t.Fatalf("response metadata was dropped: %#v", got)
+ }
+ if got.Header.Get("X-Request-Id") != "r1" {
+ t.Fatalf("headers = %#v", got.Header)
+ }
+ got.Header.Set("X-Request-Id", "changed")
+ if lastResponse.Header.Get("X-Request-Id") != "r1" {
+ t.Fatal("the merged response must not share headers with the last hop")
+ }
+ body, err := io.ReadAll(got.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(body) != `{"id":"i1","ids":["i1"]}` || got.ContentLength != int64(len(body)) {
+ t.Fatalf("body = %s, content length %d", body, got.ContentLength)
+ }
+}
+
+func TestContinuationResultCombinedArtifactDownloadsFromAPIOrigin(t *testing.T) {
+ ResetAgentMode()
+ ResetPreparsedRendering()
+ var authorization string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ authorization = r.Header.Get("Authorization")
+ w.Header().Set("Content-Type", "image/png")
+ _, _ = w.Write([]byte("png"))
+ }))
+ t.Cleanup(server.Close)
+
+ recipe, _ := json.Marshal(continuationConfig{
+ Bind: []continuationBinding{{Pointer: "/token", To: "$.token", ToPath: []string{"token"}}},
+ Collect: []continuationCollect{{To: "/ids", From: []string{"/id"}}},
+ })
+ outcome, _ := json.Marshal(outcomeConfig{StatePointer: "/status", States: map[string]string{"completed": "success", "more": "continue"}})
+ artifact, _ := json.Marshal(artifactConfig{Pointer: []artifactSegment{{Field: "outputs"}, {Wild: true}}, Kind: "image", DefaultPath: "asset.png"})
+ var stdout, stderr bytes.Buffer
+ cmd := &cobra.Command{Use: "image", Annotations: map[string]string{
+ continuationAnnotation: string(recipe),
+ outcomeAnnotation: string(outcome),
+ artifactAnnotation: string(artifact),
+ }}
+ cmd.SetContext(context.Background())
+ cmd.SetOut(&stdout)
+ cmd.SetErr(&stderr)
+ cmd.Flags().Bool("auto-continue", true, "")
+ cmd.Flags().String("out", filepath.Join(t.TempDir(), "asset.png"), "")
+ cmd.Flags().String("output-format", "pretty", "")
+
+ request := map[string]interface{}{"prompt": "hi"}
+ hop := func() (interface{}, error) {
+ apiRequest, err := http.NewRequest(http.MethodPost, server.URL+"/v1/widgets", nil)
+ if err != nil {
+ return nil, err
+ }
+ apiRequest.Header.Set("Authorization", "Bearer secret")
+ raw := `{"status":"completed","id":"i1","outputs":[{"type":"image","uri":"` + server.URL + `/asset.png"}]}`
+ return &continuationResultEnvelope{HTTPMeta: continuationHTTPMeta{Response: &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"application/json"}},
+ Body: io.NopCloser(strings.NewReader(raw)),
+ Request: apiRequest,
+ }}}, nil
+ }
+ if err := ContinuationResult(cmd, &request, hop); err != nil {
+ t.Fatalf("ContinuationResult: %v (stderr %q)", err, stderr.String())
+ }
+ if authorization != "Bearer secret" {
+ t.Fatalf("the same-origin download must carry the API credentials, got %q", authorization)
+ }
+}
+
+func TestContinuationResumeHintNamesOmittedFields(t *testing.T) {
+ newRun := func(body map[string]interface{}) *continuationRun {
+ return &continuationRun{
+ cfg: &continuationConfig{
+ Bind: []continuationBinding{{Pointer: "/token", To: "$.token", ToPath: []string{"token"}, Flag: "token"}},
+ Omit: []continuationOmit{{Name: "$.prompt", Path: []string{"prompt"}, UnlessRequest: &continuationRequestCondition{Pointer: "/persist", Equals: false}}},
+ },
+ outcome: &outcomeConfig{StatePointer: "/status", States: map[string]string{"more": "continue"}},
+ original: body,
+ values: map[string]string{"$.token": "t1"},
+ state: "more",
+ }
+ }
+ if got := newRun(map[string]interface{}{"prompt": "hi"}).resumeHint(); got != `To continue, re-run the same command with --token "t1", leaving $.prompt out of the request body` {
+ t.Fatalf("hint = %q", got)
+ }
+ if got := newRun(map[string]interface{}{"prompt": "hi", "persist": false}).resumeHint(); got != `To continue, re-run the same command with --token "t1"` {
+ t.Fatalf("hint = %q", got)
+ }
+}
+
+func TestUpdateContinuationBodySetsAndOmits(t *testing.T) {
+ request := map[string]interface{}{"prompt": "hi", "nested": map[string]interface{}{"prompt": "x", "keep": 1}, "engine": "e"}
+ err := updateContinuationBody(&request, []continuationBodySet{{to: "$.token", path: []string{"token"}, value: "t1"}}, [][]string{{"prompt"}, {"nested", "prompt"}, {"missing", "prompt"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := continuationTestJSON(t, request); got != `{"engine":"e","nested":{"keep":1},"token":"t1"}` {
+ t.Fatalf("request = %s", got)
+ }
+}
+
+func TestContinuationIgnoresUnboundedNumbers(t *testing.T) {
+ for _, number := range unboundedJSONNumbers() {
+ if _, ok := continuationNumber(number); ok {
+ t.Errorf("continuationNumber(%.20q) parsed", number)
+ }
+ if continuationValuesEqual(number, json.Number("1")) {
+ t.Errorf("continuationValuesEqual(%.20q, 1) = true", number)
+ }
+ if _, ok := continuationGroupKey(number); ok {
+ t.Errorf("continuationGroupKey(%.20q) grouped", number)
+ }
+ payloads := []interface{}{map[string]interface{}{
+ "total": number,
+ "counts": []interface{}{map[string]interface{}{"id": number, "n": json.Number("1")}, map[string]interface{}{"id": "a", "n": number}},
+ }}
+ if total, ok := sumContinuationValues(payloads, "/total"); ok {
+ t.Errorf("sumContinuationValues(%.20q) = %s", number, total)
+ }
+ items, ok := sumContinuationGroups(payloads, continuationSumBy{Pointer: "/counts", Key: "id", Value: "n"})
+ if !ok || len(items) != 2 || !reflect.DeepEqual(items[0], map[string]interface{}{"id": number, "n": json.Number("1")}) || !reflect.DeepEqual(items[1], map[string]interface{}{"id": "a", "n": number}) {
+ t.Errorf("sumContinuationGroups(%.20q) = %v", number, items)
+ }
+ }
+}
+
+func TestContinuationSumSkipsTotalsWithUnboundedTerms(t *testing.T) {
+ payloads := []interface{}{
+ map[string]interface{}{"total": json.Number("1"), "counts": []interface{}{map[string]interface{}{"id": "a", "n": json.Number("1")}, map[string]interface{}{"id": "b", "n": json.Number("1")}}},
+ map[string]interface{}{"total": json.Number("1e100000000"), "counts": []interface{}{map[string]interface{}{"id": "a", "n": json.Number("1e100000000")}, map[string]interface{}{"id": "b", "n": json.Number("2")}}},
+ }
+ if total, ok := sumContinuationValues(payloads, "/total"); ok {
+ t.Errorf("sumContinuationValues = %s, want no total", total)
+ }
+ items, ok := sumContinuationGroups(payloads, continuationSumBy{Pointer: "/counts", Key: "id", Value: "n"})
+ want := []interface{}{map[string]interface{}{"id": "a", "n": json.Number("1")}, map[string]interface{}{"id": "b", "n": json.Number("3")}}
+ if !ok || !reflect.DeepEqual(items, want) {
+ t.Errorf("sumContinuationGroups = %v, want %v", items, want)
+ }
+}
func unboundedJSONNumbers() []json.Number {
return []json.Number{
diff --git a/internal/usage/schema.go b/internal/usage/schema.go
index ba8dcfb3..d7298e10 100644
--- a/internal/usage/schema.go
+++ b/internal/usage/schema.go
@@ -45,7 +45,7 @@ type usageNode struct {
var usageNodes = map[string]usageNode{
"": {head: "name \"gemini-api\"\nbin \"gemini-api\"\nabout \"\"\"\n Gemini API: Use the Gemini Interactions API and managed-agent platform from the command line.\n\n Get started:\n Set GEMINI_API_KEY, or run: gemini-api configure\n Then run a model or managed agent: gemini-api agent --help\n Add --dry-run to preview any API call without sending it.\n \"\"\"\nversion \"0.5.0\"\nconfig {\n file \"~/.config/gemini-api/config.yaml\"\n}", flags: []usageItem{{key: "usage", text: "flag \"--usage\" help=\"Print the CLI Usage schema in KDL format\" global=#true"}, {key: "help-global", text: "flag \"--help-global\" help=\"Print global flags shared by every command\""}, {key: "version", text: "flag \"-v --version\" help=\"Print the CLI version\""}, {key: "output-format", text: "flag \"-o --output-format \" help=\"Specify the output format. Options: pretty, json, yaml, table, toon.\" global=#true config=\"output_format\" default=\"pretty\""}, {key: "color", text: "flag \"--color \" help=\"Control colored output: auto (color when output is a TTY), always, or never. Respects NO_COLOR and FORCE_COLOR env vars.\" global=#true default=\"auto\""}, {key: "jq", text: "flag \"-q --jq \" help=\"Filter and transform output using a jq expression (e.g., '.name', '.items[] | .id')\" global=#true"}, {key: "raw-output", text: "flag \"--raw-output\" help=\"Write --jq string results as raw text instead of JSON strings (like jq -r); non-string results stay JSON\" global=#true default=#true"}, {key: "server-url", text: "flag \"--server-url \" help=\"Override the default server URL\" global=#true"}, {key: "header", text: "flag \"-H --header \" help=\"Set a custom HTTP request header (format: \\\"Key: Value\\\"). Can be specified multiple times.\" global=#true var=#true"}, {key: "include-headers", text: "flag \"--include-headers\" help=\"Include HTTP response headers in the output\" global=#true default=#false"}, {key: "timeout", text: "flag \"--timeout \" help=\"HTTP request timeout (e.g., 30s, 5m, 100ms)\" global=#true config=\"timeout\""}, {key: "interactive", text: "flag \"--interactive\" help=\"Prompt for missing inputs and open guided configure/auth forms (forms fall back to line prompts on stdin off-TTY)\" global=#true default=#false"}, {key: "no-interactive", text: "flag \"--no-interactive\" help=\"Disable all interactive features (auto-prompting, explorer auto-launch, TUI forms)\" global=#true default=#false"}, {key: "dry-run", text: "flag \"--dry-run\" help=\"Preview API requests without sending them (no network, no OS keychain). Human preview on stderr; with -o json or --jq, one JSON object per request on stdout. Local mutation commands (auth login, auth logout and configure) make no request: they skip prompts and writes and report a no-op (stderr, or one JSON object on stdout in the machine form)\" global=#true default=#false"}, {key: "debug", text: "flag \"-d --debug\" help=\"Log request and response diagnostics to stderr\" global=#true default=#false"}, {key: "agent-mode", text: "flag \"--agent-mode\" help=\"Enable structured errors and default TOON output for AI coding agents.\" global=#true default=#false"}, {key: "no-retries", text: "flag \"--no-retries\" help=\"Disable automatic retries (default: retries enabled with exponential backoff)\" global=#true config=\"no_retries\" default=#false hide=#true", hidden: true}, {key: "retry-max-elapsed-time", text: "flag \"--retry-max-elapsed-time \" help=\"Maximum total time for retries (e.g., 30s, 5m). Default: 30s\" global=#true config=\"retry_max_elapsed_time\" hide=#true", hidden: true}, {key: "retry-connection-errors", text: "flag \"--retry-connection-errors\" help=\"Retry on connection errors (EOF, reset, etc.)\" global=#true config=\"retry_connection_errors\" default=#false hide=#true", hidden: true}, {key: "retry-config", text: "flag \"--retry-config \" help=\"Full retry config as JSON. Schema: {\\\"strategy\\\":\\\"backoff\\\",\\\"backoff\\\":{\\\"initialInterval\\\":500,\\\"maxInterval\\\":10000,\\\"exponent\\\":1.5,\\\"maxElapsedTime\\\":30000},\\\"retryConnectionErrors\\\":false}. Use strategy \\\"attempt-count-backoff\\\" with maxRetries for attempt-count retries. Times are in milliseconds.\" global=#true config=\"retry_config\" hide=#true", hidden: true}, {key: "api-key", text: "flag \"--api-key \" help=\"Gemini API key sent as x-goog-api-key.\" global=#true env=\"GEMINI_API_KEY\" config=\"security.api_key\""}, {key: "access-token", text: "flag \"--access-token \" help=\"OAuth access token sent as a bearer Authorization header.\" global=#true env=\"GEMINI_ACCESS_TOKEN\" config=\"security.access_token\""}, {key: "no-keyring", text: "flag \"--no-keyring\" help=\"Never read or write the OS keychain; store secrets in the config file instead\" global=#true env=\"GEMINI_NO_KEYRING\" config=\"no_keyring\" default=#false"}, {key: "api-version", text: "flag \"--api-version \" help=\"Which version of the API to use\" global=#true env=\"GEMINI_API_VERSION\" config=\"globals.api_version\" default=\"v1beta\""}, {key: "api-revision", text: "flag \"--api-revision \" help=\"Interactions API revision to request\" global=#true env=\"GEMINI_API_REVISION\" config=\"globals.api_revision\""}, {key: "user-project", text: "flag \"--user-project \" help=\"Quota project header to send with Google GenAI API requests\" global=#true env=\"GEMINI_USER_PROJECT\" config=\"globals.user_project\""}}, children: []string{"agent", "analyze", "auth", "configure", "credentials", "environments", "files", "generate", "image", "models", "music", "transcribe", "triggers", "tts", "video", "voices", "webhooks", "whoami", "completion", "explore", "help", "version"}},
"agent": {head: "cmd \"agent\" help=\"Run interactions with Gemini models or managed agents, and manage agent definitions\"", children: []string{"run", "cancel", "create", "delete", "delete-interaction", "get", "list", "status"}},
- "agent run": {head: "cmd \"run\" help=\"Run an interaction with a Gemini model or a managed agent\"", args: []usageItem{{key: "input", text: " arg \"input\" help=\"Prompt or task to send\" required=#true var=#true"}}, flags: []usageItem{{key: "body", text: " flag \"--body \" help=\"Request body as JSON (advanced; merges with intent inputs, rejecting duplicate keys). Can also be provided via stdin; @path reads a file, @- reads stdin to EOF. Use --schema to print the exact JSON Schema.\""}, {key: "schema", text: " flag \"--schema\" help=\"Print the exact JSON Schema of the request body and exit\""}, {key: "agent", text: " flag \"--agent \" help=\"Managed agent to run (see \\\"gemini-api agent list\\\") (e.g. deep-research-preview-04-2026, deep-research-max-preview-04-2026, antigravity-preview-05-2026, antigravity-preview-09-2026)\" {\n suggestions \"deep-research-preview-04-2026\" \"deep-research-max-preview-04-2026\" \"antigravity-preview-05-2026\" \"antigravity-preview-09-2026\"\n }"}, {key: "background", text: " flag \"--background\" help=\"Return immediately with an interaction ID; poll with \\\"gemini-api agent status\\\"\""}, {key: "model", text: " flag \"-m --model \" help=\"Model to run (see \\\"gemini-api models\\\") (e.g. gemma-4-26b-a4b-it, gemma-4-31b-it, gemini-flash-latest, gemini-flash-lite-latest, ..., default: gemini-4-hydrogen)\" default=\"gemini-4-hydrogen\" {\n suggestions \"gemma-4-26b-a4b-it\" \"gemma-4-31b-it\" \"gemini-flash-latest\" \"gemini-flash-lite-latest\" \"gemini-pro-latest\" \"gemini-2.5-flash\" \"gemini-2.5-pro\" \"gemini-2.5-flash-lite\" \"gemini-3.5-flash-lite\" \"gemini-2.5-flash-image\" \"gemini-3-flash-preview\" \"gemini-3.1-pro-preview\" \"gemini-3.1-pro-preview-customtools\" \"gemini-3.1-flash-lite\" \"gemini-3.1-flash-lite-image\" \"gemini-3-pro-image\" \"nano-banana-pro-preview\" \"gemini-3.1-flash-image\" \"gemini-nano-banana-2.1\" \"gemini-3.1-flash-tts-preview\" \"gemini-3.5-flash\" \"gemini-3.6-flash\" \"gemini-3.7-flash\" \"gemini-3.8-flash\" \"gemini-4-argon\" \"gemini-4-carbon\" \"gemini-4-hydrogen\" \"gemini-4-neon\" \"gemini-3.8-flash-tts\" \"gemini-3.8-flash-lite-tts\" \"gemini-3.5-transcribe\" \"lyria-3-clip-preview\" \"lyria-3-pro-preview\" \"gemini-robotics-er-1.6-preview\" \"gemini-robotics-er-2-preview\" \"lyria-3.5\" \"gemini-omni-1.2-flash\" \"gemini-omni-1.1-flash\" \"gemini-omni-flash-preview\"\n }"}, {key: "previous-interaction-id", text: " flag \"--previous-interaction-id \" help=\"Continue from an earlier interaction by passing its interaction ID\""}, {key: "stream", text: " flag \"--stream\" help=\"Stream the reply as it is generated; use --stream=false for one complete interaction (default: true)\" default=#true"}}},
+ "agent run": {head: "cmd \"run\" help=\"Run an interaction with a Gemini model or a managed agent\"", args: []usageItem{{key: "input", text: " arg \"input\" help=\"Prompt or task to send\" var=#true"}}, flags: []usageItem{{key: "body", text: " flag \"--body \" help=\"Request body as JSON (advanced; merges with intent inputs, rejecting duplicate keys). Can also be provided via stdin; @path reads a file, @- reads stdin to EOF. Use --schema to print the exact JSON Schema.\""}, {key: "schema", text: " flag \"--schema\" help=\"Print the exact JSON Schema of the request body and exit\""}, {key: "agent", text: " flag \"--agent \" help=\"Managed agent to run (see \\\"gemini-api agent list\\\") (e.g. deep-research-preview-04-2026, deep-research-max-preview-04-2026, antigravity-preview-05-2026, antigravity-preview-09-2026)\" {\n suggestions \"deep-research-preview-04-2026\" \"deep-research-max-preview-04-2026\" \"antigravity-preview-05-2026\" \"antigravity-preview-09-2026\"\n }"}, {key: "background", text: " flag \"--background\" help=\"Return immediately with an interaction ID; poll with \\\"gemini-api agent status\\\"\""}, {key: "continuation-token", text: " flag \"--continuation-token \" help=\"Resume a cut-off interaction from its checkpoint token\""}, {key: "model", text: " flag \"-m --model \" help=\"Model to run (see \\\"gemini-api models\\\") (e.g. gemma-4-26b-a4b-it, gemma-4-31b-it, gemini-flash-latest, gemini-flash-lite-latest, ..., default: gemini-4-hydrogen)\" default=\"gemini-4-hydrogen\" {\n suggestions \"gemma-4-26b-a4b-it\" \"gemma-4-31b-it\" \"gemini-flash-latest\" \"gemini-flash-lite-latest\" \"gemini-pro-latest\" \"gemini-2.5-flash\" \"gemini-2.5-pro\" \"gemini-2.5-flash-lite\" \"gemini-3.5-flash-lite\" \"gemini-2.5-flash-image\" \"gemini-3-flash-preview\" \"gemini-3.1-pro-preview\" \"gemini-3.1-pro-preview-customtools\" \"gemini-3.1-flash-lite\" \"gemini-3.1-flash-lite-image\" \"gemini-3-pro-image\" \"nano-banana-pro-preview\" \"gemini-3.1-flash-image\" \"gemini-nano-banana-2.1\" \"gemini-3.1-flash-tts-preview\" \"gemini-3.5-flash\" \"gemini-3.6-flash\" \"gemini-3.7-flash\" \"gemini-3.8-flash\" \"gemini-4-argon\" \"gemini-4-carbon\" \"gemini-4-hydrogen\" \"gemini-4-neon\" \"gemini-3.8-flash-tts\" \"gemini-3.8-flash-lite-tts\" \"gemini-3.5-transcribe\" \"lyria-3-clip-preview\" \"lyria-3-pro-preview\" \"gemini-robotics-er-1.6-preview\" \"gemini-robotics-er-2-preview\" \"lyria-3.5\" \"gemini-omni-1.2-flash\" \"gemini-omni-1.1-flash\" \"gemini-omni-flash-preview\"\n }"}, {key: "previous-interaction-id", text: " flag \"--previous-interaction-id \" help=\"Continue from an earlier interaction by passing its interaction ID\""}, {key: "store", text: " flag \"--store\" help=\"Store the interaction server-side for later retrieval or multi-turn continuation\""}, {key: "stream", text: " flag \"--stream\" help=\"Stream the reply as it is generated; use --stream=false for one complete interaction (default: true)\" default=#true"}}},
"agent cancel": {head: "cmd \"cancel\" help=\"Cancel an in-progress interaction by interaction ID\"", args: []usageItem{{key: "id", text: " arg \"id\" help=\"Required. The name of the interaction to cancel. (or use --id)\""}}, flags: []usageItem{{key: "id", text: " flag \"-i --id \" help=\"Required. The name of the interaction to cancel. (or pass it as the [id] argument)\""}}},
"agent create": {head: "cmd \"create\" help=\"Create a managed agent definition\"", flags: []usageItem{{key: "agent-config", text: " flag \"-a --agent-config \" help=\"{ \\\"max_total_tokens\\\": string, \\\"model\\\": string }\""}, {key: "base-agent", text: " flag \"--base-agent \" help=\"The base agent to extend. [required]\""}, {key: "base-environment", text: " flag \"--base-environment \" help=\"{ \\\"custom_config\\\": object, \\\"env\\\": object, \\\"environment_id\\\": string, \\\"mode\\\": string, ... } | string\""}, {key: "description", text: " flag \"--description \" help=\"Agent description for developers to quickly read and understand.\""}, {key: "id", text: " flag \"-i --id \" help=\"The unique identifier for the agent. [required]\""}, {key: "system-instruction", text: " flag \"-s --system-instruction \" help=\"System instruction for the agent.\""}, {key: "tools", text: " flag \"-t --tools \" help=\"The tools available to the agent. (JSON array)\""}, {key: "body", text: " flag \"--body \" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin; @path reads a file, @- reads stdin to EOF. Use --schema to print the exact JSON Schema.\""}, {key: "schema", text: " flag \"--schema\" help=\"Print the exact JSON Schema of the request body and exit\""}}},
"agent delete": {head: "cmd \"delete\" help=\"Delete a managed agent definition by ID\"", args: []usageItem{{key: "id", text: " arg \"id\" help=\"Required. The name of the agent to delete. (or use --id)\""}}, flags: []usageItem{{key: "id", text: " flag \"-i --id \" help=\"Required. The name of the agent to delete. (or pass it as the [id] argument)\""}}},
@@ -78,7 +78,7 @@ var usageNodes = map[string]usageNode{
"files get": {head: "cmd \"get\" help=\"Get a file's metadata and processing state\"", args: []usageItem{{key: "file", text: " arg \"file\" help=\"File to get, as files/ or a bare id (or use --file)\""}}, flags: []usageItem{{key: "file", text: " flag \"-f --file \" help=\"File to get, as files/ or a bare id (or pass it as the [file] argument)\""}}},
"files list": {head: "cmd \"list\" help=\"List uploaded and registered files\"", flags: []usageItem{{key: "page-size", text: " flag \"--page-size \" help=\"Maximum number of files to return per page (default 10, maximum 100)\""}, {key: "page-token", text: " flag \"--page-token \" help=\"Page token from a previous files list call\""}, {key: "all", text: " flag \"-a --all\" help=\"Automatically paginate and fetch all results (streams NDJSON for JSON output)\""}, {key: "max-pages", text: " flag \"--max-pages \" help=\"Maximum number of pages to fetch when using --all (0 = no limit)\" default=0"}}},
"files register": {head: "cmd \"register\" help=\"Register Google Cloud Storage objects as files without copying them\"", flags: []usageItem{{key: "uris", text: " flag \"-u --uris \" help=\"Required. The gs:// URIs of the Google Cloud Storage objects to register. (JSON array) [required]\""}, {key: "body", text: " flag \"--body \" help=\"Request body as JSON (alternative to individual flags). Can also be provided via stdin; @path reads a file, @- reads stdin to EOF. Use --schema to print the exact JSON Schema.\""}, {key: "schema", text: " flag \"--schema\" help=\"Print the exact JSON Schema of the request body and exit\""}}},
- "generate": {head: "cmd \"generate\" help=\"Text & multimodal generation (gemini-4-hydrogen)\"", args: []usageItem{{key: "prompt", text: " arg \"prompt\" help=\"Prompt to send to the model\" required=#true var=#true"}}, flags: []usageItem{{key: "body", text: " flag \"--body \" help=\"Request body as JSON (advanced; merges with intent inputs, rejecting duplicate keys). Can also be provided via stdin; @path reads a file, @- reads stdin to EOF. Use --schema to print the exact JSON Schema.\""}, {key: "schema", text: " flag \"--schema\" help=\"Print the exact JSON Schema of the request body and exit\""}, {key: "model", text: " flag \"-m --model \" help=\"Model to use (see \\\"gemini-api models\\\") (e.g. gemma-4-26b-a4b-it, gemma-4-31b-it, gemini-flash-latest, gemini-flash-lite-latest, ..., default: gemini-4-hydrogen)\" default=\"gemini-4-hydrogen\" {\n suggestions \"gemma-4-26b-a4b-it\" \"gemma-4-31b-it\" \"gemini-flash-latest\" \"gemini-flash-lite-latest\" \"gemini-pro-latest\" \"gemini-2.5-flash\" \"gemini-2.5-pro\" \"gemini-2.5-flash-lite\" \"gemini-3.5-flash-lite\" \"gemini-2.5-flash-image\" \"gemini-3-flash-preview\" \"gemini-3.1-pro-preview\" \"gemini-3.1-pro-preview-customtools\" \"gemini-3.1-flash-lite\" \"gemini-3.1-flash-lite-image\" \"gemini-3-pro-image\" \"nano-banana-pro-preview\" \"gemini-3.1-flash-image\" \"gemini-nano-banana-2.1\" \"gemini-3.1-flash-tts-preview\" \"gemini-3.5-flash\" \"gemini-3.6-flash\" \"gemini-3.7-flash\" \"gemini-3.8-flash\" \"gemini-4-argon\" \"gemini-4-carbon\" \"gemini-4-hydrogen\" \"gemini-4-neon\" \"gemini-3.8-flash-tts\" \"gemini-3.8-flash-lite-tts\" \"gemini-3.5-transcribe\" \"lyria-3-clip-preview\" \"lyria-3-pro-preview\" \"gemini-robotics-er-1.6-preview\" \"gemini-robotics-er-2-preview\" \"lyria-3.5\" \"gemini-omni-1.2-flash\" \"gemini-omni-1.1-flash\" \"gemini-omni-flash-preview\"\n }"}, {key: "previous-interaction-id", text: " flag \"--previous-interaction-id \" help=\"Continue from an earlier interaction by passing its interaction ID\""}, {key: "stream", text: " flag \"--stream\" help=\"Stream the reply as it is generated; use --stream=false for a single complete result (default: true)\" default=#true"}, {key: "system", text: " flag \"--system \" help=\"System instruction to steer the model\""}}},
+ "generate": {head: "cmd \"generate\" help=\"Text & multimodal generation (gemini-4-hydrogen)\"", args: []usageItem{{key: "prompt", text: " arg \"prompt\" help=\"Prompt to send to the model\" var=#true"}}, flags: []usageItem{{key: "body", text: " flag \"--body \" help=\"Request body as JSON (advanced; merges with intent inputs, rejecting duplicate keys). Can also be provided via stdin; @path reads a file, @- reads stdin to EOF. Use --schema to print the exact JSON Schema.\""}, {key: "schema", text: " flag \"--schema\" help=\"Print the exact JSON Schema of the request body and exit\""}, {key: "continuation-token", text: " flag \"--continuation-token \" help=\"Resume a cut-off interaction from its checkpoint token\""}, {key: "model", text: " flag \"-m --model \" help=\"Model to use (see \\\"gemini-api models\\\") (e.g. gemma-4-26b-a4b-it, gemma-4-31b-it, gemini-flash-latest, gemini-flash-lite-latest, ..., default: gemini-4-hydrogen)\" default=\"gemini-4-hydrogen\" {\n suggestions \"gemma-4-26b-a4b-it\" \"gemma-4-31b-it\" \"gemini-flash-latest\" \"gemini-flash-lite-latest\" \"gemini-pro-latest\" \"gemini-2.5-flash\" \"gemini-2.5-pro\" \"gemini-2.5-flash-lite\" \"gemini-3.5-flash-lite\" \"gemini-2.5-flash-image\" \"gemini-3-flash-preview\" \"gemini-3.1-pro-preview\" \"gemini-3.1-pro-preview-customtools\" \"gemini-3.1-flash-lite\" \"gemini-3.1-flash-lite-image\" \"gemini-3-pro-image\" \"nano-banana-pro-preview\" \"gemini-3.1-flash-image\" \"gemini-nano-banana-2.1\" \"gemini-3.1-flash-tts-preview\" \"gemini-3.5-flash\" \"gemini-3.6-flash\" \"gemini-3.7-flash\" \"gemini-3.8-flash\" \"gemini-4-argon\" \"gemini-4-carbon\" \"gemini-4-hydrogen\" \"gemini-4-neon\" \"gemini-3.8-flash-tts\" \"gemini-3.8-flash-lite-tts\" \"gemini-3.5-transcribe\" \"lyria-3-clip-preview\" \"lyria-3-pro-preview\" \"gemini-robotics-er-1.6-preview\" \"gemini-robotics-er-2-preview\" \"lyria-3.5\" \"gemini-omni-1.2-flash\" \"gemini-omni-1.1-flash\" \"gemini-omni-flash-preview\"\n }"}, {key: "previous-interaction-id", text: " flag \"--previous-interaction-id \" help=\"Continue from an earlier interaction by passing its interaction ID\""}, {key: "store", text: " flag \"--store\" help=\"Store the interaction server-side for later retrieval or multi-turn continuation\""}, {key: "stream", text: " flag \"--stream\" help=\"Stream the reply as it is generated; use --stream=false for a single complete result (default: true)\" default=#true"}, {key: "system", text: " flag \"--system \" help=\"System instruction to steer the model\""}}},
"image": {head: "cmd \"image\" help=\"Generate or edit images (gemini-nano-banana-2.1)\"", args: []usageItem{{key: "prompt", text: " arg \"prompt\" help=\"Image prompt\" required=#true var=#true"}}, flags: []usageItem{{key: "body", text: " flag \"--body \" help=\"Request body as JSON (advanced; merges with intent inputs, rejecting duplicate keys). Can also be provided via stdin; @path reads a file, @- reads stdin to EOF. Use --schema to print the exact JSON Schema.\""}, {key: "schema", text: " flag \"--schema\" help=\"Print the exact JSON Schema of the request body and exit\""}, {key: "aspect-ratio", text: " flag \"--aspect-ratio \" help=\"Aspect ratio of the output image (e.g. 1:1, 2:3, 3:2, 3:4, ...)\" {\n suggestions \"1:1\" \"2:3\" \"3:2\" \"3:4\" \"4:3\" \"4:5\" \"5:4\" \"9:16\" \"16:9\" \"21:9\" \"1:8\" \"8:1\" \"1:4\" \"4:1\"\n }"}, {key: "image-size", text: " flag \"--image-size \" help=\"Size of the output image (e.g. 512, 1K, 2K, 4K)\" {\n suggestions \"512\" \"1K\" \"2K\" \"4K\"\n }"}, {key: "model", text: " flag \"-m --model \" help=\"Override the image model (e.g. gemini-3.1-flash-image, gemini-3.1-flash-lite-image, gemini-3-pro-image, nano-banana-pro-preview, default: gemini-nano-banana-2.1)\" default=\"gemini-nano-banana-2.1\" {\n suggestions \"gemini-nano-banana-2.1\" \"gemini-3.1-flash-image\" \"gemini-3.1-flash-lite-image\" \"gemini-3-pro-image\" \"nano-banana-pro-preview\"\n }"}, {key: "output-mime-type", text: " flag \"--output-mime-type \" help=\"MIME type of the output image (e.g. image/jpeg)\" {\n suggestions \"image/jpeg\"\n }"}, {key: "previous-interaction-id", text: " flag \"--previous-interaction-id \" help=\"Continue from an earlier interaction, editing the image it produced\""}, {key: "out", text: " flag \"--out \" help=\"Write the image to this file (or into this directory). Default: ./gemini-image-{timestamp}-{rand}.{ext}\""}, {key: "raw-response", text: " flag \"--raw-response\" help=\"Print the raw API response instead of writing the image to a file\""}}},
"models": {head: "cmd \"models\" help=\"Show the curated offline model catalog; list/get query the live API\"", children: []string{"get", "list"}},
"models get": {head: "cmd \"get\" help=\"Get a model's live metadata (version, token limits, supported methods)\"", args: []usageItem{{key: "model", text: " arg \"model\" help=\"Model id, e.g. gemini-4-hydrogen (or use --model)\""}}, flags: []usageItem{{key: "model", text: " flag \"-m --model \" help=\"Model id, e.g. gemini-4-hydrogen (or pass it as the [model] argument)\""}}},
diff --git a/tests/contract/continuation_test.go b/tests/contract/continuation_test.go
new file mode 100644
index 00000000..6d6c93df
--- /dev/null
+++ b/tests/contract/continuation_test.go
@@ -0,0 +1,1264 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package contract_test
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "sync"
+ "testing"
+)
+
+type recordedHop struct {
+ Method string
+ Path string
+ Accept string
+ Body map[string]any
+}
+
+type continuationTestServer struct {
+ *httptest.Server
+ mu sync.Mutex
+ hops []recordedHop
+}
+
+func newContinuationServer(t *testing.T, handler func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request)) *continuationTestServer {
+ t.Helper()
+ s := &continuationTestServer{}
+ s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ raw, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Errorf("read request body: %v", err)
+ }
+ var body map[string]any
+ if len(raw) > 0 {
+ if err := json.Unmarshal(raw, &body); err != nil {
+ t.Errorf("unmarshal request body %q: %v", string(raw), err)
+ }
+ }
+ rec := recordedHop{
+ Method: r.Method,
+ Path: r.URL.Path,
+ Accept: r.Header.Get("Accept"),
+ Body: body,
+ }
+ s.mu.Lock()
+ s.hops = append(s.hops, rec)
+ hopNum := len(s.hops)
+ s.mu.Unlock()
+ handler(hopNum, rec, w, r)
+ }))
+ t.Cleanup(s.Close)
+ return s
+}
+
+func (s *continuationTestServer) recorded() []recordedHop {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ out := make([]recordedHop, len(s.hops))
+ copy(out, s.hops)
+ return out
+}
+
+func contHumanArgs(serverURL string, extra ...string) []string {
+ args := []string{
+ "--server-url", serverURL,
+ "--api-version", "v1beta",
+ "--no-interactive",
+ "--no-retries",
+ "--color", "never",
+ "--api-key", "test",
+ }
+ return append(args, extra...)
+}
+
+func TestContinuationMultiHopJSON(t *testing.T) {
+ runThreeHopJSON := func(t *testing.T, cmdArgs []string) {
+ t.Helper()
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch hop {
+ case 1:
+ fmt.Fprint(w, `{
+ "id": "int-1",
+ "status": "requires_continuation",
+ "continuation_token": "ct-1",
+ "previous_interaction_id": "parent-0",
+ "created": "2026-11-01T00:00:00Z",
+ "updated": "2026-11-01T00:00:01Z",
+ "input": "Write a long report",
+ "steps": [
+ {"type": "user_input", "content": [{"type": "text", "text": "Write a long report"}]},
+ {"type": "model_output", "content": [{"type": "text", "text": "Alpha "}]}
+ ],
+ "usage": {
+ "total_input_tokens": 100,
+ "total_output_tokens": 50,
+ "total_thought_tokens": 10,
+ "total_tool_use_tokens": 2,
+ "total_cached_tokens": 20,
+ "total_tokens": 162,
+ "input_tokens_by_modality": [{"modality": "text", "tokens": 90}, {"modality": "image", "tokens": 10}],
+ "output_tokens_by_modality": [{"modality": "text", "tokens": 50}],
+ "cached_tokens_by_modality": [{"modality": "text", "tokens": 20}],
+ "tool_use_tokens_by_modality": [{"modality": "text", "tokens": 2}],
+ "grounding_tool_count": [{"type": "google_search", "count": 1}]
+ }
+ }`)
+ case 2:
+ fmt.Fprint(w, `{
+ "id": "int-2",
+ "status": "requires_continuation",
+ "continuation_token": "ct-2",
+ "previous_interaction_id": "int-1",
+ "created": "2026-11-01T00:00:01Z",
+ "updated": "2026-11-01T00:00:02Z",
+ "steps": [
+ {"type": "user_input", "content": [{"type": "text", "text": "repeated prompt"}]},
+ {"type": "model_output", "content": [{"type": "text", "text": "Beta "}]}
+ ],
+ "usage": {
+ "initial_input_tokens": 150,
+ "total_input_tokens": 150,
+ "total_output_tokens": 60,
+ "total_thought_tokens": 15,
+ "total_tool_use_tokens": 3,
+ "total_cached_tokens": 25,
+ "total_tokens": 228,
+ "input_tokens_by_modality": [{"modality": "text", "tokens": 150}],
+ "output_tokens_by_modality": [{"modality": "text", "tokens": 60}],
+ "cached_tokens_by_modality": [{"modality": "text", "tokens": 25}],
+ "tool_use_tokens_by_modality": [{"modality": "text", "tokens": 3}],
+ "grounding_tool_count": [{"type": "google_search", "count": 2}, {"type": "url_context", "count": 1}]
+ }
+ }`)
+ case 3:
+ fmt.Fprint(w, `{
+ "id": "int-3",
+ "status": "completed",
+ "previous_interaction_id": "int-2",
+ "created": "2026-11-01T00:00:02Z",
+ "updated": "2026-11-01T00:00:03Z",
+ "steps": [
+ {"type": "user_input", "content": [{"type": "text", "text": "repeated prompt"}]},
+ {"type": "model_output", "content": [{"type": "text", "text": "Gamma"}]}
+ ],
+ "usage": {
+ "initial_input_tokens": 210,
+ "total_input_tokens": 210,
+ "total_output_tokens": 70,
+ "total_thought_tokens": 20,
+ "total_tool_use_tokens": 5,
+ "total_cached_tokens": 30,
+ "total_tokens": 305,
+ "input_tokens_by_modality": [{"modality": "text", "tokens": 210}],
+ "output_tokens_by_modality": [{"modality": "text", "tokens": 70}],
+ "cached_tokens_by_modality": [{"modality": "text", "tokens": 30}],
+ "tool_use_tokens_by_modality": [{"modality": "text", "tokens": 5}],
+ "grounding_tool_count": [{"type": "google_search", "count": 1}]
+ }
+ }`)
+ default:
+ t.Errorf("unexpected hop %d", hop)
+ w.WriteHeader(http.StatusInternalServerError)
+ }
+ })
+
+ args := append(baseArgs(srv.URL), cmdArgs...)
+ res := runCLI(t, t.TempDir(), nil, args...)
+ if res.err != nil {
+ t.Fatalf("%v failed: %v\nstderr: %s", cmdArgs, res.err, res.stderr)
+ }
+ if res.stderr != "" {
+ t.Errorf("machine-mode stderr must be empty on success, got %q", res.stderr)
+ }
+
+ hops := srv.recorded()
+ if len(hops) != 3 {
+ t.Fatalf("recorded %d hops, want 3", len(hops))
+ }
+
+ // Verify Hop 1 carries the initial input, parent ID, and settings, while
+ // stored continuation Hops 2-3 chain continuation_token + previous_interaction_id,
+ // omit input (already stored server-side), and preserve request settings.
+ wantPrevIDs := []any{"parent-0", "int-1", "int-2"}
+ wantTokens := []any{nil, "ct-1", "ct-2"}
+ for i, hop := range hops {
+ if hop.Method != http.MethodPost || hop.Path != "/v1beta/interactions" {
+ t.Errorf("hop %d request = %s %s, want POST /v1beta/interactions", i+1, hop.Method, hop.Path)
+ }
+ if i == 0 {
+ if got := hop.Body["input"]; got != "Write a long report" {
+ t.Errorf("hop 1 input = %#v, want %q", got, "Write a long report")
+ }
+ } else {
+ if _, hasInput := hop.Body["input"]; hasInput {
+ t.Errorf("stored hop %d must omit input, got %#v", i+1, hop.Body["input"])
+ }
+ }
+ if got := hop.Body["model"]; got != "gemini-3.8-flash" {
+ t.Errorf("hop %d model = %#v, want %q", i+1, got, "gemini-3.8-flash")
+ }
+ if got := hop.Body["stream"]; got != false {
+ t.Errorf("hop %d stream = %#v, want false", i+1, got)
+ }
+ if got := hop.Body["previous_interaction_id"]; got != wantPrevIDs[i] {
+ t.Errorf("hop %d previous_interaction_id = %#v, want %#v", i+1, got, wantPrevIDs[i])
+ }
+ if got := hop.Body["continuation_token"]; got != wantTokens[i] {
+ t.Errorf("hop %d continuation_token = %#v, want %#v", i+1, got, wantTokens[i])
+ }
+ if got := hop.Body["system_instruction"]; got != "Be thorough" {
+ t.Errorf("hop %d system_instruction = %#v, want %q", i+1, got, "Be thorough")
+ }
+ genCfg, ok := hop.Body["generation_config"].(map[string]any)
+ if !ok {
+ t.Fatalf("hop %d missing generation_config: %#v", i+1, hop.Body)
+ }
+ if genCfg["max_output_tokens"] != float64(4096) || genCfg["thinking_level"] != "high" || genCfg["thinking_summaries"] != "auto" {
+ t.Errorf("hop %d generation_config = %#v, want preserved settings", i+1, genCfg)
+ }
+ }
+
+ var combined map[string]any
+ if err := json.Unmarshal([]byte(res.stdout), &combined); err != nil {
+ t.Fatalf("unmarshal combined response: %v\nstdout: %s", err, res.stdout)
+ }
+ if combined["id"] != "int-3" || combined["status"] != "completed" || combined["updated"] != "2026-11-01T00:00:03Z" {
+ t.Errorf("top-level fields must come from last response, got id=%v status=%v updated=%v", combined["id"], combined["status"], combined["updated"])
+ }
+ // keepFirst preserves turn-start fields from hop 1.
+ if combined["previous_interaction_id"] != "parent-0" || combined["created"] != "2026-11-01T00:00:00Z" || combined["input"] != "Write a long report" {
+ t.Errorf("keepFirst fields must come from hop 1, got previous_interaction_id=%v created=%v input=%v", combined["previous_interaction_id"], combined["created"], combined["input"])
+ }
+ // collect gathers all hop IDs in order.
+ if !reflect.DeepEqual(combined["continuation_ids"], []any{"int-1", "int-2", "int-3"}) {
+ t.Errorf("continuation_ids = %#v, want [int-1 int-2 int-3]", combined["continuation_ids"])
+ }
+ if _, hasToken := combined["continuation_token"]; hasToken {
+ t.Errorf("last response had no continuation_token, but combined has %v", combined["continuation_token"])
+ }
+
+ // Steps must keep hop 1's user_input and drop repeated leading user_input
+ // steps on continuation hops 2-3.
+ steps, ok := combined["steps"].([]any)
+ if !ok || len(steps) != 4 {
+ t.Fatalf("combined steps = %#v, want 4 steps (1 user_input + 3 model_output)", combined["steps"])
+ }
+ var stepTypes, modelTexts []string
+ for _, s := range steps {
+ sm, _ := s.(map[string]any)
+ typ, _ := sm["type"].(string)
+ stepTypes = append(stepTypes, typ)
+ if typ == "model_output" {
+ content, _ := sm["content"].([]any)
+ cm, _ := content[0].(map[string]any)
+ text, _ := cm["text"].(string)
+ modelTexts = append(modelTexts, text)
+ }
+ }
+ if !reflect.DeepEqual(stepTypes, []string{"user_input", "model_output", "model_output", "model_output"}) {
+ t.Errorf("step types = %#v, want [user_input model_output model_output model_output]", stepTypes)
+ }
+ if !reflect.DeepEqual(modelTexts, []string{"Alpha ", "Beta ", "Gamma"}) {
+ t.Errorf("concatenated model step texts = %#v, want [Alpha , Beta , Gamma]", modelTexts)
+ }
+
+ // Per-hop usage counters are summed; initial_input_tokens falls back to
+ // hop 1's total_input_tokens (100) and is NOT summed.
+ usage, ok := combined["usage"].(map[string]any)
+ if !ok {
+ t.Fatalf("combined usage missing: %#v", combined)
+ }
+ wantUsage := map[string]float64{
+ "initial_input_tokens": 100, // fallback from hop 1 total_input_tokens
+ "total_input_tokens": 460, // 100 + 150 + 210
+ "total_output_tokens": 180, // 50 + 60 + 70
+ "total_thought_tokens": 45, // 10 + 15 + 20
+ "total_tool_use_tokens": 10, // 2 + 3 + 5
+ "total_cached_tokens": 75, // 20 + 25 + 30
+ "total_tokens": 695, // 162 + 228 + 305
+ }
+ for k, want := range wantUsage {
+ if got, _ := usage[k].(float64); got != want {
+ t.Errorf("usage.%s = %v, want %v", k, usage[k], want)
+ }
+ }
+
+ // sumBy aggregates modality token breakdowns and grounding tool counts by key.
+ wantInputMod := []any{
+ map[string]any{"modality": "text", "tokens": float64(450)},
+ map[string]any{"modality": "image", "tokens": float64(10)},
+ }
+ if !reflect.DeepEqual(usage["input_tokens_by_modality"], wantInputMod) {
+ t.Errorf("usage.input_tokens_by_modality = %#v, want %#v", usage["input_tokens_by_modality"], wantInputMod)
+ }
+ wantOutputMod := []any{map[string]any{"modality": "text", "tokens": float64(180)}}
+ if !reflect.DeepEqual(usage["output_tokens_by_modality"], wantOutputMod) {
+ t.Errorf("usage.output_tokens_by_modality = %#v, want %#v", usage["output_tokens_by_modality"], wantOutputMod)
+ }
+ wantCachedMod := []any{map[string]any{"modality": "text", "tokens": float64(75)}}
+ if !reflect.DeepEqual(usage["cached_tokens_by_modality"], wantCachedMod) {
+ t.Errorf("usage.cached_tokens_by_modality = %#v, want %#v", usage["cached_tokens_by_modality"], wantCachedMod)
+ }
+ wantToolMod := []any{map[string]any{"modality": "text", "tokens": float64(10)}}
+ if !reflect.DeepEqual(usage["tool_use_tokens_by_modality"], wantToolMod) {
+ t.Errorf("usage.tool_use_tokens_by_modality = %#v, want %#v", usage["tool_use_tokens_by_modality"], wantToolMod)
+ }
+ wantGrounding := []any{
+ map[string]any{"type": "google_search", "count": float64(4)},
+ map[string]any{"type": "url_context", "count": float64(1)},
+ }
+ if !reflect.DeepEqual(usage["grounding_tool_count"], wantGrounding) {
+ t.Errorf("usage.grounding_tool_count = %#v, want %#v", usage["grounding_tool_count"], wantGrounding)
+ }
+ }
+
+ t.Run("generate intent with generation_config and system", func(t *testing.T) {
+ runThreeHopJSON(t, []string{
+ "generate", "Write a long report",
+ "--model", "gemini-3.8-flash",
+ "--system", "Be thorough",
+ "--previous-interaction-id", "parent-0",
+ "--stream=false",
+ "--body", `{"generation_config":{"max_output_tokens":4096,"thinking_level":"high","thinking_summaries":"auto"}}`,
+ })
+ })
+
+ t.Run("agent run model route", func(t *testing.T) {
+ runThreeHopJSON(t, []string{
+ "agent", "run", "Write a long report",
+ "--model", "gemini-3.8-flash",
+ "--previous-interaction-id", "parent-0",
+ "--stream=false",
+ "--body", `{"system_instruction":"Be thorough","generation_config":{"max_output_tokens":4096,"thinking_level":"high","thinking_summaries":"auto"}}`,
+ })
+ })
+
+ t.Run("agent run agent route skips client-side continuation via unlessRequest", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprint(w, `{"id":"int-agent-1","status":"requires_continuation","continuation_token":"ct-agent-1","steps":[{"type":"model_output","content":[{"type":"text","text":"Managed"}]}]}`)
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL),
+ "agent", "run", "Write a long report",
+ "--agent", "deep-research-preview-04-2026",
+ "--stream=false")...)
+ if res.err != nil {
+ t.Fatalf("agent route failed: %v\nstderr: %s", res.err, res.stderr)
+ }
+ if len(srv.recorded()) != 1 {
+ t.Fatalf("agent route sent %d requests, want 1 (client-side continuation skipped)", len(srv.recorded()))
+ }
+ var out map[string]any
+ if err := json.Unmarshal([]byte(res.stdout), &out); err != nil {
+ t.Fatalf("unmarshal stdout: %v\nstdout: %s", err, res.stdout)
+ }
+ if out["id"] != "int-agent-1" || out["status"] != "requires_continuation" || out["continuation_token"] != "ct-agent-1" {
+ t.Errorf("agent route response = %#v, want verbatim server response", out)
+ }
+ if _, hasIDs := out["continuation_ids"]; hasIDs {
+ t.Errorf("skipped agent route must not add continuation_ids, got %#v", out["continuation_ids"])
+ }
+ })
+
+ t.Run("human mode prints continuation count on stderr while jq and agent-mode keep stderr silent", func(t *testing.T) {
+ newTwoHopServer := func(t *testing.T) *continuationTestServer {
+ return newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if hop == 1 {
+ fmt.Fprint(w, `{"id":"int-1","status":"requires_continuation","continuation_token":"ct-1","steps":[{"type":"model_output","content":[{"type":"text","text":"First"}]}],"usage":{"total_tokens":10}}`)
+ return
+ }
+ fmt.Fprint(w, `{"id":"int-2","status":"completed","steps":[{"type":"model_output","content":[{"type":"text","text":"Second"}]}],"usage":{"total_tokens":15}}`)
+ })
+ }
+
+ srvHuman := newTwoHopServer(t)
+ resHuman := runCLI(t, t.TempDir(), nil, contHumanArgs(srvHuman.URL, "generate", "hi", "--stream=false")...)
+ if resHuman.err != nil {
+ t.Fatalf("human mode failed: %v\nstderr: %s", resHuman.err, resHuman.stderr)
+ }
+ if !strings.Contains(resHuman.stderr, "Continued across 2 responses.") {
+ t.Errorf("human stderr = %q, want 'Continued across 2 responses.'", resHuman.stderr)
+ }
+
+ srvJQ := newTwoHopServer(t)
+ resJQ := runCLI(t, t.TempDir(), nil, contHumanArgs(srvJQ.URL, "generate", "hi", "--stream=false", "--jq", `[.steps[].content[].text, .usage.total_tokens]`)...)
+ if resJQ.err != nil {
+ t.Fatalf("jq mode failed: %v\nstderr: %s", resJQ.err, resJQ.stderr)
+ }
+ if resJQ.stderr != "" {
+ t.Errorf("jq stderr must be silent, got %q", resJQ.stderr)
+ }
+ var jqOut []any
+ if err := json.Unmarshal([]byte(resJQ.stdout), &jqOut); err != nil {
+ t.Fatalf("unmarshal jq stdout: %v\nstdout: %s", err, resJQ.stdout)
+ }
+ if !reflect.DeepEqual(jqOut, []any{"First", "Second", float64(25)}) {
+ t.Errorf("jq stdout = %#v, want [First Second 25]", jqOut)
+ }
+
+ srvAgent := newTwoHopServer(t)
+ resAgent := runCLI(t, t.TempDir(), nil, contHumanArgs(srvAgent.URL, "--agent-mode", "generate", "hi", "--stream=false")...)
+ if resAgent.err != nil {
+ t.Fatalf("agent-mode failed: %v\nstderr: %s", resAgent.err, resAgent.stderr)
+ }
+ if resAgent.stderr != "" {
+ t.Errorf("agent-mode stderr must be silent on success, got %q", resAgent.stderr)
+ }
+ if !strings.Contains(resAgent.stdout, "steps[2]:") || !strings.Contains(resAgent.stdout, "total_tokens: 25") {
+ t.Errorf("agent-mode TOON stdout = %q, want merged steps[2] and summed total_tokens: 25", resAgent.stdout)
+ }
+ })
+}
+
+func TestContinuationMultiHopStreaming(t *testing.T) {
+ newThreeHopSSEServer := func(t *testing.T) *continuationTestServer {
+ return newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ flusher, _ := w.(http.Flusher)
+ switch hop {
+ case 1:
+ // Hop 1: id arrives on interaction.created, text on step.delta,
+ // and status + continuation_token + interaction_id arrive on interaction.status_update ($.data.*).
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.created\",\"interaction\":{\"id\":\"int-s1\",\"status\":\"in_progress\"}}\n\n")
+ fmt.Fprint(w, "data: {\"event_type\":\"step.delta\",\"delta\":{\"type\":\"text\",\"text\":\"Hello \"},\"index\":0}\n\n")
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.status_update\",\"interaction_id\":\"int-s1\",\"status\":\"requires_continuation\",\"continuation_token\":\"ct-s1\"}\n\n")
+ fmt.Fprint(w, "data: [DONE]\n\n")
+ case 2:
+ // Hop 2: token, id, and status arrive across separate events and on interaction.completed ($.data.interaction.*).
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.status_update\",\"interaction_id\":\"int-s2\",\"status\":\"in_progress\"}\n\n")
+ fmt.Fprint(w, "data: {\"event_type\":\"step.delta\",\"delta\":{\"type\":\"text\",\"text\":\"streaming \"},\"index\":0}\n\n")
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.completed\",\"interaction\":{\"id\":\"int-s2\",\"status\":\"requires_continuation\",\"continuation_token\":\"ct-s2\"}}\n\n")
+ fmt.Fprint(w, "data: [DONE]\n\n")
+ case 3:
+ fmt.Fprint(w, "data: {\"event_type\":\"step.delta\",\"delta\":{\"type\":\"text\",\"text\":\"world!\"},\"index\":0}\n\n")
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.completed\",\"interaction\":{\"id\":\"int-s3\",\"status\":\"completed\"}}\n\n")
+ fmt.Fprint(w, "data: [DONE]\n\n")
+ default:
+ t.Errorf("unexpected SSE hop %d", hop)
+ }
+ if flusher != nil {
+ flusher.Flush()
+ }
+ })
+ }
+
+ t.Run("human stream projection across hops", func(t *testing.T) {
+ srv := newThreeHopSSEServer(t)
+ res := runCLI(t, t.TempDir(), nil, contHumanArgs(srv.URL, "generate", "Tell a story")...)
+ if res.err != nil {
+ t.Fatalf("streaming generate failed: %v\nstderr: %s", res.err, res.stderr)
+ }
+ if res.stdout != "Hello streaming world!\n" {
+ t.Errorf("stdout = %q, want %q", res.stdout, "Hello streaming world!\n")
+ }
+ if !strings.Contains(res.stderr, `Interaction ID: "int-s3"`) {
+ t.Errorf("stderr = %q, want final metadata 'Interaction ID: \"int-s3\"'", res.stderr)
+ }
+ if !strings.Contains(res.stderr, "Continued across 3 responses.") {
+ t.Errorf("stderr = %q, want 'Continued across 3 responses.'", res.stderr)
+ }
+
+ hops := srv.recorded()
+ if len(hops) != 3 {
+ t.Fatalf("recorded %d hops, want 3", len(hops))
+ }
+ if hops[0].Body["continuation_token"] != nil || hops[0].Body["previous_interaction_id"] != nil {
+ t.Errorf("hop 1 unexpected resume fields: %#v", hops[0].Body)
+ }
+ if hops[1].Body["continuation_token"] != "ct-s1" || hops[1].Body["previous_interaction_id"] != "int-s1" {
+ t.Errorf("hop 2 body = %#v, want ct-s1 and int-s1", hops[1].Body)
+ }
+ if hops[2].Body["continuation_token"] != "ct-s2" || hops[2].Body["previous_interaction_id"] != "int-s2" {
+ t.Errorf("hop 3 body = %#v, want ct-s2 and int-s2", hops[2].Body)
+ }
+ })
+
+ t.Run("NDJSON machine stream across hops", func(t *testing.T) {
+ srv := newThreeHopSSEServer(t)
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL), "agent", "run", "Tell a story")...)
+ if res.err != nil {
+ t.Fatalf("agent run -o json failed: %v\nstderr: %s", res.err, res.stderr)
+ }
+ if res.stderr != "" {
+ t.Errorf("stderr must be empty in -o json mode, got %q", res.stderr)
+ }
+ var nonEmpty []string
+ for _, txt := range deltaTexts(t, res.stdout) {
+ if txt != "" {
+ nonEmpty = append(nonEmpty, txt)
+ }
+ }
+ if !reflect.DeepEqual(nonEmpty, []string{"Hello ", "streaming ", "world!"}) {
+ t.Errorf("NDJSON delta texts = %#v, want [Hello , streaming , world!]", nonEmpty)
+ }
+ })
+}
+
+func TestContinuationStoredAndStatelessModes(t *testing.T) {
+ t.Run("stateless --store=false without parent id never sends previous_interaction_id", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if hop == 1 {
+ fmt.Fprint(w, `{"id":"int-stateless-1","status":"requires_continuation","continuation_token":"ct-stateless-1","steps":[{"type":"model_output","content":[{"type":"text","text":"One "}]}]}`)
+ return
+ }
+ fmt.Fprint(w, `{"id":"int-stateless-2","status":"completed","steps":[{"type":"model_output","content":[{"type":"text","text":"Two"}]}]}`)
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL), "generate", "hi", "--store=false", "--stream=false")...)
+ if res.err != nil {
+ t.Fatalf("stateless generate failed: %v\nstderr: %s", res.err, res.stderr)
+ }
+ hops := srv.recorded()
+ if len(hops) != 2 {
+ t.Fatalf("recorded %d hops, want 2", len(hops))
+ }
+ for i, hop := range hops {
+ if hop.Body["store"] != false {
+ t.Errorf("hop %d store = %#v, want false", i+1, hop.Body["store"])
+ }
+ if hop.Body["input"] != "hi" {
+ t.Errorf("hop %d in stateless mode must resend input, got %#v", i+1, hop.Body["input"])
+ }
+ if _, hasPrev := hop.Body["previous_interaction_id"]; hasPrev {
+ t.Errorf("hop %d in stateless mode must not send previous_interaction_id, got %#v", i+1, hop.Body["previous_interaction_id"])
+ }
+ }
+ if hops[1].Body["continuation_token"] != "ct-stateless-1" {
+ t.Errorf("hop 2 continuation_token = %#v, want ct-stateless-1", hops[1].Body["continuation_token"])
+ }
+ })
+
+ t.Run("stateless --store=false with initial previous_interaction_id preserves parent id across hops and omits it from resume hints", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if hop == 1 {
+ fmt.Fprint(w, `{"id":"ephemeral-hop-1","status":"requires_continuation","continuation_token":"ct-ephemeral-1","steps":[{"type":"model_output","content":[{"type":"text","text":"One "}]}]}`)
+ return
+ }
+ fmt.Fprint(w, `{"id":"ephemeral-hop-2","status":"completed","steps":[{"type":"model_output","content":[{"type":"text","text":"Two"}]}]}`)
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL),
+ "generate", "hi", "--store=false", "--previous-interaction-id", "stored-parent-0", "--stream=false")...)
+ if res.err != nil {
+ t.Fatalf("stateless generate with parent id failed: %v\nstderr: %s", res.err, res.stderr)
+ }
+ hops := srv.recorded()
+ if len(hops) != 2 {
+ t.Fatalf("recorded %d hops, want 2", len(hops))
+ }
+ for i, hop := range hops {
+ if got := hop.Body["previous_interaction_id"]; got != "stored-parent-0" {
+ t.Errorf("hop %d previous_interaction_id = %#v, want preserved 'stored-parent-0' (not ephemeral hop id)", i+1, got)
+ }
+ }
+
+ // With --auto-continue=false in stateless mode, the resume hint must NOT
+ // suggest --previous-interaction-id "ephemeral-hop-1".
+ srvHint := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprint(w, `{"id":"ephemeral-hop-1","status":"requires_continuation","continuation_token":"ct-ephemeral-1","steps":[]}`)
+ })
+ resHint := runCLI(t, t.TempDir(), nil, contHumanArgs(srvHint.URL,
+ "generate", "hi", "--store=false", "--previous-interaction-id", "stored-parent-0", "--stream=false", "--auto-continue=false")...)
+ if resHint.err != nil {
+ t.Fatalf("stateless --auto-continue=false failed: %v\nstderr: %s", resHint.err, resHint.stderr)
+ }
+ if !strings.Contains(resHint.stderr, `--continuation-token "ct-ephemeral-1"`) {
+ t.Errorf("stderr = %q, want --continuation-token hint", resHint.stderr)
+ }
+ if strings.Contains(resHint.stderr, "previous-interaction-id") || strings.Contains(resHint.stderr, "ephemeral-hop-1") {
+ t.Errorf("stateless resume hint must not include previous-interaction-id, got: %q", resHint.stderr)
+ }
+ })
+
+ t.Run("stateless streaming with store:false in --body never binds previous_interaction_id", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ if hop == 1 {
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.status_update\",\"interaction_id\":\"ephemeral-s1\",\"status\":\"requires_continuation\",\"continuation_token\":\"ct-s1\"}\n\n")
+ fmt.Fprint(w, "data: [DONE]\n\n")
+ return
+ }
+ fmt.Fprint(w, "data: {\"event_type\":\"step.delta\",\"delta\":{\"type\":\"text\",\"text\":\"Done\"},\"index\":0}\n\n")
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.completed\",\"interaction\":{\"id\":\"ephemeral-s2\",\"status\":\"completed\"}}\n\n")
+ fmt.Fprint(w, "data: [DONE]\n\n")
+ })
+
+ res := runCLI(t, t.TempDir(), nil, contHumanArgs(srv.URL,
+ "agent", "run", "--body", `{"model":"gemini-3.8-flash","input":"hi","store":false}`)...)
+ if res.err != nil {
+ t.Fatalf("stateless streaming agent run failed: %v\nstderr: %s", res.err, res.stderr)
+ }
+ hops := srv.recorded()
+ if len(hops) != 2 {
+ t.Fatalf("recorded %d hops, want 2", len(hops))
+ }
+ if _, hasPrev := hops[1].Body["previous_interaction_id"]; hasPrev {
+ t.Errorf("hop 2 in stateless streaming must not send previous_interaction_id, got %#v", hops[1].Body)
+ }
+ if hops[1].Body["continuation_token"] != "ct-s1" {
+ t.Errorf("hop 2 continuation_token = %#v, want ct-s1", hops[1].Body["continuation_token"])
+ }
+ })
+}
+
+func TestContinuationControlsAndLimits(t *testing.T) {
+ t.Run("--auto-continue=false stops after one hop and prints manual resume guidance in human mode only", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprint(w, `{"id":"int-manual-1","status":"requires_continuation","continuation_token":"ct-manual-1","steps":[{"type":"model_output","content":[{"type":"text","text":"Partial"}]}]}`)
+ })
+
+ resHuman := runCLI(t, t.TempDir(), nil, contHumanArgs(srv.URL, "generate", "hi", "--stream=false", "--auto-continue=false")...)
+ if resHuman.err != nil {
+ t.Fatalf("--auto-continue=false failed: %v\nstderr: %s", resHuman.err, resHuman.stderr)
+ }
+ if len(srv.recorded()) != 1 {
+ t.Fatalf("recorded %d hops, want 1", len(srv.recorded()))
+ }
+ wantHint := `re-run the same command with --continuation-token "ct-manual-1" --previous-interaction-id "int-manual-1", leaving $.input out of the request body`
+ if !strings.Contains(resHuman.stderr, wantHint) {
+ t.Errorf("human stderr = %q, want %q", resHuman.stderr, wantHint)
+ }
+
+ // Machine mode (-o json) must keep stderr silent.
+ srvJSON := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprint(w, `{"id":"int-manual-1","status":"requires_continuation","continuation_token":"ct-manual-1","steps":[]}`)
+ })
+ resJSON := runCLI(t, t.TempDir(), nil, append(baseArgs(srvJSON.URL), "generate", "hi", "--stream=false", "--auto-continue=false")...)
+ if resJSON.err != nil {
+ t.Fatalf("-o json --auto-continue=false failed: %v\nstderr: %s", resJSON.err, resJSON.stderr)
+ }
+ if resJSON.stderr != "" {
+ t.Errorf("-o json stderr = %q, want empty", resJSON.stderr)
+ }
+ })
+
+ t.Run("manual stored-mode resume omits input on generate and agent run across flags and --body", func(t *testing.T) {
+ cases := []struct {
+ name string
+ args []string
+ }{
+ {
+ name: "generate flags without prompt",
+ args: []string{"generate", "--continuation-token", "ct-resume-99", "--previous-interaction-id", "int-prev-99", "--stream=false"},
+ },
+ {
+ name: "generate --body without input",
+ args: []string{"generate", "--body", `{"continuation_token":"ct-resume-99","previous_interaction_id":"int-prev-99","stream":false}`},
+ },
+ {
+ name: "agent run flags without input",
+ args: []string{"agent", "run", "--continuation-token", "ct-resume-99", "--previous-interaction-id", "int-prev-99", "--stream=false"},
+ },
+ {
+ name: "agent run --body without input",
+ args: []string{"agent", "run", "--body", `{"model":"gemini-3.8-flash","continuation_token":"ct-resume-99","previous_interaction_id":"int-prev-99","stream":false}`},
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if hop == 1 {
+ fmt.Fprint(w, `{"id":"int-resumed-1","status":"requires_continuation","continuation_token":"ct-resume-100","steps":[{"type":"model_output","content":[{"type":"text","text":"Part 2"}]}],"usage":{"total_tokens":5}}`)
+ return
+ }
+ fmt.Fprint(w, `{"id":"int-resumed-2","status":"completed","steps":[{"type":"model_output","content":[{"type":"text","text":"Part 3"}]}],"usage":{"total_tokens":7}}`)
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL), tc.args...)...)
+ if res.err != nil {
+ t.Fatalf("manual resume failed: %v\nstderr: %s", res.err, res.stderr)
+ }
+ hops := srv.recorded()
+ if len(hops) != 2 {
+ t.Fatalf("recorded %d hops, want 2 (resumed hop + follow-up continuation)", len(hops))
+ }
+ if hops[0].Body["continuation_token"] != "ct-resume-99" || hops[0].Body["previous_interaction_id"] != "int-prev-99" {
+ t.Errorf("hop 1 body = %#v, want ct-resume-99 and int-prev-99", hops[0].Body)
+ }
+ if _, hasInput := hops[0].Body["input"]; hasInput {
+ t.Errorf("hop 1 stored manual resume must omit input, got %#v", hops[0].Body["input"])
+ }
+ if hops[1].Body["continuation_token"] != "ct-resume-100" || hops[1].Body["previous_interaction_id"] != "int-resumed-1" {
+ t.Errorf("hop 2 body = %#v, want ct-resume-100 and int-resumed-1", hops[1].Body)
+ }
+ if _, hasInput := hops[1].Body["input"]; hasInput {
+ t.Errorf("hop 2 stored continuation must omit input, got %#v", hops[1].Body["input"])
+ }
+ })
+ }
+
+ t.Run("generate piped stdin JSON resume without input", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprint(w, `{"id":"int-stdin-resumed","status":"completed","steps":[{"type":"model_output","content":[{"type":"text","text":"Done"}]}]}`)
+ })
+ res := runCLIWithStdin(t, t.TempDir(), nil,
+ `{"continuation_token":"ct-stdin-1","previous_interaction_id":"int-stdin-0","stream":false}`,
+ append(baseArgs(srv.URL), "generate")...)
+ if res.err != nil {
+ t.Fatalf("stdin manual resume failed: %v\nstderr: %s", res.err, res.stderr)
+ }
+ hops := srv.recorded()
+ if len(hops) != 1 {
+ t.Fatalf("recorded %d hops, want 1", len(hops))
+ }
+ if _, hasInput := hops[0].Body["input"]; hasInput {
+ t.Errorf("stdin stored manual resume must omit input, got %#v", hops[0].Body["input"])
+ }
+ if hops[0].Body["continuation_token"] != "ct-stdin-1" || hops[0].Body["previous_interaction_id"] != "int-stdin-0" {
+ t.Errorf("stdin resume body = %#v, want ct-stdin-1 and int-stdin-0", hops[0].Body)
+ }
+ })
+
+ t.Run("manual stateless resume with prompt re-sends input", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprint(w, `{"id":"int-stateless-resumed","status":"completed","steps":[]}`)
+ })
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL),
+ "generate", "original prompt", "--continuation-token", "ct-s-1", "--store=false", "--stream=false")...)
+ if res.err != nil {
+ t.Fatalf("stateless manual resume with prompt failed: %v\nstderr: %s", res.err, res.stderr)
+ }
+ hops := srv.recorded()
+ if len(hops) != 1 || hops[0].Body["input"] != "original prompt" || hops[0].Body["store"] != false {
+ t.Errorf("stateless manual resume body = %#v, want input and store=false", hops)
+ }
+ })
+ })
+
+ t.Run("missing input still fails CLI_VALIDATION when not resuming a stored model continuation", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ t.Errorf("unexpected HTTP request on hop %d: %#v", hop, req.Body)
+ })
+
+ badCases := []struct {
+ name string
+ args []string
+ wantSub string
+ wantHelp bool
+ }{
+ {
+ name: "bare generate",
+ args: []string{"generate"},
+ wantSub: "missing required argument ",
+ wantHelp: true,
+ },
+ {
+ name: "bare agent run",
+ args: []string{"agent", "run"},
+ wantSub: "missing required argument ",
+ wantHelp: true,
+ },
+ {
+ name: "generate with --model only",
+ args: []string{"generate", "--model", "gemini-3.8-flash"},
+ wantSub: "missing required argument ",
+ },
+ {
+ name: "generate with --body missing input and token",
+ args: []string{"generate", "--body", `{"model":"gemini-3.8-flash"}`},
+ wantSub: `has no "input"`,
+ },
+ {
+ name: "generate with empty --continuation-token",
+ args: []string{"generate", "--continuation-token", ""},
+ wantSub: "missing required argument ",
+ },
+ {
+ name: "generate stateless resume without prompt",
+ args: []string{"generate", "--continuation-token", "ct-1", "--store=false"},
+ wantSub: "stateless continuation (store=false) requires ",
+ },
+ {
+ name: "agent run with --model only",
+ args: []string{"agent", "run", "--model", "gemini-3.8-flash"},
+ wantSub: "missing required argument ",
+ },
+ {
+ name: "agent run with --body missing input and token",
+ args: []string{"agent", "run", "--body", `{"model":"gemini-3.8-flash"}`},
+ wantSub: `has no "input"`,
+ },
+ {
+ name: "agent run stateless --body resume without input",
+ args: []string{"agent", "run", "--body", `{"model":"gemini-3.8-flash","continuation_token":"ct-1","store":false}`},
+ wantSub: "stateless continuation (store=false) requires ",
+ },
+ {
+ name: "agent run --agent without input",
+ args: []string{"agent", "run", "--agent", "deep-research-preview-04-2026"},
+ wantSub: "missing required argument ",
+ },
+ {
+ name: "agent run --agent with --continuation-token without input",
+ args: []string{"agent", "run", "--agent", "deep-research-preview-04-2026", "--continuation-token", "ct-1"},
+ wantSub: "missing required argument ",
+ },
+ {
+ name: "agent run --background with --continuation-token without input",
+ args: []string{"agent", "run", "--background", "--continuation-token", "ct-1"},
+ wantSub: "missing required argument ",
+ },
+ }
+ for _, tc := range badCases {
+ t.Run(tc.name, func(t *testing.T) {
+ var cmdArgs []string
+ if tc.wantHelp {
+ cmdArgs = contHumanArgs(srv.URL, tc.args...)
+ } else {
+ cmdArgs = append(baseArgs(srv.URL), tc.args...)
+ }
+ res := runCLI(t, t.TempDir(), nil, cmdArgs...)
+ if code := exitCode(t, res); code != 2 {
+ t.Fatalf("exit code = %d, want 2\nstderr: %s", code, res.stderr)
+ }
+ if tc.wantHelp {
+ if !strings.Contains(res.stderr, tc.wantSub) {
+ t.Errorf("stderr = %q, want substring %q", res.stderr, tc.wantSub)
+ }
+ if !strings.Contains(res.stderr, "Usage:") {
+ t.Errorf("bare invocation stderr missing Usage help:\n%s", res.stderr)
+ }
+ return
+ }
+ var env struct {
+ Error string `json:"error"`
+ ErrorReason string `json:"error_reason"`
+ }
+ if err := json.Unmarshal([]byte(res.stderr), &env); err != nil {
+ t.Fatalf("unmarshal error JSON: %v\nstderr: %s", err, res.stderr)
+ }
+ if env.ErrorReason != "CLI_VALIDATION" {
+ t.Errorf("error_reason = %q, want CLI_VALIDATION (stderr: %s)", env.ErrorReason, res.stderr)
+ }
+ if !strings.Contains(env.Error, tc.wantSub) {
+ t.Errorf("error = %q, want substring %q", env.Error, tc.wantSub)
+ }
+ })
+ }
+ if len(srv.recorded()) != 0 {
+ t.Errorf("recorded %d requests, want 0", len(srv.recorded()))
+ }
+ })
+
+ t.Run("--max-continuations counts total responses including initial response and fails with CLI_CONTINUATION_LIMIT", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprintf(w, `{"id":"int-%d","status":"requires_continuation","continuation_token":"ct-%d","steps":[]}`, hop, hop)
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL),
+ "generate", "hi", "--stream=false", "--max-continuations", "2")...)
+ if code := exitCode(t, res); code != 1 {
+ t.Fatalf("exit code = %d, want 1\nstderr: %s", code, res.stderr)
+ }
+ if len(srv.recorded()) != 2 {
+ t.Fatalf("recorded %d hops, want 2 (initial + 1 continuation)", len(srv.recorded()))
+ }
+
+ var errEnv struct {
+ ErrorType string `json:"error_type"`
+ ErrorReason string `json:"error_reason"`
+ Hops int `json:"hops"`
+ Continuation map[string]string `json:"continuation"`
+ Hints []string `json:"hints"`
+ }
+ if err := json.Unmarshal([]byte(res.stderr), &errEnv); err != nil {
+ t.Fatalf("unmarshal error JSON: %v\nstderr: %s", err, res.stderr)
+ }
+ if errEnv.ErrorReason != "CLI_CONTINUATION_LIMIT" || errEnv.Hops != 2 {
+ t.Errorf("error = %+v, want error_reason=CLI_CONTINUATION_LIMIT hops=2", errEnv)
+ }
+ wantCont := map[string]string{
+ "$.continuation_token": "ct-2",
+ "$.previous_interaction_id": "int-2",
+ }
+ if !reflect.DeepEqual(errEnv.Continuation, wantCont) {
+ t.Errorf("continuation = %#v, want %#v", errEnv.Continuation, wantCont)
+ }
+ joinedHints := strings.Join(errEnv.Hints, " | ")
+ if !strings.Contains(joinedHints, `--continuation-token "ct-2" --previous-interaction-id "int-2"`) {
+ t.Errorf("hints = %q, want flag resume guidance", joinedHints)
+ }
+ })
+
+ t.Run("--max-continuations <= 0 fails locally with CLI_VALIDATION exit 2 before sending a request", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ t.Errorf("unexpected HTTP request on hop %d", hop)
+ })
+
+ for _, bad := range []string{"0", "-2"} {
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL),
+ "generate", "hi", "--max-continuations", bad)...)
+ if code := exitCode(t, res); code != 2 {
+ t.Errorf("--max-continuations %s exit code = %d, want 2\nstderr: %s", bad, code, res.stderr)
+ }
+ if !strings.Contains(res.stderr, "CLI_VALIDATION") {
+ t.Errorf("--max-continuations %s stderr = %q, want CLI_VALIDATION", bad, res.stderr)
+ }
+ }
+ if len(srv.recorded()) != 0 {
+ t.Errorf("recorded %d requests, want 0", len(srv.recorded()))
+ }
+ })
+
+ t.Run("missing required continuation_token when status is requires_continuation fails with CLI_PROTOCOL exit 1", func(t *testing.T) {
+ srvJSON := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprint(w, `{"id":"int-bad","status":"requires_continuation","steps":[]}`)
+ })
+ resJSON := runCLI(t, t.TempDir(), nil, append(baseArgs(srvJSON.URL), "generate", "hi", "--stream=false")...)
+ if code := exitCode(t, resJSON); code != 1 {
+ t.Fatalf("missing token JSON exit code = %d, want 1\nstderr: %s", code, resJSON.stderr)
+ }
+ if !strings.Contains(resJSON.stderr, `"error_reason": "CLI_PROTOCOL"`) {
+ t.Errorf("missing token JSON stderr = %s, want CLI_PROTOCOL", resJSON.stderr)
+ }
+
+ srvSSE := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.status_update\",\"interaction_id\":\"int-bad-sse\",\"status\":\"requires_continuation\"}\n\n")
+ fmt.Fprint(w, "data: [DONE]\n\n")
+ })
+ resSSE := runCLI(t, t.TempDir(), nil, append(baseArgs(srvSSE.URL), "generate", "hi")...)
+ if code := exitCode(t, resSSE); code != 1 {
+ t.Fatalf("missing token SSE exit code = %d, want 1\nstderr: %s", code, resSSE.stderr)
+ }
+ if !strings.Contains(resSSE.stderr, `"error_reason": "CLI_PROTOCOL"`) {
+ t.Errorf("missing token SSE stderr = %s, want CLI_PROTOCOL", resSSE.stderr)
+ }
+ })
+}
+
+func TestContinuationStatusClassificationAndTokenGuard(t *testing.T) {
+ // Token presence alone must NEVER trigger another request or emit a resume hint.
+ for _, status := range []string{"completed", "incomplete", "budget_exceeded", "requires_action"} {
+ t.Run("non-continue status "+status+" stops after one hop even with continuation_token", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprintf(w, `{"id":"int-term","status":%q,"continuation_token":"ct-should-not-use","steps":[{"type":"model_output","content":[{"type":"text","text":"Done"}]}]}`, status)
+ })
+
+ res := runCLI(t, t.TempDir(), nil, contHumanArgs(srv.URL,
+ "generate", "hi", "--stream=false",
+ "--body", `{"generation_config":{"max_output_tokens":256}}`)...)
+ if res.err != nil {
+ t.Fatalf("status %s failed: %v\nstderr: %s", status, res.err, res.stderr)
+ }
+ if len(srv.recorded()) != 1 {
+ t.Fatalf("status %s made %d hops, want 1", status, len(srv.recorded()))
+ }
+ if strings.Contains(res.stderr, "ct-should-not-use") || strings.Contains(res.stderr, "--continuation-token") {
+ t.Errorf("status %s unexpectedly emitted continuation hint on stderr: %q", status, res.stderr)
+ }
+ })
+ }
+
+ // Failed and cancelled responses must fail with CLI_OUTCOME_FAILED (exit 1)
+ // and never auto-resume, even when a continuation_token is present.
+ for _, status := range []string{"failed", "cancelled"} {
+ t.Run("failure status "+status+" on hop 1 exits 1 without auto-resuming", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprintf(w, `{"id":"int-fail-1","status":%q,"continuation_token":"ct-do-not-resume","errors":[{"message":"interaction %s"}]}`, status, status)
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL), "generate", "hi", "--stream=false")...)
+ if code := exitCode(t, res); code != 1 {
+ t.Fatalf("status %s exit code = %d, want 1\nstderr: %s", status, code, res.stderr)
+ }
+ if len(srv.recorded()) != 1 {
+ t.Fatalf("status %s made %d hops, want 1", status, len(srv.recorded()))
+ }
+ if !strings.Contains(res.stderr, `"error_reason": "CLI_OUTCOME_FAILED"`) {
+ t.Errorf("status %s stderr = %s, want CLI_OUTCOME_FAILED", status, res.stderr)
+ }
+ if strings.Contains(res.stderr, "ct-do-not-resume") {
+ t.Errorf("status %s on hop 1 must not offer a continuation checkpoint, got: %s", status, res.stderr)
+ }
+ })
+ }
+}
+
+func TestContinuationMidFlightFailuresCarryResumeContext(t *testing.T) {
+ t.Run("dropped stream on hop 1 after checkpoint token fails with resume context and never replays", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ // Emit a checkpoint token and partial text, then close the stream before [DONE]
+ // without reporting a terminal state.
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.created\",\"interaction\":{\"id\":\"int-drop-1\",\"status\":\"in_progress\"}}\n\n")
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.status_update\",\"interaction_id\":\"int-drop-1\",\"status\":\"in_progress\",\"continuation_token\":\"ct-drop-1\"}\n\n")
+ fmt.Fprint(w, "data: {\"event_type\":\"step.delta\",\"delta\":{\"type\":\"text\",\"text\":\"partial\"},\"index\":0}\n\n")
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL), "generate", "hi")...)
+ if code := exitCode(t, res); code != 1 {
+ t.Fatalf("dropped stream exit code = %d, want 1\nstderr: %s", code, res.stderr)
+ }
+ if len(srv.recorded()) != 1 {
+ t.Fatalf("dropped stream made %d hops, want 1 (no silent replay)", len(srv.recorded()))
+ }
+ var errEnv struct {
+ ErrorReason string `json:"error_reason"`
+ Hops int `json:"hops"`
+ Continuation map[string]string `json:"continuation"`
+ Hints []string `json:"hints"`
+ }
+ if err := json.Unmarshal([]byte(res.stderr), &errEnv); err != nil {
+ t.Fatalf("unmarshal error JSON: %v\nstderr: %s", err, res.stderr)
+ }
+ if errEnv.ErrorReason != "CLI_CONNECTION" || errEnv.Hops != 1 {
+ t.Errorf("error = %+v, want error_reason=CLI_CONNECTION hops=1", errEnv)
+ }
+ if errEnv.Continuation["$.continuation_token"] != "ct-drop-1" || errEnv.Continuation["$.previous_interaction_id"] != "int-drop-1" {
+ t.Errorf("continuation context = %#v, want ct-drop-1 and int-drop-1", errEnv.Continuation)
+ }
+ joinedHints := strings.Join(errEnv.Hints, " | ")
+ if !strings.Contains(joinedHints, `--continuation-token "ct-drop-1" --previous-interaction-id "int-drop-1"`) {
+ t.Errorf("hints = %q, want flag resume guidance", joinedHints)
+ }
+ })
+
+ t.Run("HTTP 500 on hop 2 reports hop 1 resume context", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if hop == 1 {
+ fmt.Fprint(w, `{"id":"int-ok-1","status":"requires_continuation","continuation_token":"ct-ok-1","steps":[{"type":"model_output","content":[{"type":"text","text":"Hop 1"}]}]}`)
+ return
+ }
+ w.WriteHeader(http.StatusInternalServerError)
+ fmt.Fprint(w, `{"error":{"message":"backend unavailable"}}`)
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL), "generate", "hi", "--stream=false")...)
+ if code := exitCode(t, res); code != 1 {
+ t.Fatalf("HTTP 500 on hop 2 exit code = %d, want 1\nstderr: %s", code, res.stderr)
+ }
+ if len(srv.recorded()) != 2 {
+ t.Fatalf("recorded %d hops, want 2", len(srv.recorded()))
+ }
+ var errEnv struct {
+ ErrorType string `json:"error_type"`
+ StatusCode int `json:"status_code"`
+ Hops int `json:"hops"`
+ Continuation map[string]string `json:"continuation"`
+ Hints []string `json:"hints"`
+ }
+ if err := json.Unmarshal([]byte(res.stderr), &errEnv); err != nil {
+ t.Fatalf("unmarshal error JSON: %v\nstderr: %s", err, res.stderr)
+ }
+ if errEnv.ErrorType != "server_error" || errEnv.StatusCode != 500 || errEnv.Hops != 1 {
+ t.Errorf("error = %+v, want error_type=server_error status_code=500 hops=1", errEnv)
+ }
+ if errEnv.Continuation["$.continuation_token"] != "ct-ok-1" || errEnv.Continuation["$.previous_interaction_id"] != "int-ok-1" {
+ t.Errorf("continuation = %#v, want ct-ok-1 and int-ok-1", errEnv.Continuation)
+ }
+ joinedHints := strings.Join(errEnv.Hints, " | ")
+ if !strings.Contains(joinedHints, `--continuation-token "ct-ok-1" --previous-interaction-id "int-ok-1"`) {
+ t.Errorf("hints = %q, want flag resume guidance", joinedHints)
+ }
+ })
+
+ t.Run("failed or cancelled status on hop 2 reports hop 1 resume context and does not overwrite with failed hop token", func(t *testing.T) {
+ for _, status := range []string{"failed", "cancelled"} {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if hop == 1 {
+ fmt.Fprint(w, `{"id":"int-good-1","status":"requires_continuation","continuation_token":"ct-good-1","steps":[]}`)
+ return
+ }
+ fmt.Fprintf(w, `{"id":"int-bad-2","status":%q,"continuation_token":"ct-bad-2","errors":[{"message":"hop 2 %s"}]}`, status, status)
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL), "generate", "hi", "--stream=false")...)
+ if code := exitCode(t, res); code != 1 {
+ t.Fatalf("hop 2 %s exit code = %d, want 1\nstderr: %s", status, code, res.stderr)
+ }
+ var errEnv struct {
+ ErrorReason string `json:"error_reason"`
+ Hops int `json:"hops"`
+ Continuation map[string]string `json:"continuation"`
+ }
+ if err := json.Unmarshal([]byte(res.stderr), &errEnv); err != nil {
+ t.Fatalf("unmarshal error JSON: %v\nstderr: %s", err, res.stderr)
+ }
+ if errEnv.ErrorReason != "CLI_OUTCOME_FAILED" || errEnv.Hops != 2 {
+ t.Errorf("hop 2 %s error = %+v, want CLI_OUTCOME_FAILED hops=2", status, errEnv)
+ }
+ if errEnv.Continuation["$.continuation_token"] != "ct-good-1" || errEnv.Continuation["$.previous_interaction_id"] != "int-good-1" {
+ t.Errorf("hop 2 %s continuation = %#v, want hop 1 checkpoint ct-good-1 / int-good-1", status, errEnv.Continuation)
+ }
+ }
+ })
+
+ t.Run("stalled repeated continuation_token stops without looping", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ // Hop 1 and Hop 2 return the exact same token; CLI must stop after hop 2.
+ fmt.Fprintf(w, `{"id":"int-stall-%d","status":"requires_continuation","continuation_token":"ct-same","steps":[{"type":"model_output","content":[{"type":"text","text":"part %d"}]}]}`, hop, hop)
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL), "generate", "hi", "--stream=false")...)
+ if res.err != nil {
+ t.Fatalf("stalled token failed unexpectedly: %v\nstderr: %s", res.err, res.stderr)
+ }
+ if len(srv.recorded()) != 2 {
+ t.Fatalf("recorded %d hops, want 2 (stop on repeated token)", len(srv.recorded()))
+ }
+ var out map[string]any
+ if err := json.Unmarshal([]byte(res.stdout), &out); err != nil {
+ t.Fatalf("unmarshal stdout: %v\nstdout: %s", err, res.stdout)
+ }
+ if out["status"] != "requires_continuation" || out["continuation_token"] != "ct-same" {
+ t.Errorf("stalled output = %#v, want requires_continuation with ct-same", out)
+ }
+ })
+
+ t.Run("authoritative interaction.completed without token clears earlier stream checkpoint", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.created\",\"interaction\":{\"id\":\"int-auth-1\",\"status\":\"in_progress\"}}\n\n")
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.status_update\",\"interaction_id\":\"int-auth-1\",\"status\":\"in_progress\",\"continuation_token\":\"ct-stale\"}\n\n")
+ // Final interaction.completed snapshot reports requires_continuation WITHOUT a token;
+ // streamAuthoritativeWhen must clear ct-stale so CLI fails with CLI_PROTOCOL instead of looping.
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.completed\",\"interaction\":{\"id\":\"int-auth-1\",\"status\":\"requires_continuation\"}}\n\n")
+ fmt.Fprint(w, "data: [DONE]\n\n")
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL), "generate", "hi")...)
+ if code := exitCode(t, res); code != 1 {
+ t.Fatalf("exit code = %d, want 1\nstderr: %s", code, res.stderr)
+ }
+ if len(srv.recorded()) != 1 {
+ t.Fatalf("recorded %d hops, want 1 (must not continue from cleared stale checkpoint)", len(srv.recorded()))
+ }
+ if !strings.Contains(res.stderr, `"error_reason": "CLI_PROTOCOL"`) {
+ t.Errorf("stderr = %s, want CLI_PROTOCOL", res.stderr)
+ }
+ })
+
+ t.Run("SSE error event on hop 2 after mid-hop checkpoint falls back to hop 1 completed resume context", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/event-stream")
+ if hop == 1 {
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.created\",\"interaction\":{\"id\":\"int-sse-1\",\"status\":\"in_progress\"}}\n\n")
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.completed\",\"interaction\":{\"id\":\"int-sse-1\",\"status\":\"requires_continuation\",\"continuation_token\":\"ct-sse-1\"}}\n\n")
+ fmt.Fprint(w, "data: [DONE]\n\n")
+ return
+ }
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.created\",\"interaction\":{\"id\":\"int-sse-2\",\"status\":\"in_progress\"}}\n\n")
+ fmt.Fprint(w, "data: {\"event_type\":\"interaction.status_update\",\"interaction_id\":\"int-sse-2\",\"status\":\"in_progress\",\"continuation_token\":\"ct-sse-2-aborted\"}\n\n")
+ fmt.Fprint(w, "data: {\"event_type\":\"error\",\"error\":{\"code\":\"503\",\"message\":\"overloaded\"}}\n\n")
+ fmt.Fprint(w, "data: [DONE]\n\n")
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL), "generate", "hi")...)
+ if code := exitCode(t, res); code != 1 {
+ t.Fatalf("SSE error on hop 2 exit code = %d, want 1\nstderr: %s", code, res.stderr)
+ }
+ var errEnv struct {
+ EventType string `json:"event_type"`
+ Continuation map[string]string `json:"continuation"`
+ }
+ if err := json.Unmarshal([]byte(res.stderr), &errEnv); err != nil {
+ t.Fatalf("unmarshal error JSON: %v\nstderr: %s", err, res.stderr)
+ }
+ if errEnv.EventType != "error" {
+ t.Errorf("event_type = %q, want error", errEnv.EventType)
+ }
+ if errEnv.Continuation["$.continuation_token"] != "ct-sse-1" || errEnv.Continuation["$.previous_interaction_id"] != "int-sse-1" {
+ t.Errorf("continuation = %#v, want hop 1 completed resume values (not aborted hop 2 checkpoint)", errEnv.Continuation)
+ }
+ })
+}
+
+func TestContinuationDryRunAndBackgroundIsolation(t *testing.T) {
+ t.Run("dry-run previews one request without entering continuation loop", func(t *testing.T) {
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs("https://example.invalid"),
+ "--dry-run", "generate", "hello", "--continuation-token", "ct-preview", "--store=false")...)
+ if res.err != nil {
+ t.Fatalf("dry-run failed: %v\nstderr: %s", res.err, res.stderr)
+ }
+ req := parseDryRunRequest(t, res.stdout)
+ body, _ := req["body"].(map[string]any)
+ if body["continuation_token"] != "ct-preview" || body["store"] != false {
+ t.Errorf("dry-run preview body = %#v, want continuation_token=ct-preview and store=false", body)
+ }
+ })
+
+ t.Run("agent run --background returns handle after one request and skips continuation even on requires_continuation", func(t *testing.T) {
+ srv := newContinuationServer(t, func(hop int, req recordedHop, w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprint(w, `{"id":"int-bg-1","status":"requires_continuation","continuation_token":"ct-bg-1"}`)
+ })
+
+ res := runCLI(t, t.TempDir(), nil, append(baseArgs(srv.URL),
+ "agent", "run", "research solar", "--model", "gemini-3.8-flash", "--background")...)
+ if res.err != nil {
+ t.Fatalf("agent run --background failed: %v\nstderr: %s", res.err, res.stderr)
+ }
+ hops := srv.recorded()
+ if len(hops) != 1 {
+ t.Fatalf("recorded %d hops, want 1", len(hops))
+ }
+ if hops[0].Body["background"] != true || hops[0].Body["stream"] != false {
+ t.Errorf("background request body = %#v, want background=true stream=false", hops[0].Body)
+ }
+ var out map[string]any
+ if err := json.Unmarshal([]byte(res.stdout), &out); err != nil {
+ t.Fatalf("unmarshal stdout: %v\nstdout: %s", err, res.stdout)
+ }
+ if _, hasIDs := out["continuation_ids"]; hasIDs {
+ t.Errorf("skipped background request must not add continuation_ids, got %#v", out["continuation_ids"])
+ }
+ })
+
+ t.Run("async polling stops immediately on requires_continuation as handoff", func(t *testing.T) {
+ pollRequiresContinuation := `{"id":"int-vid","object":"interaction","status":"requires_continuation","continuation_token":"ct-poll-1","steps":[]}`
+ handoff := newAsyncVideoServer(t, asyncCreateInProgress, pollRequiresContinuation)
+ dir := t.TempDir()
+ result := runCLIInDir(t, t.TempDir(), dir, nil, videoArgs(handoff.URL, "--output-format", "json")...)
+ if result.err != nil {
+ t.Fatalf("requires_continuation handoff must exit 0: %v\nstderr: %s", result.err, result.stderr)
+ }
+ var payload struct {
+ ID string `json:"id"`
+ Status string `json:"status"`
+ ContinuationToken string `json:"continuation_token"`
+ }
+ if err := json.Unmarshal([]byte(result.stdout), &payload); err != nil || payload.Status != "requires_continuation" || payload.ID != "int-vid" || payload.ContinuationToken != "ct-poll-1" {
+ t.Errorf("handoff stdout = %q (err %v), want requires_continuation payload", result.stdout, err)
+ }
+ if seen := handoff.seen(); countPrefix(seen, "GET ") != 1 {
+ t.Errorf("handoff must stop polling after first requires_continuation, requests: %v", seen)
+ }
+ })
+}
diff --git a/tests/contract/help_test.go b/tests/contract/help_test.go
index a6f37db7..d9f0f1a7 100644
--- a/tests/contract/help_test.go
+++ b/tests/contract/help_test.go
@@ -100,6 +100,12 @@ func TestHelpDefaultsAndEscalation(t *testing.T) {
"Defaults: MIME type detected from the extension",
"Learn: https://aistudio.google.com/docs/files · escalate: metadata-only registration via gemini-api files register",
}},
+ {[]string{"agent", "run"}, []string{
+ "streams text as it arrives (--stream=false or --background for one interaction unless --stream is passed; --body takes exact request JSON).",
+ "Arguments: Prompt or task to send",
+ "Request variants: Agent (--agent), Model (--model; default). Variant-specific flags cannot be combined.",
+ "Escalate: exact request JSON via --body @request.json (schema with --schema)",
+ }},
}
for _, tc := range cases {
name := strings.Join(tc.args, " ")
diff --git a/tests/contract/porcelain_interactive_test.go b/tests/contract/porcelain_interactive_test.go
index f03cdd2d..84497903 100644
--- a/tests/contract/porcelain_interactive_test.go
+++ b/tests/contract/porcelain_interactive_test.go
@@ -270,3 +270,41 @@ func TestTextSourceFlagSatisfiesInteractiveArgument(t *testing.T) {
t.Errorf("dry-run did not use --file text:\n%s", stderr)
}
}
+
+// TestContinuationTokenSatisfiesInteractiveArgument: resuming a stored
+// continuation with --continuation-token satisfies the positional prompt/input,
+// so --interactive never prompts for a new turn that would contradict resumeHint.
+func TestContinuationTokenSatisfiesInteractiveArgument(t *testing.T) {
+ clearAgentModeEnvironment(t)
+ for _, tc := range []struct {
+ name string
+ args []string
+ }{
+ {"generate", []string{"generate", "--continuation-token", "ct-1", "--previous-interaction-id", "int-1"}},
+ {"agent run", []string{"agent", "run", "--continuation-token", "ct-1", "--previous-interaction-id", "int-1"}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ prompter := &scriptedPrompter{
+ t: t,
+ answers: map[string][]string{"arg:prompt": {"should not be used"}, "arg:input": {"should not be used"}},
+ }
+ cmdArgs := append([]string{"--interactive", "--dry-run", "--api-key", "k", "--server-url", "https://example.invalid"}, tc.args...)
+ _, stderr, err := executeInteractive(t, prompter, cmdArgs...)
+ if err != nil {
+ t.Fatalf("%s --continuation-token failed: %v\nstderr: %s", tc.name, err, stderr)
+ }
+ if len(prompter.calls) != 0 {
+ t.Fatalf("prompter called even though --continuation-token satisfied input: %#v", prompter.calls)
+ }
+ if !strings.Contains(stderr, `"continuation_token": "ct-1"`) {
+ t.Errorf("dry-run missing continuation_token:\n%s", stderr)
+ }
+ if !strings.Contains(stderr, `"previous_interaction_id": "int-1"`) {
+ t.Errorf("dry-run missing previous_interaction_id:\n%s", stderr)
+ }
+ if strings.Contains(stderr, `"input"`) {
+ t.Errorf("dry-run unexpectedly included input on stored resume:\n%s", stderr)
+ }
+ })
+ }
+}