copilot-sdk-supercharged 2.5.3 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,6 +16,15 @@ module Copilot
16
16
  @data = data
17
17
  super("JSON-RPC Error #{code}: #{message}")
18
18
  end
19
+
20
+ # Structured Policy Helper failure attached to a failed session.create or
21
+ # session.resume (+error.data.policyHelperFailure+).
22
+ #
23
+ # @return [PolicyHelperFailure, nil]
24
+ def policy_helper_failure
25
+ raw = @data.is_a?(Hash) ? @data["policyHelperFailure"] : nil
26
+ raw.is_a?(Hash) ? PolicyHelperFailure.from_hash(raw) : nil
27
+ end
19
28
  end
20
29
 
21
30
  # Minimal threaded JSON-RPC 2.0 client for stdio / TCP IO transport.
@@ -43,6 +52,7 @@ module Copilot
43
52
 
44
53
  @notification_handler = nil # Proc(method, params)
45
54
  @request_handlers = {} # method => Proc(params) -> Hash
55
+ @async_request_methods = {} # method => true when handled off the reader thread
46
56
 
47
57
  @running = false
48
58
  @reader_thread = nil
@@ -148,13 +158,21 @@ module Copilot
148
158
  # The handler receives +(params)+ and must return a Hash result.
149
159
  #
150
160
  # @param method [String] the RPC method to handle
161
+ # @param async [Boolean] run the handler on its own thread so the reader keeps
162
+ # processing messages (for example a cancellation) while it runs
151
163
  # @yield [params] the request parameters
152
164
  # @yieldreturn [Hash] the result to send back
153
- def on_request(method, &handler)
165
+ def on_request(method, async: false, &handler)
154
166
  if handler.nil?
155
167
  @request_handlers.delete(method)
168
+ @async_request_methods.delete(method)
156
169
  else
157
170
  @request_handlers[method] = handler
171
+ if async
172
+ @async_request_methods[method] = true
173
+ else
174
+ @async_request_methods.delete(method)
175
+ end
158
176
  end
159
177
  end
160
178
 
@@ -293,6 +311,19 @@ module Copilot
293
311
  return
294
312
  end
295
313
 
314
+ if @async_request_methods[method]
315
+ Thread.new do
316
+ dispatch_request(method, request_id, params, handler)
317
+ rescue StandardError
318
+ # The connection closed before the response could be written.
319
+ end
320
+ else
321
+ dispatch_request(method, request_id, params, handler)
322
+ end
323
+ end
324
+
325
+ # Run a request handler and write its response (or error).
326
+ def dispatch_request(method, request_id, params, handler)
296
327
  # Execute handler (may be synchronous or may raise)
297
328
  begin
298
329
  result = handler.call(params)
@@ -300,7 +331,8 @@ module Copilot
300
331
  # as JSON null (the CLI decodes the result as `SessionFsError | undefined`).
301
332
  # Coercing nil to {} would be decoded as a malformed SessionFsError
302
333
  # ("missing field `code`"), so preserve nil for those methods only.
303
- result = {} if result.nil? && !method.to_s.start_with?("sessionFs.")
334
+ # memoryStore.store also answers with JSON null.
335
+ result = {} if result.nil? && !null_result_method?(method)
304
336
  send_response(request_id, result)
305
337
  rescue JsonRpcError => e
306
338
  send_error_response(request_id, e.code, e.message, e.data)
@@ -309,6 +341,11 @@ module Copilot
309
341
  end
310
342
  end
311
343
 
344
+ # @return [Boolean] true for methods whose successful result is JSON null
345
+ def null_result_method?(method)
346
+ method.to_s.start_with?("sessionFs.") || method == "memoryStore.store"
347
+ end
348
+
312
349
  # Send a successful response.
313
350
  def send_response(request_id, result)
314
351
  send_message({
@@ -7,7 +7,7 @@
7
7
  module Copilot
8
8
  # The SDK protocol version.
9
9
  # This must match the version expected by the copilot-agent-runtime server.
10
- SDK_PROTOCOL_VERSION = 3
10
+ SDK_PROTOCOL_VERSION = 4
11
11
 
12
12
  # @return [Integer] the SDK protocol version number
13
13
  def self.sdk_protocol_version
@@ -2,6 +2,7 @@
2
2
 
3
3
  # Copyright (c) Microsoft Corporation. All rights reserved.
4
4
 
5
+ require "json"
5
6
  require "thread"
6
7
 
7
8
  module Copilot
@@ -58,6 +59,15 @@ module Copilot
58
59
  @exit_plan_mode_handler_lock = Mutex.new
59
60
 
60
61
  @trace_context_provider = nil
62
+
63
+ @shell_authentication_handler = nil
64
+ @pending_shell_authentications = {} # request id => Queue
65
+ @shell_authentication_lock = Mutex.new
66
+
67
+ @memory_store_handler = nil
68
+ @memory_store_lock = Mutex.new
69
+
70
+ @destroy_callbacks = []
61
71
  end
62
72
 
63
73
  # Send a message to this session.
@@ -67,15 +77,31 @@ module Copilot
67
77
  # @param mode [String, nil] "enqueue" (default) or "immediate"
68
78
  # @param response_format [String, nil] desired response format ("text", "image", "json_object")
69
79
  # @param image_options [ImageOptions, nil] options for image generation
80
+ # @param source [String, nil] message provenance: "user", "system", or
81
+ # "agent-<id>" (see {MessageSource})
82
+ # @param response_schema [Hash, nil] JSON Schema requesting structured output; sent as
83
+ # +responseFormat: { type: "json_schema", jsonSchema: { name: "response", strict: true, schema: } }+
84
+ # and takes precedence over +response_format+
85
+ # @param client_turn_id [String, nil] opaque caller-chosen turn identifier, echoed on
86
+ # the turn's events so you can correlate them with this send
70
87
  # @return [String] the message ID
71
- def send(prompt:, attachments: nil, mode: nil, agent_mode: nil, display_prompt: nil, request_headers: nil, response_format: nil, image_options: nil)
88
+ def send(prompt:, attachments: nil, mode: nil, agent_mode: nil, display_prompt: nil, request_headers: nil, response_format: nil, image_options: nil, source: nil, response_schema: nil, client_turn_id: nil)
72
89
  payload = { sessionId: @session_id, prompt: prompt }
90
+ payload[:source] = source if source
91
+ payload[:clientTurnId] = client_turn_id if client_turn_id
73
92
  payload[:attachments] = attachments if attachments
74
93
  payload[:mode] = mode if mode
75
94
  payload[:agentMode] = agent_mode if agent_mode
76
95
  payload[:displayPrompt] = display_prompt if display_prompt
77
96
  payload[:requestHeaders] = request_headers if request_headers
78
- payload[:responseFormat] = response_format if response_format
97
+ if response_schema
98
+ payload[:responseFormat] = {
99
+ type: "json_schema",
100
+ jsonSchema: { name: "response", strict: true, schema: response_schema },
101
+ }
102
+ elsif response_format
103
+ payload[:responseFormat] = response_format
104
+ end
79
105
  payload[:imageOptions] = image_options.to_h if image_options
80
106
 
81
107
  # Inject trace context if provider is available
@@ -107,11 +133,14 @@ module Copilot
107
133
  # @param mode [String, nil] delivery mode
108
134
  # @param response_format [String, nil] desired response format ("text", "image", "json_object")
109
135
  # @param image_options [ImageOptions, nil] options for image generation
136
+ # @param source [String, nil] message provenance (see {MessageSource})
137
+ # @param response_schema [Hash, nil] JSON Schema requesting structured output
138
+ # @param client_turn_id [String, nil] opaque caller-chosen turn identifier
110
139
  # @param timeout [Numeric] seconds to wait (default 60)
111
140
  # @return [SessionEvent, nil] the final assistant.message event, or nil
112
141
  # @raise [Timeout::Error] if the timeout expires before session.idle
113
142
  # @raise [RuntimeError] if the session emits a session.error event
114
- def send_and_wait(prompt:, attachments: nil, mode: nil, agent_mode: nil, display_prompt: nil, request_headers: nil, response_format: nil, image_options: nil, timeout: 60)
143
+ def send_and_wait(prompt:, attachments: nil, mode: nil, agent_mode: nil, display_prompt: nil, request_headers: nil, response_format: nil, image_options: nil, source: nil, response_schema: nil, client_turn_id: nil, timeout: 60)
115
144
  idle_mutex = Mutex.new
116
145
  idle_cv = ConditionVariable.new
117
146
  idle_fired = false
@@ -144,7 +173,9 @@ module Copilot
144
173
  self.send(prompt: prompt, attachments: attachments, mode: mode,
145
174
  agent_mode: agent_mode, display_prompt: display_prompt,
146
175
  request_headers: request_headers,
147
- response_format: response_format, image_options: image_options)
176
+ response_format: response_format, image_options: image_options,
177
+ source: source, response_schema: response_schema,
178
+ client_turn_id: client_turn_id)
148
179
 
149
180
  idle_mutex.synchronize do
150
181
  unless idle_fired
@@ -164,6 +195,37 @@ module Copilot
164
195
  end
165
196
  end
166
197
 
198
+ # Send a message requesting structured output and wait until the session is idle.
199
+ #
200
+ # Sets +response_schema+ on the message, waits via {#send_and_wait}, and returns the
201
+ # final assistant content parsed as JSON.
202
+ #
203
+ # @param prompt_or_options [String, Hash, MessageOptions] the prompt text, or message
204
+ # options accepted by {#send_and_wait} (e.g. +{ prompt:, attachments: }+)
205
+ # @param schema [Hash] JSON Schema the response must satisfy
206
+ # @param timeout [Numeric] seconds to wait (default 60)
207
+ # @return [Object] the parsed JSON value (usually a Hash)
208
+ # @raise [RuntimeError] if the run completed without assistant content
209
+ # @raise [JSON::ParserError] if the content is not valid JSON
210
+ def send_and_wait_structured(prompt_or_options, schema, timeout = 60)
211
+ options =
212
+ case prompt_or_options
213
+ when Hash then prompt_or_options.transform_keys(&:to_sym)
214
+ when Struct then prompt_or_options.to_h.compact
215
+ else { prompt: prompt_or_options.to_s }
216
+ end
217
+ options = options.reject { |key, _| key == :response_schema || key == :timeout }
218
+
219
+ event = send_and_wait(**options, response_schema: schema, timeout: timeout)
220
+ data = event&.data
221
+ content = data.is_a?(Hash) ? data["content"] : nil
222
+ if content.nil? || content.to_s.strip.empty?
223
+ raise "The requested run completed without a structured assistant response"
224
+ end
225
+
226
+ JSON.parse(content)
227
+ end
228
+
167
229
  # Subscribe to events from this session.
168
230
  #
169
231
  # When called with a block only, subscribes to all events.
@@ -217,9 +279,54 @@ module Copilot
217
279
  @rpc_client.request("session.getMetadata", { sessionId: @session_id })
218
280
  end
219
281
 
282
+ # Change the Auto routing preference without changing the selected model
283
+ # (experimental). The runtime records the request and commits it on a later
284
+ # turn that uses the "auto" model.
285
+ #
286
+ # @param auto_tier [String, nil] "efficiency", "balance", "intelligence" or "fast"
287
+ # (see {AutoTier}); nil returns to the provider's default Auto routing
288
+ # @return [Hash] the result (status, effectiveAutoTier, pendingAutoTier,
289
+ # activatingAutoTier, supersededAutoTier)
290
+ def set_auto_tier(auto_tier)
291
+ @rpc_client.request("session.model.switchAutoTier", { sessionId: @session_id, autoTier: auto_tier })
292
+ end
293
+
294
+ # Retrieve the managed (enterprise policy) settings in effect for this session.
295
+ #
296
+ # @return [Hash] the managed settings
297
+ def get_managed_settings
298
+ @rpc_client.request("session.managedSettings.get", { sessionId: @session_id })
299
+ end
300
+
301
+ # Ask the runtime to re-run the managed-settings policy helper for this session.
302
+ #
303
+ # @return [Hash] the raw result
304
+ def recheck_policy_helper
305
+ @rpc_client.request("session.managedSettings.recheckPolicyHelper", { sessionId: @session_id })
306
+ end
307
+
308
+ # Change the session's permission mode.
309
+ #
310
+ # @param mode [String] "manual", "assisted" or "allow-all" (see {PermissionMode})
311
+ # @return [PermissionModeSetResult] whether the mode was applied, the authoritative
312
+ # mode afterwards, and the refusal +reason+ when known ("managed_policy")
313
+ def set_permission_mode(mode)
314
+ result = @rpc_client.request("session.permissions.setMode", { sessionId: @session_id, mode: mode })
315
+ PermissionModeSetResult.from_hash(result.is_a?(Hash) ? result : {})
316
+ end
317
+
220
318
  # Destroy this session and release associated resources.
319
+ #
320
+ # Sends +session.detach+ (falling back to +session.destroy+ on older CLIs), so
321
+ # on-disk session state is preserved and the session can be resumed later.
221
322
  def destroy
222
- @rpc_client.request("session.destroy", { sessionId: @session_id })
323
+ begin
324
+ @rpc_client.request("session.detach", { sessionId: @session_id })
325
+ rescue JsonRpcError => e
326
+ raise unless e.code == -32601
327
+
328
+ @rpc_client.request("session.destroy", { sessionId: @session_id })
329
+ end
223
330
  @event_handlers_lock.synchronize do
224
331
  @event_handlers.clear
225
332
  @typed_event_handlers.clear
@@ -230,6 +337,22 @@ module Copilot
230
337
  @hooks_lock.synchronize { @hooks = nil }
231
338
  @exit_plan_mode_handler_lock.synchronize { @exit_plan_mode_handler = nil }
232
339
  @trace_context_provider = nil
340
+ @memory_store_lock.synchronize { @memory_store_handler = nil }
341
+ pending = @shell_authentication_lock.synchronize do
342
+ @shell_authentication_handler = nil
343
+ queues = @pending_shell_authentications.values
344
+ @pending_shell_authentications.clear
345
+ queues
346
+ end
347
+ pending.each { |queue| queue << [:cancelled, nil] }
348
+
349
+ callbacks = @destroy_callbacks.dup
350
+ @destroy_callbacks.clear
351
+ callbacks.each do |callback|
352
+ callback.call
353
+ rescue StandardError
354
+ # ignore cleanup errors
355
+ end
233
356
  end
234
357
 
235
358
  # Abort the currently processing message.
@@ -340,6 +463,89 @@ module Copilot
340
463
  @trace_context_provider = provider
341
464
  end
342
465
 
466
+ # @api private
467
+ def _register_shell_authentication_handler(handler)
468
+ @shell_authentication_lock.synchronize { @shell_authentication_handler = handler }
469
+ end
470
+
471
+ # @api private
472
+ # Asks the registered handler for a shell program's credentials. A failure, a
473
+ # malformed answer, or a cancellation (see {#_cancel_shell_authentication_request})
474
+ # answers "cancel" so the program fails instead of receiving a wrong value. The
475
+ # answer is never logged. The handler runs on its own thread so a cancellation
476
+ # answers immediately even while the handler is still prompting.
477
+ #
478
+ # @param request [ShellAuthenticationRequest]
479
+ # @return [Hash] +{ action: "accept", value: }+ or +{ action: "cancel" }+
480
+ def _handle_shell_authentication_request(request)
481
+ handler = nil
482
+ outcome = Queue.new
483
+ @shell_authentication_lock.synchronize do
484
+ handler = @shell_authentication_handler
485
+ return { action: "cancel" } if handler.nil? || @pending_shell_authentications.key?(request.request_id)
486
+
487
+ @pending_shell_authentications[request.request_id] = outcome
488
+ end
489
+
490
+ Thread.new do
491
+ outcome << [:done, handler.call(request, { session_id: @session_id })]
492
+ rescue StandardError => e
493
+ # The error text could contain the answer, so only its type is logged.
494
+ $stderr.puts("[CopilotSDK] Shell authentication handler failed (#{e.class})")
495
+ outcome << [:done, nil]
496
+ end
497
+
498
+ status, result = outcome.pop
499
+ @shell_authentication_lock.synchronize do
500
+ @pending_shell_authentications.delete(request.request_id) if @pending_shell_authentications[request.request_id].equal?(outcome)
501
+ end
502
+ return { action: "cancel" } unless status == :done
503
+
504
+ answer = (result.is_a?(Hash) || result.is_a?(Struct)) ? result.to_h : {}
505
+ action = answer[:action] || answer["action"]
506
+ value = answer.key?(:value) ? answer[:value] : answer["value"]
507
+ return { action: "accept", value: value } if action.to_s == "accept" && value.is_a?(String)
508
+
509
+ { action: "cancel" }
510
+ end
511
+
512
+ # @api private
513
+ # Cancels a pending shell authentication prompt; it then answers "cancel".
514
+ def _cancel_shell_authentication_request(request_id)
515
+ outcome = @shell_authentication_lock.synchronize { @pending_shell_authentications.delete(request_id) }
516
+ outcome&.push([:cancelled, nil])
517
+ end
518
+
519
+ # @api private
520
+ def _register_memory_store(handler)
521
+ @memory_store_lock.synchronize { @memory_store_handler = handler }
522
+ end
523
+
524
+ # @api private
525
+ # Hands a memory the agent asked to store to the registered +store_memory+ callback.
526
+ #
527
+ # @param memory [StoredMemory]
528
+ # @return [nil]
529
+ def _handle_memory_store(memory)
530
+ handler = @memory_store_lock.synchronize { @memory_store_handler }
531
+ raise "No memory store is registered" unless handler
532
+
533
+ begin
534
+ handler.call(memory, { session_id: @session_id })
535
+ rescue StandardError => e
536
+ # The runtime reports a generic failure to the model; keep the cause visible here.
537
+ $stderr.puts("[CopilotSDK] Memory store callback failed: #{e.class}: #{e.message}")
538
+ raise "Memory store callback failed"
539
+ end
540
+ nil
541
+ end
542
+
543
+ # @api private
544
+ # Registers a callback run once after {#destroy} releases the session.
545
+ def _on_destroy(&callback)
546
+ @destroy_callbacks << callback if callback
547
+ end
548
+
343
549
  # @api private
344
550
  def _handle_hooks_invoke(hook_type, input_data)
345
551
  hooks = @hooks_lock.synchronize { @hooks }
@@ -353,6 +559,8 @@ module Copilot
353
559
  "sessionStart" => hooks.on_session_start,
354
560
  "sessionEnd" => hooks.on_session_end,
355
561
  "errorOccurred" => hooks.on_error_occurred,
562
+ "subagentStart" => hooks.on_subagent_start,
563
+ "subagentStop" => hooks.on_subagent_stop,
356
564
  }
357
565
 
358
566
  handler = handler_map[hook_type]
@@ -0,0 +1,261 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright (c) Microsoft Corporation. All rights reserved.
4
+
5
+ module Copilot
6
+ # Option groups of the SDK protocol 4 session.create / session.resume payloads.
7
+ SESSION_PARAM_GROUP_NAMES = %i[
8
+ inference tools permissions interaction events agents skills mcp github filesystem
9
+ execution instructions hooks git state plugins canvases extensions experiments policy
10
+ ].freeze
11
+
12
+ # Flat wire keys that are only valid on session.create (dropped on resume).
13
+ SESSION_CREATE_ONLY_PARAMS = %i[name cloud trustWorkingDirectory refreshCustomInstructions].freeze
14
+
15
+ # Flat wire keys that are only valid on session.resume (dropped on create).
16
+ SESSION_RESUME_ONLY_PARAMS = %i[
17
+ disableResume suppressResumeEvent continuePendingWork allowTranscriptRecovery
18
+ requestedEnvironmentVariables openCanvases
19
+ ].freeze
20
+
21
+ # Flat (SDK protocol 3) wire keys and the SDK protocol 4 [group, member] they move to.
22
+ # Root keys (sessionId, model, name, clientName, workingDirectory, configDirectory,
23
+ # enableConfigDiscovery, systemMessage, diagnostics, lifecycleDiagnostics, cloud,
24
+ # traceparent, tracestate and the resume controls) and unknown keys stay top level.
25
+ SESSION_PARAM_GROUPS = {
26
+ reasoningEffort: %i[inference reasoningEffort],
27
+ reasoningSummary: %i[inference reasoningSummary],
28
+ contextTier: %i[inference contextTier],
29
+ allowMultipleToolCalls: %i[inference allowMultipleToolCalls],
30
+ enableCitations: %i[inference enableCitations],
31
+ modelCapabilities: %i[inference capabilities],
32
+ verbosity: %i[inference verbosity],
33
+ providers: %i[inference providers],
34
+ models: %i[inference models],
35
+ defaultProvider: %i[inference defaultProvider],
36
+ tools: %i[tools definitions],
37
+ availableTools: %i[tools availableTools],
38
+ excludedTools: %i[tools excludedTools],
39
+ toolSearch: %i[tools search],
40
+ largeOutput: %i[tools largeOutput],
41
+ imageGeneration: %i[tools imageGeneration],
42
+ manageScheduleEnabled: %i[tools manageScheduleEnabled],
43
+ webSearch: %i[tools webSearch],
44
+ shell: %i[tools shell],
45
+ maxInlineBinaryBytes: %i[tools maxInlineBinaryBytes],
46
+ requestPermission: %i[permissions request],
47
+ sandboxConfig: %i[permissions sandbox],
48
+ sandbox: %i[permissions sandbox],
49
+ permissionMode: %i[permissions mode],
50
+ sandboxConfigSource: %i[permissions sandboxSource],
51
+ commands: %i[interaction commands],
52
+ askUserVariant: %i[interaction askUserVariant],
53
+ requestUserInput: %i[interaction requestUserInput],
54
+ requestElicitation: %i[interaction requestElicitation],
55
+ requestShellAuthentication: %i[interaction requestShellAuthentication],
56
+ requestExitPlanMode: %i[interaction requestExitPlanMode],
57
+ requestAutoModeSwitch: %i[interaction requestAutoModeSwitch],
58
+ requestAutoModeRecovery: %i[interaction requestAutoModeRecovery],
59
+ streaming: %i[events streaming],
60
+ includeSubAgentStreamingEvents: %i[events includeSubAgentStreamingEvents],
61
+ customAgents: %i[agents definitions],
62
+ defaultAgent: %i[agents default],
63
+ agent: %i[agents selected],
64
+ includedBuiltinAgents: %i[agents includedBuiltinAgents],
65
+ excludedBuiltinAgents: %i[agents excludedBuiltinAgents],
66
+ customAgentsLocalOnly: %i[agents localDiscoveryOnly],
67
+ agentDirectories: %i[agents directories],
68
+ skillDirectories: %i[skills directories],
69
+ enableSkills: %i[skills enabled],
70
+ includedBuiltinSkills: %i[skills includedBuiltinSkills],
71
+ disabledSkills: %i[skills disabledSkills],
72
+ hasSkillProvider: %i[skills hasProvider],
73
+ ignoredSkillsLocations: %i[skills ignoredLocations],
74
+ mcpServers: %i[mcp servers],
75
+ disabledMcpServers: %i[mcp disabledServers],
76
+ requestMcpApps: %i[mcp enableApps],
77
+ enableMcpApps: %i[mcp enableApps],
78
+ mcpOAuthTokenStorage: %i[mcp oauthTokenStorage],
79
+ authClientIdMetadataUrl: %i[mcp authClientIdMetadataUrl],
80
+ envValueMode: %i[mcp envValueMode],
81
+ managedMcpServers: %i[mcp managedServers],
82
+ allowAllMcpServerInstructions: %i[mcp allowAllServerInstructions],
83
+ gitHubToken: %i[github token],
84
+ gitHubTokenProviderRegistrationId: %i[github tokenProviderRegistrationId],
85
+ githubMcpToolConfig: %i[github mcp],
86
+ capi: %i[github capi],
87
+ enableSessionTelemetry: %i[github telemetryEnabled],
88
+ enableManagedSettings: %i[github fetchManagedSettings],
89
+ interactiveUser: %i[github interactiveUser],
90
+ enableGitHubTelemetryForwarding: %i[github telemetryForwarding],
91
+ authInfo: %i[github authInfo],
92
+ copilotUrl: %i[github copilotUrl],
93
+ additionalDirectories: %i[filesystem additionalDirectories],
94
+ enableFileChangeTracking: %i[filesystem trackFileChanges],
95
+ trustWorkingDirectory: %i[filesystem trustWorkingDirectory],
96
+ sessionLimits: %i[execution limits],
97
+ autopilot: %i[execution autopilot],
98
+ autopilotContinuation: %i[execution autopilotContinuation],
99
+ instructionDirectories: %i[instructions directories],
100
+ organizationCustomInstructions: %i[instructions organizationText],
101
+ enableOnDemandInstructionDiscovery: %i[instructions onDemandDiscovery],
102
+ skipCustomInstructions: %i[instructions skipCustomInstructions],
103
+ refreshCustomInstructions: %i[instructions refreshCustomInstructions],
104
+ hooks: %i[hooks hasHandlers],
105
+ hookDirectories: %i[hooks directories],
106
+ enableFileHooks: %i[hooks enableRepositoryHooks],
107
+ coauthorEnabled: %i[git coauthorEnabled],
108
+ enableHostGitOperations: %i[git enableHostGitOperations],
109
+ infiniteSessions: %i[state infiniteSessions],
110
+ memory: %i[state memory],
111
+ hasMemoryStore: %i[state hasMemoryStore],
112
+ enableSessionStore: %i[state enableCrossSessionStore],
113
+ skipEmbeddingRetrieval: %i[state skipEmbeddingRetrieval],
114
+ embeddingCacheStorage: %i[state embeddingCacheStorage],
115
+ pluginDirectories: %i[plugins directories],
116
+ installedPlugins: %i[plugins installed],
117
+ canvases: %i[canvases definitions],
118
+ canvasProvider: %i[canvases provider],
119
+ requestCanvasRenderer: %i[canvases requestRenderer],
120
+ openCanvases: %i[canvases open],
121
+ requestExtensions: %i[extensions enabled],
122
+ extensionSdkPath: %i[extensions sdkPath],
123
+ extensionInfo: %i[extensions identity],
124
+ enableExperimentalMode: %i[experiments enableExperimentalMode],
125
+ isExperimentalMode: %i[experiments enableExperimentalMode],
126
+ featureFlags: %i[experiments flags],
127
+ expAssignments: %i[experiments assignments],
128
+ featureFlagConfiguration: %i[experiments configuration],
129
+ allowedModels: %i[policy allowedModels],
130
+ managedSettings: %i[policy managedSettings],
131
+ excludedManagedSettings: %i[policy excludedManagedSettings],
132
+ enforceManagedModelDefaults: %i[policy enforceManagedModelDefaults],
133
+ }.freeze
134
+
135
+ # Legacy single-provider fields that describe the model rather than the connection.
136
+ LEGACY_PROVIDER_MODEL_FIELDS = %i[
137
+ modelId wireModel maxPromptTokens maxContextWindowTokens maxOutputTokens capabilities
138
+ ].freeze
139
+
140
+ # Session defaults applied under the caller's values when the client mode is "empty".
141
+ EMPTY_MODE_SESSION_DEFAULTS = [
142
+ [:experiments, :enableExperimentalMode, false],
143
+ [:github, :telemetryEnabled, false],
144
+ [:mcp, :oauthTokenStorage, "in-memory"],
145
+ [:state, :skipEmbeddingRetrieval, true],
146
+ [:state, :embeddingCacheStorage, "in-memory"],
147
+ [:state, :enableCrossSessionStore, false],
148
+ [:state, :memory, { enabled: false }.freeze],
149
+ [:instructions, :onDemandDiscovery, false],
150
+ [:hooks, :enableRepositoryHooks, false],
151
+ [:git, :enableHostGitOperations, false],
152
+ ].freeze
153
+
154
+ # @api private
155
+ #
156
+ # Converts the flat session.create / session.resume payload built by the client into
157
+ # the grouped SDK protocol 4 shape. Root keys stay top level, known flat keys move into
158
+ # their option group (for example +streaming+ becomes +events.streaming+), and unknown
159
+ # keys pass through unchanged. Nil values and empty groups are dropped, except an
160
+ # explicit +defaultProvider: nil+ on resume, which clears the default provider. Group
161
+ # objects already present in +flat+ are merged and their members win. A legacy single
162
+ # +provider+ becomes a "default" named provider with Copilot API models disabled,
163
+ # unless explicit +providers+, +defaultProvider+ or +capi.enabled+ are present.
164
+ #
165
+ # @param flat [Hash] flat payload (Symbol or String keys)
166
+ # @param resume [Boolean] true for session.resume, false for session.create
167
+ # @return [Hash] grouped payload
168
+ def self.group_session_params(flat, resume: false)
169
+ payload = {}
170
+ groups = {}
171
+ explicit_groups = {}
172
+ legacy_provider = nil
173
+
174
+ flat.each do |raw_key, value|
175
+ key = raw_key.to_sym
176
+ next if value.nil? && !(resume && key == :defaultProvider)
177
+ next if resume && SESSION_CREATE_ONLY_PARAMS.include?(key)
178
+ next if !resume && SESSION_RESUME_ONLY_PARAMS.include?(key)
179
+
180
+ if SESSION_PARAM_GROUP_NAMES.include?(key) && value.is_a?(Hash)
181
+ explicit_groups[key] = value
182
+ elsif key == :configDir
183
+ payload[:configDirectory] = value
184
+ elsif key == :disableResume
185
+ payload[:suppressResumeEvent] = value
186
+ elsif key == :provider
187
+ legacy_provider = value
188
+ elsif (path = SESSION_PARAM_GROUPS[key])
189
+ (groups[path[0]] ||= {})[path[1]] = value
190
+ else
191
+ payload[key] = value
192
+ end
193
+ end
194
+
195
+ explicit_groups.each do |name, members|
196
+ target = (groups[name] ||= {})
197
+ members.each { |member, value| target[member.to_sym] = value unless value.nil? }
198
+ end
199
+
200
+ legacy_provider = legacy_provider.to_wire if legacy_provider.respond_to?(:to_wire)
201
+ group_legacy_provider(legacy_provider, payload[:model], groups) if legacy_provider.is_a?(Hash)
202
+
203
+ mcp = groups[:mcp]
204
+ mcp[:envValueMode] ||= "direct" if mcp&.key?(:servers)
205
+
206
+ groups.each { |name, members| payload[name] = members unless members.empty? }
207
+ payload
208
+ end
209
+
210
+ # @api private
211
+ #
212
+ # Applies the "empty" client mode session defaults to a grouped payload. Values the
213
+ # caller already set win.
214
+ #
215
+ # @param payload [Hash] grouped payload from {group_session_params}
216
+ # @return [Hash] the same payload
217
+ def self.apply_empty_mode_session_defaults(payload)
218
+ EMPTY_MODE_SESSION_DEFAULTS.each do |group, member, value|
219
+ target = payload[group]
220
+ target = payload[group] = {} unless target.is_a?(Hash)
221
+ next unless target[member].nil?
222
+
223
+ target[member] = value.is_a?(Hash) ? value.dup : value
224
+ end
225
+ payload
226
+ end
227
+
228
+ # @api private
229
+ # Translates a legacy single +provider+ into +inference.providers+ /
230
+ # +inference.models+ / +inference.defaultProvider+ and +github.capi.enabled = false+.
231
+ def self.group_legacy_provider(provider, model, groups)
232
+ inference = (groups[:inference] ||= {})
233
+ github = (groups[:github] ||= {})
234
+ capi = github[:capi]
235
+ explicit_capi = capi.is_a?(Hash) && (capi.key?(:enabled) || capi.key?("enabled"))
236
+ return if inference.key?(:providers) || inference.key?(:defaultProvider) || explicit_capi
237
+
238
+ connection = { name: "default" }
239
+ model_fields = {}
240
+ provider.each do |raw_key, value|
241
+ next if value.nil?
242
+
243
+ key = raw_key.to_sym
244
+ next if key == :name
245
+
246
+ if LEGACY_PROVIDER_MODEL_FIELDS.include?(key)
247
+ model_fields[key] = value
248
+ else
249
+ connection[key] = value
250
+ end
251
+ end
252
+
253
+ inference[:providers] = [connection]
254
+ inference[:defaultProvider] = "default"
255
+ github[:capi] = (capi.is_a?(Hash) ? capi : {}).merge(enabled: false)
256
+ return if model_fields.empty? || model.nil?
257
+
258
+ inference[:models] = [{ provider: "default", id: model }.merge(model_fields)]
259
+ end
260
+ private_class_method :group_legacy_provider
261
+ end