Compare commits

...
82 Commits
Author SHA1 Message Date
David KayaandCopilot 898e27e64d refactor: remove premium request subtitle from ChatPane footer
The Activity Panel already shows premium request counts in the
Session Usage section, so the ChatPane footer only needs the
context-window bar.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 00:47:08 +01:00
David KayaandCopilot 92832c6116 feat: surface Copilot usage and quota data across the UI
Add three layers of usage visibility:

- ChatPane footer: premium request count, AIU consumed, and quota
  remaining below the existing context-window bar
- Settings / CopilotStatusCard: on-demand account quota section with
  progress bars, overage indicators, and reset dates fetched via
  the new get-quota sidecar command
- Activity Panel: per-agent token/cost/duration totals on each agent
  row and a Session Usage summary section between agents and timeline

Backend (sidecar):
- New get-quota command using SDK account.getQuota RPC
- New assistant-usage turn-scoped event from SDK assistant.usage
- QuotaSnapshotMapper for both typed and untyped SDK quota payloads
- DTOs: GetQuotaCommandDto, QuotaSnapshotDto, AccountQuotaResultEventDto,
  AssistantUsageEventDto

Frontend:
- Shared types: AssistantUsageEvent, QuotaSnapshot, GetQuotaCommand
- IPC bridge: getQuota channel, assistant-usage event dispatch
- State: SessionRequestUsageMap accumulator with per-agent breakdown
- 8 new tests for accumulator logic and formatting helpers

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 00:46:09 +01:00
David KayaandCopilot 48efbf36f9 fix: prevent crash when pressing Shift+Enter in empty code block
The CodeHighlightPlugin's selection restoration could create an invalid
Lexical selection targeting a LineBreakNode with type 'element'. Since
LineBreakNode is not an ElementNode, Lexical threw during reconciliation
and the LexicalErrorBoundary replaced the editor with an error state.

The fix ensures findPoint never targets a LineBreakNode directly.
Instead it falls back to an element-level selection on the parent
CodeNode using the child index, which is always a valid target.

Extracted the selection helpers (getCodeNodeAbsoluteOffset,
findCodeNodeSelectionPoint, restoreCodeNodeSelection) into
markdownEditor.ts for testability and added regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 00:12:20 +01:00
David KayaandCopilot 21f0ccb184 feat: show sub-agent activity cards in chat stream
Display compact status cards in the chat transcript showing each
sub-agent's name, current activity (Thinking, Using grep, etc.),
and elapsed time. Cards appear while sub-agents are running and
clear when the session goes idle.

- Extend SessionEventRecord with description, error, toolCallId,
  and model fields for subagent events
- Forward additional subagent fields in handleTurnScopedEvent
- Add subagentTracker reducer to derive active subagent state from
  session events, including agent-activity correlation
- Create SubagentActivityCard component with spinner, status icon,
  agent name, activity label, and live elapsed timer
- Wire activeSubagents state in App.tsx and pass to ChatPane
- Add 16 unit tests for the subagent tracker

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-29 00:04:05 +01:00
David KayaandCopilot 7921b6648f fix: auto-complete previous pending messages when a new assistant message starts
When the agent produces multiple intermediate responses during a turn,
each gets a unique messageId but all stay pending until finalizeTurn().
This caused multiple stacked 'Thinking' bubbles in the chat transcript.

Now, when a new messageId arrives in applyTurnDelta, any previously
pending assistant messages are marked complete and message-complete
events are emitted before the new message-delta. The renderer reducer
mirrors this logic for defensive consistency.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 23:59:06 +01:00
David KayaandCopilot 6d12cce836 fix: prevent composer action bar from overlaying text field
Change the bottom action bar from absolute positioning to normal
document flow so it sits below the editable area instead of floating
on top. Reduce editable bottom padding since buttons no longer overlap.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 23:37:01 +01:00
David KayaandCopilot e4142a6def refactor: move Terminal and Prompts pills into composer
Declutter the pill row above the chat composer by relocating Terminal
and Prompts pills from the session-config rows into the composer's
bottom action bar (left side). The session-config row now only shows
session-scoped controls: Tools, Approval, Model, and Thinking.

The relocated pills use a lighter, borderless style matching the
inner-composer aesthetic alongside the existing Attach, Plan mode,
and Send buttons.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 23:34:58 +01:00
David KayaandCopilot edd4c7381a feat: add integrated terminal frontend
- Add TerminalPanel component with xterm.js, FitAddon, drag-to-resize,
  header bar (status dot, shell label, cwd, restart/minimize/close)
- Modify AppShell to accept terminal panel in vertical flex layout
- Add terminal state management in App.tsx (open/height/running state,
  Ctrl+backtick toggle, height persistence via IPC)
- Add InlineTerminalPill to composer pill row (both single/multi-agent)
- Install @xterm/xterm and @xterm/addon-fit as devDependencies
- Update ARCHITECTURE.md with frontend terminal component details
- Add Integrated Terminal feature card to marketing website

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 23:29:18 +01:00
David KayaandCopilot 251316596c feat: add integrated terminal backend
- add a PTY manager with platform shell resolution and streamed data/exit events
- expose terminal lifecycle and terminal height IPC through preload and app service
- persist terminal panel height in workspace settings and document the backend contract
- add backend tests and validate native packaging with bun run package

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 23:15:16 +01:00
David KayaandCopilot 651a7d27fc feat: show MCP probe progress in approval pill
- Thread mcpProbingServerIds from workspace state through App → ChatPane → InlineApprovalPill
- Show animated spinner and 'probing…' label on pill button while any MCP server is being probed
- Show per-server probing indicator in popover: spinning icon, 'probing…' badge, hidden toggle
- Render approval pill during probing even when no MCP tools are known yet

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 22:08:25 +01:00
David KayaandCopilot cc13ed29f5 feat: stream MCP probe progress
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 21:58:07 +01:00
David KayaandCopilot 9ddd831b34 fix: preserve probed MCP tools across session switches
mergeDiscoveredToolingState now carries over probedTools from existing
servers when the config fingerprint is unchanged. The equality check in
syncProjectDiscoveredTooling also strips probedTools before comparing,
so runtime-only probe data never triggers a spurious state replacement.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 20:09:45 +01:00
David KayaandCopilot 08876f694d fix: handle MCP tools with complex JSON schema \ in outputSchema
The SDK's listTools() calls cacheToolMetadata() which compiles
outputSchema validators. Servers with \ in their schemas (e.g.,
icm-mcp) cause a JSON schema resolution error. Fall back to a raw
JSON-RPC tools/list request that skips schema compilation, since we
only need tool names and descriptions for the approval pill.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 20:00:53 +01:00
David KayaandCopilot 216b17b2ac fix: add origin-only well-known URL fallback for OAuth discovery
Some MCP servers (e.g., eschat.microsoft.com/mcp) serve their
OAuth Protected Resource Metadata at the origin without the path
suffix. Add a third candidate URL that strips the path, matching
VS Code's discovery behavior.

Tried in order:
1. RFC 9728: {origin}/.well-known/{suffix}{path}
2. Appended: {origin}{path}/.well-known/{suffix}
3. Origin-only: {origin}/.well-known/{suffix}

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:53:25 +01:00
David KayaandCopilot b985a06df3 fix: re-probe MCP servers after OAuth authentication
Tokens are in-memory and empty at startup, so HTTP servers requiring
OAuth return 401 during initial probing. After the user completes
OAuth (either via session auth prompt or proactive auth), re-probe
the authenticated server so its tools appear in the approval pill
without requiring an app restart.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:47:45 +01:00
David KayaandCopilot 169a9617c8 fix: improve MCP probe error reporting and SSE fallback
When SSE fallback gets 405 (confirming a Streamable HTTP server),
surface the original Streamable HTTP error instead of the misleading
SSE 405. Extract HTTP status codes from SDK error objects to produce
clearer log messages like 'HTTP 401: Streamable HTTP error: ...'.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:43:53 +01:00
David KayaandCopilot e38a663834 fix: fall back to SSE transport when Streamable HTTP probe fails
Many MCP servers only support legacy SSE despite being configured as
generic HTTP endpoints. Follow the MCP SDK's recommended fallback
pattern: try Streamable HTTP first, then retry with SSE on failure.
This matches VS Code's behavior for these servers.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:39:23 +01:00
David KayaandCopilot f0114058ba fix: show MCP tools in all provider groups when shared
When multiple MCP servers expose the same tool names (e.g., several
kusto-mcp instances), each server's group now shows its tools instead
of only the first server getting the tools and others showing 0/0.

Deduplicate the effectiveAutoApprovedCount to avoid double-counting
shared tools in the pill header.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:35:56 +01:00
David KayaandCopilot 6505493735 fix: resolve nested button DOM nesting in approval pill
Change the approval group header from <button> to a <div> with
role='button' and keyboard handling to avoid nesting the GroupToggle
<button> inside another <button>, which is invalid HTML.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:33:41 +01:00
David KayaandCopilot b4b0bf54d2 fix: improve MCP tool probing reliability
- Increase default probe timeout from 10s to 30s to handle slow
  package managers (uvx, npx) that install on first run
- Add console logging for probe success/failure to aid debugging
- Probe manually configured MCP servers (not just discovered ones)
  so all servers with wildcard tools get their tools discovered

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:30:42 +01:00
David KayaandCopilot 8312a47bf1 feat: discover MCP tools via protocol probing for approval pill
When MCP server configs declare wildcard tools (empty tools array),
the Copilot SDK has no API to list individual tool names. Add direct
MCP protocol probing using @modelcontextprotocol/sdk to discover
available tools from each accepted server.

- Add McpToolProber service supporting stdio/SSE/HTTP transports
- Probe accepted MCP servers on project load, acceptance, and rescan
- Store probed tools on DiscoveredMcpServer and McpServerDefinition
- Use probed tools in listApprovalToolDefinitions when declared tools
  are empty, so the approval pill shows individual tool toggles
- Remove unused isMcpServerApprovalKey helper
- Fix effectiveAutoApprovedCount Math.max workaround in ChatPane
- Add comprehensive tests for probed tool behavior
- Update ARCHITECTURE.md tooling integration section

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 19:23:57 +01:00
David KayaandCopilot 3937904548 feat: add server-level MCP auto-approval for wildcard tool servers
MCP servers configured with empty tools arrays (wildcard) now appear in the
auto-approval pill with a server-level toggle. When toggled, a server-level
approval key (mcp_server:<name>) is added to autoApprovedToolNames. The
sidecar matches this key against PermissionRequestMcp.ServerName to auto-
approve all tools from that server without needing individual tool names.

- Add buildMcpServerApprovalKey/isMcpServerApprovalKey helpers
- Create approval groups for all MCP servers including empty-tools ones
- Add serverApprovalKey to ApprovalToolGroup for server-level toggles
- Update sidecar RequiresToolCallApproval to check server-level keys
- Include server-level keys in listApprovalToolNames for pruning safety
- Add tests for both shared domain and sidecar approval matching

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 18:34:19 +01:00
David KayaandCopilot 53a08e0ed4 feat: redesign auto-approval pill with server-level grouping and batch toggle
Group MCP tools by server and LSP tools by profile in the approval popover
instead of showing a flat list. Each server/profile group gets a collapsible
header with a batch toggle to approve/unapprove all tools at once. Add a
search filter (visible when >10 tools) and partial-state indicators for
groups with mixed approval. Add groupApprovalToolsByProvider shared helper
with tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 18:18:17 +01:00
David KayaandCopilot 5ad85db0f5 refactor: redesign project settings with sidebar navigation
Replace flat scrolling layout with sidebar + content panel matching the global
SettingsPanel pattern. Sections: Overview, Instructions (with expandable
previews), Custom Agents (with enable/disable), Prompt Files, MCP Servers,
Danger Zone. Add count badges, pending indicators, project name in header,
section-level rescan buttons, and contextual empty states.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 17:59:31 +01:00
David KayaandCopilot dd203ddde5 feat: add frontend customization UI and prompt picker
Add Copilot Customization section to ProjectSettingsPanel with instruction file
previews, agent profile enable/disable toggles, and prompt file listing. Add
InlinePromptPill to chat input for selecting and sending prompt files with
variable substitution. Wire rescan and agent profile IPC in App.tsx. Update
website with Copilot Customization feature card.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 17:40:21 +01:00
David KayaandCopilot 75b9ff667a feat: support project copilot customization
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 17:29:37 +01:00
David KayaandCopilot f53907755a feat: add dedicated project settings panel accessible from sidebar
Move project-specific settings (discovered MCP servers) out of the
global Settings panel and into a dedicated ProjectSettingsPanel overlay.
Users can now access any project's settings via a gear icon on the
sidebar project header, or by clicking the pending-discovery badge.

- Add ProjectSettingsPanel component with project info, discovered MCP
  server management (accept/dismiss/rescan), and project removal
- Add gear icon and clickable discovery badge to Sidebar ProjectGroup
- Remove project-specific discovery props from SettingsPanel (now
  shows only user-level discovered servers)
- Wire ProjectSettingsPanel overlay in App.tsx with auto-close on
  project removal

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 16:51:57 +01:00
David KayaandCopilot 3c57cb6ded fix: clean up interrupted session state on restart
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 16:22:12 +01:00
David KayaandCopilot b946359c69 fix: stabilize macOS CI validation
Remove the packaging-only create-dmg dependency in favor of native hdiutil, and make the hook runner working-directory test assert behavior without depending on macOS temp-path canonicalization.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 15:43:13 +01:00
David Kaya e4eb221308 fix: new screenshot for website 2026-03-28 15:30:41 +01:00
David KayaandCopilot 036fb4d4fa fix: stabilize cross-platform CI checks
Use the repository's default Electron import pattern in the MCP OAuth service, make the attachment-path test platform-neutral, and ensure the hook runner cwd/env test drains stdin before asserting shell output.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 15:27:48 +01:00
David KayaandCopilot 6321f9192d docs(website): add missing feature cards and expand existing copy
Add 5 new feature cards: Visual Pattern Editor, Extensible Tooling, Tooling
Discovery, Plan Review & Agent Questions, and Run Timeline. Expand Real
Project Context (git awareness), Persistent Sessions (search/duplicate),
and Get Started step 1 (Copilot diagnostics). Enrich tech banner with
React Flow and Open Source. Feature grid goes from 8 to 13 cards.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 14:52:48 +01:00
David KayaandCopilot 147b437e36 fix: isolate scratchpad session working directories
Give each scratchpad session its own working directory, migrate existing scratchpad sessions on workspace load, and route sidecar turns through the session-specific cwd. Add regression coverage for create, duplicate, delete, and migration flows, and document the new persistence model.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 14:31:39 +01:00
David KayaandCopilot fa5774cbc0 docs: strengthen backend/frontend plan-splitting requirement in AGENTS.md
Make the two-phase planning rule a hard, no-exceptions requirement.
Clarify sequencing, separate-session expectation, and handover
artifact contract coverage. Add when-in-doubt-split directive.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 14:08:30 +01:00
David KayaandCopilot ae56d55c85 fix: clean up hook event labels in Activity panel
Replace raw SDK identifiers with human-friendly labels (e.g.
sessionStart → Session start) and drop the meaningless UUID detail.
Labels now read like 'Session start hook started' instead of
'Hook sessionStart started'.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 14:06:21 +01:00
David KayaandCopilot 1fbfdbbac4 fix: suppress noisy hook lifecycle events
Stop forwarding hook lifecycle events when a project has no configured
.github/hooks/*.json commands so the UI only receives meaningful hook
activity. Also expose the configured-hook state on the bundle, cover the
suppression wiring with tests, and document the updated event semantics.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 14:05:10 +01:00
David KayaandCopilot db9ffe8399 fix: disambiguate hook lifecycle events in Activity panel
Append phase text (started/completed) to hook event labels so
start and end phases are visually distinct instead of appearing
as duplicates.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 13:25:35 +01:00
David KayaandCopilot dff97efd58 feat: support project hook commands
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 13:23:01 +01:00
David KayaandCopilot f459cc7291 fix: stop forcing copilot session ids
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 12:52:52 +01:00
David KayaandCopilot e13e3b818a fix: restore final assistant responses
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 12:44:14 +01:00
David KayaandCopilot f1fa52f9c3 feat: full Copilot SDK feature parity — custom agents, hooks, image input, skills, steering, session persistence
Backend (sidecar):
- Extended ProtocolModels with DTOs for custom agents, hooks, skills,
  infinite sessions, session lifecycle, and 9 new event types
- Added CopilotManagedSessionIds for stable SDK session ID mapping
- Added CopilotSessionManager/ICopilotSessionManager for session lifecycle
- Added CopilotSessionHooks for hook registration
- Added CopilotMessageOptionsMetadata for mid-turn steering
- Extended CopilotAgentBundle to wire custom agents, hooks, skills,
  infinite sessions, and stable session IDs
- Extended CopilotTurnExecutionState to project 13 new SDK event types
- Widened ITurnWorkflowRunner callback to accept SidecarEventDto
- Added list/delete/disconnect session commands to SidecarProtocolHost
- Added AryxCopilotAgentMessageOptionsTests (14 new tests, 142 total)

Frontend (renderer + main + shared):
- Added ChatMessageAttachment type and helpers (attachment.ts)
- Extended sidecar contracts with MessageMode, 3 new command types,
  9 new event types, and agent/session config DTOs
- Extended SessionEventRecord with 6 new event kinds and ~20 fields
- Added PatternAgentCopilotConfig to pattern domain
- Added attachments support to ChatMessageRecord
- Updated sidecar client with session lifecycle methods and
  turn-scoped event routing via onTurnScopedEvent callback
- Updated main process: handleTurnScopedEvent(), deleteSession(),
  steering bypass for mid-turn messages, attachment passthrough
- Added deleteSession IPC handler and preload binding
- Added TurnEventLog state tracker with format/apply/prune helpers
- ChatPane: always-enabled composer, steering indicator, attachment
  picker with preview, image thumbnails in message history,
  context-usage bar, amber steer mode for send button
- ActivityPanel: turn events section with sub-agent, hook, skill,
  and compaction event rendering
- Sidebar: delete session action in context menu
- App.tsx: wired sessionUsage, turnEventLogs, and deleteSession

Documentation:
- AGENTS.md: added glob safety rule for node_modules
- README.md: added steering, image input, and richer observability
- ARCHITECTURE.md: added turn-scoped events, steering, and attachments
- Website: added steering and image input feature cards, updated
  live visibility and session cards

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-28 12:28:20 +01:00
David Kaya 0c2973c599 fix: add plan to .gitignore 2026-03-28 11:54:32 +01:00
David KayaandCopilot c1dab96bfd fix: wire PatternEditor to mode-aware graph mutations
Replace the old disconnected-node addAgentNodeToGraph with the
mode-aware addAgentToGraph so new agents are automatically wired
into the graph topology. Replace the graph-nuking removeAgent
path with removeAgentFromGraph for surgical node removal. Split
emitChange into graph-preserving and mode-change paths so editing
agent properties no longer discards custom positions and edges.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 21:55:54 +01:00
David KayaandCopilot bb7e5d4108 fix: preserve editable pattern graphs
Add mode-aware graph mutation helpers for pattern topology so backend
code can add and remove agents without forcing a full graph rebuild.
Also preserve an existing pattern graph in savePattern instead of
re-syncing it from defaults, and cover the new behavior with shared
and main-process tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 21:50:01 +01:00
David KayaandCopilot b5ab92e444 fix: auto-resolve queued approvals of the same category
When multiple tool calls of the same permission category (e.g. three
concurrent view/read calls) arrive simultaneously, approving one now
cascades to all queued approvals sharing the same category key. This
eliminates repeated approval prompts for parallel tool calls.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 21:43:21 +01:00
David KayaandCopilot 689b335220 feat: category-based approval for runtime tools
Replace 20+ individual runtime tool toggles with 5 permission categories
(read, write, shell, web_fetch, store_memory) matching how Copilot CLI,
Cline, and other coding agents handle approvals.

- Add resolveApprovalToolKey() to map permission kinds to category IDs
- Simplify fallbackRuntimeApprovalTools to 5 categories
- Thread alwaysApprove through PendingApprovalHandle → sidecar resolve
- Update ApprovalBanner to use category labels for Always Approve button
- Update ResolveApprovalCommand contract with alwaysApprove field
- Update tests for category-based model

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 21:36:27 +01:00
David KayaandCopilot f04e3b9dcc feat: cache same-turn approval selections
Add an AlwaysApprove flag to resolve-approval commands and cache
approved tool keys for the current request so repeated runtime
permissions are auto-approved immediately within the same turn.
The cache is cleared when the turn finishes to avoid leaking across
future requests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 21:24:55 +01:00
David KayaandCopilot 3ec69d990b feat: enable 'always approve for session' for runtime tools
Runtime tool permission requests (read, write, shell, store_memory) now
resolve stable approval names via fallback in the sidecar approval
coordinator, enabling the 'Always approve' button and session-level
auto-approval for built-in tools.

Backend:
- Add fallback tool names for PermissionRequestRead (read),
  PermissionRequestWrite (write), PermissionRequestShell (shell),
  and PermissionRequestMemory (store_memory)
- Add autoApprovedToolName parameter to RequiresToolCallApproval
  for permission-kind-based session approval matching
- Track tool.execution_start events in ToolNamesByCallId for
  supplementary exact-name resolution

Frontend:
- Use approval.toolName ?? approval.permissionKind as fallback key
  in resolveSessionApproval and ApprovalBanner
- Add shell, read, write permission-kind entries to builtin approval
  tool definitions so pruning preserves session overrides

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 21:20:14 +01:00
David KayaandCopilot 154787c336 fix: only project handoff tool calls as FunctionCallContent
AryxCopilotAgent was converting ALL Copilot tool requests (ask_user,
MCP tools, etc.) into FunctionCallContent. The Agent Framework's
AIAgentHostExecutor tracks every FunctionCallContent as an outstanding
request.  Since SDK-handled tools like ask_user never produce a
matching FunctionResultContent, HasOutstandingRequests stayed true and
TurnToken was never emitted — stalling group-chat advancement after
an ask_user interaction.

Now only handoff_to_* tool requests are projected as FunctionCallContent.
All other tool calls remain invisible to the Agent Framework executor,
matching the upstream GitHubCopilotAgent behaviour.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 21:12:42 +01:00
David KayaandCopilot 9d65e3d209 fix: restore real Copilot handoffs
Replace the broken forced-tool workaround with a repo-local Copilot
agent adapter that merges runtime handoff instructions and tool
declarations into Copilot sessions and projects Copilot tool requests
back into Agent Framework function-call updates.

Also add regression coverage for the adapter and document the runtime
integration detail in the architecture guide.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 21:07:58 +01:00
David KayaandCopilot 7247a68f24 fix: enforce real entry handoffs
Constrain the initial handoff triage agent so it cannot use regular
session tooling and must use a handoff tool on its first invocation.
This prevents the model from narrating delegation in plain text while
never actually transferring control.

Also add regression tests for the new entry-agent constraints.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 20:58:31 +01:00
David Kaya 85a9327f65 fix: surface handoff specialist activity\n\nQueue per-agent thinking updates from synchronous Copilot SDK session\nevents, flush them through the workflow runner, and promote handoff\ntargets to thinking immediately after handoff activity is emitted.\nThis fixes the UI case where downstream agents stayed on 'No status\nyet' during handoff patterns.\n\nAlso add targeted handoff diagnostics and regression tests.\n\nCo-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> 2026-03-27 20:49:52 +01:00
David KayaandCopilot 2a952dfebe fix: workspace reset now properly clears UI state
resetLocalWorkspace() deleted workspace.json and the scratchpad
directory but never broadcast the fresh state to the renderer.
The renderer also discarded the IPC return value. This left stale
projects, sessions, and activities visible in the UI after reset.

- Emit workspace-updated after reloading the workspace in the backend
- Use the returned fresh workspace to immediately update renderer state
- Clear sessionActivities and close the settings panel on reset

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 20:48:37 +01:00
David KayaandCopilot cf41279ff5 fix: clamp auto-approval pill count to known tools
The auto-approval pill displayed effectiveAutoApproved.size as the
numerator, which could include tool names not present in the approval
tool list (e.g. names added via 'Always approve' for tools that aren't
in runtimeTools yet). This caused impossible counts like '17/14'.

Compute the count by intersecting effectiveAutoApproved with the actual
approvalTools list, so the numerator never exceeds the denominator.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 20:40:30 +01:00
David KayaandCopilot c02589f4c0 fix: only probe OAuth for newly enabled MCP servers
Previously, every tooling update re-probed all enabled HTTP MCP servers
for OAuth requirements. Now it compares the new selection against the
previous one and only probes servers that were just enabled.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 20:31:29 +01:00
David KayaandCopilot 73595039fc fix: support provider-specific MCP OAuth settings
Use provider-aware OAuth handling instead of a single hardcoded client ID.
GitHub now follows VS Code's GitHub auth setup with the GitHub client ID,
GitHub authorize/token endpoints, prompt=select_account, vscode.dev/redirect,
and JSON-compatible token exchange. Entra keeps the Copilot client ID via a
known provider match, while unknown providers still fall back to metadata
and dynamic registration.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 20:23:26 +01:00
David KayaandCopilot 81bddcbd63 fix: align MCP OAuth flow with Copilot client ID requirements
- Use vscode.dev/redirect as redirect URI when using the Copilot client
  ID, with the local callback URL encoded in the state parameter
- Use PRM resource scopes (e.g. api://icmmcpapi-prod/mcp.tools) instead
  of generic OIDC scopes, always include offline_access
- Listen on root path instead of /callback to match vscode.dev/redirect
  behavior
- Extract PRM scopes from protected resource metadata discovery

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 20:15:25 +01:00
David KayaandCopilot 53f1167681 feat: use GitHub Copilot client ID as default for MCP OAuth
Use the well-known Copilot client ID (aebc6443-996d-45c2-90f0-388ff96faa56)
when no static client config is provided and the auth server doesn't
support dynamic client registration. This matches how VS Code authenticates
with Entra ID-backed MCP servers.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 20:08:40 +01:00
David KayaandCopilot 4f7b479996 fix: fall back to openid-configuration for auth server metadata discovery
Microsoft Entra ID and other OIDC providers expose metadata at
.well-known/openid-configuration rather than RFC 8414's
.well-known/oauth-authorization-server. Now tries both suffixes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 20:06:02 +01:00
David KayaandCopilot 0fd7a04a51 fix: try both RFC 9728 and appended well-known URL paths for MCP OAuth discovery
Some MCP servers place .well-known metadata at the appended path
(e.g. /v1/.well-known/oauth-protected-resource) instead of the
RFC 9728 compliant inserted path. Now tries the RFC-compliant URL
first and falls back to the appended form.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 20:00:50 +01:00
David KayaandCopilot 6c6b49fde4 fix: probe PRM directly instead of GET-ing the MCP server URL
MCP servers use POST/SSE, not GET. A plain GET to the server URL can
return 405, 404, or other codes unrelated to authentication. Instead,
go directly to the .well-known/oauth-protected-resource endpoint and
check whether it returns valid metadata with authorization_servers.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 19:48:49 +01:00
David KayaandCopilot d73eaae30b fix: correct well-known URL construction per RFC 9728
The .well-known/{suffix} segment was being appended to the full URL
path instead of inserted after the origin. For example:

  Wrong:   https://api.example.com/mcp/.well-known/oauth-protected-resource
  Correct: https://api.example.com/.well-known/oauth-protected-resource/mcp/

- Extract buildWellKnownUrl() helper in mcpTokenStore (Electron-free)
- Fix all 3 call sites: requiresOAuth probe, PRM discovery, auth
  server metadata
- Add 6 unit tests for URL construction with various path shapes

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 19:46:25 +01:00
David KayaandCopilot 1868a79d9a feat: add 'Always approve' button for tool-call approvals
When a tool-call approval banner appears, users can now click 'Always
approve' to both approve the current call AND add the tool to the
session's autoApprovedToolNames. Future calls to that tool are then
auto-approved without showing the banner.

- Add alwaysApprove?: boolean to ResolveSessionApprovalInput
- In resolveSessionApproval, atomically append tool to session
  approvalSettings when alwaysApprove is true (avoids running guard)
- Add 'Always approve' button in ApprovalBanner (tool-call kind only)
- Wire through ChatPane and App.tsx with updated callback signatures

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 19:34:50 +01:00
David KayaandCopilot 4f1ae86021 fix: add diagnostic logging to MCP OAuth probing
Add [aryx oauth] log messages throughout the proactive auth flow so
failures are visible in the Electron main process console (DevTools →
Main Process or terminal output). Logs cover: probe start, HTTP status,
PRM discovery, token skip, flow start, and success/failure.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 19:31:03 +01:00
David KayaandCopilot f0c2b4982b feat: proactive OAuth when enabling HTTP MCP servers
When a user enables an HTTP MCP server for a session, proactively probe
the server URL. If it returns 401 and has discoverable OAuth metadata
(RFC 9728), automatically trigger the full OAuth 2.1 + PKCE flow and
open the browser for consent — matching VS Code's behavior.

- Add requiresOAuth() probe: GET server URL → check 401 → check PRM
- Add probeAndAuthenticateHttpMcpServers() in AryxAppService
- Call proactive probe from updateSessionTooling (fire-and-forget)
- Skip servers that already have stored tokens

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 19:26:59 +01:00
David KayaandCopilot ac48aa58e0 feat: implement MCP OAuth 2.1 flow, token storage, and injection
- Create mcpTokenStore: in-memory token storage keyed by normalized server URL
  with automatic expiry checking
- Create mcpOAuthService: full OAuth 2.1 + PKCE flow implementation
  - Protected Resource Metadata discovery (RFC 9728)
  - Authorization Server Metadata fetch (RFC 8414)
  - Dynamic Client Registration (RFC 7591) when no static client ID
  - PKCE S256 code challenge generation
  - Local HTTP callback server for auth code receipt
  - Browser-based consent via Electron shell.openExternal
  - Authorization code to token exchange
- Add startSessionMcpAuth IPC channel and handler to trigger OAuth flow
- Inject stored OAuth tokens as Authorization headers in buildRunTurnToolingConfig
- Update McpAuthBanner with 'Authenticate in browser' button and loading state
- Add tests for token store (7 tests) and token injection (3 tests)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 19:15:37 +01:00
David KayaandCopilot f9757d5ce2 feat: add MCP OAuth authentication frontend wiring and banner
- Add McpOauthRequiredEvent and McpOauthStaticClientConfigEvent to sidecar contracts
- Add PendingMcpAuthRecord domain type with status tracking (pending/authenticating/failed/done)
- Add pendingMcpAuth field to SessionRecord for session-level auth state
- Wire onMcpOAuthRequired callback through sidecarProcess, runTurnPending, and AryxAppService
- Handle mcp-oauth-required events: set session pendingMcpAuth, clear on turn finalize/cancel
- Add dismissSessionMcpAuth IPC channel with preload binding and handler registration
- Create McpAuthBanner component (amber-themed, shows server name/URL, dismiss button)
- Integrate McpAuthBanner into ChatPane with placeholder text and App.tsx callback
- Update test fixtures for new RunTurnPendingCommand.onMcpOAuthRequired field

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 19:09:11 +01:00
David KayaandCopilot 192c28f721 feat: surface MCP OAuth sidecar events
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-27 19:01:46 +01:00
David KayaandCopilot b670680a7d refactor: improve plan mode UX with composer-integrated toggle and guidance text
- Move plan mode toggle from pills row to composer send button area
- Plan toggle sits next to the send button as a mode switch icon
- Send button turns emerald when plan mode is active
- Add mode indicator strip below composer when plan mode is on
- Replace 'Implement this plan' auto-send button with instructional
  guidance text that tells the user to send a follow-up message
- Keep Dismiss button to clear the plan review banner

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 23:46:04 +01:00
David KayaandCopilot 231be36e6c feat: add plan mode frontend support with mode toggle and plan review UI
- Add InteractionMode type and ExitPlanModeRequestedEvent to sidecar contracts
- Add PendingPlanReviewRecord domain type and interactionMode to SessionRecord
- Wire onExitPlanMode callback through SidecarClient and RunTurnPendingCommand
- Pass session interaction mode to RunTurnCommand for sidecar consumption
- Handle exit-plan-mode-requested events in AryxAppService
- Add setSessionInteractionMode and dismissSessionPlanReview IPC methods
- Create PlanReviewBanner component with summary, markdown content, and actions
- Add plan mode toggle pill in ChatPane composer area
- Wire implement action as follow-up message (graceful degradation)
- Clear pending plan review on new turn, turn completion, and cancellation

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 23:39:48 +01:00
David KayaandCopilot 380e402512 feat: add backend plan mode checkpoints
Add backend support for plan-mode turn shaping and exit-plan review
checkpoints. Run-turn commands now accept an interaction mode,
plan-mode prompt guidance tells agents to produce a plan and call
exit_plan_mode, and the sidecar emits a structured
exit-plan-mode-requested event when the SDK raises that session event.

For now the backend intentionally treats exit_plan_mode as a turn
boundary and graceful-degradation review checkpoint. The current
Agent Framework GitHubCopilotAgent wrapper does not expose a clean way
to bridge the live CopilotSession back into same-turn exit-plan
resolution, so that follow-up remains documented for the frontend and a
future backend slice.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 23:29:32 +01:00
David KayaandCopilot c069b86add docs: add website update guideline to AGENTS.md
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 23:24:37 +01:00
David KayaandCopilot 912677fba0 feat: add tool metadata registry with human-readable labels
Add a builtin tool label registry mapping all ~30 official SDK tool IDs
to human-readable display names. Update listApprovalToolDefinitions to
resolve labels from the registry instead of showing raw tool IDs like
read_bash or fetch_copilot_cli_documentation. Expand the fallback
runtime tool catalog from 6 to 23 non-internal standard tools.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 19:27:36 +01:00
David KayaandCopilot a1a044e7ca fix: filter internal runtime tools
Exclude internal runtime tools from sidecar capability discovery so they do not surface in the approval tool catalog.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 19:23:48 +01:00
David KayaandCopilot f15b1aedb1 feat: add ask_user interactive user input to frontend
Wire the sidecar user-input-requested protocol event through the main
process, IPC layer, and renderer UI so agents can ask the user
interactive questions with choices and freeform input.

- Add UserInputRequestedEvent and ResolveUserInputCommand to sidecar
  protocol types
- Add resolveUserInput method to SidecarClient and onUserInput callback
  to runTurn
- Create PendingUserInputRecord domain type and add pendingUserInput to
  SessionRecord
- Add handleUserInputRequested and resolveSessionUserInput to
  AryxAppService with handle management
- Register sessions:resolve-user-input IPC channel with preload bridge
- Create UserInputBanner component with choice buttons and freeform
  input
- Integrate UserInputBanner into ChatPane with header indicator

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 17:45:27 +01:00
David KayaandCopilot 2ae4bd01b4 feat: add ask_user support to sidecar
Implement the Copilot SDK user input round-trip in the backend:
- add user-input-requested and resolve-user-input protocol DTOs
- add a CopilotUserInputCoordinator that mirrors approval flow with
  pending TaskCompletionSource state and explicit resolution
- wire SessionConfig.OnUserInputRequest through CopilotAgentBundle
  and CopilotWorkflowRunner
- extend SidecarProtocolHost to emit user input events, accept
  resolve-user-input commands, and filter ask_user from runtime
  approval tools
- add regression tests for the new coordinator and protocol flow

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 17:34:49 +01:00
David KayaandCopilot 4c01d8b1a7 feat: surface structured permission details in approval UI
Wire the sidecar's new permissionDetail payload through the frontend:
- Add PermissionDetail interface to sidecar contract
- Add permissionDetail field to PendingApprovalRecord and thread
  through normalization and AryxAppService mapping
- Create PermissionDetailView component with kind-specific rendering:
  shell (command block + warning), write (filename + diff), read (path),
  mcp (server badge + args), url (prominent URL), memory (subject/fact),
  custom-tool (description + args), hook (message + args)
- ApprovalBanner shows structured detail when available, falls back to
  generic text for backward compatibility
- QueuedApprovalsList shows brief kind-specific summaries

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 16:59:15 +01:00
David KayaandCopilot 13c543e2fd feat: add structured tool approval details to sidecar protocol
Expose SDK permission request details on approval-requested events via a
new permissionDetail payload. This preserves the existing title/detail
summary while carrying the command, URL, diff, args, and other
kind-specific data needed for richer approval UI in the renderer.

Also adds sidecar coverage for all supported permission request kinds and
verifies the new payload serializes over the protocol.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 16:40:41 +01:00
David KayaandCopilot 69562c19f3 fix: fix Inno Setup preprocessor defines via environment variables
ISCC's /D command-line flag combined with Node.js spawn on Windows
produces broken ISPP defines due to argument quoting conflicts.
Switch to environment variables read via GetEnv() — robust and
avoids all quoting issues. Product name and publisher are now
hardcoded in the ISS (they never change).

Verified: installer shows 'Aryx' and correct version in metadata.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 16:14:14 +01:00
David KayaandCopilot 7c1852f79f refactor: replace NSIS with Inno Setup for Windows installer
Switch from NSIS (early 2000s) to Inno Setup 6 — the modern standard
used by VS Code and most Electron apps. Features:

- Modern wizard UI (WizardStyle=modern)
- LZMA2/ultra64 solid compression (138.9 MB, down from 143 MB with NSIS)
- Per-user install to %LOCALAPPDATA%\Programs\Aryx (no admin needed)
- Optional desktop shortcut, Start Menu group
- Auto-closes running instance before install/uninstall
- Proper Add/Remove Programs integration via AppId
- Launch-after-install option

CI updated to install Inno Setup via Chocolatey on windows-latest.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 14:47:11 +01:00
David KayaandCopilot d7d1b33a53 fix: fix CI installer creation for all platforms
- Windows: add NSIS installation step via Chocolatey in CI workflow
- macOS: fix create-dmg CLI invocation to match sindresorhus package
  API (--overwrite, --no-version-in-filename, --no-code-sign) and
  rename output to expected asset name
- Add rename import to create-installer.ts

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 13:35:20 +01:00
David KayaandCopilot f838d2ac15 feat: add native platform installers for Windows, macOS, and Linux
Replace zip/tar archive distribution with platform-native installers:

- Windows: NSIS installer (.exe) with per-user install to
  %LOCALAPPDATA%\Programs\Aryx, Start Menu and Desktop shortcuts,
  Add/Remove Programs registration, and silent install support
- macOS: DMG disk image (.dmg) with drag-to-Applications experience
  via create-dmg
- Linux: Debian package (.deb) with /opt/aryx installation,
  /usr/bin/aryx symlink, desktop entry, hicolor icons, and
  libsecret-1-0 dependency declaration

Add scripts/create-installer.ts as the platform-dispatching entry
point. Update CI workflow to produce native installers instead of
archives. Add installerAssetName to ReleaseTarget interface.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-26 13:06:50 +01:00
129 changed files with 18872 additions and 523 deletions
+11 -16
View File
@@ -97,19 +97,19 @@ jobs:
- os: windows-latest
label: Windows
release_dir_name: Aryx-windows-x64
asset_path: release/Aryx-windows-x64.zip
asset_path: release/Aryx-windows-x64-setup.exe
- os: macos-15-intel
label: macOS (x64)
release_dir_name: Aryx-macos-x64
asset_path: release/Aryx-macos-x64.zip
asset_path: release/Aryx-macos-x64.dmg
- os: macos-15
label: macOS (arm64)
release_dir_name: Aryx-macos-arm64
asset_path: release/Aryx-macos-arm64.zip
asset_path: release/Aryx-macos-arm64.dmg
- os: ubuntu-latest
label: Linux
release_dir_name: Aryx-linux-x64
asset_path: release/Aryx-linux-x64.tar.gz
asset_path: release/aryx-linux-x64.deb
steps:
- name: Check out repository
@@ -131,6 +131,11 @@ jobs:
sudo apt-get update
sudo apt-get install -y libsecret-1-dev
- name: Install Inno Setup
if: runner.os == 'Windows'
shell: pwsh
run: choco install innosetup -y --no-progress
- name: Install dependencies
run: bun install --frozen-lockfile
@@ -141,18 +146,8 @@ jobs:
if: runner.os == 'macOS'
run: codesign --force --deep --sign - "release/${{ matrix.release_dir_name }}/Aryx.app"
- name: Create Windows release archive
if: runner.os == 'Windows'
shell: pwsh
run: Compress-Archive -Path 'release\Aryx-windows-x64\*' -DestinationPath 'release\Aryx-windows-x64.zip' -Force
- name: Create macOS release archive
if: runner.os == 'macOS'
run: ditto -c -k --sequesterRsrc --keepParent "release/${{ matrix.release_dir_name }}/Aryx.app" "${{ matrix.asset_path }}"
- name: Create Linux release archive
if: runner.os == 'Linux'
run: tar -czf release/Aryx-linux-x64.tar.gz -C release Aryx-linux-x64
- name: Create platform installer
run: bun run scripts/create-installer.ts
- name: Upload asset to GitHub release
shell: bash
+1
View File
@@ -9,3 +9,4 @@ sidecar/**/obj/
.DS_Store
Thumbs.db
plan/
+8 -3
View File
@@ -42,6 +42,7 @@ These instructions apply to any automated or semi-automated agent working in thi
- Treat tests as part of the implementation, not as follow-up work. Every fix, behavior change, and new feature must be covered by tests, and the relevant test suite must pass before the work is considered complete.
- Always check whether `README.md` needs an update before handing work off. If the change affects user-facing behavior, workflows, prerequisites, installation, packaging, or product positioning, update the README in the same change.
- Always check whether `ARCHITECTURE.md` needs an update before handing work off. If the change affects runtime boundaries, data flow, persistence, IPC, orchestration, tooling integration, packaging, or other material technical design, update `ARCHITECTURE.md` in the same change.
- Always check whether the product website (`website/`) needs an update before handing work off. If the change introduces a major new feature, or a minor feature that is particularly interesting or noteworthy to end users, update the relevant website content in the same change. The website is a standalone Astro app under `website/` and validates with `bun run build` from that directory.
- Do not ship quick fixes, hacks, or "temporary" patches as final solutions. Take the time to understand the problem, plan the change, and implement a maintainable solution that fits the codebase cleanly.
- Remove code that is no longer necessary before handing work off. If an experiment, workaround, hotfix, helper, or test path does not end up being part of the final correct solution, delete it rather than leaving dead or misleading code behind.
- Apply the same quality bar to feature work. Think through scope, edge cases, integration points, and long-term maintainability before implementing.
@@ -153,13 +154,17 @@ Every interactive component must include basic accessibility:
- Keep changes focused and reviewable. Avoid mixing unrelated concerns into a single change.
- Always commit completed repository changes before handing work off. If unrelated pre-existing changes are present in the worktree, stop and ask the user how to proceed before creating the commit.
- Do not mark work as done until both the implementation and its verification are complete.
- **Never use unscoped glob patterns** (e.g. `**/*`) at or near the repository root. The repository contains large `node_modules/` directories that will cause glob operations to hang or exhaust resources. Always scope globs to a specific subdirectory (e.g. `src/**/*.ts`, `sidecar/src/**/*.cs`) or use `view` on known directories instead.
## 8. Planning requirements
- If a task spans both backend and frontend work, the implementation plan must be split into **Part 1 — Backend** and **Part 2 — Frontend**. The Frontend part will be launched manually by the user.
- Backend work must be planned and executed first.
- Before frontend work begins, backend work must produce a handover artifact in the session workspace `files\` directory. Do not put this handover document in the repository.
> **Hard rule — no exceptions.** Every task that touches both backend (C# / sidecar) and frontend (TypeScript / renderer) code **must** produce a plan with exactly two phases: **Part 1 — Backend** and **Part 2 — Frontend**. A single combined plan that mixes backend and frontend work is never acceptable, even if the changes seem small or tightly coupled. When in doubt about whether a task spans both surfaces, treat it as spanning both and split the plan.
- **Part 1 — Backend** is always planned, implemented, tested, and committed first. No frontend work may begin until Part 1 is complete.
- **Part 2 — Frontend** is launched manually by the user in a separate session. Do not start frontend implementation in the same session as backend work.
- Before frontend work begins, backend work must produce a handover artifact in the session workspace `files\` directory. Do not put this handover document in the repository. The handover must describe every new or changed contract (DTOs, IPC messages, events, API shapes) that the frontend needs to consume.
- The frontend phase must consume that backend handover artifact and build on it rather than rediscovering backend contracts from scratch.
- If a task is frontend-only or backend-only, a two-part split is not required — but you must still confirm the scope before planning.
## 9. Validation checklist
+41 -4
View File
@@ -33,7 +33,7 @@ flowchart LR
Renderer[Renderer UI<br/>React + Tailwind]
Preload[Preload bridge]
Main[Electron main process]
Workspace[Workspace storage<br/>JSON + scratchpad files]
Workspace[Workspace storage<br/>workspace.json + per-session scratchpad directories]
Git[Local git repositories]
Sidecar[.NET sidecar]
Copilot[GitHub Copilot CLI<br/>+ agent runtime]
@@ -55,7 +55,7 @@ flowchart LR
| --- | --- | --- | --- |
| Renderer | Screens, interaction, local view composition, theme application | Filesystem, process spawning, raw Electron access, Copilot runtime | Typed preload API and pushed events |
| Preload | Narrow bridge between browser context and Electron IPC | Business logic, persistence, orchestration | `ipcRenderer` / `ipcMain` |
| Main process | Workspace mutation, persistence, git inspection, session lifecycle, native window state, sidecar lifecycle | UI rendering, LLM orchestration internals | IPC, filesystem, git CLI, stdio with sidecar |
| Main process | Workspace mutation, persistence, git inspection, session lifecycle, native window state, sidecar lifecycle, PTY-backed terminal lifecycle | UI rendering, LLM orchestration internals | IPC, filesystem, git CLI, stdio with sidecar, native child processes |
| Sidecar | Capability discovery, pattern validation, run execution, streaming deltas and activity | UI, workspace persistence, Electron APIs | Line-delimited JSON over stdio |
| External systems | Git data, Copilot account/model access, OS window chrome | Application state and UI behavior | Controlled adapters owned by main or sidecar |
@@ -122,7 +122,9 @@ Projects are the container for context. There are two kinds:
- a special **scratchpad** project for lightweight work
- normal **project-backed** entries pointing at local folders
The scratchpad is modeled inside the same workspace system instead of as a separate subsystem. That keeps the UI and session model consistent while still allowing special rules for scratchpad behavior.
The scratchpad is modeled inside the same workspace system instead of as a separate subsystem. That keeps the UI and session model consistent while still allowing special rules for scratchpad behavior. Each scratchpad session receives its own working directory under the shared scratchpad root, so session-created files stay isolated from other scratchpad conversations.
Project-backed entries also persist scanned Copilot customization metadata discovered from repository files such as `.github/copilot-instructions.md`, `AGENTS.md`, `.github/agents/*.agent.md`, and `.github/prompts/*.prompt.md`. The main process owns that scan step and stores the normalized results on the project record so repo instructions and enabled custom agent profiles can participate in later run execution without turning the renderer into a filesystem crawler.
### Patterns
@@ -136,6 +138,8 @@ Patterns describe how agents collaborate. The architecture supports:
Their runtime semantics follow the Agent Framework orchestration model: sequential and group chat preserve a visible shared conversation, concurrent aggregates multiple independent responses into one turn, and handoff turns can end once the active agent has responded and is waiting for the next user input.
For Copilot-backed agents, Aryx uses a repo-local adapter around the Copilot SDK session layer so handoff routes still behave like Agent Framework handoffs. This is necessary because the upstream `GitHubCopilotAgent` does not currently project run-time handoff tool declarations into Copilot sessions or surface Copilot tool requests back as `FunctionCallContent` for the workflow runtime.
Patterns are shared application data, not renderer-only configuration. That means the same pattern definition can drive validation, persistence, UI rendering, and sidecar execution.
Patterns now persist an explicit graph-backed topology alongside the flat agent list. Agent nodes carry stable agent ids, ordering, and layout metadata, while system nodes such as user input/output, distributor, collector, and orchestrator make mode-specific flow visible in the saved contract.
@@ -183,16 +187,20 @@ Typical examples:
- create session
- send message
- update theme
- create or restart the integrated terminal
- toggle session tooling
- update session approval overrides
The renderer does not reach into Electron or the filesystem directly. It talks through a constrained API surface.
The integrated terminal uses the same boundary. The renderer never opens a shell directly; it asks the main process to create or restart a PTY, sends fire-and-forget input and resize messages over IPC, and listens for streamed terminal data and exit events pushed back through preload. The `TerminalPanel` component manages an xterm.js terminal instance with a FitAddon, a drag-to-resize handle, and a header bar showing shell status.
### 2. Main process <-> sidecar
This is a structured stdio protocol used for:
- capability discovery
- on-demand account quota lookup
- pattern validation
- run execution
- streaming partial output
@@ -200,6 +208,24 @@ This is a structured stdio protocol used for:
This protocol boundary keeps the AI execution runtime replaceable and prevents the Electron main process from becoming overloaded with workflow-specific behavior.
The protocol also carries **turn-scoped lifecycle events** alongside output deltas. These events let the UI visualize execution internals without the main process having to interpret AI workflow semantics:
- **Sub-agent events**: started, completed, failed, selected, deselected — surfaced when custom agents are defined
- **Skill invocation events**: emitted when an agent-side skill is triggered
- **Hook lifecycle events**: start and end of configured project hook commands discovered from `.github/hooks/*.json`; Aryx suppresses the SDK's built-in no-op hook chatter so the UI only sees meaningful hook activity
- **Assistant usage events**: per-LLM-call tokens, cost, AIU, and quota snapshots from the Copilot SDK's `assistant.usage` stream
- **Session compaction events**: start and complete, with token-reduction metrics when infinite sessions trigger context trimming
- **Session usage events**: current token count and context-window limit from `session.usage_info` for context-bar rendering
- **Pending-messages-modified events**: emitted when mid-turn steering changes the pending message queue
These events flow through a single `onTurnScopedEvent` callback on the `runTurn` command, avoiding per-event-type callback proliferation. The main process maps each event to a `SessionEventRecord` and pushes it to the renderer, where lightweight state maps (activity, usage, turn-event log) consume them without touching the persisted workspace.
The same boundary also supports server-scoped sidecar commands that do not require a live Copilot session. The new `get-quota` command uses the SDK's `account.getQuota` RPC to fetch account quota snapshots on demand, then returns them as a `quota-result` protocol event followed by the usual `command-complete` sentinel.
For project-backed sessions, the sidecar also discovers GitHub Copilot CLI hook definitions from `.github/hooks/*.json` under the repository root. Those files are parsed and merged once per run bundle, then projected onto the SDK session hook delegates. Hook commands run synchronously in the sidecar through the platform shell, with stdin JSON payloads shaped to match Copilot CLI hook expectations as closely as the SDK allows. Hook failures are logged to stderr and treated as non-fatal diagnostics, while `preToolUse` hook outputs can still deny a tool call before Aryx falls back to its built-in approval policy.
The `run-turn` command now also carries a project-instruction payload derived from scanned repo customization files. The main process composes that payload from repo-level instruction files and merges enabled discovered custom agent profiles into the primary pattern agent's Copilot configuration before sending the command across the stdio boundary. The sidecar then folds those project instructions into the final SDK system message alongside the agent's own instructions and runtime guidance.
## Security model
Security in this system is mostly about **desktop trust boundaries**.
@@ -256,6 +282,8 @@ Tooling is deliberately split into two levels:
- **dynamic runtime tools** reported by the Copilot CLI, with a fallback catalog for startup/offline cases
- **global definitions** for MCP servers and LSP profiles
- **MCP tool discovery** — when MCP server configs declare wildcard tools (empty `tools` array), the main process probes each server directly via the MCP protocol `tools/list` method to discover available tools, using the same auth credentials Aryx manages for OAuth-protected servers
- **incremental probe progress** — MCP probing runs concurrently and publishes per-server progress through the pushed workspace snapshot, using the runtime-only `mcpProbingServerIds` field so the renderer can reflect in-flight discovery without persisting transient UI state
- **pattern defaults** where tool-call approval is enabled by default, plus which known runtime tools can bypass manual approval
- **per-session overrides** for both tool enablement and tool auto-approval
@@ -263,7 +291,7 @@ This lets the application treat tooling as reusable workspace capability while s
### Project awareness
Project-backed sessions can carry repository context such as branch and dirty state, while scratchpad sessions omit git context but still support MCP, LSP, and runtime tooling. Both session kinds share the same tooling selection and approval model. This keeps the architecture grounded in real codebases without forcing every conversation to be project-heavy, while still letting scratchpad sessions leverage configured tools when useful.
Project-backed sessions can carry repository context such as branch and dirty state, while scratchpad sessions omit git context but still support MCP, LSP, and runtime tooling. Scratchpad execution uses a per-session working directory instead of a single shared scratchpad folder, so file-based context and generated artifacts stay scoped to the active scratchpad session. Both session kinds share the same tooling selection and approval model. This keeps the architecture grounded in real codebases without forcing every conversation to be project-heavy, while still letting scratchpad sessions leverage configured tools when useful.
### Execution observability
@@ -271,11 +299,20 @@ The architecture treats execution as observable by design:
- partial output is streamed
- agent activity is surfaced
- turn-scoped lifecycle events (sub-agent, hook, skill, compaction, usage) are streamed
- runs are persisted as timeline history
- failures are represented explicitly
This improves trust and debuggability, especially for multi-agent workflows.
### Mid-turn steering
Aryx supports sending user messages while a turn is actively running. These messages are delivered with a `messageMode` flag (`immediate` or `enqueue`) that tells the sidecar to inject the content into the current Copilot session rather than starting a new turn. This enables real-time steering without waiting for turn completion. The main process allows the IPC call even when the session is in `running` status, and the renderer keeps the composer enabled throughout.
### Image attachments
User messages can carry image attachments as base64-encoded blobs. These flow from the renderer through IPC, the main process, and the sidecar protocol as `ChatMessageAttachmentDto` objects alongside the text content. The sidecar maps them into the Copilot SDK's `DataPart` model. Attachment metadata is persisted on the `ChatMessageRecord` so thumbnail previews render correctly when revisiting a session.
## Persistence and repair
Workspace persistence is intentionally simple: the app stores a durable workspace document and repairs or normalizes it when loading.
+17 -4
View File
@@ -17,8 +17,10 @@ It works especially well when you want AI help that stays grounded in an actual
- **Start fast** with a scratchpad conversation for quick questions and ad-hoc work.
- **Work against real projects** by attaching local folders and letting Aryx stay aware of repository context.
- **Go beyond one assistant** with orchestration patterns such as single-agent, sequential, concurrent, handoff, and group-chat flows.
- **See what is happening** with live activity for each agent while a run is in progress.
- **Stay organized** with persistent sessions you can rename, pin, archive, and return to later.
- **See what is happening** with live activity for each agent while a run is in progress, including sub-agent delegations, hook lifecycle, skill invocations, and context compaction.
- **Stay organized** with persistent sessions you can rename, pin, archive, delete, and return to later.
- **Steer while agents work** by sending follow-up messages mid-turn — the agent receives your input immediately.
- **Attach images** to any message for visual context the model can reason about.
- **Tune how you work** by choosing models and reusing saved patterns that fit different tasks.
## What you can do in the app
@@ -26,6 +28,7 @@ It works especially well when you want AI help that stays grounded in an actual
### Ask quick questions in a scratchpad
If you just want to think through an idea, draft something, or ask for help without connecting a project, start a scratchpad session and begin chatting.
Each scratchpad session keeps its own isolated working directory, so files created in one scratchpad do not leak into another.
### Connect a real project
@@ -49,13 +52,23 @@ This keeps machine-wide tooling reusable while still letting each session decide
Patterns now require tool-call approval by default. They can also store default auto-approval for known MCP and LSP tools, and each session can override those auto-approval defaults from the Activity panel before a run starts.
Project-backed sessions also honor GitHub Copilot CLI-style hook files from `.github/hooks/*.json`. Aryx discovers them automatically in the connected repository and runs the supported lifecycle hooks inside the sidecar, with `preToolUse` deny decisions applied before Aryx's own approval policy.
### Watch runs as they happen
You can follow agent activity while a session is running, which makes longer or more complex workflows easier to trust and understand.
You can follow agent activity while a session is running, which makes longer or more complex workflows easier to trust and understand. The activity panel shows sub-agent delegations, skill invocations, hook lifecycle events, and context compaction in real time. A context-usage bar below the composer shows how much of the model's context window the current session occupies.
### Steer agents mid-turn
While an agent is working, you can type a follow-up message that is delivered immediately into the current turn. This lets you redirect, refine, or add context without waiting for the turn to finish. The composer shows an amber "steering" indicator when a message will be injected into an active run.
### Attach images
You can attach images (JPEG, PNG, GIF, WebP) to any message using the clip button, drag-and-drop, or paste from clipboard. Image attachments are sent as base64-encoded blobs so the model can reason about visual content alongside your text.
### Keep important work around
Sessions are persistent, so you can return to ongoing work instead of starting from scratch every time. You can also rename, pin, archive, and duplicate sessions as your workspace grows.
Sessions are persistent, so you can return to ongoing work instead of starting from scratch every time. You can also rename, pin, archive, delete, and duplicate sessions as your workspace grows.
## Before you start
+9
View File
@@ -0,0 +1,9 @@
[Desktop Entry]
Name=Aryx
Comment=Copilot-powered agent workflow orchestrator
Exec=/opt/aryx/Aryx %U
Icon=aryx
Terminal=false
Type=Application
Categories=Development;
StartupWMClass=Aryx
+86
View File
@@ -0,0 +1,86 @@
; Inno Setup script for Aryx
; Dynamic values are read from environment variables set by the build script.
#define PRODUCT_NAME "Aryx"
#define PRODUCT_PUBLISHER "David Kaya"
#define PRODUCT_VERSION GetEnv("ARYX_BUILD_VERSION")
#define SOURCE_DIR GetEnv("ARYX_BUILD_SOURCE_DIR")
#define OUTPUT_DIR GetEnv("ARYX_BUILD_OUTPUT_DIR")
#define OUTPUT_FILENAME GetEnv("ARYX_BUILD_OUTPUT_FILENAME")
#define ICON_PATH GetEnv("ARYX_BUILD_ICON_PATH")
#if PRODUCT_VERSION == ""
#error "ARYX_BUILD_VERSION environment variable must be set."
#endif
#if SOURCE_DIR == ""
#error "ARYX_BUILD_SOURCE_DIR environment variable must be set."
#endif
#if OUTPUT_DIR == ""
#error "ARYX_BUILD_OUTPUT_DIR environment variable must be set."
#endif
#if OUTPUT_FILENAME == ""
#error "ARYX_BUILD_OUTPUT_FILENAME environment variable must be set."
#endif
#if ICON_PATH == ""
#define ICON_PATH SOURCE_DIR + "\" + PRODUCT_NAME + ".exe"
#endif
[Setup]
AppId={{B8A3E7F1-4D2C-4A9B-8E6F-1C3D5A7B9E0F}
AppName={#PRODUCT_NAME}
AppVersion={#PRODUCT_VERSION}
AppPublisher={#PRODUCT_PUBLISHER}
AppSupportURL=https://github.com/davidkaya/aryx
DefaultDirName={localappdata}\Programs\{#PRODUCT_NAME}
DefaultGroupName={#PRODUCT_NAME}
PrivilegesRequired=lowest
OutputDir={#OUTPUT_DIR}
OutputBaseFilename={#OUTPUT_FILENAME}
Compression=lzma2/ultra64
SolidCompression=yes
SetupIconFile={#ICON_PATH}
UninstallDisplayIcon={app}\{#PRODUCT_NAME}.exe
WizardStyle=modern
DisableProgramGroupPage=yes
CloseApplications=force
RestartApplications=no
[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"
[Files]
Source: "{#SOURCE_DIR}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
[Icons]
Name: "{group}\{#PRODUCT_NAME}"; Filename: "{app}\{#PRODUCT_NAME}.exe"
Name: "{autodesktop}\{#PRODUCT_NAME}"; Filename: "{app}\{#PRODUCT_NAME}.exe"; Tasks: desktopicon
[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
[Run]
Filename: "{app}\{#PRODUCT_NAME}.exe"; Description: "{cm:LaunchProgram,{#PRODUCT_NAME}}"; Flags: nowait postinstall skipifsilent
[UninstallDelete]
Type: filesandordirs; Name: "{app}"
[Code]
procedure CurStepChanged(CurStep: TSetupStep);
var
ResultCode: Integer;
begin
if CurStep = ssInstall then
begin
Exec('taskkill', '/F /IM {#PRODUCT_NAME}.exe', '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
end;
end;
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
var
ResultCode: Integer;
begin
if CurUninstallStep = usUninstall then
begin
Exec('taskkill', '/F /IM {#PRODUCT_NAME}.exe', '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
end;
end;
+169
View File
@@ -6,6 +6,7 @@
"name": "kopaya",
"dependencies": {
"keytar": "^7.9.0",
"node-pty": "^1.1.0",
},
"devDependencies": {
"@dagrejs/dagre": "^3.0.0",
@@ -17,11 +18,14 @@
"@lexical/markdown": "0.42.0",
"@lexical/react": "0.42.0",
"@lexical/rich-text": "0.42.0",
"@modelcontextprotocol/sdk": "^1.28.0",
"@tailwindcss/vite": "^4.2.2",
"@types/node": "^25.5.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "5.1.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"@xyflow/react": "^12.10.1",
"bun-types": "^1.3.11",
"electron": "^41.0.3",
@@ -38,6 +42,7 @@
"typescript": "^5.9.3",
"typescript-language-server": "^5.1.3",
"vite": "7.1.10",
"yaml": "^2.8.3",
},
},
},
@@ -152,6 +157,8 @@
"@floating-ui/utils": ["@floating-ui/utils@0.2.11", "", {}, "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg=="],
"@hono/node-server": ["@hono/node-server@1.19.11", "", { "peerDependencies": { "hono": "^4" } }, "sha512-dr8/3zEaB+p0D2n/IUrlPF1HZm586qgJNXK1a9fhg/PzdtkK7Ksd5l312tJX2yBuALqDYBlG20QEbayqPyxn+g=="],
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
@@ -214,6 +221,8 @@
"@malept/cross-spawn-promise": ["@malept/cross-spawn-promise@1.1.1", "", { "dependencies": { "cross-spawn": "^7.0.1" } }, "sha512-RTBGWL5FWQcg9orDOCcp4LvItNzUPcyEU9bwaeJX0rJ1IQxzucC48Y0/sQLp/g6t99IQgAlGIaesJS+gTn7tVQ=="],
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.28.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-gmloF+i+flI8ouQK7MWW4mOwuMh4RePBuPFAEPC6+pdqyWOUMDOixb6qZ69owLJpz6XmyllCouc4t8YWO+E2Nw=="],
"@preact/signals-core": ["@preact/signals-core@1.14.0", "", {}, "sha512-AowtCcCU/33lFlh1zRFf/u+12rfrhtNakj7UpaGEsmMwUKpKWMVvcktOGcwBBNiB4lWrZWc01LhiyyzVklJyaQ=="],
"@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-beta.43", "", {}, "sha512-5Uxg7fQUCmfhax7FJke2+8B6cqgeUJUD9o2uXIKXhD+mG0mL6NObmVoi9wXEU1tY89mZKgAYA6fTbftx3q2ZPQ=="],
@@ -362,10 +371,20 @@
"@xmldom/xmldom": ["@xmldom/xmldom@0.8.11", "", {}, "sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw=="],
"@xterm/addon-fit": ["@xterm/addon-fit@0.11.0", "", {}, "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g=="],
"@xterm/xterm": ["@xterm/xterm@6.0.0", "", {}, "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg=="],
"@xyflow/react": ["@xyflow/react@12.10.1", "", { "dependencies": { "@xyflow/system": "0.0.75", "classcat": "^5.0.3", "zustand": "^4.4.0" }, "peerDependencies": { "react": ">=17", "react-dom": ">=17" } }, "sha512-5eSWtIK/+rkldOuFbOOz44CRgQRjtS9v5nufk77DV+XBnfCGL9HAQ8PG00o2ZYKqkEU/Ak6wrKC95Tu+2zuK3Q=="],
"@xyflow/system": ["@xyflow/system@0.0.75", "", { "dependencies": { "@types/d3-drag": "^3.0.7", "@types/d3-interpolate": "^3.0.4", "@types/d3-selection": "^3.0.10", "@types/d3-transition": "^3.0.8", "@types/d3-zoom": "^3.0.8", "d3-drag": "^3.0.0", "d3-interpolate": "^3.0.1", "d3-selection": "^3.0.0", "d3-zoom": "^3.0.0" } }, "sha512-iXs+AGFLi8w/VlAoc/iSxk+CxfT6o64Uw/k0CKASOPqjqz6E0rb5jFZgJtXGZCpfQI6OQpu5EnumP5fGxQheaQ=="],
"accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
"ajv": ["ajv@8.18.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="],
"ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
"bail": ["bail@2.0.2", "", {}, "sha512-0xO6mYd7JB2YesxDKplafRpsiOzPt9V02ddPCLbY1xYGPOX24NTyN50qnUxgCPcSoYMhKpAuBTjQoRZCAkUDRw=="],
"balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
@@ -376,6 +395,8 @@
"bl": ["bl@4.1.0", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
"body-parser": ["body-parser@2.2.2", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],
"boolean": ["boolean@3.2.0", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
"brace-expansion": ["brace-expansion@5.0.5", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ=="],
@@ -388,12 +409,18 @@
"bun-types": ["bun-types@1.3.11", "", { "dependencies": { "@types/node": "*" } }, "sha512-1KGPpoxQWl9f6wcZh57LvrPIInQMn2TQ7jsgxqpRzg+l0QPOFvJVH7HmvHo/AiPgwXy+/Thf6Ov3EdVn1vOabg=="],
"bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
"cac": ["cac@6.7.14", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="],
"cacheable-lookup": ["cacheable-lookup@5.0.4", "", {}, "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA=="],
"cacheable-request": ["cacheable-request@7.0.4", "", { "dependencies": { "clone-response": "^1.0.2", "get-stream": "^5.1.0", "http-cache-semantics": "^4.0.0", "keyv": "^4.0.0", "lowercase-keys": "^2.0.0", "normalize-url": "^6.0.1", "responselike": "^2.0.0" } }, "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg=="],
"call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="],
"call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
"caniuse-lite": ["caniuse-lite@1.0.30001780", "", {}, "sha512-llngX0E7nQci5BPJDqoZSbuZ5Bcs9F5db7EtgfwBerX9XGtkkiO4NwfDDIRzHTTwcYC8vC7bmeUEPGrKlR/TkQ=="],
"ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="],
@@ -416,8 +443,18 @@
"commander": ["commander@13.1.0", "", {}, "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw=="],
"content-disposition": ["content-disposition@1.0.1", "", {}, "sha512-oIXISMynqSqm241k6kcQ5UwttDILMK4BiurCfGEREw6+X9jkkpEe5T9FZaApyLGGOnFuyMWZpdolTXMtvEJ08Q=="],
"content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
"convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],
"cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="],
"cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],
"cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"cross-spawn-windows-exe": ["cross-spawn-windows-exe@1.2.0", "", { "dependencies": { "@malept/cross-spawn-promise": "^1.1.0", "is-wsl": "^2.2.0", "which": "^2.0.2" } }, "sha512-mkLtJJcYbDCxEG7Js6eUnUNndWjyUZwJ3H7bErmmtOYU/Zb99DyUkpamuIZE0b3bhmJyZ7D90uS6f+CGxRRjOw=="],
@@ -456,6 +493,8 @@
"define-properties": ["define-properties@1.2.1", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
"depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
"dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="],
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
@@ -464,12 +503,18 @@
"devlop": ["devlop@1.1.0", "", { "dependencies": { "dequal": "^2.0.0" } }, "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA=="],
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
"electron": ["electron@41.0.3", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-IDjx8liW1q+r7+MOip5W1Eo1eMwJzVObmYrd9yz2dPCkS7XlgLq3qPVMR80TpiROFp73iY30kTzMdpA6fEVs3A=="],
"electron-to-chromium": ["electron-to-chromium@1.5.321", "", {}, "sha512-L2C7Q279W2D/J4PLZLk7sebOILDSWos7bMsMNN06rK482umHUrh/3lM8G7IlHFOYip2oAg5nha1rCMxr/rs6ZQ=="],
"electron-vite": ["electron-vite@5.0.0", "", { "dependencies": { "@babel/core": "^7.28.4", "@babel/plugin-transform-arrow-functions": "^7.27.1", "cac": "^6.7.14", "esbuild": "^0.25.11", "magic-string": "^0.30.19", "picocolors": "^1.1.1" }, "peerDependencies": { "@swc/core": "^1.0.0", "vite": "^5.0.0 || ^6.0.0 || ^7.0.0" }, "optionalPeers": ["@swc/core"], "bin": { "electron-vite": "bin/electron-vite.js" } }, "sha512-OHp/vjdlubNlhNkPkL/+3JD34ii5ov7M0GpuXEVdQeqdQ3ulvVR7Dg/rNBLfS5XPIFwgoBLDf9sjjrL+CuDyRQ=="],
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
"end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
"enhanced-resolve": ["enhanced-resolve@5.20.1", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.0" } }, "sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA=="],
@@ -482,34 +527,64 @@
"es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
"es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="],
"es6-error": ["es6-error@4.1.1", "", {}, "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg=="],
"esbuild": ["esbuild@0.25.12", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="],
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
"escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="],
"escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],
"estree-util-is-identifier-name": ["estree-util-is-identifier-name@3.0.0", "", {}, "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg=="],
"etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="],
"eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="],
"eventsource-parser": ["eventsource-parser@3.0.6", "", {}, "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg=="],
"expand-template": ["expand-template@2.0.3", "", {}, "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg=="],
"express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],
"express-rate-limit": ["express-rate-limit@8.3.1", "", { "dependencies": { "ip-address": "10.1.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-D1dKN+cmyPWuvB+G2SREQDzPY1agpBIcTa9sJxOPMCNeH3gwzhqJRDWCXW3gg0y//+LQ/8j52JbMROWyrKdMdw=="],
"extend": ["extend@3.0.2", "", {}, "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g=="],
"extract-zip": ["extract-zip@2.0.1", "", { "dependencies": { "debug": "^4.1.1", "get-stream": "^5.1.0", "yauzl": "^2.10.0" }, "optionalDependencies": { "@types/yauzl": "^2.9.1" }, "bin": { "extract-zip": "cli.js" } }, "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg=="],
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-uri": ["fast-uri@3.1.0", "", {}, "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA=="],
"fd-slicer": ["fd-slicer@1.1.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g=="],
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="],
"forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="],
"fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],
"fs-constants": ["fs-constants@1.0.0", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
"fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
"gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
"get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
"get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
"get-stream": ["get-stream@5.2.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="],
"github-from-package": ["github-from-package@0.0.0", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="],
@@ -530,18 +605,28 @@
"has-property-descriptors": ["has-property-descriptors@1.0.2", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="],
"has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
"hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="],
"hast-util-to-jsx-runtime": ["hast-util-to-jsx-runtime@2.3.6", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
"hast-util-whitespace": ["hast-util-whitespace@3.0.0", "", { "dependencies": { "@types/hast": "^3.0.0" } }, "sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw=="],
"highlight.js": ["highlight.js@11.11.1", "", {}, "sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w=="],
"hono": ["hono@4.12.9", "", {}, "sha512-wy3T8Zm2bsEvxKZM5w21VdHDDcwVS1yUFFY6i8UobSsKfFceT7TOwhbhfKsDyx7tYQlmRM5FLpIuYvNFyjctiA=="],
"html-url-attributes": ["html-url-attributes@3.0.1", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="],
"http-cache-semantics": ["http-cache-semantics@4.2.0", "", {}, "sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ=="],
"http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
"http2-wrapper": ["http2-wrapper@1.0.3", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.0.0" } }, "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg=="],
"iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
"inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
@@ -550,6 +635,10 @@
"inline-style-parser": ["inline-style-parser@0.2.7", "", {}, "sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA=="],
"ip-address": ["ip-address@10.1.0", "", {}, "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q=="],
"ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="],
"is-alphabetical": ["is-alphabetical@2.0.1", "", {}, "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ=="],
"is-alphanumerical": ["is-alphanumerical@2.0.1", "", { "dependencies": { "is-alphabetical": "^2.0.0", "is-decimal": "^2.0.0" } }, "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw=="],
@@ -562,6 +651,8 @@
"is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="],
"is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
"is-wsl": ["is-wsl@2.2.0", "", { "dependencies": { "is-docker": "^2.0.0" } }, "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
@@ -570,12 +661,18 @@
"jiti": ["jiti@2.6.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="],
"jose": ["jose@6.2.2", "", {}, "sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ=="],
"js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
"jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
"json-buffer": ["json-buffer@3.0.1", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="],
"json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
"json-stringify-safe": ["json-stringify-safe@5.0.1", "", {}, "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA=="],
"json5": ["json5@2.2.3", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
@@ -628,6 +725,8 @@
"matcher": ["matcher@3.0.0", "", { "dependencies": { "escape-string-regexp": "^4.0.0" } }, "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng=="],
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
"mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg=="],
"mdast-util-from-markdown": ["mdast-util-from-markdown@2.0.3", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q=="],
@@ -658,6 +757,10 @@
"mdast-util-to-string": ["mdast-util-to-string@4.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0" } }, "sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg=="],
"media-typer": ["media-typer@1.1.0", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],
"merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="],
"micromark": ["micromark@4.0.2", "", { "dependencies": { "@types/debug": "^4.0.0", "debug": "^4.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-encode": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-sanitize-uri": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA=="],
"micromark-core-commonmark": ["micromark-core-commonmark@2.0.3", "", { "dependencies": { "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-destination": "^2.0.0", "micromark-factory-label": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-title": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-chunked": "^2.0.0", "micromark-util-classify-character": "^2.0.0", "micromark-util-html-tag-name": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-resolve-all": "^2.0.0", "micromark-util-subtokenize": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg=="],
@@ -714,6 +817,10 @@
"micromark-util-types": ["micromark-util-types@2.0.2", "", {}, "sha512-Yw0ECSpJoViF1qTU4DC6NwtC4aWGt1EkzaQB8KPPyCRR8z9TWeV0HbEFGTO+ZY1wB22zmxnJqhPyTpOVCpeHTA=="],
"mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
"mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"mimic-response": ["mimic-response@3.1.0", "", {}, "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ=="],
"minimatch": ["minimatch@10.2.4", "", { "dependencies": { "brace-expansion": "^5.0.2" } }, "sha512-oRjTw/97aTBN0RHbYCdtF1MQfvusSIBQM0IZEgzl6426+8jSC0nF1a/GmnVLpfB9yyr6g6FTqWqiZVbxrtaCIg=="],
@@ -730,32 +837,48 @@
"napi-build-utils": ["napi-build-utils@2.0.0", "", {}, "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA=="],
"negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
"node-abi": ["node-abi@3.89.0", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-6u9UwL0HlAl21+agMN3YAMXcKByMqwGx+pq+P76vii5f7hTPtKDp08/H9py6DY+cfDw7kQNTGEj/rly3IgbNQA=="],
"node-addon-api": ["node-addon-api@4.3.0", "", {}, "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ=="],
"node-pty": ["node-pty@1.1.0", "", { "dependencies": { "node-addon-api": "^7.1.0" } }, "sha512-20JqtutY6JPXTUnL0ij1uad7Qe1baT46lyolh2sSENDd4sTzKZ4nmAFkeAARDKwmlLjPx6XKRlwRUxwjOy+lUg=="],
"node-releases": ["node-releases@2.0.36", "", {}, "sha512-TdC8FSgHz8Mwtw9g5L4gR/Sh9XhSP/0DEkQxfEFXOpiul5IiHgHan2VhYYb6agDSfp4KuvltmGApc8HMgUrIkA=="],
"normalize-url": ["normalize-url@6.1.0", "", {}, "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A=="],
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
"object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
"object-keys": ["object-keys@1.1.1", "", {}, "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA=="],
"on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="],
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
"p-cancelable": ["p-cancelable@2.1.1", "", {}, "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg=="],
"parse-entities": ["parse-entities@4.0.2", "", { "dependencies": { "@types/unist": "^2.0.0", "character-entities-legacy": "^3.0.0", "character-reference-invalid": "^2.0.0", "decode-named-character-reference": "^1.0.0", "is-alphanumerical": "^2.0.0", "is-decimal": "^2.0.0", "is-hexadecimal": "^2.0.0" } }, "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw=="],
"parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"path-scurry": ["path-scurry@2.0.2", "", { "dependencies": { "lru-cache": "^11.0.0", "minipass": "^7.1.2" } }, "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg=="],
"path-to-regexp": ["path-to-regexp@8.4.0", "", {}, "sha512-PuseHIvAnz3bjrM2rGJtSgo1zjgxapTLZ7x2pjhzWwlp4SJQgK3f3iZIQwkpEnBaKz6seKBADpM4B4ySkuYypg=="],
"pend": ["pend@1.2.0", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="],
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
"picomatch": ["picomatch@4.0.3", "", {}, "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q=="],
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"plist": ["plist@3.1.0", "", { "dependencies": { "@xmldom/xmldom": "^0.8.8", "base64-js": "^1.5.1", "xmlbuilder": "^15.1.1" } }, "sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ=="],
"postcss": ["postcss@8.5.8", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg=="],
@@ -768,10 +891,18 @@
"property-information": ["property-information@7.1.0", "", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="],
"proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
"pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="],
"qs": ["qs@6.15.0", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ=="],
"quick-lru": ["quick-lru@5.1.1", "", {}, "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA=="],
"range-parser": ["range-parser@1.2.1", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="],
"raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
"rc": ["rc@1.2.8", "", { "dependencies": { "deep-extend": "^0.6.0", "ini": "~1.3.0", "minimist": "^1.2.0", "strip-json-comments": "~2.0.1" }, "bin": { "rc": "./cli.js" } }, "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw=="],
"rcedit": ["rcedit@5.0.2", "", { "dependencies": { "cross-spawn-windows-exe": "^1.1.0" } }, "sha512-dgysxaeXZ4snLpPjn8aVtHvZDCx+aRcvZbaWBgl1poU6OPustMvOkj9a9ZqASQ6i5Y5szJ13LSvglEOwrmgUxA=="],
@@ -796,6 +927,8 @@
"remark-stringify": ["remark-stringify@11.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-to-markdown": "^2.0.0", "unified": "^11.0.0" } }, "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw=="],
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
"resolve-alpn": ["resolve-alpn@1.2.1", "", {}, "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g=="],
"responselike": ["responselike@2.0.1", "", { "dependencies": { "lowercase-keys": "^2.0.0" } }, "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw=="],
@@ -804,20 +937,38 @@
"rollup": ["rollup@4.60.0", "", { "dependencies": { "@types/estree": "1.0.8" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.60.0", "@rollup/rollup-android-arm64": "4.60.0", "@rollup/rollup-darwin-arm64": "4.60.0", "@rollup/rollup-darwin-x64": "4.60.0", "@rollup/rollup-freebsd-arm64": "4.60.0", "@rollup/rollup-freebsd-x64": "4.60.0", "@rollup/rollup-linux-arm-gnueabihf": "4.60.0", "@rollup/rollup-linux-arm-musleabihf": "4.60.0", "@rollup/rollup-linux-arm64-gnu": "4.60.0", "@rollup/rollup-linux-arm64-musl": "4.60.0", "@rollup/rollup-linux-loong64-gnu": "4.60.0", "@rollup/rollup-linux-loong64-musl": "4.60.0", "@rollup/rollup-linux-ppc64-gnu": "4.60.0", "@rollup/rollup-linux-ppc64-musl": "4.60.0", "@rollup/rollup-linux-riscv64-gnu": "4.60.0", "@rollup/rollup-linux-riscv64-musl": "4.60.0", "@rollup/rollup-linux-s390x-gnu": "4.60.0", "@rollup/rollup-linux-x64-gnu": "4.60.0", "@rollup/rollup-linux-x64-musl": "4.60.0", "@rollup/rollup-openbsd-x64": "4.60.0", "@rollup/rollup-openharmony-arm64": "4.60.0", "@rollup/rollup-win32-arm64-msvc": "4.60.0", "@rollup/rollup-win32-ia32-msvc": "4.60.0", "@rollup/rollup-win32-x64-gnu": "4.60.0", "@rollup/rollup-win32-x64-msvc": "4.60.0", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-yqjxruMGBQJ2gG4HtjZtAfXArHomazDHoFwFFmZZl0r7Pdo7qCIXKqKHZc8yeoMgzJJ+pO6pEEHa+V7uzWlrAQ=="],
"router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
"safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
"semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
"semver-compare": ["semver-compare@1.0.0", "", {}, "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow=="],
"send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],
"serialize-error": ["serialize-error@7.0.1", "", { "dependencies": { "type-fest": "^0.13.1" } }, "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw=="],
"serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],
"setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
"side-channel": ["side-channel@1.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],
"side-channel-list": ["side-channel-list@1.0.0", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3" } }, "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA=="],
"side-channel-map": ["side-channel-map@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="],
"side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="],
"simple-concat": ["simple-concat@1.0.1", "", {}, "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="],
"simple-get": ["simple-get@4.0.1", "", { "dependencies": { "decompress-response": "^6.0.0", "once": "^1.3.1", "simple-concat": "^1.0.0" } }, "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA=="],
@@ -828,6 +979,8 @@
"sprintf-js": ["sprintf-js@1.1.3", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="],
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
"stringify-entities": ["stringify-entities@4.0.4", "", { "dependencies": { "character-entities-html4": "^2.0.0", "character-entities-legacy": "^3.0.0" } }, "sha512-IwfBptatlO+QCJUo19AqvrPNqlVMpW9YEL2LIVY+Rpv2qsjCGxaDLNRgeGsQWJhfItebuJhsGSLjaBbNSQ+ieg=="],
@@ -852,6 +1005,8 @@
"tinyglobby": ["tinyglobby@0.2.15", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.3" } }, "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ=="],
"toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
"trim-lines": ["trim-lines@3.0.1", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="],
"trough": ["trough@2.2.0", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="],
@@ -860,6 +1015,8 @@
"type-fest": ["type-fest@0.13.1", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
"type-is": ["type-is@2.0.1", "", { "dependencies": { "content-type": "^1.0.5", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"typescript-language-server": ["typescript-language-server@5.1.3", "", { "bin": { "typescript-language-server": "lib/cli.mjs" } }, "sha512-r+pAcYtWdN8tKlYZPwiiHNA2QPjXnI02NrW5Sf2cVM3TRtuQ3V9EKKwOxqwaQ0krsaEXk/CbN90I5erBuf84Vg=="],
@@ -880,12 +1037,16 @@
"universalify": ["universalify@0.1.2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
"unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
"update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
"use-sync-external-store": ["use-sync-external-store@1.6.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
"util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
"vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
"vfile": ["vfile@6.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "vfile-message": "^4.0.0" } }, "sha512-KzIbH/9tXat2u30jf+smMwFCsno4wHVdNmzFyL+T/L3UGqqk6JKfVqOFOZEpZSHADH1k40ab6NUIXZq422ov3Q=="],
"vfile-message": ["vfile-message@4.0.3", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-QTHzsGd1EhbZs4AsQ20JX1rC3cOlt/IWJruk893DfLRr57lcnOeMaWG4K0JrRta4mIJZKth2Au3mM3u03/JWKw=="],
@@ -904,10 +1065,16 @@
"yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
"yaml": ["yaml@2.8.3", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-AvbaCLOO2Otw/lW5bmh9d/WEdcDFdQp2Z2ZUH3pX9U2ihyUY0nvLv7J6TrWowklRGPYbB/IuIMfYgxaCPg5Bpg=="],
"yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
"yjs": ["yjs@13.6.30", "", { "dependencies": { "lib0": "^0.2.99" } }, "sha512-vv/9h42eCMC81ZHDFswuu/MKzkl/vyq1BhaNGfHyOonwlG4CJbQF4oiBBJPvfdeCt/PlVDWh7Nov9D34YY09uQ=="],
"zod": ["zod@4.3.6", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="],
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
"zustand": ["zustand@4.5.7", "", { "dependencies": { "use-sync-external-store": "^1.2.2" }, "peerDependencies": { "@types/react": ">=16.8", "immer": ">=9.0.6", "react": ">=16.8" }, "optionalPeers": ["@types/react", "immer", "react"] }, "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw=="],
"zwitch": ["zwitch@2.0.4", "", {}, "sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A=="],
@@ -936,6 +1103,8 @@
"node-abi/semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
"node-pty/node-addon-api": ["node-addon-api@7.1.1", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
"parse-entities/@types/unist": ["@types/unist@2.0.11", "", {}, "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="],
"electron/@types/node/undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
+1 -1
View File
@@ -9,7 +9,7 @@ export default defineConfig({
build: {
outDir: 'dist-electron/main',
},
plugins: [externalizeDepsPlugin()],
plugins: [externalizeDepsPlugin({ exclude: ['@modelcontextprotocol/sdk'] })],
resolve: {
alias: {
'@main': resolve(__dirname, 'src/main'),
+8 -2
View File
@@ -9,6 +9,7 @@
"build:electron": "electron-vite build",
"build": "bun run build:electron && bun run sidecar:build",
"package": "bun run build:electron && bun run sidecar:publish && bun run scripts/package-electron.ts",
"installer": "bun run package && bun run scripts/create-installer.ts",
"preview": "electron-vite preview",
"lsp:typescript": "typescript-language-server --stdio",
"typecheck": "tsc --noEmit -p tsconfig.json",
@@ -40,11 +41,14 @@
"@lexical/markdown": "0.42.0",
"@lexical/react": "0.42.0",
"@lexical/rich-text": "0.42.0",
"@modelcontextprotocol/sdk": "^1.28.0",
"@tailwindcss/vite": "^4.2.2",
"@types/node": "^25.5.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "5.1.0",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
"@xyflow/react": "^12.10.1",
"bun-types": "^1.3.11",
"electron": "^41.0.3",
@@ -60,9 +64,11 @@
"tailwindcss": "^4.2.2",
"typescript": "^5.9.3",
"typescript-language-server": "^5.1.3",
"vite": "7.1.10"
"vite": "7.1.10",
"yaml": "^2.8.3"
},
"dependencies": {
"keytar": "^7.9.0"
"keytar": "^7.9.0",
"node-pty": "^1.1.0"
}
}
+227
View File
@@ -0,0 +1,227 @@
import { spawn } from 'node:child_process';
import { constants } from 'node:fs';
import {
access,
cp,
mkdir,
readFile,
symlink,
writeFile,
} from 'node:fs/promises';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { productName, resolveReleaseTarget } from './releaseTarget';
function runCommand(command: string, args: string[], cwd: string): Promise<void> {
return new Promise((resolvePromise, rejectPromise) => {
const child = spawn(command, args, {
cwd,
stdio: 'inherit',
});
child.on('error', rejectPromise);
child.on('exit', (code, signal) => {
if (code === 0) {
resolvePromise();
return;
}
if (signal) {
rejectPromise(new Error(`${command} exited because of signal ${signal}.`));
return;
}
rejectPromise(new Error(`${command} exited with code ${code ?? 'unknown'}.`));
});
});
}
async function pathExists(path: string): Promise<boolean> {
try {
await access(path, constants.F_OK);
return true;
} catch {
return false;
}
}
const scriptDirectory = dirname(fileURLToPath(import.meta.url));
const repositoryRoot = resolve(scriptDirectory, '..');
const releaseTarget = resolveReleaseTarget(process.platform, process.arch);
const releaseRootDirectory = join(repositoryRoot, 'release');
const packagedAppDirectory = join(releaseRootDirectory, releaseTarget.outputDirectoryName);
const installerOutputPath = join(releaseRootDirectory, releaseTarget.installerAssetName);
const installerAssetsDirectory = join(repositoryRoot, 'assets', 'installer');
async function readVersion(): Promise<string> {
const packageJson = JSON.parse(
await readFile(join(repositoryRoot, 'package.json'), 'utf8'),
) as { version: string };
return packageJson.version;
}
// --- Windows: Inno Setup installer ---
async function resolveInnoSetupCompilerPath(): Promise<string> {
const candidates = [
'C:\\Program Files (x86)\\Inno Setup 6\\ISCC.exe',
'C:\\Program Files\\Inno Setup 6\\ISCC.exe',
'iscc',
];
for (const candidate of candidates) {
if (candidate.includes('\\') && (await pathExists(candidate))) {
return candidate;
}
}
return 'iscc';
}
async function createWindowsInstaller(version: string): Promise<void> {
const issScript = join(installerAssetsDirectory, 'windows.iss');
const isccPath = await resolveInnoSetupCompilerPath();
const outputFilename = releaseTarget.installerAssetName.replace(/\.exe$/, '');
const iconPath = join(repositoryRoot, 'assets', 'icons', 'windows', 'icon.ico');
process.env.ARYX_BUILD_VERSION = version;
process.env.ARYX_BUILD_SOURCE_DIR = packagedAppDirectory;
process.env.ARYX_BUILD_OUTPUT_DIR = releaseRootDirectory;
process.env.ARYX_BUILD_OUTPUT_FILENAME = outputFilename;
process.env.ARYX_BUILD_ICON_PATH = iconPath;
await runCommand(isccPath, [issScript], repositoryRoot);
}
// --- macOS: DMG disk image ---
async function createMacInstaller(): Promise<void> {
const appBundleName = releaseTarget.appBundleName;
if (!appBundleName) {
throw new Error('macOS installer requires an app bundle name.');
}
const appBundlePath = join(packagedAppDirectory, appBundleName);
// Use macOS's native disk image tooling so packaging does not depend on
// create-dmg's native node-gyp install path on CI runners.
await runCommand(
'hdiutil',
[
'create',
'-volname',
productName,
'-srcfolder',
appBundlePath,
'-ov',
'-format',
'UDZO',
installerOutputPath,
],
repositoryRoot,
);
}
// --- Linux: .deb package ---
const linuxIconSizes = ['16x16', '32x32', '48x48', '64x64', '128x128', '256x256', '512x512'];
async function createLinuxInstaller(version: string): Promise<void> {
const stagingDirectory = join(releaseRootDirectory, 'deb-staging');
const debianDirectory = join(stagingDirectory, 'DEBIAN');
const optDirectory = join(stagingDirectory, 'opt', 'aryx');
const binDirectory = join(stagingDirectory, 'usr', 'bin');
const applicationsDirectory = join(stagingDirectory, 'usr', 'share', 'applications');
await mkdir(debianDirectory, { recursive: true });
await mkdir(binDirectory, { recursive: true });
await mkdir(applicationsDirectory, { recursive: true });
// Copy packaged app into /opt/aryx/
await cp(packagedAppDirectory, optDirectory, { recursive: true });
// Create symlink /usr/bin/aryx -> /opt/aryx/Aryx
await symlink('/opt/aryx/Aryx', join(binDirectory, 'aryx'));
// Copy desktop entry
await cp(
join(installerAssetsDirectory, 'linux', 'aryx.desktop'),
join(applicationsDirectory, 'aryx.desktop'),
);
// Install icons into hicolor theme
const sourceIconsDirectory = join(repositoryRoot, 'assets', 'icons', 'linux', 'icons');
for (const size of linuxIconSizes) {
const sourceIcon = join(sourceIconsDirectory, `${size}.png`);
if (!(await pathExists(sourceIcon))) {
continue;
}
const targetIconDirectory = join(
stagingDirectory, 'usr', 'share', 'icons', 'hicolor', size, 'apps',
);
await mkdir(targetIconDirectory, { recursive: true });
await cp(sourceIcon, join(targetIconDirectory, 'aryx.png'));
}
// Determine installed size (in KB)
const { stdout } = await new Promise<{ stdout: string }>((resolvePromise, rejectPromise) => {
const child = spawn('du', ['-sk', optDirectory], { stdio: ['pipe', 'pipe', 'pipe'] });
let out = '';
child.stdout.on('data', (data: Buffer) => { out += data.toString(); });
child.on('error', rejectPromise);
child.on('exit', () => resolvePromise({ stdout: out }));
});
const installedSizeKb = parseInt(stdout.split('\t')[0] ?? '0', 10);
const debArch = releaseTarget.arch === 'x64' ? 'amd64' : 'arm64';
// Write DEBIAN/control
const controlContent = [
`Package: aryx`,
`Version: ${version}`,
`Section: devel`,
`Priority: optional`,
`Architecture: ${debArch}`,
`Installed-Size: ${installedSizeKb}`,
`Depends: libsecret-1-0`,
`Maintainer: David Kaya`,
`Description: ${productName} — Copilot-powered agent workflow orchestrator`,
` Electron desktop app for orchestrating Copilot-driven agent workflows`,
` across multiple projects.`,
'',
].join('\n');
await writeFile(join(debianDirectory, 'control'), controlContent);
// Build the .deb
await runCommand(
'dpkg-deb',
['--build', '--root-owner-group', stagingDirectory, installerOutputPath],
repositoryRoot,
);
}
// --- Entry point ---
if (!(await pathExists(packagedAppDirectory))) {
throw new Error(
`Packaged app not found at ${packagedAppDirectory}. Run "bun run package" first.`,
);
}
const version = await readVersion();
switch (releaseTarget.platform) {
case 'win32':
await createWindowsInstaller(version);
break;
case 'darwin':
await createMacInstaller();
break;
case 'linux':
await createLinuxInstaller(version);
break;
}
console.log(`Created installer: ${installerOutputPath}`);
+4
View File
@@ -11,6 +11,7 @@ export interface ReleaseTarget {
readonly dotnetRuntime: `${string}-${SupportedArch}`;
readonly outputDirectoryName: string;
readonly archiveBaseName: string;
readonly installerAssetName: string;
readonly sidecarExecutableName: string;
readonly packagedExecutableName?: string;
readonly appBundleName?: string;
@@ -43,6 +44,7 @@ export function resolveReleaseTarget(
dotnetRuntime: `win-${supportedArch}`,
outputDirectoryName: archiveBaseName,
archiveBaseName,
installerAssetName: `${archiveBaseName}-setup.exe`,
sidecarExecutableName: 'Aryx.AgentHost.exe',
packagedExecutableName: `${productName}.exe`,
};
@@ -58,6 +60,7 @@ export function resolveReleaseTarget(
dotnetRuntime: `osx-${supportedArch}`,
outputDirectoryName: archiveBaseName,
archiveBaseName,
installerAssetName: `${archiveBaseName}.dmg`,
sidecarExecutableName: 'Aryx.AgentHost',
appBundleName: `${productName}.app`,
};
@@ -73,6 +76,7 @@ export function resolveReleaseTarget(
dotnetRuntime: `linux-${supportedArch}`,
outputDirectoryName: archiveBaseName,
archiveBaseName,
installerAssetName: `aryx-linux-${supportedArch}.deb`,
sidecarExecutableName: 'Aryx.AgentHost',
packagedExecutableName: productName,
};
@@ -0,0 +1,62 @@
using System.Text.Json.Serialization;
namespace Aryx.AgentHost.Contracts;
internal static class HookTypeNames
{
public const string SessionStart = "sessionStart";
public const string SessionEnd = "sessionEnd";
public const string UserPromptSubmitted = "userPromptSubmitted";
public const string PreToolUse = "preToolUse";
public const string PostToolUse = "postToolUse";
public const string ErrorOccurred = "errorOccurred";
}
internal sealed class HookConfigFile
{
public int Version { get; init; }
public HookConfigHooks Hooks { get; init; } = new();
}
internal sealed class HookConfigHooks
{
public IReadOnlyList<HookCommandDefinition>? SessionStart { get; init; }
public IReadOnlyList<HookCommandDefinition>? SessionEnd { get; init; }
public IReadOnlyList<HookCommandDefinition>? UserPromptSubmitted { get; init; }
public IReadOnlyList<HookCommandDefinition>? PreToolUse { get; init; }
public IReadOnlyList<HookCommandDefinition>? PostToolUse { get; init; }
public IReadOnlyList<HookCommandDefinition>? ErrorOccurred { get; init; }
}
internal sealed class HookCommandDefinition
{
public string Type { get; init; } = string.Empty;
public string? Bash { get; init; }
[JsonPropertyName("powershell")]
public string? PowerShell { get; init; }
public string? Cwd { get; init; }
public IReadOnlyDictionary<string, string>? Env { get; init; }
public int? TimeoutSec { get; init; }
}
internal sealed class ResolvedHookSet
{
public static ResolvedHookSet Empty { get; } = new();
public IReadOnlyList<HookCommandDefinition> SessionStart { get; init; } = [];
public IReadOnlyList<HookCommandDefinition> SessionEnd { get; init; } = [];
public IReadOnlyList<HookCommandDefinition> UserPromptSubmitted { get; init; } = [];
public IReadOnlyList<HookCommandDefinition> PreToolUse { get; init; } = [];
public IReadOnlyList<HookCommandDefinition> PostToolUse { get; init; } = [];
public IReadOnlyList<HookCommandDefinition> ErrorOccurred { get; init; } = [];
public bool IsEmpty =>
SessionStart.Count == 0
&& SessionEnd.Count == 0
&& UserPromptSubmitted.Count == 0
&& PreToolUse.Count == 0
&& PostToolUse.Count == 0
&& ErrorOccurred.Count == 0;
}
@@ -10,6 +10,16 @@ public sealed class PatternAgentDefinitionDto
public string Instructions { get; init; } = string.Empty;
public string Model { get; init; } = string.Empty;
public string? ReasoningEffort { get; init; }
public PatternAgentCopilotConfigDto? Copilot { get; init; }
}
public sealed class PatternAgentCopilotConfigDto
{
public IReadOnlyList<RunTurnCustomAgentConfigDto> CustomAgents { get; init; } = [];
public string? Agent { get; init; }
public IReadOnlyList<string> SkillDirectories { get; init; } = [];
public IReadOnlyList<string> DisabledSkills { get; init; } = [];
public RunTurnInfiniteSessionsConfigDto? InfiniteSessions { get; init; }
}
public sealed class PatternGraphPositionDto
@@ -75,6 +85,16 @@ public sealed class ChatMessageDto
public string AuthorName { get; init; } = string.Empty;
public string Content { get; init; } = string.Empty;
public string CreatedAt { get; init; } = string.Empty;
public IReadOnlyList<ChatMessageAttachmentDto> Attachments { get; init; } = [];
}
public sealed class ChatMessageAttachmentDto
{
public string Type { get; init; } = string.Empty;
public string? Path { get; init; }
public string? Data { get; init; }
public string? MimeType { get; init; }
public string? DisplayName { get; init; }
}
public sealed class PatternValidationIssueDto
@@ -161,6 +181,9 @@ public sealed class RunTurnCommandDto : SidecarCommandEnvelope
public string SessionId { get; init; } = string.Empty;
public string ProjectPath { get; init; } = string.Empty;
public string WorkspaceKind { get; init; } = "project";
public string Mode { get; init; } = "interactive";
public string MessageMode { get; init; } = "enqueue";
public string? ProjectInstructions { get; init; }
public PatternDefinitionDto Pattern { get; init; } = new();
public IReadOnlyList<ChatMessageDto> Messages { get; init; } = [];
public RunTurnToolingConfigDto? Tooling { get; init; }
@@ -175,8 +198,34 @@ public sealed class ResolveApprovalCommandDto : SidecarCommandEnvelope
{
public string ApprovalId { get; init; } = string.Empty;
public string Decision { get; init; } = string.Empty;
public bool AlwaysApprove { get; init; }
}
public sealed class ResolveUserInputCommandDto : SidecarCommandEnvelope
{
public string UserInputId { get; init; } = string.Empty;
public string Answer { get; init; } = string.Empty;
public bool WasFreeform { get; init; }
}
public sealed class ListSessionsCommandDto : SidecarCommandEnvelope
{
public CopilotSessionListFilterDto? Filter { get; init; }
}
public sealed class DeleteSessionCommandDto : SidecarCommandEnvelope
{
public string? SessionId { get; init; }
public string? CopilotSessionId { get; init; }
}
public sealed class DisconnectSessionCommandDto : SidecarCommandEnvelope
{
public string SessionId { get; init; } = string.Empty;
}
public sealed class GetQuotaCommandDto : SidecarCommandEnvelope;
public sealed class RunTurnToolingConfigDto
{
public IReadOnlyList<RunTurnMcpServerConfigDto> McpServers { get; init; } = [];
@@ -208,6 +257,48 @@ public sealed class RunTurnLspProfileConfigDto
public IReadOnlyList<string> FileExtensions { get; init; } = [];
}
public sealed class RunTurnCustomAgentConfigDto
{
public string Name { get; init; } = string.Empty;
public string? DisplayName { get; init; }
public string? Description { get; init; }
public IReadOnlyList<string>? Tools { get; init; }
public string Prompt { get; init; } = string.Empty;
public IReadOnlyList<RunTurnMcpServerConfigDto> McpServers { get; init; } = [];
public bool? Infer { get; init; }
}
public sealed class RunTurnInfiniteSessionsConfigDto
{
public bool? Enabled { get; init; }
public double? BackgroundCompactionThreshold { get; init; }
public double? BufferExhaustionThreshold { get; init; }
}
public sealed class CopilotSessionListFilterDto
{
public string? Cwd { get; init; }
public string? GitRoot { get; init; }
public string? Repository { get; init; }
public string? Branch { get; init; }
}
public sealed class CopilotSessionInfoDto
{
public string CopilotSessionId { get; init; } = string.Empty;
public bool ManagedByAryx { get; init; }
public string? SessionId { get; init; }
public string? AgentId { get; init; }
public string StartTime { get; init; } = string.Empty;
public string ModifiedTime { get; init; } = string.Empty;
public string? Summary { get; init; }
public bool IsRemote { get; init; }
public string? Cwd { get; init; }
public string? GitRoot { get; init; }
public string? Repository { get; init; }
public string? Branch { get; init; }
}
public abstract class SidecarEventDto
{
public string Type { get; init; } = string.Empty;
@@ -251,6 +342,167 @@ public sealed class AgentActivityEventDto : SidecarEventDto
public string? ToolName { get; init; }
}
public sealed class SubagentEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string EventKind { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
public string? ToolCallId { get; init; }
public string? CustomAgentName { get; init; }
public string? CustomAgentDisplayName { get; init; }
public string? CustomAgentDescription { get; init; }
public string? Error { get; init; }
public string? Model { get; init; }
public double? TotalToolCalls { get; init; }
public double? TotalTokens { get; init; }
public double? DurationMs { get; init; }
public IReadOnlyList<string>? Tools { get; init; }
}
public sealed class SkillInvokedEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
public string SkillName { get; init; } = string.Empty;
public string Path { get; init; } = string.Empty;
public string Content { get; init; } = string.Empty;
public IReadOnlyList<string>? AllowedTools { get; init; }
public string? PluginName { get; init; }
public string? PluginVersion { get; init; }
public string? Description { get; init; }
}
public sealed class HookLifecycleEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
public string HookInvocationId { get; init; } = string.Empty;
public string HookType { get; init; } = string.Empty;
public string Phase { get; init; } = string.Empty;
public bool? Success { get; init; }
public object? Input { get; init; }
public object? Output { get; init; }
public string? Error { get; init; }
}
public sealed class QuotaSnapshotDto
{
public double EntitlementRequests { get; init; }
public double UsedRequests { get; init; }
public double RemainingPercentage { get; init; }
public double Overage { get; init; }
public bool OverageAllowedWithExhaustedQuota { get; init; }
public string? ResetDate { get; init; }
}
public sealed class AccountQuotaResultEventDto : SidecarEventDto
{
public Dictionary<string, QuotaSnapshotDto> QuotaSnapshots { get; init; } = new(StringComparer.Ordinal);
}
public sealed class AssistantUsageEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
public string Model { get; init; } = string.Empty;
public double? InputTokens { get; init; }
public double? OutputTokens { get; init; }
public double? CacheReadTokens { get; init; }
public double? CacheWriteTokens { get; init; }
public double? Cost { get; init; }
public double? Duration { get; init; }
public double? TotalNanoAiu { get; init; }
public Dictionary<string, QuotaSnapshotDto>? QuotaSnapshots { get; init; }
}
public sealed class SessionUsageEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
public double TokenLimit { get; init; }
public double CurrentTokens { get; init; }
public double MessagesLength { get; init; }
public double? SystemTokens { get; init; }
public double? ConversationTokens { get; init; }
public double? ToolDefinitionsTokens { get; init; }
public bool? IsInitial { get; init; }
}
public sealed class SessionCompactionEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
public string Phase { get; init; } = string.Empty;
public bool? Success { get; init; }
public string? Error { get; init; }
public double? SystemTokens { get; init; }
public double? ConversationTokens { get; init; }
public double? ToolDefinitionsTokens { get; init; }
public double? PreCompactionTokens { get; init; }
public double? PostCompactionTokens { get; init; }
public double? PreCompactionMessagesLength { get; init; }
public double? MessagesRemoved { get; init; }
public double? TokensRemoved { get; init; }
public string? SummaryContent { get; init; }
public double? CheckpointNumber { get; init; }
public string? CheckpointPath { get; init; }
}
public sealed class PendingMessagesModifiedEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
}
public sealed class SessionsListedEventDto : SidecarEventDto
{
public IReadOnlyList<CopilotSessionInfoDto> Sessions { get; init; } = [];
}
public sealed class SessionsDeletedEventDto : SidecarEventDto
{
public string? SessionId { get; init; }
public IReadOnlyList<CopilotSessionInfoDto> Sessions { get; init; } = [];
}
public sealed class SessionDisconnectedEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public IReadOnlyList<string> CancelledRequestIds { get; init; } = [];
}
public sealed class PermissionDetailDto
{
public string Kind { get; init; } = string.Empty;
public string? Intention { get; init; }
public string? Command { get; init; }
public string? Warning { get; init; }
public IReadOnlyList<string>? PossiblePaths { get; init; }
public IReadOnlyList<string>? PossibleUrls { get; init; }
public bool? HasWriteFileRedirection { get; init; }
public string? FileName { get; init; }
public string? Diff { get; init; }
public string? NewFileContents { get; init; }
public string? Path { get; init; }
public string? ServerName { get; init; }
public string? ToolTitle { get; init; }
public object? Args { get; init; }
public bool? ReadOnly { get; init; }
public string? Url { get; init; }
public string? Subject { get; init; }
public string? Fact { get; init; }
public string? Citations { get; init; }
public string? ToolDescription { get; init; }
public string? HookMessage { get; init; }
}
public sealed class ApprovalRequestedEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
@@ -262,6 +514,47 @@ public sealed class ApprovalRequestedEventDto : SidecarEventDto
public string? PermissionKind { get; init; }
public string Title { get; init; } = string.Empty;
public string? Detail { get; init; }
public PermissionDetailDto? PermissionDetail { get; init; }
}
public sealed class UserInputRequestedEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string UserInputId { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
public string Question { get; init; } = string.Empty;
public IReadOnlyList<string>? Choices { get; init; }
public bool? AllowFreeform { get; init; }
}
public sealed class McpOauthStaticClientConfigDto
{
public string ClientId { get; init; } = string.Empty;
public bool? PublicClient { get; init; }
}
public sealed class McpOauthRequiredEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string OauthRequestId { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
public string ServerName { get; init; } = string.Empty;
public string ServerUrl { get; init; } = string.Empty;
public McpOauthStaticClientConfigDto? StaticClientConfig { get; init; }
}
public sealed class ExitPlanModeRequestedEventDto : SidecarEventDto
{
public string SessionId { get; init; } = string.Empty;
public string ExitPlanId { get; init; } = string.Empty;
public string? AgentId { get; init; }
public string? AgentName { get; init; }
public string Summary { get; init; } = string.Empty;
public string PlanContent { get; init; } = string.Empty;
public IReadOnlyList<string>? Actions { get; init; }
public string? RecommendedAction { get; init; }
}
public sealed class CommandErrorEventDto : SidecarEventDto
@@ -8,9 +8,12 @@ internal static class AgentInstructionComposer
PatternDefinitionDto pattern,
PatternAgentDefinitionDto agent,
int agentIndex,
string workspaceKind = "project")
string workspaceKind = "project",
string interactionMode = "interactive",
string? projectInstructions = null)
{
string baseInstructions = agent.Instructions.Trim();
string repositoryInstructions = projectInstructions?.Trim() ?? string.Empty;
string workspaceGuidance = string.Equals(workspaceKind, "scratchpad", StringComparison.OrdinalIgnoreCase)
? """
You are operating in scratchpad mode.
@@ -20,6 +23,14 @@ internal static class AgentInstructionComposer
Answer conversationally and focus on the user's question directly.
"""
: string.Empty;
string planModeGuidance = string.Equals(interactionMode, "plan", StringComparison.OrdinalIgnoreCase)
? """
You are operating in plan mode.
Your job in this phase is to analyze the request, identify constraints, and produce a concrete implementation plan instead of carrying out the implementation.
Once the plan is ready, call the built-in `exit_plan_mode` tool so the host can present the plan for review.
Do not continue into implementation, file edits, builds, or tests after producing the plan unless the user explicitly asks to leave plan mode and proceed.
"""
: string.Empty;
if (string.Equals(pattern.Mode, "group-chat", StringComparison.OrdinalIgnoreCase))
{
@@ -37,12 +48,12 @@ internal static class AgentInstructionComposer
Focus on refining the answer already in progress.
""";
return JoinInstructionBlocks(baseInstructions, workspaceGuidance, groupChatGuidance);
return JoinInstructionBlocks(baseInstructions, repositoryInstructions, workspaceGuidance, planModeGuidance, groupChatGuidance);
}
if (!string.Equals(pattern.Mode, "handoff", StringComparison.OrdinalIgnoreCase))
{
return JoinInstructionBlocks(baseInstructions, workspaceGuidance);
return JoinInstructionBlocks(baseInstructions, repositoryInstructions, workspaceGuidance, planModeGuidance);
}
string runtimeGuidance = agentIndex == 0
@@ -60,7 +71,7 @@ internal static class AgentInstructionComposer
Do not push the actual work back to triage unless you are blocked or the request is clearly outside your specialty.
""";
return JoinInstructionBlocks(baseInstructions, workspaceGuidance, runtimeGuidance);
return JoinInstructionBlocks(baseInstructions, repositoryInstructions, workspaceGuidance, planModeGuidance, runtimeGuidance);
}
private static string JoinInstructionBlocks(params string[] blocks)
@@ -0,0 +1,637 @@
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Channels;
using Aryx.AgentHost.Contracts;
using GitHub.Copilot.SDK;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
namespace Aryx.AgentHost.Services;
internal sealed class AryxCopilotAgent : AIAgent, IAsyncDisposable
{
private const string DefaultName = "GitHub Copilot Agent";
private const string DefaultDescription = "An AI agent powered by GitHub Copilot";
private const string HandoffToolPrefix = "handoff_to_";
private readonly CopilotClient _copilotClient;
private readonly string? _id;
private readonly string _name;
private readonly string _description;
private readonly SessionConfig? _sessionConfig;
private readonly bool _ownsClient;
public AryxCopilotAgent(
CopilotClient copilotClient,
SessionConfig? sessionConfig = null,
bool ownsClient = false,
string? id = null,
string? name = null,
string? description = null)
{
_copilotClient = copilotClient ?? throw new ArgumentNullException(nameof(copilotClient));
_sessionConfig = sessionConfig;
_ownsClient = ownsClient;
_id = id;
_name = name ?? DefaultName;
_description = description ?? DefaultDescription;
}
protected override ValueTask<AgentSession> CreateSessionCoreAsync(CancellationToken cancellationToken = default)
=> new(new AryxCopilotAgentSession());
protected override ValueTask<JsonElement> SerializeSessionCoreAsync(
AgentSession session,
JsonSerializerOptions? jsonSerializerOptions = null,
CancellationToken cancellationToken = default)
{
if (session is not AryxCopilotAgentSession typedSession)
{
throw new InvalidOperationException(
$"The provided session type '{session.GetType().Name}' is not compatible with this agent. Only sessions of type '{nameof(AryxCopilotAgentSession)}' can be serialized by this agent.");
}
return new(typedSession.Serialize(jsonSerializerOptions));
}
protected override ValueTask<AgentSession> DeserializeSessionCoreAsync(
JsonElement serializedState,
JsonSerializerOptions? jsonSerializerOptions = null,
CancellationToken cancellationToken = default)
=> new(AryxCopilotAgentSession.Deserialize(serializedState, jsonSerializerOptions));
protected override Task<AgentResponse> RunCoreAsync(
IEnumerable<ChatMessage> messages,
AgentSession? session = null,
AgentRunOptions? options = null,
CancellationToken cancellationToken = default)
=> RunCoreStreamingAsync(messages, session, options, cancellationToken).ToAgentResponseAsync(cancellationToken);
protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
IEnumerable<ChatMessage> messages,
AgentSession? session = null,
AgentRunOptions? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(messages);
session ??= await CreateSessionAsync(cancellationToken).ConfigureAwait(false);
if (session is not AryxCopilotAgentSession typedSession)
{
throw new InvalidOperationException(
$"The provided session type '{session.GetType().Name}' is not compatible with this agent. Only sessions of type '{nameof(AryxCopilotAgentSession)}' can be used by this agent.");
}
await EnsureClientStartedAsync(cancellationToken).ConfigureAwait(false);
SessionConfig sessionConfig = CreateConfiguredSessionConfig(_sessionConfig, options);
CopilotSession copilotSession;
if (typedSession.SessionId is not null)
{
copilotSession = await _copilotClient.ResumeSessionAsync(
typedSession.SessionId,
CreateResumeConfig(sessionConfig),
cancellationToken).ConfigureAwait(false);
}
else
{
copilotSession = await _copilotClient.CreateSessionAsync(sessionConfig, cancellationToken).ConfigureAwait(false);
typedSession.SessionId = copilotSession.SessionId;
}
try
{
Channel<AgentResponseUpdate> channel = Channel.CreateUnbounded<AgentResponseUpdate>();
using IDisposable subscription = copilotSession.On(evt =>
{
switch (evt)
{
case AssistantMessageDeltaEvent deltaEvent:
channel.Writer.TryWrite(ConvertToAgentResponseUpdate(deltaEvent));
break;
case AssistantMessageEvent assistantMessage:
channel.Writer.TryWrite(ConvertToAgentResponseUpdate(assistantMessage));
break;
case AssistantUsageEvent usageEvent:
channel.Writer.TryWrite(ConvertToAgentResponseUpdate(usageEvent));
break;
case SessionIdleEvent idleEvent:
channel.Writer.TryWrite(ConvertToAgentResponseUpdate(idleEvent));
channel.Writer.TryComplete();
break;
case SessionErrorEvent errorEvent:
channel.Writer.TryWrite(ConvertToAgentResponseUpdate(errorEvent));
channel.Writer.TryComplete(new InvalidOperationException(
$"Session error: {errorEvent.Data?.Message ?? "Unknown error"}"));
break;
default:
channel.Writer.TryWrite(ConvertToAgentResponseUpdate(evt));
break;
}
});
string? tempDir = null;
try
{
string prompt = string.Join("\n", messages.Select(message => message.Text));
(List<UserMessageDataAttachmentsItem>? attachments, string? messageMode, tempDir) = await ProcessMessageAttachmentsAsync(
messages,
cancellationToken).ConfigureAwait(false);
MessageOptions messageOptions = new()
{
Prompt = prompt,
Mode = string.IsNullOrWhiteSpace(messageMode) ? null : messageMode,
};
if (attachments is not null)
{
messageOptions.Attachments = [.. attachments];
}
await copilotSession.SendAsync(messageOptions, cancellationToken).ConfigureAwait(false);
await foreach (AgentResponseUpdate update in channel.Reader.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
yield return update;
}
}
finally
{
CleanupTempDir(tempDir);
}
}
finally
{
await copilotSession.DisposeAsync().ConfigureAwait(false);
}
}
protected override string? IdCore => _id;
public override string Name => _name;
public override string Description => _description;
public async ValueTask DisposeAsync()
{
if (_ownsClient)
{
await _copilotClient.DisposeAsync().ConfigureAwait(false);
}
}
internal static SessionConfig CreateConfiguredSessionConfig(SessionConfig? source, AgentRunOptions? options)
{
SessionConfig sessionConfig = source?.Clone() ?? new SessionConfig();
sessionConfig.Streaming = true;
if (sessionConfig.SystemMessage is not null)
{
sessionConfig.SystemMessage = CloneSystemMessage(sessionConfig.SystemMessage);
}
if (options is not ChatClientAgentRunOptions { ChatOptions: { } chatOptions })
{
return sessionConfig;
}
if (!string.IsNullOrWhiteSpace(chatOptions.ModelId))
{
sessionConfig.Model = chatOptions.ModelId;
}
if (!string.IsNullOrWhiteSpace(chatOptions.Instructions))
{
AppendInstructions(sessionConfig, chatOptions.Instructions);
}
sessionConfig.Tools = MergeTools(sessionConfig.Tools, chatOptions.Tools);
return sessionConfig;
}
internal static IReadOnlyList<FunctionCallContent> ConvertToolRequestsToFunctionCalls(
AssistantMessageDataToolRequestsItem[]? toolRequests)
{
if (toolRequests is not { Length: > 0 })
{
return [];
}
List<FunctionCallContent> contents = [];
foreach (AssistantMessageDataToolRequestsItem toolRequest in toolRequests)
{
if (string.IsNullOrWhiteSpace(toolRequest.ToolCallId) || string.IsNullOrWhiteSpace(toolRequest.Name))
{
continue;
}
// Only project handoff tool calls as FunctionCallContent for the Agent Framework.
// Other tool calls (ask_user, MCP tools, etc.) are resolved by the Copilot SDK
// internally and must not be surfaced, because AIAgentHostExecutor tracks every
// FunctionCallContent as an outstanding request. An unmatched request prevents
// the executor from emitting a TurnToken, which stalls group-chat advancement.
if (!IsHandoffToolName(toolRequest.Name))
{
continue;
}
contents.Add(new FunctionCallContent(
toolRequest.ToolCallId,
toolRequest.Name,
ParseToolArguments(toolRequest.Arguments)));
}
return contents;
}
private static bool IsHandoffToolName(string? name)
{
return !string.IsNullOrWhiteSpace(name)
&& name.StartsWith(HandoffToolPrefix, StringComparison.Ordinal);
}
private async Task EnsureClientStartedAsync(CancellationToken cancellationToken)
{
if (_copilotClient.State != ConnectionState.Connected)
{
await _copilotClient.StartAsync(cancellationToken).ConfigureAwait(false);
}
}
private static ResumeSessionConfig CreateResumeConfig(SessionConfig source)
{
return new ResumeSessionConfig
{
ClientName = source.ClientName,
Model = source.Model,
Tools = source.Tools is not null ? [.. source.Tools] : null,
SystemMessage = CloneSystemMessage(source.SystemMessage),
AvailableTools = source.AvailableTools is not null ? [.. source.AvailableTools] : null,
ExcludedTools = source.ExcludedTools is not null ? [.. source.ExcludedTools] : null,
Provider = source.Provider,
OnPermissionRequest = source.OnPermissionRequest,
OnUserInputRequest = source.OnUserInputRequest,
Hooks = source.Hooks,
WorkingDirectory = source.WorkingDirectory,
ConfigDir = source.ConfigDir,
Streaming = true,
McpServers = source.McpServers is not null
? new Dictionary<string, object>(source.McpServers, source.McpServers.Comparer)
: null,
CustomAgents = source.CustomAgents is not null ? [.. source.CustomAgents] : null,
Agent = source.Agent,
SkillDirectories = source.SkillDirectories is not null ? [.. source.SkillDirectories] : null,
DisabledSkills = source.DisabledSkills is not null ? [.. source.DisabledSkills] : null,
InfiniteSessions = source.InfiniteSessions,
OnEvent = source.OnEvent,
ReasoningEffort = source.ReasoningEffort,
};
}
private static SystemMessageConfig? CloneSystemMessage(SystemMessageConfig? source)
{
if (source is null)
{
return null;
}
return new SystemMessageConfig
{
Mode = source.Mode,
Content = source.Content,
Sections = source.Sections is not null ? new Dictionary<string, SectionOverride>(source.Sections) : null,
};
}
private static void AppendInstructions(SessionConfig sessionConfig, string instructions)
{
string trimmedInstructions = instructions.Trim();
if (trimmedInstructions.Length == 0)
{
return;
}
if (sessionConfig.SystemMessage is null)
{
sessionConfig.SystemMessage = new SystemMessageConfig
{
Mode = SystemMessageMode.Append,
Content = trimmedInstructions,
};
return;
}
string? existingContent = sessionConfig.SystemMessage.Content;
sessionConfig.SystemMessage.Content = string.IsNullOrWhiteSpace(existingContent)
? trimmedInstructions
: $"{existingContent.Trim()}\n\n{trimmedInstructions}";
}
private static ICollection<AIFunction>? MergeTools(
ICollection<AIFunction>? sessionTools,
IList<AITool>? runtimeTools)
{
if (runtimeTools is not { Count: > 0 })
{
return sessionTools;
}
List<AIFunction> mergedTools = sessionTools is not null ? [.. sessionTools] : [];
foreach (AITool runtimeTool in runtimeTools)
{
mergedTools.Add(MapRuntimeTool(runtimeTool));
}
return mergedTools;
}
private static AIFunction MapRuntimeTool(AITool tool)
{
return tool switch
{
AIFunction function => function,
AIFunctionDeclaration declaration when IsHandoffDeclaration(declaration) => CreateInvokableHandoffFunction(declaration),
AIFunctionDeclaration declaration => throw new NotSupportedException(
$"GitHub Copilot session tools must be invokable AIFunctions. Runtime tool '{declaration.Name}' is declaration-only."),
_ => throw new NotSupportedException(
$"GitHub Copilot session tools must be invokable AIFunctions. Runtime tool '{tool.Name}' is not supported."),
};
}
private static bool IsHandoffDeclaration(AIFunctionDeclaration declaration)
{
return IsHandoffToolName(declaration.Name);
}
private static AIFunction CreateInvokableHandoffFunction(AIFunctionDeclaration declaration)
{
AIFunction function = AIFunctionFactory.Create(
(string? reasonForHandoff) => "Transferred.",
new AIFunctionFactoryOptions
{
Name = declaration.Name,
Description = declaration.Description,
AdditionalProperties = new Dictionary<string, object?>
{
["skip_permission"] = true,
},
});
return function;
}
private AgentResponseUpdate ConvertToAgentResponseUpdate(AssistantMessageDeltaEvent deltaEvent)
{
TextContent textContent = new(deltaEvent.Data?.DeltaContent ?? string.Empty)
{
RawRepresentation = deltaEvent,
};
return new AgentResponseUpdate(ChatRole.Assistant, [textContent])
{
AgentId = Id,
MessageId = deltaEvent.Data?.MessageId,
CreatedAt = deltaEvent.Timestamp,
};
}
private AgentResponseUpdate ConvertToAgentResponseUpdate(AssistantMessageEvent assistantMessage)
{
List<AIContent> contents = [];
contents.AddRange(ConvertToolRequestsToFunctionCalls(assistantMessage.Data?.ToolRequests));
contents.Add(new AIContent
{
RawRepresentation = assistantMessage,
});
return new AgentResponseUpdate(ChatRole.Assistant, contents)
{
AgentId = Id,
ResponseId = assistantMessage.Data?.MessageId,
MessageId = assistantMessage.Data?.MessageId,
CreatedAt = assistantMessage.Timestamp,
};
}
private AgentResponseUpdate ConvertToAgentResponseUpdate(AssistantUsageEvent usageEvent)
{
UsageDetails usageDetails = new()
{
InputTokenCount = (int?)usageEvent.Data?.InputTokens,
OutputTokenCount = (int?)usageEvent.Data?.OutputTokens,
TotalTokenCount = (int?)((usageEvent.Data?.InputTokens ?? 0) + (usageEvent.Data?.OutputTokens ?? 0)),
CachedInputTokenCount = (int?)usageEvent.Data?.CacheReadTokens,
};
UsageContent usageContent = new(usageDetails)
{
RawRepresentation = usageEvent,
};
return new AgentResponseUpdate(ChatRole.Assistant, [usageContent])
{
AgentId = Id,
CreatedAt = usageEvent.Timestamp,
};
}
private AgentResponseUpdate ConvertToAgentResponseUpdate(SessionEvent sessionEvent)
{
AIContent content = new()
{
RawRepresentation = sessionEvent,
};
return new AgentResponseUpdate(ChatRole.Assistant, [content])
{
AgentId = Id,
CreatedAt = sessionEvent.Timestamp,
};
}
private static Dictionary<string, object?>? ParseToolArguments(object? arguments)
{
if (arguments is null)
{
return null;
}
if (arguments is Dictionary<string, object?> dictionary)
{
return new Dictionary<string, object?>(dictionary, StringComparer.Ordinal);
}
if (arguments is JsonElement jsonElement)
{
if (jsonElement.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
{
return null;
}
return JsonSerializer.Deserialize<Dictionary<string, object?>>(jsonElement.GetRawText());
}
string json = JsonSerializer.Serialize(arguments, arguments.GetType());
return JsonSerializer.Deserialize<Dictionary<string, object?>>(json);
}
internal static async Task<(List<UserMessageDataAttachmentsItem>? Attachments, string? MessageMode, string? TempDir)> ProcessMessageAttachmentsAsync(
IEnumerable<ChatMessage> messages,
CancellationToken cancellationToken)
{
List<UserMessageDataAttachmentsItem>? attachments = null;
string? messageMode = null;
string? tempDir = null;
foreach (ChatMessage message in messages)
{
foreach (AIContent content in message.Contents)
{
if (content is DataContent dataContent)
{
tempDir ??= Directory.CreateDirectory(
Path.Combine(Path.GetTempPath(), $"af_copilot_{Guid.NewGuid():N}")).FullName;
string tempFilePath = await dataContent.SaveToAsync(tempDir, cancellationToken).ConfigureAwait(false);
attachments ??= [];
attachments.Add(new UserMessageDataAttachmentsItemFile
{
Path = tempFilePath,
DisplayName = Path.GetFileName(tempFilePath),
});
continue;
}
if (content.RawRepresentation is ChatMessageAttachmentDto protocolAttachment)
{
attachments ??= [];
attachments.Add(CreateProtocolAttachment(protocolAttachment));
continue;
}
if (content.RawRepresentation is CopilotMessageOptionsMetadata metadata
&& !string.IsNullOrWhiteSpace(metadata.MessageMode))
{
messageMode = metadata.MessageMode.Trim();
}
}
}
return (attachments, messageMode, tempDir);
}
private static UserMessageDataAttachmentsItem CreateProtocolAttachment(ChatMessageAttachmentDto attachment)
{
ArgumentNullException.ThrowIfNull(attachment);
return attachment.Type switch
{
"file" => CreateFileAttachment(attachment),
"blob" => CreateBlobAttachment(attachment),
_ => throw new NotSupportedException($"Unsupported attachment type '{attachment.Type}'."),
};
}
private static UserMessageDataAttachmentsItemFile CreateFileAttachment(ChatMessageAttachmentDto attachment)
{
if (string.IsNullOrWhiteSpace(attachment.Path))
{
throw new InvalidOperationException("File attachments require an absolute path.");
}
string path = attachment.Path.Trim();
if (!Path.IsPathRooted(path))
{
throw new InvalidOperationException($"File attachment path '{path}' must be absolute.");
}
return new UserMessageDataAttachmentsItemFile
{
Path = path,
DisplayName = string.IsNullOrWhiteSpace(attachment.DisplayName)
? Path.GetFileName(path)
: attachment.DisplayName.Trim(),
};
}
private static UserMessageDataAttachmentsItemBlob CreateBlobAttachment(ChatMessageAttachmentDto attachment)
{
if (string.IsNullOrWhiteSpace(attachment.Data))
{
throw new InvalidOperationException("Blob attachments require base64-encoded data.");
}
if (string.IsNullOrWhiteSpace(attachment.MimeType))
{
throw new InvalidOperationException("Blob attachments require a MIME type.");
}
return new UserMessageDataAttachmentsItemBlob
{
Data = attachment.Data.Trim(),
MimeType = attachment.MimeType.Trim(),
DisplayName = string.IsNullOrWhiteSpace(attachment.DisplayName) ? null : attachment.DisplayName.Trim(),
};
}
private static void CleanupTempDir(string? tempDir)
{
if (tempDir is null)
{
return;
}
try
{
Directory.Delete(tempDir, recursive: true);
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
}
}
internal sealed class AryxCopilotAgentSession : AgentSession
{
public AryxCopilotAgentSession()
{
}
[JsonConstructor]
public AryxCopilotAgentSession(string? sessionId, AgentSessionStateBag? stateBag = null)
: base(stateBag ?? new AgentSessionStateBag())
{
SessionId = sessionId;
}
[JsonPropertyName("sessionId")]
public string? SessionId { get; set; }
internal JsonElement Serialize(JsonSerializerOptions? jsonSerializerOptions = null)
{
JsonSerializerOptions options = jsonSerializerOptions ?? new JsonSerializerOptions(JsonSerializerDefaults.Web);
return JsonSerializer.SerializeToElement(this, options);
}
internal static AryxCopilotAgentSession Deserialize(
JsonElement serializedState,
JsonSerializerOptions? jsonSerializerOptions = null)
{
if (serializedState.ValueKind != JsonValueKind.Object)
{
throw new ArgumentException("The serialized session state must be a JSON object.", nameof(serializedState));
}
JsonSerializerOptions options = jsonSerializerOptions ?? new JsonSerializerOptions(JsonSerializerDefaults.Web);
return serializedState.Deserialize<AryxCopilotAgentSession>(options)
?? new AryxCopilotAgentSession();
}
}
@@ -1,3 +1,4 @@
using System.Threading;
using GitHub.Copilot.SDK;
using Aryx.AgentHost.Contracts;
using Microsoft.Agents.AI;
@@ -12,22 +13,29 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable
{
private readonly List<IAsyncDisposable> _disposables = [];
private CopilotAgentBundle(IReadOnlyList<AIAgent> agents)
internal CopilotAgentBundle(IReadOnlyList<AIAgent> agents, bool hasConfiguredHooks)
{
Agents = agents;
HasConfiguredHooks = hasConfiguredHooks;
}
public IReadOnlyList<AIAgent> Agents { get; }
public bool HasConfiguredHooks { get; }
public static async Task<CopilotAgentBundle> CreateAsync(
RunTurnCommandDto command,
Func<PatternAgentDefinitionDto, PermissionRequest, PermissionInvocation, Task<PermissionRequestResult>> onPermissionRequest,
Func<PatternAgentDefinitionDto, UserInputRequest, UserInputInvocation, Task<UserInputResponse>> onUserInputRequest,
Action<PatternAgentDefinitionDto, SessionEvent>? onSessionEvent,
CancellationToken cancellationToken)
{
List<IAsyncDisposable> disposables = [];
List<AIAgent> agents = [];
CopilotClientOptions clientOptions = CopilotCliPathResolver.CreateClientOptions();
ResolvedHookSet configuredHooks = await HookConfigLoader.LoadAsync(command.ProjectPath, cancellationToken)
.ConfigureAwait(false);
IHookCommandRunner hookCommandRunner = HookCommandRunner.Instance;
SessionToolingBundle? toolingBundle = command.Tooling is null
? null
: await SessionToolingBundle.CreateAsync(command.Tooling, command.ProjectPath, cancellationToken)
@@ -43,23 +51,19 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable
CopilotClient client = new(clientOptions);
await client.StartAsync(cancellationToken).ConfigureAwait(false);
SessionConfig sessionConfig = new()
{
Model = definition.Model,
ReasoningEffort = definition.ReasoningEffort,
SystemMessage = new SystemMessageConfig
{
Content = AgentInstructionComposer.Compose(command.Pattern, definition, agentIndex, command.WorkspaceKind),
},
WorkingDirectory = command.ProjectPath,
OnPermissionRequest = (request, invocation) => onPermissionRequest(definition, request, invocation),
OnEvent = evt => onSessionEvent?.Invoke(definition, evt),
Streaming = true,
};
SessionConfig sessionConfig = CreateSessionConfig(
command,
definition,
agentIndex,
(request, invocation) => onPermissionRequest(definition, request, invocation),
(request, invocation) => onUserInputRequest(definition, request, invocation),
evt => onSessionEvent?.Invoke(definition, evt),
configuredHooks,
hookCommandRunner);
ApplySessionTooling(sessionConfig, toolingBundle?.McpServers, toolingBundle?.Tools);
GitHubCopilotAgent agent = new(
AryxCopilotAgent agent = new(
client,
sessionConfig,
ownsClient: true,
@@ -71,11 +75,51 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable
disposables.Add(agent);
}
CopilotAgentBundle bundle = new(agents);
CopilotAgentBundle bundle = new(agents, hasConfiguredHooks: !configuredHooks.IsEmpty);
bundle._disposables.AddRange(disposables);
return bundle;
}
internal static SessionConfig CreateSessionConfig(
RunTurnCommandDto command,
PatternAgentDefinitionDto definition,
int agentIndex,
PermissionRequestHandler? onPermissionRequest = null,
UserInputHandler? onUserInputRequest = null,
SessionEventHandler? onSessionEvent = null,
ResolvedHookSet? configuredHooks = null,
IHookCommandRunner? hookCommandRunner = null)
{
// Let the Copilot SDK allocate session IDs. Explicit custom SessionId values currently
// cause turns to complete without assistant output, even for simple single-agent prompts.
return new SessionConfig
{
Model = definition.Model,
ReasoningEffort = definition.ReasoningEffort,
SystemMessage = new SystemMessageConfig
{
Content = AgentInstructionComposer.Compose(
command.Pattern,
definition,
agentIndex,
command.WorkspaceKind,
command.Mode,
command.ProjectInstructions),
},
WorkingDirectory = command.ProjectPath,
OnPermissionRequest = onPermissionRequest,
OnUserInputRequest = onUserInputRequest,
Hooks = CopilotSessionHooks.Create(command, definition, configuredHooks, hookCommandRunner),
OnEvent = onSessionEvent,
Streaming = true,
CustomAgents = CreateCustomAgents(definition.Copilot?.CustomAgents),
Agent = NormalizeOptionalString(definition.Copilot?.Agent),
SkillDirectories = CreateStringList(definition.Copilot?.SkillDirectories),
DisabledSkills = CreateStringList(definition.Copilot?.DisabledSkills),
InfiniteSessions = CreateInfiniteSessions(definition.Copilot?.InfiniteSessions),
};
}
internal static void ApplySessionTooling(
SessionConfig sessionConfig,
Dictionary<string, object>? mcpServers,
@@ -92,6 +136,55 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable
}
}
internal static List<CustomAgentConfig>? CreateCustomAgents(
IReadOnlyList<RunTurnCustomAgentConfigDto>? customAgents)
{
if (customAgents is not { Count: > 0 })
{
return null;
}
return customAgents.Select(customAgent => new CustomAgentConfig
{
Name = customAgent.Name,
DisplayName = NormalizeOptionalString(customAgent.DisplayName),
Description = NormalizeOptionalString(customAgent.Description),
Tools = customAgent.Tools is null ? null : [.. customAgent.Tools],
Prompt = customAgent.Prompt,
McpServers = customAgent.McpServers.Count == 0
? null
: SessionToolingBundle.BuildMcpServerConfigurations(customAgent.McpServers),
Infer = customAgent.Infer,
}).ToList();
}
internal static InfiniteSessionConfig? CreateInfiniteSessions(RunTurnInfiniteSessionsConfigDto? config)
{
if (config is null)
{
return null;
}
return new InfiniteSessionConfig
{
Enabled = config.Enabled,
BackgroundCompactionThreshold = config.BackgroundCompactionThreshold,
BufferExhaustionThreshold = config.BufferExhaustionThreshold,
};
}
private static List<string>? CreateStringList(IReadOnlyList<string>? values)
{
return values is { Count: > 0 }
? [.. values]
: null;
}
private static string? NormalizeOptionalString(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
public Workflow BuildWorkflow(PatternDefinitionDto pattern)
{
return pattern.Mode switch
@@ -124,7 +217,10 @@ internal sealed class CopilotAgentBundle : IAsyncDisposable
definition => definition,
StringComparer.Ordinal);
PatternHandoffTopology topology = PatternGraphResolver.ResolveHandoff(pattern);
AIAgent entryAgent = agentMap.GetValueOrDefault(topology.EntryAgentId) ?? Agents[0];
string entryAgentId = agentMap.ContainsKey(topology.EntryAgentId)
? topology.EntryAgentId
: pattern.Agents.FirstOrDefault()?.Id ?? topology.EntryAgentId;
AIAgent entryAgent = agentMap.GetValueOrDefault(entryAgentId) ?? Agents[0];
HandoffsWorkflowBuilder builder = AgentWorkflowBuilder.CreateHandoffBuilderWith(entryAgent)
.WithHandoffInstructions(HandoffWorkflowGuidance.CreateWorkflowInstructions());
@@ -9,9 +9,19 @@ internal sealed class CopilotApprovalCoordinator
private const string ApprovedDecision = "approved";
private const string RejectedDecision = "rejected";
private const string ToolCallApprovalKind = "tool-call";
private const string StoreMemoryToolName = "store_memory";
private const string WebFetchToolName = "web_fetch";
private const string ShellPermissionKind = "shell";
private const string WritePermissionKind = "write";
private const string ReadPermissionKind = "read";
private const string McpPermissionKind = "mcp";
private const string UrlPermissionKind = "url";
private const string MemoryPermissionKind = "memory";
private const string CustomToolPermissionKind = "custom-tool";
private const string HookPermissionKind = "hook";
private readonly ConcurrentDictionary<string, PendingApprovalRequest> _pendingApprovals = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, byte>> _requestApprovedTools = new(StringComparer.Ordinal);
public Task ResolveApprovalAsync(
ResolveApprovalCommandDto command,
@@ -28,6 +38,11 @@ internal sealed class CopilotApprovalCoordinator
throw new InvalidOperationException($"Approval \"{approvalId}\" is no longer pending.");
}
if (decision == PermissionRequestResultKind.Approved && command.AlwaysApprove)
{
CacheApprovedToolForRequest(pending.RequestId, pending.ApprovalCacheKey);
}
return Task.CompletedTask;
}
@@ -41,12 +56,16 @@ internal sealed class CopilotApprovalCoordinator
CancellationToken cancellationToken)
{
string? toolName = ResolveApprovalToolName(request, toolNamesByCallId);
if (!RequiresToolCallApproval(command.Pattern.ApprovalPolicy, agent.Id, toolName))
string? autoApprovedToolName = ResolveAutoApprovedToolName(request);
string? mcpServerApprovalKey = ResolveMcpServerApprovalKey(request);
string? approvalCacheKey = ResolveApprovalCacheKey(toolName, autoApprovedToolName);
if (IsToolApprovedForRequest(command.RequestId, approvalCacheKey)
|| !RequiresToolCallApproval(command.Pattern.ApprovalPolicy, agent.Id, toolName, autoApprovedToolName, mcpServerApprovalKey))
{
return CreateApprovalResult(PermissionRequestResultKind.Approved);
}
PendingApprovalRequest pending = CreatePendingApproval(command);
PendingApprovalRequest pending = CreatePendingApproval(command, approvalCacheKey);
if (!_pendingApprovals.TryAdd(pending.ApprovalId, pending))
{
throw new InvalidOperationException($"Approval \"{pending.ApprovalId}\" is already pending.");
@@ -131,13 +150,86 @@ internal sealed class CopilotApprovalCoordinator
PermissionKind = permissionKind,
Title = title,
Detail = detail,
PermissionDetail = BuildPermissionDetail(request),
};
}
internal static PermissionDetailDto BuildPermissionDetail(PermissionRequest request)
{
ArgumentNullException.ThrowIfNull(request);
return request switch
{
PermissionRequestShell shell => new PermissionDetailDto
{
Kind = ShellPermissionKind,
Intention = NormalizeOptionalString(shell.Intention),
Command = NormalizeOptionalString(shell.FullCommandText),
Warning = NormalizeOptionalString(shell.Warning),
PossiblePaths = NormalizeOptionalStringList(shell.PossiblePaths),
PossibleUrls = NormalizeOptionalStringList(shell.PossibleUrls.Select(static candidate => candidate.Url)),
HasWriteFileRedirection = shell.HasWriteFileRedirection,
},
PermissionRequestWrite write => new PermissionDetailDto
{
Kind = WritePermissionKind,
Intention = NormalizeOptionalString(write.Intention),
FileName = NormalizeOptionalString(write.FileName),
Diff = NormalizeOptionalString(write.Diff),
NewFileContents = NormalizeOptionalString(write.NewFileContents),
},
PermissionRequestRead read => new PermissionDetailDto
{
Kind = ReadPermissionKind,
Intention = NormalizeOptionalString(read.Intention),
Path = NormalizeOptionalString(read.Path),
},
PermissionRequestMcp mcp => new PermissionDetailDto
{
Kind = McpPermissionKind,
ServerName = NormalizeOptionalString(mcp.ServerName),
ToolTitle = NormalizeOptionalString(mcp.ToolTitle),
Args = mcp.Args,
ReadOnly = mcp.ReadOnly,
},
PermissionRequestUrl url => new PermissionDetailDto
{
Kind = UrlPermissionKind,
Intention = NormalizeOptionalString(url.Intention),
Url = NormalizeOptionalString(url.Url),
},
PermissionRequestMemory memory => new PermissionDetailDto
{
Kind = MemoryPermissionKind,
Subject = NormalizeOptionalString(memory.Subject),
Fact = NormalizeOptionalString(memory.Fact),
Citations = NormalizeOptionalString(memory.Citations),
},
PermissionRequestCustomTool customTool => new PermissionDetailDto
{
Kind = CustomToolPermissionKind,
ToolDescription = NormalizeOptionalString(customTool.ToolDescription),
Args = customTool.Args,
},
PermissionRequestHook hook => new PermissionDetailDto
{
Kind = HookPermissionKind,
Args = hook.ToolArgs,
HookMessage = NormalizeOptionalString(hook.HookMessage),
},
_ => new PermissionDetailDto
{
Kind = NormalizeOptionalString(request.Kind) ?? "unknown",
},
};
}
internal static bool RequiresToolCallApproval(
ApprovalPolicyDto? approvalPolicy,
string agentId,
string? toolName)
string? toolName,
string? autoApprovedToolName = null,
string? mcpServerApprovalKey = null)
{
if (approvalPolicy?.Rules is null || approvalPolicy.Rules.Count == 0)
{
@@ -149,9 +241,14 @@ internal sealed class CopilotApprovalCoordinator
return false;
}
return string.IsNullOrWhiteSpace(toolName)
|| !approvalPolicy.AutoApprovedToolNames.Any(candidate =>
string.Equals(candidate, toolName, StringComparison.OrdinalIgnoreCase));
IReadOnlyList<string> autoApprovedToolNames = approvalPolicy.AutoApprovedToolNames;
if (autoApprovedToolNames.Count == 0)
{
return true;
}
return !MatchesAutoApprovedTool(autoApprovedToolNames, toolName, autoApprovedToolName)
&& !MatchesAutoApprovedToolName(autoApprovedToolNames, mcpServerApprovalKey);
}
internal static bool TryGetApprovalToolName(
@@ -166,6 +263,17 @@ internal sealed class CopilotApprovalCoordinator
internal static bool TryGetApprovalToolName(PermissionRequest request, out string? toolName)
=> TryGetApprovalToolName(request, toolNamesByCallId: null, out toolName);
internal void ClearRequestApprovals(string requestId)
{
string? normalizedRequestId = NormalizeOptionalString(requestId);
if (normalizedRequestId is null)
{
return;
}
_requestApprovedTools.TryRemove(normalizedRequestId, out _);
}
private static bool HasMatchingToolCallCheckpoint(
IReadOnlyList<ApprovalCheckpointRuleDto> rules,
string agentId)
@@ -188,12 +296,15 @@ internal sealed class CopilotApprovalCoordinator
return false;
}
private static PendingApprovalRequest CreatePendingApproval(RunTurnCommandDto command)
private static PendingApprovalRequest CreatePendingApproval(
RunTurnCommandDto command,
string? approvalCacheKey)
{
return new PendingApprovalRequest(
command.RequestId,
command.SessionId,
CreateApprovalRequestId(),
NormalizeOptionalString(approvalCacheKey),
new TaskCompletionSource<PermissionRequestResultKind>(TaskCreationOptions.RunContinuationsAsynchronously));
}
@@ -214,6 +325,32 @@ internal sealed class CopilotApprovalCoordinator
?? GetFallbackToolName(request);
}
private static string? ResolveAutoApprovedToolName(PermissionRequest request)
{
return GetFallbackToolName(request);
}
private const string McpServerApprovalPrefix = "mcp_server:";
private static string? ResolveMcpServerApprovalKey(PermissionRequest request)
{
if (request is not PermissionRequestMcp mcp)
{
return null;
}
string? serverName = NormalizeOptionalString(mcp.ServerName);
return serverName is not null ? $"{McpServerApprovalPrefix}{serverName}" : null;
}
private static string? ResolveApprovalCacheKey(
string? toolName,
string? autoApprovedToolName)
{
return NormalizeOptionalString(autoApprovedToolName)
?? NormalizeOptionalString(toolName);
}
private static string? GetDirectToolName(PermissionRequest request)
{
return request switch
@@ -265,10 +402,61 @@ internal sealed class CopilotApprovalCoordinator
return request switch
{
PermissionRequestUrl => WebFetchToolName,
PermissionRequestShell => ShellPermissionKind,
PermissionRequestWrite => WritePermissionKind,
PermissionRequestRead => ReadPermissionKind,
PermissionRequestMemory => StoreMemoryToolName,
_ => null,
};
}
private static bool MatchesAutoApprovedTool(
IReadOnlyList<string> autoApprovedToolNames,
string? toolName,
string? autoApprovedToolName)
{
return MatchesAutoApprovedToolName(autoApprovedToolNames, toolName)
|| MatchesAutoApprovedToolName(autoApprovedToolNames, autoApprovedToolName);
}
private static bool MatchesAutoApprovedToolName(
IReadOnlyList<string> autoApprovedToolNames,
string? toolName)
{
string? normalizedToolName = NormalizeOptionalString(toolName);
return normalizedToolName is not null
&& autoApprovedToolNames.Any(candidate =>
string.Equals(candidate, normalizedToolName, StringComparison.OrdinalIgnoreCase));
}
private bool IsToolApprovedForRequest(string requestId, string? approvalCacheKey)
{
string? normalizedRequestId = NormalizeOptionalString(requestId);
string? normalizedApprovalCacheKey = NormalizeOptionalString(approvalCacheKey);
if (normalizedRequestId is null || normalizedApprovalCacheKey is null)
{
return false;
}
return _requestApprovedTools.TryGetValue(normalizedRequestId, out ConcurrentDictionary<string, byte>? approvedTools)
&& approvedTools.ContainsKey(normalizedApprovalCacheKey);
}
private void CacheApprovedToolForRequest(string requestId, string? approvalCacheKey)
{
string? normalizedRequestId = NormalizeOptionalString(requestId);
string? normalizedApprovalCacheKey = NormalizeOptionalString(approvalCacheKey);
if (normalizedRequestId is null || normalizedApprovalCacheKey is null)
{
return;
}
ConcurrentDictionary<string, byte> approvedTools = _requestApprovedTools.GetOrAdd(
normalizedRequestId,
static _ => new ConcurrentDictionary<string, byte>(StringComparer.OrdinalIgnoreCase));
approvedTools.TryAdd(normalizedApprovalCacheKey, 0);
}
private PendingApprovalRequest GetPendingApproval(string approvalId)
{
if (_pendingApprovals.TryGetValue(approvalId, out PendingApprovalRequest? pending))
@@ -307,9 +495,21 @@ internal sealed class CopilotApprovalCoordinator
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
private static IReadOnlyList<string>? NormalizeOptionalStringList(IEnumerable<string?> values)
{
List<string> normalized = values
.Select(NormalizeOptionalString)
.Where(static value => value is not null)
.Cast<string>()
.ToList();
return normalized.Count > 0 ? normalized : null;
}
private sealed record PendingApprovalRequest(
string RequestId,
string SessionId,
string ApprovalId,
string? ApprovalCacheKey,
TaskCompletionSource<PermissionRequestResultKind> Decision);
}
@@ -0,0 +1,81 @@
using System.Collections.Concurrent;
using Aryx.AgentHost.Contracts;
using GitHub.Copilot.SDK;
namespace Aryx.AgentHost.Services;
internal sealed class CopilotExitPlanModeCoordinator
{
private readonly ConcurrentDictionary<string, ExitPlanModeRequestedEventDto> _pendingExitPlanRequests =
new(StringComparer.Ordinal);
public ExitPlanModeRequestedEventDto RecordExitPlanModeRequest(
RunTurnCommandDto command,
PatternAgentDefinitionDto agent,
ExitPlanModeRequestedEvent request)
{
ArgumentNullException.ThrowIfNull(command);
ArgumentNullException.ThrowIfNull(agent);
ArgumentNullException.ThrowIfNull(request);
ExitPlanModeRequestedEventDto exitPlanEvent = BuildExitPlanModeRequestedEvent(command, agent, request);
_pendingExitPlanRequests[command.RequestId] = exitPlanEvent;
return exitPlanEvent;
}
public ExitPlanModeRequestedEventDto? ConsumePendingRequest(string turnRequestId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(turnRequestId);
return _pendingExitPlanRequests.TryRemove(turnRequestId, out ExitPlanModeRequestedEventDto? pending)
? pending
: null;
}
internal static ExitPlanModeRequestedEventDto BuildExitPlanModeRequestedEvent(
RunTurnCommandDto command,
PatternAgentDefinitionDto agent,
ExitPlanModeRequestedEvent request)
{
ArgumentNullException.ThrowIfNull(command);
ArgumentNullException.ThrowIfNull(agent);
ArgumentNullException.ThrowIfNull(request);
ExitPlanModeRequestedData requestData = request.Data
?? throw new InvalidOperationException("Exit plan mode request data is required.");
string exitPlanId = NormalizeOptionalString(requestData.RequestId)
?? throw new InvalidOperationException("Exit plan mode request ID is required.");
string? normalizedAgentId = NormalizeOptionalString(agent.Id);
string? normalizedAgentName = NormalizeOptionalString(agent.Name) ?? normalizedAgentId;
return new ExitPlanModeRequestedEventDto
{
Type = "exit-plan-mode-requested",
RequestId = command.RequestId,
SessionId = command.SessionId,
ExitPlanId = exitPlanId,
AgentId = normalizedAgentId,
AgentName = normalizedAgentName,
Summary = NormalizeOptionalString(requestData.Summary) ?? string.Empty,
PlanContent = NormalizeOptionalString(requestData.PlanContent) ?? string.Empty,
Actions = NormalizeOptionalStringList(requestData.Actions ?? []),
RecommendedAction = NormalizeOptionalString(requestData.RecommendedAction),
};
}
private static string? NormalizeOptionalString(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
private static IReadOnlyList<string>? NormalizeOptionalStringList(IEnumerable<string?> values)
{
List<string> normalized = values
.Select(NormalizeOptionalString)
.Where(static value => value is not null)
.Cast<string>()
.ToList();
return normalized.Count > 0 ? normalized : null;
}
}
@@ -0,0 +1,50 @@
namespace Aryx.AgentHost.Services;
internal static class CopilotManagedSessionIds
{
private const string Prefix = "aryx::";
private const string Separator = "::";
public static string Build(string aryxSessionId, string agentId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(aryxSessionId);
ArgumentException.ThrowIfNullOrWhiteSpace(agentId);
return $"{Prefix}{Uri.EscapeDataString(aryxSessionId)}{Separator}{Uri.EscapeDataString(agentId)}";
}
public static bool IsManagedByAryx(string copilotSessionId)
=> TryParse(copilotSessionId, out _, out _);
public static bool IsManagedByAryx(string copilotSessionId, string aryxSessionId)
{
return TryParse(copilotSessionId, out string? parsedSessionId, out _)
&& string.Equals(parsedSessionId, aryxSessionId, StringComparison.Ordinal);
}
public static bool TryParse(string? copilotSessionId, out string aryxSessionId, out string agentId)
{
aryxSessionId = string.Empty;
agentId = string.Empty;
if (string.IsNullOrWhiteSpace(copilotSessionId)
|| !copilotSessionId.StartsWith(Prefix, StringComparison.Ordinal))
{
return false;
}
string payload = copilotSessionId[Prefix.Length..];
string[] parts = payload.Split(Separator, StringSplitOptions.None);
if (parts.Length != 2
|| string.IsNullOrWhiteSpace(parts[0])
|| string.IsNullOrWhiteSpace(parts[1]))
{
return false;
}
aryxSessionId = Uri.UnescapeDataString(parts[0]);
agentId = Uri.UnescapeDataString(parts[1]);
return true;
}
}
@@ -0,0 +1,58 @@
using Aryx.AgentHost.Contracts;
using GitHub.Copilot.SDK;
namespace Aryx.AgentHost.Services;
internal sealed class CopilotMcpOAuthCoordinator
{
public McpOauthRequiredEventDto BuildMcpOauthRequiredEvent(
RunTurnCommandDto command,
PatternAgentDefinitionDto agent,
McpOauthRequiredEvent request)
{
ArgumentNullException.ThrowIfNull(command);
ArgumentNullException.ThrowIfNull(agent);
ArgumentNullException.ThrowIfNull(request);
McpOauthRequiredData requestData = request.Data
?? throw new InvalidOperationException("MCP OAuth request data is required.");
string oauthRequestId = NormalizeOptionalString(requestData.RequestId)
?? throw new InvalidOperationException("MCP OAuth request ID is required.");
string? normalizedAgentId = NormalizeOptionalString(agent.Id);
string? normalizedAgentName = NormalizeOptionalString(agent.Name) ?? normalizedAgentId;
return new McpOauthRequiredEventDto
{
Type = "mcp-oauth-required",
RequestId = command.RequestId,
SessionId = command.SessionId,
OauthRequestId = oauthRequestId,
AgentId = normalizedAgentId,
AgentName = normalizedAgentName,
ServerName = NormalizeOptionalString(requestData.ServerName) ?? string.Empty,
ServerUrl = NormalizeOptionalString(requestData.ServerUrl) ?? string.Empty,
StaticClientConfig = BuildStaticClientConfig(requestData.StaticClientConfig),
};
}
private static McpOauthStaticClientConfigDto? BuildStaticClientConfig(
McpOauthRequiredDataStaticClientConfig? staticClientConfig)
{
if (staticClientConfig is null)
{
return null;
}
return new McpOauthStaticClientConfigDto
{
ClientId = NormalizeOptionalString(staticClientConfig.ClientId) ?? string.Empty,
PublicClient = staticClientConfig.PublicClient,
};
}
private static string? NormalizeOptionalString(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
}
@@ -0,0 +1,3 @@
namespace Aryx.AgentHost.Services;
internal sealed record CopilotMessageOptionsMetadata(string MessageMode);
@@ -0,0 +1,328 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Aryx.AgentHost.Contracts;
using GitHub.Copilot.SDK;
namespace Aryx.AgentHost.Services;
internal static class CopilotSessionHooks
{
private const string AllowDecision = "allow";
private const string AskDecision = "ask";
private const string DenyDecision = "deny";
private static readonly JsonSerializerOptions HookJsonOptions = new(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
public static SessionHooks Create(
RunTurnCommandDto command,
PatternAgentDefinitionDto agentDefinition,
ResolvedHookSet? configuredHooks = null,
IHookCommandRunner? hookCommandRunner = null)
{
ArgumentNullException.ThrowIfNull(command);
ArgumentNullException.ThrowIfNull(agentDefinition);
ResolvedHookSet hooks = configuredHooks ?? ResolvedHookSet.Empty;
IHookCommandRunner runner = hookCommandRunner ?? HookCommandRunner.Instance;
return new SessionHooks
{
OnPreToolUse = (input, _) => CreatePreToolUseOutputAsync(command, agentDefinition, hooks, runner, input),
OnPostToolUse = (input, _) => RunPostToolUseHooksAsync(command, hooks, runner, input),
OnUserPromptSubmitted = (input, _) => RunUserPromptSubmittedHooksAsync(command, hooks, runner, input),
OnSessionStart = (input, _) => RunSessionStartHooksAsync(command, hooks, runner, input),
OnSessionEnd = (input, _) => RunSessionEndHooksAsync(command, hooks, runner, input),
OnErrorOccurred = (input, _) => RunErrorOccurredHooksAsync(command, hooks, runner, input),
};
}
private static async Task<PreToolUseHookOutput?> CreatePreToolUseOutputAsync(
RunTurnCommandDto command,
PatternAgentDefinitionDto agentDefinition,
ResolvedHookSet configuredHooks,
IHookCommandRunner hookCommandRunner,
PreToolUseHookInput input)
{
if (configuredHooks.PreToolUse.Count > 0)
{
string payload = SerializeHookInput(new FilePreToolUseHookInput
{
Timestamp = input.Timestamp,
Cwd = input.Cwd,
ToolName = input.ToolName,
ToolArgs = SerializeHookValue(input.ToolArgs),
});
foreach (HookCommandDefinition hook in configuredHooks.PreToolUse)
{
string? hookOutput = await hookCommandRunner.RunAsync(
hook,
payload,
command.ProjectPath,
CancellationToken.None)
.ConfigureAwait(false);
PreToolUseHookOutput? decision = ParsePreToolUseDecision(hookOutput);
if (string.Equals(decision?.PermissionDecision, DenyDecision, StringComparison.OrdinalIgnoreCase))
{
return decision;
}
}
}
return CreateApprovalPolicyOutput(command, agentDefinition, input);
}
private static async Task<PostToolUseHookOutput?> RunPostToolUseHooksAsync(
RunTurnCommandDto command,
ResolvedHookSet configuredHooks,
IHookCommandRunner hookCommandRunner,
PostToolUseHookInput input)
{
await RunConfiguredHooksAsync(
configuredHooks.PostToolUse,
hookCommandRunner,
command.ProjectPath,
SerializeHookInput(new FilePostToolUseHookInput
{
Timestamp = input.Timestamp,
Cwd = input.Cwd,
ToolName = input.ToolName,
ToolArgs = SerializeHookValue(input.ToolArgs),
ToolResult = input.ToolResult,
}))
.ConfigureAwait(false);
return null;
}
private static async Task<UserPromptSubmittedHookOutput?> RunUserPromptSubmittedHooksAsync(
RunTurnCommandDto command,
ResolvedHookSet configuredHooks,
IHookCommandRunner hookCommandRunner,
UserPromptSubmittedHookInput input)
{
await RunConfiguredHooksAsync(
configuredHooks.UserPromptSubmitted,
hookCommandRunner,
command.ProjectPath,
SerializeHookInput(new FileUserPromptSubmittedHookInput
{
Timestamp = input.Timestamp,
Cwd = input.Cwd,
Prompt = input.Prompt,
}))
.ConfigureAwait(false);
return null;
}
private static async Task<SessionStartHookOutput?> RunSessionStartHooksAsync(
RunTurnCommandDto command,
ResolvedHookSet configuredHooks,
IHookCommandRunner hookCommandRunner,
SessionStartHookInput input)
{
await RunConfiguredHooksAsync(
configuredHooks.SessionStart,
hookCommandRunner,
command.ProjectPath,
SerializeHookInput(new FileSessionStartHookInput
{
Timestamp = input.Timestamp,
Cwd = input.Cwd,
Source = input.Source,
InitialPrompt = input.InitialPrompt,
}))
.ConfigureAwait(false);
return null;
}
private static async Task<SessionEndHookOutput?> RunSessionEndHooksAsync(
RunTurnCommandDto command,
ResolvedHookSet configuredHooks,
IHookCommandRunner hookCommandRunner,
SessionEndHookInput input)
{
await RunConfiguredHooksAsync(
configuredHooks.SessionEnd,
hookCommandRunner,
command.ProjectPath,
SerializeHookInput(new FileSessionEndHookInput
{
Timestamp = input.Timestamp,
Cwd = input.Cwd,
Reason = input.Reason,
FinalMessage = input.FinalMessage,
Error = input.Error,
}))
.ConfigureAwait(false);
return null;
}
private static async Task<ErrorOccurredHookOutput?> RunErrorOccurredHooksAsync(
RunTurnCommandDto command,
ResolvedHookSet configuredHooks,
IHookCommandRunner hookCommandRunner,
ErrorOccurredHookInput input)
{
await RunConfiguredHooksAsync(
configuredHooks.ErrorOccurred,
hookCommandRunner,
command.ProjectPath,
SerializeHookInput(new FileErrorOccurredHookInput
{
Timestamp = input.Timestamp,
Cwd = input.Cwd,
Error = new FileHookError
{
Message = input.Error,
Context = input.ErrorContext,
Recoverable = input.Recoverable,
},
}))
.ConfigureAwait(false);
return null;
}
private static async Task RunConfiguredHooksAsync(
IReadOnlyList<HookCommandDefinition> hooks,
IHookCommandRunner hookCommandRunner,
string projectPath,
string payload)
{
if (hooks.Count == 0)
{
return;
}
foreach (HookCommandDefinition hook in hooks)
{
await hookCommandRunner.RunAsync(
hook,
payload,
projectPath,
CancellationToken.None)
.ConfigureAwait(false);
}
}
private static PreToolUseHookOutput CreateApprovalPolicyOutput(
RunTurnCommandDto command,
PatternAgentDefinitionDto agentDefinition,
PreToolUseHookInput input)
{
bool requiresApproval = CopilotApprovalCoordinator.RequiresToolCallApproval(
command.Pattern.ApprovalPolicy,
agentDefinition.Id,
Normalize(input.ToolName),
Normalize(input.ToolName));
return new PreToolUseHookOutput
{
PermissionDecision = requiresApproval ? AskDecision : AllowDecision,
};
}
private static PreToolUseHookOutput? ParsePreToolUseDecision(string? hookOutput)
{
if (string.IsNullOrWhiteSpace(hookOutput))
{
return null;
}
try
{
FilePreToolUseHookOutput? parsed = JsonSerializer.Deserialize<FilePreToolUseHookOutput>(hookOutput, HookJsonOptions);
if (!string.Equals(parsed?.PermissionDecision, DenyDecision, StringComparison.OrdinalIgnoreCase))
{
return null;
}
return new PreToolUseHookOutput
{
PermissionDecision = DenyDecision,
PermissionDecisionReason = Normalize(parsed?.PermissionDecisionReason),
};
}
catch (JsonException exception)
{
Console.Error.WriteLine($"[aryx hooks] Ignoring invalid preToolUse hook output: {exception.Message}");
return null;
}
}
private static string SerializeHookInput<T>(T input)
=> JsonSerializer.Serialize(input, HookJsonOptions);
private static string SerializeHookValue(object? value)
=> JsonSerializer.Serialize(value, HookJsonOptions);
private static string? Normalize(string? value)
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
private sealed class FileSessionStartHookInput
{
public long Timestamp { get; init; }
public string Cwd { get; init; } = string.Empty;
public string Source { get; init; } = string.Empty;
public string? InitialPrompt { get; init; }
}
private sealed class FileSessionEndHookInput
{
public long Timestamp { get; init; }
public string Cwd { get; init; } = string.Empty;
public string Reason { get; init; } = string.Empty;
public string? FinalMessage { get; init; }
public string? Error { get; init; }
}
private sealed class FileUserPromptSubmittedHookInput
{
public long Timestamp { get; init; }
public string Cwd { get; init; } = string.Empty;
public string Prompt { get; init; } = string.Empty;
}
private sealed class FilePreToolUseHookInput
{
public long Timestamp { get; init; }
public string Cwd { get; init; } = string.Empty;
public string ToolName { get; init; } = string.Empty;
public string ToolArgs { get; init; } = "null";
}
private sealed class FilePostToolUseHookInput
{
public long Timestamp { get; init; }
public string Cwd { get; init; } = string.Empty;
public string ToolName { get; init; } = string.Empty;
public string ToolArgs { get; init; } = "null";
public object? ToolResult { get; init; }
}
private sealed class FileErrorOccurredHookInput
{
public long Timestamp { get; init; }
public string Cwd { get; init; } = string.Empty;
public FileHookError Error { get; init; } = new();
}
private sealed class FileHookError
{
public string Message { get; init; } = string.Empty;
public string Context { get; init; } = string.Empty;
public bool Recoverable { get; init; }
}
private sealed class FilePreToolUseHookOutput
{
public string? PermissionDecision { get; init; }
public string? PermissionDecisionReason { get; init; }
}
}
@@ -0,0 +1,134 @@
using Aryx.AgentHost.Contracts;
using GitHub.Copilot.SDK;
using GitHub.Copilot.SDK.Rpc;
namespace Aryx.AgentHost.Services;
internal sealed class CopilotSessionManager : ICopilotSessionManager
{
public async Task<IReadOnlyDictionary<string, QuotaSnapshotDto>> GetQuotaAsync(
CancellationToken cancellationToken)
{
await using CopilotClient client = await CreateStartedClientAsync(cancellationToken).ConfigureAwait(false);
AccountGetQuotaResult result = await client.Rpc.Account.GetQuotaAsync(cancellationToken).ConfigureAwait(false);
return QuotaSnapshotMapper.Map(result.QuotaSnapshots);
}
public async Task<IReadOnlyList<CopilotSessionInfoDto>> ListSessionsAsync(
CopilotSessionListFilterDto? filter,
CancellationToken cancellationToken)
{
await using CopilotClient client = await CreateStartedClientAsync(cancellationToken).ConfigureAwait(false);
List<SessionMetadata> sessions = await client.ListSessionsAsync(CreateFilter(filter), cancellationToken)
.ConfigureAwait(false);
return sessions
.Select(MapSession)
.OrderByDescending(session => session.ModifiedTime, StringComparer.Ordinal)
.ToList();
}
public async Task<IReadOnlyList<CopilotSessionInfoDto>> DeleteSessionsAsync(
string? aryxSessionId,
string? copilotSessionId,
CancellationToken cancellationToken)
{
string? normalizedAryxSessionId = Normalize(aryxSessionId);
string? normalizedCopilotSessionId = Normalize(copilotSessionId);
if (normalizedAryxSessionId is null && normalizedCopilotSessionId is null)
{
throw new InvalidOperationException("delete-session requires a sessionId or copilotSessionId.");
}
await using CopilotClient client = await CreateStartedClientAsync(cancellationToken).ConfigureAwait(false);
List<SessionMetadata> sessions = await client.ListSessionsAsync(null, cancellationToken).ConfigureAwait(false);
List<CopilotSessionInfoDto> targets = sessions
.Select(MapSession)
.Where(session =>
(normalizedCopilotSessionId is not null
&& string.Equals(session.CopilotSessionId, normalizedCopilotSessionId, StringComparison.Ordinal))
|| (normalizedAryxSessionId is not null
&& string.Equals(session.SessionId, normalizedAryxSessionId, StringComparison.Ordinal)
&& session.ManagedByAryx))
.ToList();
if (targets.Count == 0 && normalizedCopilotSessionId is not null)
{
targets.Add(CreateUnknownSessionInfo(normalizedCopilotSessionId));
}
foreach (CopilotSessionInfoDto target in targets)
{
await client.DeleteSessionAsync(target.CopilotSessionId, cancellationToken).ConfigureAwait(false);
}
return targets;
}
private static async Task<CopilotClient> CreateStartedClientAsync(CancellationToken cancellationToken)
{
CopilotClient client = new(CopilotCliPathResolver.CreateClientOptions());
await client.StartAsync(cancellationToken).ConfigureAwait(false);
return client;
}
private static SessionListFilter? CreateFilter(CopilotSessionListFilterDto? filter)
{
if (filter is null)
{
return null;
}
return new SessionListFilter
{
Cwd = Normalize(filter.Cwd),
GitRoot = Normalize(filter.GitRoot),
Repository = Normalize(filter.Repository),
Branch = Normalize(filter.Branch),
};
}
private static CopilotSessionInfoDto MapSession(SessionMetadata session)
{
bool managedByAryx = CopilotManagedSessionIds.TryParse(
session.SessionId,
out string aryxSessionId,
out string agentId);
return new CopilotSessionInfoDto
{
CopilotSessionId = session.SessionId,
ManagedByAryx = managedByAryx,
SessionId = managedByAryx ? aryxSessionId : null,
AgentId = managedByAryx ? agentId : null,
StartTime = session.StartTime.ToUniversalTime().ToString("O"),
ModifiedTime = session.ModifiedTime.ToUniversalTime().ToString("O"),
Summary = Normalize(session.Summary),
IsRemote = session.IsRemote,
Cwd = Normalize(session.Context?.Cwd),
GitRoot = Normalize(session.Context?.GitRoot),
Repository = Normalize(session.Context?.Repository),
Branch = Normalize(session.Context?.Branch),
};
}
private static CopilotSessionInfoDto CreateUnknownSessionInfo(string copilotSessionId)
{
bool managedByAryx = CopilotManagedSessionIds.TryParse(
copilotSessionId,
out string aryxSessionId,
out string agentId);
return new CopilotSessionInfoDto
{
CopilotSessionId = copilotSessionId,
ManagedByAryx = managedByAryx,
SessionId = managedByAryx ? aryxSessionId : null,
AgentId = managedByAryx ? agentId : null,
};
}
private static string? Normalize(string? value)
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
@@ -9,6 +9,8 @@ internal sealed class CopilotTurnExecutionState
{
private readonly RunTurnCommandDto _command;
private readonly HashSet<string> _startedAgents = new(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentQueue<SidecarEventDto> _pendingEvents = new();
private readonly ConcurrentQueue<McpOauthRequiredEventDto> _pendingMcpOauthRequests = new();
private readonly ConcurrentDictionary<string, AgentIdentity> _observedAgentsByMessageId = new(StringComparer.Ordinal);
private readonly StreamingTranscriptBuffer _transcriptBuffer = new();
private int _fallbackMessageIndex;
@@ -24,31 +26,36 @@ internal sealed class CopilotTurnExecutionState
public List<ChatMessageDto> CompletedMessages { get; private set; } = [];
public bool HasPendingExitPlanModeRequest { get; private set; }
public bool SuppressHookLifecycleEvents { get; set; }
public async Task EmitThinkingIfNeeded(
AgentIdentity agent,
Func<AgentActivityEventDto, Task> onActivity)
Func<SidecarEventDto, Task> onEvent)
{
ActiveAgent = agent;
if (!_startedAgents.Add(agent.AgentId))
AgentActivityEventDto? thinkingActivity = CreateThinkingActivityIfNeeded(agent);
if (thinkingActivity is null)
{
return;
}
await onActivity(new AgentActivityEventDto
{
Type = "agent-activity",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
ActivityType = "thinking",
AgentId = agent.AgentId,
AgentName = agent.AgentName,
}).ConfigureAwait(false);
await onEvent(thinkingActivity).ConfigureAwait(false);
}
public void ApplyActivity(AgentActivityEventDto activity)
public void QueueThinkingIfNeeded(AgentIdentity agent)
{
if (string.Equals(activity.ActivityType, "handoff", StringComparison.Ordinal)
AgentActivityEventDto? thinkingActivity = CreateThinkingActivityIfNeeded(agent);
if (thinkingActivity is not null)
{
_pendingEvents.Enqueue(thinkingActivity);
}
}
public void ApplyEvent(SidecarEventDto evt)
{
if (evt is AgentActivityEventDto activity
&& string.Equals(activity.ActivityType, "handoff", StringComparison.Ordinal)
&& !string.IsNullOrWhiteSpace(activity.AgentId)
&& !string.IsNullOrWhiteSpace(activity.AgentName))
{
@@ -67,16 +74,117 @@ internal sealed class CopilotTurnExecutionState
{
case AssistantMessageDeltaEvent messageDelta when !string.IsNullOrWhiteSpace(messageDelta.Data?.MessageId):
RecordObservedAgentForMessage(agent, messageDelta.Data!.MessageId);
QueueThinkingIfNeeded(agent);
break;
case AssistantMessageEvent assistantMessage when !string.IsNullOrWhiteSpace(assistantMessage.Data?.MessageId):
RecordObservedAgentForMessage(agent, assistantMessage.Data!.MessageId);
QueueThinkingIfNeeded(agent);
break;
case ToolExecutionStartEvent toolExecutionStart
when !string.IsNullOrWhiteSpace(toolExecutionStart.Data?.ToolCallId)
&& !string.IsNullOrWhiteSpace(toolExecutionStart.Data?.ToolName):
ToolNamesByCallId[toolExecutionStart.Data.ToolCallId.Trim()] = toolExecutionStart.Data.ToolName.Trim();
break;
case AssistantReasoningDeltaEvent:
ActiveAgent = agent;
QueueThinkingIfNeeded(agent);
break;
case SubagentStartedEvent started:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreateSubagentEvent(agent, "started", started.Data));
break;
case SubagentCompletedEvent completed:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreateSubagentCompletedEvent(agent, completed.Data));
break;
case SubagentFailedEvent failed:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreateSubagentFailedEvent(agent, failed.Data));
break;
case SubagentSelectedEvent selected:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreateSubagentSelectedEvent(agent, selected.Data));
break;
case SubagentDeselectedEvent:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreateSubagentDeselectedEvent(agent));
break;
case SkillInvokedEvent skillInvoked:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreateSkillInvokedEvent(agent, skillInvoked.Data));
break;
case HookStartEvent hookStart:
ActiveAgent = agent;
if (!SuppressHookLifecycleEvents)
{
_pendingEvents.Enqueue(CreateHookLifecycleEvent(agent, "start", hookStart.Data));
}
break;
case HookEndEvent hookEnd:
ActiveAgent = agent;
if (!SuppressHookLifecycleEvents)
{
_pendingEvents.Enqueue(CreateHookLifecycleEvent(agent, "end", hookEnd.Data));
}
break;
case AssistantUsageEvent assistantUsage:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreateAssistantUsageEvent(agent, assistantUsage.Data));
break;
case SessionUsageInfoEvent usageInfo:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreateUsageEvent(agent, usageInfo.Data));
break;
case SessionCompactionStartEvent compactionStart:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreateCompactionStartEvent(agent, compactionStart.Data));
break;
case SessionCompactionCompleteEvent compactionComplete:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreateCompactionCompleteEvent(agent, compactionComplete.Data));
break;
case PendingMessagesModifiedEvent:
ActiveAgent = agent;
_pendingEvents.Enqueue(CreatePendingMessagesModifiedEvent(agent));
break;
case McpOauthRequiredEvent:
ActiveAgent = agent;
break;
case ExitPlanModeRequestedEvent:
HasPendingExitPlanModeRequest = true;
ActiveAgent = agent;
break;
}
}
public IReadOnlyList<SidecarEventDto> DrainPendingEvents()
{
List<SidecarEventDto> pending = [];
while (_pendingEvents.TryDequeue(out SidecarEventDto? pendingEvent))
{
pending.Add(pendingEvent);
}
return pending;
}
public void EnqueuePendingMcpOauthRequest(McpOauthRequiredEventDto request)
{
ArgumentNullException.ThrowIfNull(request);
_pendingMcpOauthRequests.Enqueue(request);
}
public IReadOnlyList<McpOauthRequiredEventDto> DrainPendingMcpOauthRequests()
{
List<McpOauthRequiredEventDto> pending = [];
while (_pendingMcpOauthRequests.TryDequeue(out McpOauthRequiredEventDto? request))
{
pending.Add(request);
}
return pending;
}
public bool TryResolveObservedAgentForMessage(string? messageId, out AgentIdentity agent)
{
agent = default;
@@ -112,6 +220,26 @@ internal sealed class CopilotTurnExecutionState
_observedAgentsByMessageId[messageId] = agent;
}
private AgentActivityEventDto? CreateThinkingActivityIfNeeded(AgentIdentity agent)
{
ActiveAgent = agent;
if (!_startedAgents.Add(agent.AgentId))
{
return null;
}
return new AgentActivityEventDto
{
Type = "agent-activity",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
ActivityType = "thinking",
AgentId = agent.AgentId,
AgentName = agent.AgentName,
};
}
public void UpdateCompletedMessages(
IReadOnlyList<ChatMessage> allMessages,
IReadOnlyList<ChatMessage> inputMessages)
@@ -137,4 +265,252 @@ internal sealed class CopilotTurnExecutionState
return CompletedMessages;
}
private SubagentEventDto CreateSubagentEvent(
AgentIdentity agent,
string eventKind,
SubagentStartedData? data)
{
return new SubagentEventDto
{
Type = "subagent-event",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
EventKind = eventKind,
AgentId = agent.AgentId,
AgentName = agent.AgentName,
ToolCallId = data?.ToolCallId,
CustomAgentName = data?.AgentName,
CustomAgentDisplayName = data?.AgentDisplayName,
CustomAgentDescription = data?.AgentDescription,
};
}
private SubagentEventDto CreateSubagentCompletedEvent(
AgentIdentity agent,
SubagentCompletedData? data)
{
return new SubagentEventDto
{
Type = "subagent-event",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
EventKind = "completed",
AgentId = agent.AgentId,
AgentName = agent.AgentName,
ToolCallId = data?.ToolCallId,
CustomAgentName = data?.AgentName,
CustomAgentDisplayName = data?.AgentDisplayName,
};
}
private SubagentEventDto CreateSubagentFailedEvent(
AgentIdentity agent,
SubagentFailedData? data)
{
return new SubagentEventDto
{
Type = "subagent-event",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
EventKind = "failed",
AgentId = agent.AgentId,
AgentName = agent.AgentName,
ToolCallId = data?.ToolCallId,
CustomAgentName = data?.AgentName,
CustomAgentDisplayName = data?.AgentDisplayName,
Error = data?.Error,
};
}
private SubagentEventDto CreateSubagentSelectedEvent(
AgentIdentity agent,
SubagentSelectedData? data)
{
return new SubagentEventDto
{
Type = "subagent-event",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
EventKind = "selected",
AgentId = agent.AgentId,
AgentName = agent.AgentName,
CustomAgentName = data?.AgentName,
CustomAgentDisplayName = data?.AgentDisplayName,
Tools = data?.Tools,
};
}
private SubagentEventDto CreateSubagentDeselectedEvent(AgentIdentity agent)
{
return new SubagentEventDto
{
Type = "subagent-event",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
EventKind = "deselected",
AgentId = agent.AgentId,
AgentName = agent.AgentName,
};
}
private SkillInvokedEventDto CreateSkillInvokedEvent(
AgentIdentity agent,
SkillInvokedData? data)
{
return new SkillInvokedEventDto
{
Type = "skill-invoked",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
AgentId = agent.AgentId,
AgentName = agent.AgentName,
SkillName = data?.Name ?? string.Empty,
Path = data?.Path ?? string.Empty,
Content = data?.Content ?? string.Empty,
AllowedTools = data?.AllowedTools,
PluginName = data?.PluginName,
PluginVersion = data?.PluginVersion,
};
}
private HookLifecycleEventDto CreateHookLifecycleEvent(
AgentIdentity agent,
string phase,
HookStartData? data)
{
return new HookLifecycleEventDto
{
Type = "hook-lifecycle",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
AgentId = agent.AgentId,
AgentName = agent.AgentName,
HookInvocationId = data?.HookInvocationId ?? string.Empty,
HookType = data?.HookType ?? string.Empty,
Phase = phase,
Input = data?.Input,
};
}
private HookLifecycleEventDto CreateHookLifecycleEvent(
AgentIdentity agent,
string phase,
HookEndData? data)
{
return new HookLifecycleEventDto
{
Type = "hook-lifecycle",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
AgentId = agent.AgentId,
AgentName = agent.AgentName,
HookInvocationId = data?.HookInvocationId ?? string.Empty,
HookType = data?.HookType ?? string.Empty,
Phase = phase,
Success = data?.Success,
Output = data?.Output,
Error = data?.Error?.Message,
};
}
private AssistantUsageEventDto CreateAssistantUsageEvent(
AgentIdentity agent,
AssistantUsageData? data)
{
return new AssistantUsageEventDto
{
Type = "assistant-usage",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
AgentId = agent.AgentId,
AgentName = agent.AgentName,
Model = data?.Model ?? string.Empty,
InputTokens = data?.InputTokens,
OutputTokens = data?.OutputTokens,
CacheReadTokens = data?.CacheReadTokens,
CacheWriteTokens = data?.CacheWriteTokens,
Cost = data?.Cost,
Duration = data?.Duration,
TotalNanoAiu = data?.CopilotUsage?.TotalNanoAiu,
QuotaSnapshots = QuotaSnapshotMapper.MapOrNull(data?.QuotaSnapshots),
};
}
private SessionUsageEventDto CreateUsageEvent(AgentIdentity agent, SessionUsageInfoData? data)
{
return new SessionUsageEventDto
{
Type = "session-usage",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
AgentId = agent.AgentId,
AgentName = agent.AgentName,
TokenLimit = data?.TokenLimit ?? 0,
CurrentTokens = data?.CurrentTokens ?? 0,
MessagesLength = data?.MessagesLength ?? 0,
SystemTokens = data?.SystemTokens,
ConversationTokens = data?.ConversationTokens,
ToolDefinitionsTokens = data?.ToolDefinitionsTokens,
IsInitial = data?.IsInitial,
};
}
private SessionCompactionEventDto CreateCompactionStartEvent(
AgentIdentity agent,
SessionCompactionStartData? data)
{
return new SessionCompactionEventDto
{
Type = "session-compaction",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
AgentId = agent.AgentId,
AgentName = agent.AgentName,
Phase = "start",
SystemTokens = data?.SystemTokens,
ConversationTokens = data?.ConversationTokens,
ToolDefinitionsTokens = data?.ToolDefinitionsTokens,
};
}
private SessionCompactionEventDto CreateCompactionCompleteEvent(
AgentIdentity agent,
SessionCompactionCompleteData? data)
{
return new SessionCompactionEventDto
{
Type = "session-compaction",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
AgentId = agent.AgentId,
AgentName = agent.AgentName,
Phase = "complete",
Success = data?.Success,
Error = data?.Error,
SystemTokens = data?.SystemTokens,
ConversationTokens = data?.ConversationTokens,
ToolDefinitionsTokens = data?.ToolDefinitionsTokens,
PreCompactionTokens = data?.PreCompactionTokens,
PostCompactionTokens = data?.PostCompactionTokens,
PreCompactionMessagesLength = data?.PreCompactionMessagesLength,
MessagesRemoved = data?.MessagesRemoved,
TokensRemoved = data?.TokensRemoved,
SummaryContent = data?.SummaryContent,
CheckpointNumber = data?.CheckpointNumber,
CheckpointPath = data?.CheckpointPath,
};
}
private PendingMessagesModifiedEventDto CreatePendingMessagesModifiedEvent(AgentIdentity agent)
{
return new PendingMessagesModifiedEventDto
{
Type = "pending-messages-modified",
RequestId = _command.RequestId,
SessionId = _command.SessionId,
AgentId = agent.AgentId,
AgentName = agent.AgentName,
};
}
}
@@ -0,0 +1,153 @@
using System.Collections.Concurrent;
using Aryx.AgentHost.Contracts;
using GitHub.Copilot.SDK;
namespace Aryx.AgentHost.Services;
internal sealed class CopilotUserInputCoordinator
{
private readonly ConcurrentDictionary<string, PendingUserInputRequest> _pendingUserInputs = new(StringComparer.Ordinal);
public Task ResolveUserInputAsync(
ResolveUserInputCommandDto command,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(command);
string userInputId = RequireUserInputId(command.UserInputId);
PendingUserInputRequest pending = GetPendingUserInput(userInputId);
UserInputResponse response = new()
{
Answer = command.Answer ?? string.Empty,
WasFreeform = command.WasFreeform,
};
if (!pending.Response.TrySetResult(response))
{
throw new InvalidOperationException($"User input request \"{userInputId}\" is no longer pending.");
}
return Task.CompletedTask;
}
public async Task<UserInputResponse> RequestUserInputAsync(
RunTurnCommandDto command,
PatternAgentDefinitionDto agent,
UserInputRequest request,
UserInputInvocation invocation,
Func<UserInputRequestedEventDto, Task> onUserInput,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(command);
ArgumentNullException.ThrowIfNull(agent);
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(invocation);
ArgumentNullException.ThrowIfNull(onUserInput);
PendingUserInputRequest pending = CreatePendingUserInput(command);
if (!_pendingUserInputs.TryAdd(pending.UserInputId, pending))
{
throw new InvalidOperationException($"User input request \"{pending.UserInputId}\" is already pending.");
}
try
{
await onUserInput(BuildUserInputRequestedEvent(command, agent, request, pending.UserInputId))
.ConfigureAwait(false);
using CancellationTokenRegistration registration = cancellationToken.Register(
static state =>
{
((TaskCompletionSource<UserInputResponse>)state!)
.TrySetCanceled();
},
pending.Response);
return await pending.Response.Task.ConfigureAwait(false);
}
finally
{
_pendingUserInputs.TryRemove(pending.UserInputId, out _);
}
}
internal static UserInputRequestedEventDto BuildUserInputRequestedEvent(
RunTurnCommandDto command,
PatternAgentDefinitionDto agent,
UserInputRequest request,
string userInputId)
{
ArgumentNullException.ThrowIfNull(command);
ArgumentNullException.ThrowIfNull(agent);
ArgumentNullException.ThrowIfNull(request);
string? normalizedAgentId = NormalizeOptionalString(agent.Id);
string? normalizedAgentName = NormalizeOptionalString(agent.Name) ?? normalizedAgentId;
return new UserInputRequestedEventDto
{
Type = "user-input-requested",
RequestId = command.RequestId,
SessionId = command.SessionId,
UserInputId = userInputId,
AgentId = normalizedAgentId,
AgentName = normalizedAgentName,
Question = NormalizeOptionalString(request.Question) ?? string.Empty,
Choices = NormalizeOptionalStringList(request.Choices ?? []),
AllowFreeform = request.AllowFreeform,
};
}
private static PendingUserInputRequest CreatePendingUserInput(RunTurnCommandDto command)
{
return new PendingUserInputRequest(
command.RequestId,
command.SessionId,
CreateUserInputRequestId(),
new TaskCompletionSource<UserInputResponse>(TaskCreationOptions.RunContinuationsAsynchronously));
}
private PendingUserInputRequest GetPendingUserInput(string userInputId)
{
if (_pendingUserInputs.TryGetValue(userInputId, out PendingUserInputRequest? pending))
{
return pending;
}
throw new InvalidOperationException($"User input request \"{userInputId}\" is not pending.");
}
private static string RequireUserInputId(string? userInputId)
{
string? normalizedUserInputId = NormalizeOptionalString(userInputId);
return normalizedUserInputId
?? throw new InvalidOperationException("User input ID is required.");
}
private static string CreateUserInputRequestId()
{
return $"user-input-{Guid.NewGuid():N}";
}
private static string? NormalizeOptionalString(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
private static IReadOnlyList<string>? NormalizeOptionalStringList(IEnumerable<string?> values)
{
List<string> normalized = values
.Select(NormalizeOptionalString)
.Where(static value => value is not null)
.Cast<string>()
.ToList();
return normalized.Count > 0 ? normalized : null;
}
private sealed record PendingUserInputRequest(
string RequestId,
string SessionId,
string UserInputId,
TaskCompletionSource<UserInputResponse> Response);
}
@@ -1,4 +1,6 @@
using System.Linq;
using Aryx.AgentHost.Contracts;
using GitHub.Copilot.SDK;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.AI;
@@ -6,8 +8,12 @@ namespace Aryx.AgentHost.Services;
public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
{
private const string HandoffFunctionPrefix = "handoff_to_";
private readonly PatternValidator _patternValidator;
private readonly CopilotApprovalCoordinator _approvalCoordinator = new();
private readonly CopilotUserInputCoordinator _userInputCoordinator = new();
private readonly CopilotMcpOAuthCoordinator _mcpOAuthCoordinator = new();
private readonly CopilotExitPlanModeCoordinator _exitPlanModeCoordinator = new();
public CopilotWorkflowRunner(PatternValidator patternValidator)
{
@@ -17,8 +23,11 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
public async Task<IReadOnlyList<ChatMessageDto>> RunTurnAsync(
RunTurnCommandDto command,
Func<TurnDeltaEventDto, Task> onDelta,
Func<AgentActivityEventDto, Task> onActivity,
Func<SidecarEventDto, Task> onEvent,
Func<ApprovalRequestedEventDto, Task> onApproval,
Func<UserInputRequestedEventDto, Task> onUserInput,
Func<McpOauthRequiredEventDto, Task> onMcpOAuthRequired,
Func<ExitPlanModeRequestedEventDto, Task> onExitPlanMode,
CancellationToken cancellationToken)
{
PatternValidationIssueDto? validationError = _patternValidator.Validate(command.Pattern).FirstOrDefault();
@@ -28,35 +37,116 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
}
CopilotTurnExecutionState state = new(command);
await using CopilotAgentBundle bundle = await CopilotAgentBundle.CreateAsync(
command,
(agent, request, invocation) => _approvalCoordinator.RequestApprovalAsync(
command,
agent,
request,
invocation,
state.ToolNamesByCallId,
onApproval,
cancellationToken),
(agent, sessionEvent) => state.ObserveSessionEvent(agent, sessionEvent),
cancellationToken);
Workflow workflow = bundle.BuildWorkflow(command.Pattern);
List<ChatMessage> inputMessages = command.Messages.Select(WorkflowTranscriptProjector.ToChatMessage).ToList();
using CancellationTokenSource runCancellation =
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
await using StreamingRun run = await InProcessExecution.RunStreamingAsync(workflow, inputMessages).ConfigureAwait(false);
await run.TrySendMessageAsync(new TurnToken(emitEvents: true)).ConfigureAwait(false);
await foreach (WorkflowEvent evt in run.WatchStreamAsync(cancellationToken).ConfigureAwait(false))
try
{
bool shouldEndTurn = await HandleWorkflowEventAsync(command, evt, inputMessages, state, onDelta, onActivity)
.ConfigureAwait(false);
if (shouldEndTurn)
{
break;
}
}
await using CopilotAgentBundle bundle = await CopilotAgentBundle.CreateAsync(
command,
(agent, request, invocation) => _approvalCoordinator.RequestApprovalAsync(
command,
agent,
request,
invocation,
state.ToolNamesByCallId,
onApproval,
runCancellation.Token),
(agent, request, invocation) => _userInputCoordinator.RequestUserInputAsync(
command,
agent,
request,
invocation,
onUserInput,
runCancellation.Token),
(agent, sessionEvent) =>
{
state.ObserveSessionEvent(agent, sessionEvent);
if (sessionEvent is McpOauthRequiredEvent mcpOauthRequired)
{
state.EnqueuePendingMcpOauthRequest(
_mcpOAuthCoordinator.BuildMcpOauthRequiredEvent(command, agent, mcpOauthRequired));
}
return state.FinalizeCompletedMessages();
if (sessionEvent is ExitPlanModeRequestedEvent exitPlanModeRequested)
{
_exitPlanModeCoordinator.RecordExitPlanModeRequest(command, agent, exitPlanModeRequested);
runCancellation.Cancel();
}
},
runCancellation.Token);
ConfigureHookLifecycleEventSuppression(state, bundle);
Workflow workflow = bundle.BuildWorkflow(command.Pattern);
List<ChatMessage> inputMessages = command.Messages.Select(WorkflowTranscriptProjector.ToChatMessage).ToList();
WorkflowTranscriptProjector.AttachMessageMode(inputMessages, command.MessageMode);
await using StreamingRun run = await InProcessExecution.RunStreamingAsync(workflow, inputMessages).ConfigureAwait(false);
await run.TrySendMessageAsync(new TurnToken(emitEvents: true)).ConfigureAwait(false);
await foreach (WorkflowEvent evt in run.WatchStreamAsync(runCancellation.Token).ConfigureAwait(false))
{
bool shouldEndTurn = await HandleWorkflowEventAsync(command, evt, inputMessages, state, onDelta, onEvent)
.ConfigureAwait(false);
await EmitPendingEventsAsync(state, onEvent).ConfigureAwait(false);
await EmitPendingMcpOauthRequestsAsync(state, onMcpOAuthRequired).ConfigureAwait(false);
if (shouldEndTurn)
{
break;
}
}
await EmitPendingEventsAsync(state, onEvent).ConfigureAwait(false);
await EmitPendingMcpOauthRequestsAsync(state, onMcpOAuthRequired).ConfigureAwait(false);
return state.FinalizeCompletedMessages();
}
catch (OperationCanceledException) when (runCancellation.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
await EmitPendingEventsAsync(state, onEvent).ConfigureAwait(false);
await EmitPendingMcpOauthRequestsAsync(state, onMcpOAuthRequired).ConfigureAwait(false);
ExitPlanModeRequestedEventDto? exitPlanModeEvent =
_exitPlanModeCoordinator.ConsumePendingRequest(command.RequestId);
if (exitPlanModeEvent is null || !state.HasPendingExitPlanModeRequest)
{
throw;
}
await onExitPlanMode(exitPlanModeEvent).ConfigureAwait(false);
return state.FinalizeCompletedMessages();
}
finally
{
_approvalCoordinator.ClearRequestApprovals(command.RequestId);
}
}
internal static void ConfigureHookLifecycleEventSuppression(
CopilotTurnExecutionState state,
CopilotAgentBundle bundle)
{
ArgumentNullException.ThrowIfNull(state);
ArgumentNullException.ThrowIfNull(bundle);
state.SuppressHookLifecycleEvents = !bundle.HasConfiguredHooks;
}
private static async Task EmitPendingEventsAsync(
CopilotTurnExecutionState state,
Func<SidecarEventDto, Task> onEvent)
{
foreach (SidecarEventDto pendingEvent in state.DrainPendingEvents())
{
await onEvent(pendingEvent).ConfigureAwait(false);
}
}
private static async Task EmitPendingMcpOauthRequestsAsync(
CopilotTurnExecutionState state,
Func<McpOauthRequiredEventDto, Task> onMcpOAuthRequired)
{
foreach (McpOauthRequiredEventDto request in state.DrainPendingMcpOauthRequests())
{
await onMcpOAuthRequired(request).ConfigureAwait(false);
}
}
public Task ResolveApprovalAsync(
@@ -66,21 +156,36 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
return _approvalCoordinator.ResolveApprovalAsync(command, cancellationToken);
}
public Task ResolveUserInputAsync(
ResolveUserInputCommandDto command,
CancellationToken cancellationToken)
{
return _userInputCoordinator.ResolveUserInputAsync(command, cancellationToken);
}
private static async Task<bool> HandleWorkflowEventAsync(
RunTurnCommandDto command,
WorkflowEvent evt,
IReadOnlyList<ChatMessage> inputMessages,
CopilotTurnExecutionState state,
Func<TurnDeltaEventDto, Task> onDelta,
Func<AgentActivityEventDto, Task> onActivity)
Func<SidecarEventDto, Task> onEvent)
{
if (evt is ExecutorInvokedEvent invoked
&& AgentIdentityResolver.TryResolveKnownAgentIdentity(
if (evt is ExecutorInvokedEvent invoked)
{
if (AgentIdentityResolver.TryResolveKnownAgentIdentity(
command.Pattern,
invoked.ExecutorId,
out AgentIdentity invokedAgent))
{
await state.EmitThinkingIfNeeded(invokedAgent, onActivity).ConfigureAwait(false);
{
TraceHandoff(command, $"Executor invoked: {invoked.ExecutorId} -> {invokedAgent.AgentName} ({invokedAgent.AgentId}).");
await state.EmitThinkingIfNeeded(invokedAgent, onEvent).ConfigureAwait(false);
}
else
{
TraceHandoff(command, $"Executor invoked without a known agent match: {invoked.ExecutorId}.");
}
return false;
}
@@ -94,28 +199,39 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
if (activity is null)
{
return WorkflowRequestInfoInterpreter.RequiresUserInputTurnBoundary(command, requestInfo);
bool requiresBoundary = WorkflowRequestInfoInterpreter.RequiresUserInputTurnBoundary(command, requestInfo);
TraceHandoff(
command,
$"Request info produced no activity for data type '{requestInfo.Request.Data.TypeId}'. Requires boundary: {requiresBoundary}.");
return requiresBoundary;
}
state.ApplyActivity(activity);
await onActivity(activity).ConfigureAwait(false);
await EmitActivityAsync(command, state, activity, onEvent).ConfigureAwait(false);
return false;
}
if (evt is AgentResponseUpdateEvent update)
{
await HandleAgentResponseUpdateAsync(command, update, state, onDelta, onActivity).ConfigureAwait(false);
await HandleAgentResponseUpdateAsync(command, update, state, onDelta, onEvent).ConfigureAwait(false);
return false;
}
if (evt is ExecutorCompletedEvent completed
&& AgentIdentityResolver.TryResolveObservedAgentIdentity(
if (evt is ExecutorCompletedEvent completed)
{
if (AgentIdentityResolver.TryResolveObservedAgentIdentity(
command.Pattern,
completed.ExecutorId,
state.ActiveAgent,
out AgentIdentity completedAgent))
{
state.ClearActiveAgentIfMatching(completedAgent);
{
TraceHandoff(command, $"Executor completed: {completed.ExecutorId} -> {completedAgent.AgentName} ({completedAgent.AgentId}).");
state.ClearActiveAgentIfMatching(completedAgent);
}
else
{
TraceHandoff(command, $"Executor completed without a known agent match: {completed.ExecutorId}.");
}
return false;
}
@@ -133,10 +249,16 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
AgentResponseUpdateEvent update,
CopilotTurnExecutionState state,
Func<TurnDeltaEventDto, Task> onDelta,
Func<AgentActivityEventDto, Task> onActivity)
Func<SidecarEventDto, Task> onEvent)
{
AgentIdentity? updateAgent = null;
string authorName = update.ExecutorId;
string[] handoffFunctionCalls = update.Update.Contents
.OfType<FunctionCallContent>()
.Select(content => content.Name)
.Where(IsHandoffFunctionName)
.Distinct(StringComparer.Ordinal)
.ToArray();
if (state.TryResolveObservedAgentForMessage(update.Update.MessageId, out AgentIdentity observedMessageAgent))
{
updateAgent = observedMessageAgent;
@@ -154,7 +276,20 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
if (updateAgent.HasValue)
{
await state.EmitThinkingIfNeeded(updateAgent.Value, onActivity).ConfigureAwait(false);
if (handoffFunctionCalls.Length > 0)
{
TraceHandoff(
command,
$"Agent response update from {updateAgent.Value.AgentName} ({updateAgent.Value.AgentId}) requested handoff via {string.Join(", ", handoffFunctionCalls)}.");
}
await state.EmitThinkingIfNeeded(updateAgent.Value, onEvent).ConfigureAwait(false);
}
else if (!string.IsNullOrEmpty(update.Update.Text) || handoffFunctionCalls.Length > 0)
{
TraceHandoff(
command,
$"Agent response update could not resolve agent for executor '{update.ExecutorId}' and message '{update.Update.MessageId ?? "<none>"}'.");
}
if (string.IsNullOrEmpty(update.Update.Text))
@@ -179,4 +314,45 @@ public sealed class CopilotWorkflowRunner : ITurnWorkflowRunner
Content = currentContent,
}).ConfigureAwait(false);
}
private static async Task EmitActivityAsync(
RunTurnCommandDto command,
CopilotTurnExecutionState state,
AgentActivityEventDto activity,
Func<SidecarEventDto, Task> onEvent)
{
state.ApplyEvent(activity);
TraceHandoff(
command,
$"Activity emitted: {activity.ActivityType} -> {activity.AgentName ?? activity.AgentId ?? "<unknown>"}.");
await onEvent(activity).ConfigureAwait(false);
if (string.Equals(activity.ActivityType, "handoff", StringComparison.Ordinal)
&& !string.IsNullOrWhiteSpace(activity.AgentId)
&& !string.IsNullOrWhiteSpace(activity.AgentName))
{
TraceHandoff(
command,
$"Promoting handoff target to thinking: {activity.AgentName} ({activity.AgentId}).");
await state.EmitThinkingIfNeeded(
new AgentIdentity(activity.AgentId, activity.AgentName),
onEvent).ConfigureAwait(false);
}
}
private static bool IsHandoffFunctionName(string? candidate)
{
return !string.IsNullOrWhiteSpace(candidate)
&& candidate.StartsWith(HandoffFunctionPrefix, StringComparison.Ordinal);
}
private static void TraceHandoff(RunTurnCommandDto command, string message)
{
if (!string.Equals(command.Pattern.Mode, "handoff", StringComparison.OrdinalIgnoreCase))
{
return;
}
Console.Error.WriteLine($"[aryx handoff] {message}");
}
}
@@ -0,0 +1,220 @@
using System.ComponentModel;
using System.Diagnostics;
using Aryx.AgentHost.Contracts;
namespace Aryx.AgentHost.Services;
internal interface IHookCommandRunner
{
Task<string?> RunAsync(
HookCommandDefinition hook,
string inputJson,
string projectPath,
CancellationToken cancellationToken);
}
internal sealed class HookCommandRunner : IHookCommandRunner
{
private const int DefaultTimeoutSeconds = 30;
public static HookCommandRunner Instance { get; } = new();
public async Task<string?> RunAsync(
HookCommandDefinition hook,
string inputJson,
string projectPath,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(hook);
ArgumentNullException.ThrowIfNull(inputJson);
ArgumentException.ThrowIfNullOrWhiteSpace(projectPath);
string? commandText = SelectCommandText(hook);
if (commandText is null)
{
Console.Error.WriteLine("[aryx hooks] Skipping hook because no compatible shell command is configured for this platform.");
return null;
}
string workingDirectory = ResolveWorkingDirectory(projectPath, hook.Cwd);
ProcessStartInfo startInfo = CreateStartInfo(commandText, workingDirectory);
ApplyEnvironment(startInfo, hook.Env);
using Process process = new()
{
StartInfo = startInfo,
};
try
{
if (!process.Start())
{
Console.Error.WriteLine($"[aryx hooks] Failed to start hook command '{commandText}'.");
return null;
}
}
catch (Win32Exception exception)
{
Console.Error.WriteLine($"[aryx hooks] Failed to start hook command '{commandText}': {exception.Message}");
return null;
}
catch (InvalidOperationException exception)
{
Console.Error.WriteLine($"[aryx hooks] Failed to start hook command '{commandText}': {exception.Message}");
return null;
}
Task<string> stdoutTask = process.StandardOutput.ReadToEndAsync();
Task<string> stderrTask = process.StandardError.ReadToEndAsync();
try
{
await process.StandardInput.WriteAsync(inputJson).ConfigureAwait(false);
await process.StandardInput.FlushAsync().ConfigureAwait(false);
process.StandardInput.Close();
}
catch (IOException exception)
{
TryKillProcess(process);
Console.Error.WriteLine($"[aryx hooks] Failed to write hook input for '{commandText}': {exception.Message}");
return null;
}
catch (ObjectDisposedException exception)
{
TryKillProcess(process);
Console.Error.WriteLine($"[aryx hooks] Failed to write hook input for '{commandText}': {exception.Message}");
return null;
}
TimeSpan timeout = TimeSpan.FromSeconds(hook.TimeoutSec ?? DefaultTimeoutSeconds);
using CancellationTokenSource timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeoutCts.CancelAfter(timeout);
try
{
await process.WaitForExitAsync(timeoutCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
TryKillProcess(process);
await DrainOutputAsync(process, stdoutTask, stderrTask).ConfigureAwait(false);
Console.Error.WriteLine($"[aryx hooks] Hook command timed out after {(int)timeout.TotalSeconds} seconds: '{commandText}'.");
return null;
}
string stdout = await stdoutTask.ConfigureAwait(false);
string stderr = await stderrTask.ConfigureAwait(false);
if (process.ExitCode != 0)
{
string detail = string.IsNullOrWhiteSpace(stderr) ? $"exit code {process.ExitCode}" : stderr.Trim();
Console.Error.WriteLine($"[aryx hooks] Hook command failed for '{commandText}': {detail}");
return null;
}
return stdout;
}
private static async Task DrainOutputAsync(Process process, Task<string> stdoutTask, Task<string> stderrTask)
{
try
{
await process.WaitForExitAsync(CancellationToken.None).ConfigureAwait(false);
}
catch (InvalidOperationException)
{
// Process already exited or could not be waited on.
}
await Task.WhenAll(stdoutTask, stderrTask).ConfigureAwait(false);
}
private static ProcessStartInfo CreateStartInfo(string commandText, string workingDirectory)
{
ProcessStartInfo startInfo = new()
{
WorkingDirectory = workingDirectory,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true,
};
if (OperatingSystem.IsWindows())
{
startInfo.FileName = "powershell.exe";
startInfo.ArgumentList.Add("-NoLogo");
startInfo.ArgumentList.Add("-NoProfile");
startInfo.ArgumentList.Add("-NonInteractive");
startInfo.ArgumentList.Add("-ExecutionPolicy");
startInfo.ArgumentList.Add("Bypass");
startInfo.ArgumentList.Add("-Command");
startInfo.ArgumentList.Add(commandText);
return startInfo;
}
startInfo.FileName = "bash";
startInfo.ArgumentList.Add("-lc");
startInfo.ArgumentList.Add(commandText);
return startInfo;
}
private static void ApplyEnvironment(ProcessStartInfo startInfo, IReadOnlyDictionary<string, string>? environment)
{
if (environment is not { Count: > 0 })
{
return;
}
foreach ((string key, string value) in environment)
{
startInfo.Environment[key] = value;
}
}
private static string ResolveWorkingDirectory(string projectPath, string? configuredCwd)
{
if (string.IsNullOrWhiteSpace(configuredCwd))
{
return Path.GetFullPath(projectPath);
}
string resolved = Path.IsPathRooted(configuredCwd)
? configuredCwd
: Path.Combine(projectPath, configuredCwd);
return Path.GetFullPath(resolved);
}
private static string? SelectCommandText(HookCommandDefinition hook)
{
if (OperatingSystem.IsWindows())
{
return NormalizeOptionalString(hook.PowerShell);
}
return NormalizeOptionalString(hook.Bash);
}
private static void TryKillProcess(Process process)
{
try
{
if (!process.HasExited)
{
process.Kill(entireProcessTree: true);
}
}
catch (InvalidOperationException)
{
// Process already exited.
}
catch (NotSupportedException)
{
// The platform does not support process tree termination.
}
}
private static string? NormalizeOptionalString(string? value)
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
@@ -0,0 +1,207 @@
using System.Text.Json;
using Aryx.AgentHost.Contracts;
namespace Aryx.AgentHost.Services;
internal static class HookConfigLoader
{
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
{
AllowTrailingCommas = true,
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
};
public static async Task<ResolvedHookSet> LoadAsync(string projectPath, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(projectPath);
string hooksDirectory = Path.Combine(projectPath, ".github", "hooks");
if (!Directory.Exists(hooksDirectory))
{
return ResolvedHookSet.Empty;
}
string[] hookFiles;
try
{
hookFiles = Directory.GetFiles(hooksDirectory, "*.json", SearchOption.TopDirectoryOnly);
}
catch (IOException exception)
{
Console.Error.WriteLine($"[aryx hooks] Failed to enumerate hook files in '{hooksDirectory}': {exception.Message}");
return ResolvedHookSet.Empty;
}
catch (UnauthorizedAccessException exception)
{
Console.Error.WriteLine($"[aryx hooks] Failed to enumerate hook files in '{hooksDirectory}': {exception.Message}");
return ResolvedHookSet.Empty;
}
if (hookFiles.Length == 0)
{
return ResolvedHookSet.Empty;
}
Array.Sort(hookFiles, StringComparer.OrdinalIgnoreCase);
List<HookCommandDefinition> sessionStart = [];
List<HookCommandDefinition> sessionEnd = [];
List<HookCommandDefinition> userPromptSubmitted = [];
List<HookCommandDefinition> preToolUse = [];
List<HookCommandDefinition> postToolUse = [];
List<HookCommandDefinition> errorOccurred = [];
foreach (string hookFile in hookFiles)
{
HookConfigFile? config = await ReadHookConfigAsync(hookFile, cancellationToken).ConfigureAwait(false);
if (config is null)
{
continue;
}
if (config.Version != 1)
{
Console.Error.WriteLine($"[aryx hooks] Skipping '{hookFile}' because it declares unsupported version '{config.Version}'.");
continue;
}
AddHooks(sessionStart, config.Hooks.SessionStart, HookTypeNames.SessionStart, hookFile);
AddHooks(sessionEnd, config.Hooks.SessionEnd, HookTypeNames.SessionEnd, hookFile);
AddHooks(userPromptSubmitted, config.Hooks.UserPromptSubmitted, HookTypeNames.UserPromptSubmitted, hookFile);
AddHooks(preToolUse, config.Hooks.PreToolUse, HookTypeNames.PreToolUse, hookFile);
AddHooks(postToolUse, config.Hooks.PostToolUse, HookTypeNames.PostToolUse, hookFile);
AddHooks(errorOccurred, config.Hooks.ErrorOccurred, HookTypeNames.ErrorOccurred, hookFile);
}
if (
sessionStart.Count == 0
&& sessionEnd.Count == 0
&& userPromptSubmitted.Count == 0
&& preToolUse.Count == 0
&& postToolUse.Count == 0
&& errorOccurred.Count == 0)
{
return ResolvedHookSet.Empty;
}
return new ResolvedHookSet
{
SessionStart = [.. sessionStart],
SessionEnd = [.. sessionEnd],
UserPromptSubmitted = [.. userPromptSubmitted],
PreToolUse = [.. preToolUse],
PostToolUse = [.. postToolUse],
ErrorOccurred = [.. errorOccurred],
};
}
private static void AddHooks(
ICollection<HookCommandDefinition> target,
IReadOnlyList<HookCommandDefinition>? definitions,
string hookType,
string hookFile)
{
if (definitions is not { Count: > 0 })
{
return;
}
foreach (HookCommandDefinition definition in definitions)
{
HookCommandDefinition? normalized = NormalizeDefinition(definition, hookType, hookFile);
if (normalized is not null)
{
target.Add(normalized);
}
}
}
private static HookCommandDefinition? NormalizeDefinition(
HookCommandDefinition definition,
string hookType,
string hookFile)
{
string type = NormalizeOptionalString(definition.Type) ?? string.Empty;
if (!string.Equals(type, "command", StringComparison.OrdinalIgnoreCase))
{
Console.Error.WriteLine($"[aryx hooks] Skipping '{hookType}' entry in '{hookFile}' because type '{definition.Type}' is unsupported.");
return null;
}
string? bash = NormalizeOptionalString(definition.Bash);
string? powerShell = NormalizeOptionalString(definition.PowerShell);
if (bash is null && powerShell is null)
{
Console.Error.WriteLine($"[aryx hooks] Skipping '{hookType}' entry in '{hookFile}' because no shell command is configured.");
return null;
}
int? timeoutSec = definition.TimeoutSec;
if (timeoutSec is <= 0)
{
timeoutSec = null;
}
IReadOnlyDictionary<string, string>? env = NormalizeEnvironment(definition.Env);
return new HookCommandDefinition
{
Type = "command",
Bash = bash,
PowerShell = powerShell,
Cwd = NormalizeOptionalString(definition.Cwd),
Env = env,
TimeoutSec = timeoutSec,
};
}
private static async Task<HookConfigFile?> ReadHookConfigAsync(string hookFile, CancellationToken cancellationToken)
{
try
{
await using FileStream stream = File.OpenRead(hookFile);
return await JsonSerializer.DeserializeAsync<HookConfigFile>(stream, JsonOptions, cancellationToken).ConfigureAwait(false);
}
catch (JsonException exception)
{
Console.Error.WriteLine($"[aryx hooks] Failed to parse '{hookFile}': {exception.Message}");
return null;
}
catch (IOException exception)
{
Console.Error.WriteLine($"[aryx hooks] Failed to read '{hookFile}': {exception.Message}");
return null;
}
catch (UnauthorizedAccessException exception)
{
Console.Error.WriteLine($"[aryx hooks] Failed to read '{hookFile}': {exception.Message}");
return null;
}
}
private static IReadOnlyDictionary<string, string>? NormalizeEnvironment(IReadOnlyDictionary<string, string>? environment)
{
if (environment is not { Count: > 0 })
{
return null;
}
Dictionary<string, string> normalized = new(StringComparer.Ordinal);
foreach ((string key, string value) in environment)
{
string? normalizedKey = NormalizeOptionalString(key);
if (normalizedKey is null)
{
continue;
}
normalized[normalizedKey] = value;
}
return normalized.Count == 0 ? null : normalized;
}
private static string? NormalizeOptionalString(string? value)
=> string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
@@ -0,0 +1,19 @@
using Aryx.AgentHost.Contracts;
namespace Aryx.AgentHost.Services;
public interface ICopilotSessionManager
{
Task<IReadOnlyList<CopilotSessionInfoDto>> ListSessionsAsync(
CopilotSessionListFilterDto? filter,
CancellationToken cancellationToken);
Task<IReadOnlyList<CopilotSessionInfoDto>> DeleteSessionsAsync(
string? aryxSessionId,
string? copilotSessionId,
CancellationToken cancellationToken);
Task<IReadOnlyDictionary<string, QuotaSnapshotDto>> GetQuotaAsync(
CancellationToken cancellationToken);
}
@@ -7,11 +7,18 @@ public interface ITurnWorkflowRunner
Task<IReadOnlyList<ChatMessageDto>> RunTurnAsync(
RunTurnCommandDto command,
Func<TurnDeltaEventDto, Task> onDelta,
Func<AgentActivityEventDto, Task> onActivity,
Func<SidecarEventDto, Task> onEvent,
Func<ApprovalRequestedEventDto, Task> onApproval,
Func<UserInputRequestedEventDto, Task> onUserInput,
Func<McpOauthRequiredEventDto, Task> onMcpOAuthRequired,
Func<ExitPlanModeRequestedEventDto, Task> onExitPlanMode,
CancellationToken cancellationToken);
Task ResolveApprovalAsync(
ResolveApprovalCommandDto command,
CancellationToken cancellationToken);
Task ResolveUserInputAsync(
ResolveUserInputCommandDto command,
CancellationToken cancellationToken);
}
@@ -0,0 +1,105 @@
using System.Text.Json;
using Aryx.AgentHost.Contracts;
using GitHub.Copilot.SDK.Rpc;
namespace Aryx.AgentHost.Services;
internal static class QuotaSnapshotMapper
{
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
{
PropertyNameCaseInsensitive = true,
};
public static Dictionary<string, QuotaSnapshotDto> Map(
IReadOnlyDictionary<string, AccountGetQuotaResultQuotaSnapshotsValue>? snapshots)
{
Dictionary<string, QuotaSnapshotDto> mapped = new(StringComparer.Ordinal);
if (snapshots is null)
{
return mapped;
}
foreach ((string key, AccountGetQuotaResultQuotaSnapshotsValue snapshot) in snapshots)
{
if (string.IsNullOrWhiteSpace(key))
{
continue;
}
mapped[key.Trim()] = Map(snapshot);
}
return mapped;
}
public static Dictionary<string, QuotaSnapshotDto>? MapOrNull(
IReadOnlyDictionary<string, object>? snapshots)
{
if (snapshots is not { Count: > 0 })
{
return null;
}
Dictionary<string, QuotaSnapshotDto> mapped = new(StringComparer.Ordinal);
foreach ((string key, object snapshot) in snapshots)
{
if (string.IsNullOrWhiteSpace(key))
{
continue;
}
QuotaSnapshotDto? mappedSnapshot = TryMap(snapshot);
if (mappedSnapshot is null)
{
continue;
}
mapped[key.Trim()] = mappedSnapshot;
}
return mapped.Count == 0 ? null : mapped;
}
public static QuotaSnapshotDto Map(AccountGetQuotaResultQuotaSnapshotsValue snapshot)
{
ArgumentNullException.ThrowIfNull(snapshot);
return new QuotaSnapshotDto
{
EntitlementRequests = snapshot.EntitlementRequests,
UsedRequests = snapshot.UsedRequests,
RemainingPercentage = snapshot.RemainingPercentage,
Overage = snapshot.Overage,
OverageAllowedWithExhaustedQuota = snapshot.OverageAllowedWithExhaustedQuota,
ResetDate = snapshot.ResetDate,
};
}
private static QuotaSnapshotDto? TryMap(object? snapshot)
{
if (snapshot is null)
{
return null;
}
if (snapshot is AccountGetQuotaResultQuotaSnapshotsValue typedSnapshot)
{
return Map(typedSnapshot);
}
JsonElement element = snapshot is JsonElement jsonElement
? jsonElement
: JsonSerializer.SerializeToElement(snapshot, JsonOptions);
if (element.ValueKind != JsonValueKind.Object)
{
return null;
}
AccountGetQuotaResultQuotaSnapshotsValue? deserialized =
element.Deserialize<AccountGetQuotaResultQuotaSnapshotsValue>(JsonOptions);
return deserialized is null ? null : Map(deserialized);
}
}
@@ -14,6 +14,18 @@ public sealed class SidecarProtocolHost
private const string RunTurnCommandType = "run-turn";
private const string CancelTurnCommandType = "cancel-turn";
private const string ResolveApprovalCommandType = "resolve-approval";
private const string ResolveUserInputCommandType = "resolve-user-input";
private const string ListSessionsCommandType = "list-sessions";
private const string DeleteSessionCommandType = "delete-session";
private const string DisconnectSessionCommandType = "disconnect-session";
private const string GetQuotaCommandType = "get-quota";
private const string AskUserToolName = "ask_user";
private static readonly HashSet<string> ExcludedRuntimeToolNames = new(StringComparer.OrdinalIgnoreCase)
{
AskUserToolName,
"report_intent",
"task_complete",
};
private static readonly string[] AuthenticationErrorIndicators =
[
@@ -31,11 +43,14 @@ public sealed class SidecarProtocolHost
private readonly Func<CancellationToken, Task<SidecarCapabilitiesDto>> _capabilitiesProvider;
private readonly PatternValidator _patternValidator;
private readonly ITurnWorkflowRunner _workflowRunner;
private readonly ICopilotSessionManager _sessionManager;
private readonly JsonSerializerOptions _jsonOptions;
private readonly IReadOnlyDictionary<string, Func<CommandContext, Task>> _commandHandlers;
private readonly SemaphoreSlim _writeLock = new(1, 1);
private readonly ConcurrentDictionary<string, Task> _inFlight = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, CancellationTokenSource> _turnCancellations = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, byte>> _turnRequestIdsBySessionId =
new(StringComparer.Ordinal);
public SidecarProtocolHost()
: this(new PatternValidator())
@@ -45,11 +60,13 @@ public sealed class SidecarProtocolHost
public SidecarProtocolHost(
PatternValidator patternValidator,
ITurnWorkflowRunner? workflowRunner = null,
Func<CancellationToken, Task<SidecarCapabilitiesDto>>? capabilitiesProvider = null)
Func<CancellationToken, Task<SidecarCapabilitiesDto>>? capabilitiesProvider = null,
ICopilotSessionManager? sessionManager = null)
{
_patternValidator = patternValidator;
_workflowRunner = workflowRunner ?? new CopilotWorkflowRunner(_patternValidator);
_capabilitiesProvider = capabilitiesProvider ?? BuildCapabilitiesAsync;
_sessionManager = sessionManager ?? new CopilotSessionManager();
_jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
@@ -62,6 +79,11 @@ public sealed class SidecarProtocolHost
[RunTurnCommandType] = HandleRunTurnAsync,
[CancelTurnCommandType] = HandleCancelTurnAsync,
[ResolveApprovalCommandType] = HandleResolveApprovalAsync,
[ResolveUserInputCommandType] = HandleResolveUserInputAsync,
[ListSessionsCommandType] = HandleListSessionsAsync,
[DeleteSessionCommandType] = HandleDeleteSessionAsync,
[DisconnectSessionCommandType] = HandleDisconnectSessionAsync,
[GetQuotaCommandType] = HandleGetQuotaAsync,
};
}
@@ -171,13 +193,17 @@ public sealed class SidecarProtocolHost
$"A turn with request ID '{context.Envelope.RequestId}' is already in progress.");
}
RegisterTurnRequest(command.SessionId, context.Envelope.RequestId);
try
{
IReadOnlyList<ChatMessageDto> messages = await _workflowRunner.RunTurnAsync(
command,
delta => WriteAsync(context.Output, delta, turnCancellation.Token),
activity => WriteAsync(context.Output, activity, turnCancellation.Token),
evt => WriteAsync(context.Output, evt, turnCancellation.Token),
approval => WriteAsync(context.Output, approval, turnCancellation.Token),
userInput => WriteAsync(context.Output, userInput, turnCancellation.Token),
mcpOauth => WriteAsync(context.Output, mcpOauth, turnCancellation.Token),
exitPlanMode => WriteAsync(context.Output, exitPlanMode, turnCancellation.Token),
turnCancellation.Token)
.ConfigureAwait(false);
@@ -204,6 +230,7 @@ public sealed class SidecarProtocolHost
finally
{
_turnCancellations.TryRemove(context.Envelope.RequestId, out _);
UnregisterTurnRequest(command.SessionId, context.Envelope.RequestId);
}
}
@@ -231,6 +258,80 @@ public sealed class SidecarProtocolHost
await _workflowRunner.ResolveApprovalAsync(command, context.CancellationToken).ConfigureAwait(false);
}
private async Task HandleResolveUserInputAsync(CommandContext context)
{
ResolveUserInputCommandDto command = DeserializeCommand<ResolveUserInputCommandDto>(context);
await _workflowRunner.ResolveUserInputAsync(command, context.CancellationToken).ConfigureAwait(false);
}
private async Task HandleListSessionsAsync(CommandContext context)
{
ListSessionsCommandDto command = DeserializeCommand<ListSessionsCommandDto>(context);
IReadOnlyList<CopilotSessionInfoDto> sessions = await _sessionManager.ListSessionsAsync(
command.Filter,
context.CancellationToken).ConfigureAwait(false);
await WriteAsync(context.Output, new SessionsListedEventDto
{
Type = "sessions-listed",
RequestId = context.Envelope.RequestId,
Sessions = sessions,
}, context.CancellationToken).ConfigureAwait(false);
}
private async Task HandleDeleteSessionAsync(CommandContext context)
{
DeleteSessionCommandDto command = DeserializeCommand<DeleteSessionCommandDto>(context);
if (!string.IsNullOrWhiteSpace(command.SessionId))
{
CancelTurnRequestsForSession(command.SessionId);
}
IReadOnlyList<CopilotSessionInfoDto> deletedSessions = await _sessionManager.DeleteSessionsAsync(
command.SessionId,
command.CopilotSessionId,
context.CancellationToken).ConfigureAwait(false);
await WriteAsync(context.Output, new SessionsDeletedEventDto
{
Type = "sessions-deleted",
RequestId = context.Envelope.RequestId,
SessionId = string.IsNullOrWhiteSpace(command.SessionId) ? null : command.SessionId.Trim(),
Sessions = deletedSessions,
}, context.CancellationToken).ConfigureAwait(false);
}
private async Task HandleDisconnectSessionAsync(CommandContext context)
{
DisconnectSessionCommandDto command = DeserializeCommand<DisconnectSessionCommandDto>(context);
IReadOnlyList<string> cancelledRequestIds = CancelTurnRequestsForSession(command.SessionId);
await WriteAsync(context.Output, new SessionDisconnectedEventDto
{
Type = "session-disconnected",
RequestId = context.Envelope.RequestId,
SessionId = command.SessionId,
CancelledRequestIds = cancelledRequestIds,
}, context.CancellationToken).ConfigureAwait(false);
}
private async Task HandleGetQuotaAsync(CommandContext context)
{
_ = DeserializeCommand<GetQuotaCommandDto>(context);
IReadOnlyDictionary<string, QuotaSnapshotDto> quotaSnapshots =
await _sessionManager.GetQuotaAsync(context.CancellationToken).ConfigureAwait(false);
await WriteAsync(context.Output, new AccountQuotaResultEventDto
{
Type = "quota-result",
RequestId = context.Envelope.RequestId,
QuotaSnapshots = quotaSnapshots.ToDictionary(
snapshot => snapshot.Key,
snapshot => snapshot.Value,
StringComparer.Ordinal),
}, context.CancellationToken).ConfigureAwait(false);
}
private TCommand DeserializeCommand<TCommand>(CommandContext context)
where TCommand : SidecarCommandEnvelope
{
@@ -291,6 +392,67 @@ public sealed class SidecarProtocolHost
}
}
private void RegisterTurnRequest(string sessionId, string requestId)
{
if (string.IsNullOrWhiteSpace(sessionId) || string.IsNullOrWhiteSpace(requestId))
{
return;
}
ConcurrentDictionary<string, byte> requestIds = _turnRequestIdsBySessionId.GetOrAdd(
sessionId.Trim(),
static _ => new ConcurrentDictionary<string, byte>(StringComparer.Ordinal));
requestIds[requestId.Trim()] = 0;
}
private void UnregisterTurnRequest(string sessionId, string requestId)
{
if (string.IsNullOrWhiteSpace(sessionId) || string.IsNullOrWhiteSpace(requestId))
{
return;
}
if (!_turnRequestIdsBySessionId.TryGetValue(sessionId.Trim(), out ConcurrentDictionary<string, byte>? requestIds))
{
return;
}
requestIds.TryRemove(requestId.Trim(), out _);
if (requestIds.IsEmpty)
{
_turnRequestIdsBySessionId.TryRemove(sessionId.Trim(), out _);
}
}
private IReadOnlyList<string> CancelTurnRequestsForSession(string sessionId)
{
if (string.IsNullOrWhiteSpace(sessionId)
|| !_turnRequestIdsBySessionId.TryGetValue(sessionId.Trim(), out ConcurrentDictionary<string, byte>? requestIds))
{
return [];
}
List<string> cancelledRequestIds = [];
foreach (string requestId in requestIds.Keys)
{
if (!_turnCancellations.TryGetValue(requestId, out CancellationTokenSource? turnCancellation))
{
continue;
}
try
{
turnCancellation.Cancel();
cancelledRequestIds.Add(requestId);
}
catch (ObjectDisposedException)
{
}
}
return cancelledRequestIds;
}
private static async Task<SidecarCapabilitiesDto> BuildCapabilitiesAsync(CancellationToken cancellationToken)
{
try
@@ -427,7 +589,13 @@ public sealed class SidecarProtocolHost
CancellationToken cancellationToken)
{
ToolsListResult result = await client.Rpc.Tools.ListAsync(null!, cancellationToken).ConfigureAwait(false);
return result.Tools
return MapRuntimeTools(result.Tools);
}
internal static IReadOnlyList<SidecarRuntimeToolDto> MapRuntimeTools(IEnumerable<Tool> tools)
{
return tools
.Where(ShouldIncludeRuntimeTool)
.Where(tool => !string.IsNullOrWhiteSpace(tool.Name))
.Select(tool => new SidecarRuntimeToolDto
{
@@ -440,6 +608,13 @@ public sealed class SidecarProtocolHost
.ToList();
}
private static bool ShouldIncludeRuntimeTool(Tool tool)
{
string? toolName = string.IsNullOrWhiteSpace(tool.Name) ? null : tool.Name.Trim();
return toolName is not null
&& !ExcludedRuntimeToolNames.Contains(toolName);
}
private static bool IsReasoningEffort(string? value)
{
return value is "low" or "medium" or "high" or "xhigh";
@@ -1,5 +1,6 @@
using System.Text;
using Aryx.AgentHost.Contracts;
using GitHub.Copilot.SDK;
using Microsoft.Extensions.AI;
namespace Aryx.AgentHost.Services;
@@ -26,9 +27,30 @@ internal static class WorkflowTranscriptProjector
mapped.AuthorName = message.AuthorName;
}
foreach (ChatMessageAttachmentDto attachment in message.Attachments)
{
mapped.Contents.Add(new AIContent
{
RawRepresentation = attachment,
});
}
return mapped;
}
public static void AttachMessageMode(IList<ChatMessage> messages, string? messageMode)
{
if (messages.Count == 0 || string.IsNullOrWhiteSpace(messageMode))
{
return;
}
messages[^1].Contents.Add(new AIContent
{
RawRepresentation = new CopilotMessageOptionsMetadata(messageMode.Trim()),
});
}
public static List<ChatMessageDto> ProjectCompletedMessages(
RunTurnCommandDto command,
IReadOnlyList<ChatMessage> newMessages,
@@ -64,7 +86,7 @@ internal static class WorkflowTranscriptProjector
assistantMessages.Count - messageIndex,
command.Pattern,
fallbackAgent);
string content = message.Text ?? matchedSegment?.Content ?? string.Empty;
string content = ResolveProjectedContent(message, matchedSegment);
if (string.IsNullOrWhiteSpace(content))
{
continue;
@@ -106,7 +128,9 @@ internal static class WorkflowTranscriptProjector
{
return new ChatMessageDto
{
Id = matchedSegment?.MessageId ?? $"{command.RequestId}-final-{fallbackOutputIndex}",
Id = matchedSegment?.MessageId
?? message.MessageId
?? $"{command.RequestId}-final-{fallbackOutputIndex}",
Role = message.Role == ChatRole.System ? "system" : "assistant",
AuthorName = ResolveProjectedAuthorName(
command.Pattern,
@@ -118,6 +142,35 @@ internal static class WorkflowTranscriptProjector
};
}
private static string ResolveProjectedContent(
ChatMessage message,
TranscriptSegment? matchedSegment)
{
return FirstNonBlank(
message.Text,
matchedSegment?.Content,
TryGetAssistantMessageContent(message))
?? string.Empty;
}
private static string? TryGetAssistantMessageContent(ChatMessage message)
{
if (TryGetAssistantMessageData(message.RawRepresentation, out AssistantMessageData? assistantMessageData))
{
return assistantMessageData?.Content;
}
foreach (AIContent content in message.Contents)
{
if (TryGetAssistantMessageData(content.RawRepresentation, out assistantMessageData))
{
return assistantMessageData?.Content;
}
}
return null;
}
private static ChatMessageDto CreateProjectedMessageFromSegment(
RunTurnCommandDto command,
TranscriptSegment segment,
@@ -339,11 +392,57 @@ internal static class WorkflowTranscriptProjector
return fallbackAgent.Value.AgentName;
}
if (fallbackAgent.HasValue
&& string.IsNullOrWhiteSpace(primaryIdentifier)
&& string.IsNullOrWhiteSpace(fallbackIdentifier))
{
return fallbackAgent.Value.AgentName;
}
if (pattern.Agents.Count == 1
&& string.IsNullOrWhiteSpace(primaryIdentifier)
&& string.IsNullOrWhiteSpace(fallbackIdentifier))
{
PatternAgentDefinitionDto singleAgent = pattern.Agents[0];
return AgentIdentityResolver.ResolveDisplayAuthorName(pattern, singleAgent.Id, singleAgent.Name);
}
return AgentIdentityResolver.ResolveDisplayAuthorName(
pattern,
primaryIdentifier,
fallbackIdentifier);
}
private static bool TryGetAssistantMessageData(
object? rawRepresentation,
out AssistantMessageData? assistantMessageData)
{
switch (rawRepresentation)
{
case AssistantMessageEvent assistantMessage when !string.IsNullOrWhiteSpace(assistantMessage.Data.Content):
assistantMessageData = assistantMessage.Data;
return true;
case AssistantMessageData data when !string.IsNullOrWhiteSpace(data.Content):
assistantMessageData = data;
return true;
default:
assistantMessageData = null;
return false;
}
}
private static string? FirstNonBlank(params string?[] values)
{
foreach (string? value in values)
{
if (!string.IsNullOrWhiteSpace(value))
{
return value;
}
}
return null;
}
}
internal sealed class StreamingTranscriptBuffer
@@ -124,6 +124,66 @@ public sealed class AgentInstructionComposerTests
Assert.DoesNotContain("Do not inspect, modify, create, or delete files", instructions, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Compose_AddsPlanModeGuidanceWhenRequested()
{
PatternDefinitionDto pattern = new()
{
Id = "pattern-single",
Name = "Single",
Mode = "single",
Availability = "available",
};
PatternAgentDefinitionDto agent = CreateAgent(
id: "agent-primary",
name: "Primary Agent",
instructions: "You are a helpful assistant.");
string instructions = AgentInstructionComposer.Compose(
pattern,
agent,
agentIndex: 0,
interactionMode: "plan");
Assert.Contains("operating in plan mode", instructions, StringComparison.OrdinalIgnoreCase);
Assert.Contains("produce a concrete implementation plan", instructions, StringComparison.OrdinalIgnoreCase);
Assert.Contains("exit_plan_mode", instructions, StringComparison.OrdinalIgnoreCase);
Assert.Contains("Do not continue into implementation", instructions, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void Compose_InsertsProjectInstructionsBetweenBaseAndRuntimeGuidance()
{
PatternDefinitionDto pattern = new()
{
Id = "pattern-single",
Name = "Single",
Mode = "single",
Availability = "available",
};
PatternAgentDefinitionDto agent = CreateAgent(
id: "agent-primary",
name: "Primary Agent",
instructions: "You are a helpful assistant.");
string instructions = AgentInstructionComposer.Compose(
pattern,
agent,
agentIndex: 0,
workspaceKind: "scratchpad",
projectInstructions: "Follow the repository guide.");
Assert.Contains("You are a helpful assistant.", instructions, StringComparison.Ordinal);
Assert.Contains("Follow the repository guide.", instructions, StringComparison.Ordinal);
Assert.Contains("scratchpad mode", instructions, StringComparison.OrdinalIgnoreCase);
Assert.True(
instructions.IndexOf("You are a helpful assistant.", StringComparison.Ordinal)
< instructions.IndexOf("Follow the repository guide.", StringComparison.Ordinal));
Assert.True(
instructions.IndexOf("Follow the repository guide.", StringComparison.Ordinal)
< instructions.IndexOf("scratchpad mode", StringComparison.OrdinalIgnoreCase));
}
private static PatternAgentDefinitionDto CreateAgent(string id, string name, string instructions)
{
return new PatternAgentDefinitionDto
@@ -0,0 +1,82 @@
using Aryx.AgentHost.Contracts;
using Aryx.AgentHost.Services;
using GitHub.Copilot.SDK;
using Microsoft.Extensions.AI;
namespace Aryx.AgentHost.Tests;
public sealed class AryxCopilotAgentMessageOptionsTests
{
[Fact]
public async Task ProcessMessageAttachmentsAsync_MapsProtocolAttachmentsAndMessageMode()
{
string attachmentPath = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "aryx-tests", "assets", "diagram.png"));
ChatMessage message = new(ChatRole.User, "Please inspect these images.");
message.Contents.Add(new AIContent
{
RawRepresentation = new ChatMessageAttachmentDto
{
Type = "file",
Path = attachmentPath,
DisplayName = "diagram.png",
},
});
message.Contents.Add(new AIContent
{
RawRepresentation = new ChatMessageAttachmentDto
{
Type = "blob",
Data = "QUJDRA==",
MimeType = "image/png",
DisplayName = "clipboard.png",
},
});
message.Contents.Add(new AIContent
{
RawRepresentation = new CopilotMessageOptionsMetadata("immediate"),
});
(List<UserMessageDataAttachmentsItem>? attachments, string? messageMode, string? tempDir) =
await AryxCopilotAgent.ProcessMessageAttachmentsAsync([message], CancellationToken.None);
Assert.Equal("immediate", messageMode);
Assert.Null(tempDir);
Assert.NotNull(attachments);
Assert.Collection(
attachments!,
first =>
{
UserMessageDataAttachmentsItemFile file = Assert.IsType<UserMessageDataAttachmentsItemFile>(first);
Assert.Equal(attachmentPath, file.Path);
Assert.Equal("diagram.png", file.DisplayName);
},
second =>
{
UserMessageDataAttachmentsItemBlob blob = Assert.IsType<UserMessageDataAttachmentsItemBlob>(second);
Assert.Equal("QUJDRA==", blob.Data);
Assert.Equal("image/png", blob.MimeType);
Assert.Equal("clipboard.png", blob.DisplayName);
});
}
[Fact]
public async Task ProcessMessageAttachmentsAsync_RejectsRelativeFileAttachments()
{
ChatMessage message = new(ChatRole.User, "Inspect this file.");
message.Contents.Add(new AIContent
{
RawRepresentation = new ChatMessageAttachmentDto
{
Type = "file",
Path = "relative\\image.png",
},
});
InvalidOperationException error = await Assert.ThrowsAsync<InvalidOperationException>(() =>
AryxCopilotAgent.ProcessMessageAttachmentsAsync([message], CancellationToken.None));
Assert.Contains("absolute", error.Message, StringComparison.OrdinalIgnoreCase);
}
}
@@ -1,6 +1,9 @@
using System.Reflection;
using Aryx.AgentHost.Services;
using System.Text.Json;
using Aryx.AgentHost.Contracts;
using GitHub.Copilot.SDK;
using Aryx.AgentHost.Services;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
namespace Aryx.AgentHost.Tests;
@@ -50,6 +53,298 @@ public sealed class CopilotAgentBundleTests
Assert.Equal(["glob", "view"], sessionConfig.AvailableTools);
}
[Fact]
public void Constructor_StoresWhetherHooksAreConfigured()
{
CopilotAgentBundle bundle = new([], hasConfiguredHooks: true);
Assert.True(bundle.HasConfiguredHooks);
Assert.Empty(bundle.Agents);
}
[Fact]
public async Task CreateConfiguredSessionConfig_MergesInstructionsAndConvertsHandoffDeclarations()
{
SessionConfig baseConfig = new()
{
Model = "gpt-5.4",
SystemMessage = new SystemMessageConfig
{
Content = "Base instructions",
},
Tools = [CreateTool()],
};
ChatClientAgentRunOptions options = new(new ChatOptions
{
Instructions = "Workflow handoff instructions",
Tools = [CreateHandoffDeclaration()],
});
SessionConfig effective = AryxCopilotAgent.CreateConfiguredSessionConfig(baseConfig, options);
Assert.Equal("gpt-5.4", effective.Model);
Assert.Equal("Base instructions\n\nWorkflow handoff instructions", effective.SystemMessage?.Content);
Assert.Equal("Base instructions", baseConfig.SystemMessage?.Content);
AIFunction[] tools = Assert.IsAssignableFrom<IEnumerable<AIFunction>>(effective.Tools).ToArray();
Assert.Equal(2, tools.Length);
AIFunction handoffTool = Assert.Single(tools, tool => tool.Name == "handoff_to_1");
Assert.True(handoffTool.AdditionalProperties.TryGetValue("skip_permission", out object? skipPermission));
Assert.Equal(true, skipPermission);
object? result = await handoffTool.InvokeAsync(new AIFunctionArguments
{
["reasonForHandoff"] = "UI specialist",
});
Assert.Equal("Transferred.", result?.ToString());
}
[Fact]
public void CreateConfiguredSessionConfig_RejectsUnsupportedRuntimeDeclarations()
{
ChatClientAgentRunOptions options = new(new ChatOptions
{
Tools = [AIFunctionFactory.CreateDeclaration("route_elsewhere", "Unsupported declaration", CreateTool().JsonSchema)],
});
Assert.Throws<NotSupportedException>(() => AryxCopilotAgent.CreateConfiguredSessionConfig(new SessionConfig(), options));
}
[Fact]
public void ConvertToolRequestsToFunctionCalls_MapsCallIdsNamesAndArguments()
{
AssistantMessageDataToolRequestsItem[] toolRequests =
{
new()
{
ToolCallId = "call-123",
Name = "handoff_to_1",
Arguments = JsonSerializer.SerializeToElement(new Dictionary<string, object?>
{
["reasonForHandoff"] = "frontend specialist",
}),
},
};
FunctionCallContent functionCall = Assert.Single(AryxCopilotAgent.ConvertToolRequestsToFunctionCalls(toolRequests));
Assert.Equal("call-123", functionCall.CallId);
Assert.Equal("handoff_to_1", functionCall.Name);
Assert.NotNull(functionCall.Arguments);
Assert.Equal("frontend specialist", functionCall.Arguments["reasonForHandoff"]?.ToString());
}
[Fact]
public void ConvertToolRequestsToFunctionCalls_SkipsNonHandoffToolCalls()
{
AssistantMessageDataToolRequestsItem[] toolRequests =
{
new() { ToolCallId = "call-001", Name = "ask_user" },
new() { ToolCallId = "call-002", Name = "web_fetch" },
new() { ToolCallId = "call-003", Name = "handoff_to_reviewer" },
new() { ToolCallId = "call-004", Name = "grep" },
};
IReadOnlyList<FunctionCallContent> result = AryxCopilotAgent.ConvertToolRequestsToFunctionCalls(toolRequests);
FunctionCallContent single = Assert.Single(result);
Assert.Equal("call-003", single.CallId);
Assert.Equal("handoff_to_reviewer", single.Name);
}
[Fact]
public void CreateCustomAgents_MapsSdkCustomAgentConfiguration()
{
List<CustomAgentConfig> customAgents = Assert.IsType<List<CustomAgentConfig>>(CopilotAgentBundle.CreateCustomAgents(
[
new RunTurnCustomAgentConfigDto
{
Name = "designer",
DisplayName = "Designer",
Description = "Design specialist",
Tools = ["view", "glob"],
Prompt = "Focus on UX design.",
Infer = true,
McpServers =
[
new RunTurnMcpServerConfigDto
{
Id = "designer-mcp",
Name = "Designer MCP",
Transport = "local",
Command = "node",
Args = ["designer.js"],
},
],
},
]));
CustomAgentConfig customAgent = Assert.Single(customAgents);
Assert.Equal("designer", customAgent.Name);
Assert.Equal("Designer", customAgent.DisplayName);
Assert.Equal("Design specialist", customAgent.Description);
Assert.Equal(["view", "glob"], customAgent.Tools);
Assert.Equal("Focus on UX design.", customAgent.Prompt);
Assert.True(customAgent.Infer);
KeyValuePair<string, object> mcpServer = Assert.Single(customAgent.McpServers!);
Assert.Equal("Designer MCP", mcpServer.Key);
McpLocalServerConfig localServer = Assert.IsType<McpLocalServerConfig>(mcpServer.Value);
Assert.Equal("node", localServer.Command);
Assert.Equal(["designer.js"], localServer.Args);
}
[Fact]
public void CreateInfiniteSessions_MapsSdkInfiniteSessionConfiguration()
{
InfiniteSessionConfig config = Assert.IsType<InfiniteSessionConfig>(CopilotAgentBundle.CreateInfiniteSessions(
new RunTurnInfiniteSessionsConfigDto
{
Enabled = true,
BackgroundCompactionThreshold = 0.75,
BufferExhaustionThreshold = 0.9,
}));
Assert.True(config.Enabled);
Assert.Equal(0.75, config.BackgroundCompactionThreshold);
Assert.Equal(0.9, config.BufferExhaustionThreshold);
}
[Fact]
public void CreateSessionConfig_DoesNotForceSessionId()
{
RunTurnCommandDto command = new()
{
SessionId = "session-1",
ProjectPath = @"C:\workspace\project",
WorkspaceKind = "project",
Mode = "interactive",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "Pattern",
Mode = "single",
Availability = "available",
Agents =
[
new PatternAgentDefinitionDto
{
Id = "agent-1",
Name = "Primary",
Model = "gpt-5.4",
Instructions = "Help.",
},
],
},
};
SessionConfig sessionConfig = CopilotAgentBundle.CreateSessionConfig(
command,
command.Pattern.Agents[0],
agentIndex: 0);
Assert.Null(sessionConfig.SessionId);
Assert.Equal(@"C:\workspace\project", sessionConfig.WorkingDirectory);
Assert.True(sessionConfig.Streaming);
Assert.NotNull(sessionConfig.Hooks);
}
[Fact]
public void CreateSessionConfig_PassesProjectInstructionsIntoTheSystemMessage()
{
RunTurnCommandDto command = new()
{
SessionId = "session-1",
ProjectPath = @"C:\workspace\project",
WorkspaceKind = "project",
Mode = "interactive",
ProjectInstructions = "Follow repository guidance.",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "Pattern",
Mode = "single",
Availability = "available",
Agents =
[
new PatternAgentDefinitionDto
{
Id = "agent-1",
Name = "Primary",
Model = "gpt-5.4",
Instructions = "Help.",
},
],
},
};
SessionConfig sessionConfig = CopilotAgentBundle.CreateSessionConfig(
command,
command.Pattern.Agents[0],
agentIndex: 0);
Assert.Equal("Help.\n\nFollow repository guidance.", sessionConfig.SystemMessage?.Content);
}
[Fact]
public async Task CopilotSessionHooks_Create_UsesApprovalPolicyForPreToolUse()
{
RunTurnCommandDto command = new()
{
RequestId = "turn-1",
SessionId = "session-1",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "Pattern",
Mode = "single",
Availability = "available",
ApprovalPolicy = new ApprovalPolicyDto
{
Rules =
[
new ApprovalCheckpointRuleDto
{
Kind = "tool-call",
AgentIds = ["agent-1"],
},
],
},
Agents =
[
new PatternAgentDefinitionDto
{
Id = "agent-1",
Name = "Primary",
Model = "gpt-5.4",
Instructions = "Help.",
},
],
},
};
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0]);
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
new PreToolUseHookInput
{
ToolName = "view",
},
null!);
Assert.Equal("ask", decision?.PermissionDecision);
}
[Fact]
public void CopilotManagedSessionIds_BuildsAndParsesStableIds()
{
string sessionId = CopilotManagedSessionIds.Build("session-1", "agent-ux");
Assert.True(CopilotManagedSessionIds.TryParse(sessionId, out string aryxSessionId, out string agentId));
Assert.Equal("session-1", aryxSessionId);
Assert.Equal("agent-ux", agentId);
}
private static AIFunction CreateTool()
{
ToolTarget target = new();
@@ -66,6 +361,14 @@ public sealed class CopilotAgentBundleTests
});
}
private static AIFunctionDeclaration CreateHandoffDeclaration()
{
return AIFunctionFactory.CreateDeclaration(
"handoff_to_1",
"Transfer ownership to a specialist",
CreateTool().JsonSchema);
}
private sealed class ToolTarget
{
public string Echo() => "ok";
@@ -0,0 +1,72 @@
using Aryx.AgentHost.Contracts;
using Aryx.AgentHost.Services;
using GitHub.Copilot.SDK;
namespace Aryx.AgentHost.Tests;
public sealed class CopilotExitPlanModeCoordinatorTests
{
[Fact]
public void RecordExitPlanModeRequest_BuildsEventAndMakesItConsumable()
{
CopilotExitPlanModeCoordinator coordinator = new();
RunTurnCommandDto command = CreateCommand();
ExitPlanModeRequestedEventDto exitPlanEvent = coordinator.RecordExitPlanModeRequest(
command,
command.Pattern.Agents[0],
new ExitPlanModeRequestedEvent
{
Data = new ExitPlanModeRequestedData
{
RequestId = "exit-plan-1",
Summary = "Proposed plan",
PlanContent = "1. Investigate\n2. Implement",
Actions = ["interactive", "autopilot"],
RecommendedAction = "interactive",
},
});
Assert.Equal("exit-plan-mode-requested", exitPlanEvent.Type);
Assert.Equal("turn-1", exitPlanEvent.RequestId);
Assert.Equal("session-1", exitPlanEvent.SessionId);
Assert.Equal("exit-plan-1", exitPlanEvent.ExitPlanId);
Assert.Equal("agent-1", exitPlanEvent.AgentId);
Assert.Equal("Primary", exitPlanEvent.AgentName);
Assert.Equal("Proposed plan", exitPlanEvent.Summary);
Assert.Equal("1. Investigate\n2. Implement", exitPlanEvent.PlanContent);
Assert.Equal(["interactive", "autopilot"], exitPlanEvent.Actions);
Assert.Equal("interactive", exitPlanEvent.RecommendedAction);
ExitPlanModeRequestedEventDto? consumed = coordinator.ConsumePendingRequest(command.RequestId);
Assert.NotNull(consumed);
Assert.Equal("exit-plan-1", consumed!.ExitPlanId);
Assert.Null(coordinator.ConsumePendingRequest(command.RequestId));
}
private static RunTurnCommandDto CreateCommand()
{
return new RunTurnCommandDto
{
RequestId = "turn-1",
SessionId = "session-1",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "Plan Mode Pattern",
Mode = "single",
Availability = "available",
Agents =
[
new PatternAgentDefinitionDto
{
Id = "agent-1",
Name = "Primary",
Model = "gpt-5.4",
Instructions = "Help with the request.",
},
],
},
};
}
}
@@ -0,0 +1,71 @@
using Aryx.AgentHost.Contracts;
using Aryx.AgentHost.Services;
using GitHub.Copilot.SDK;
namespace Aryx.AgentHost.Tests;
public sealed class CopilotMcpOAuthCoordinatorTests
{
[Fact]
public void BuildMcpOauthRequiredEvent_MapsSdkEventToProtocolEvent()
{
CopilotMcpOAuthCoordinator coordinator = new();
RunTurnCommandDto command = CreateCommand();
McpOauthRequiredEventDto oauthEvent = coordinator.BuildMcpOauthRequiredEvent(
command,
command.Pattern.Agents[0],
new McpOauthRequiredEvent
{
Data = new McpOauthRequiredData
{
RequestId = " oauth-request-1 ",
ServerName = " Example MCP ",
ServerUrl = " https://example.com/mcp ",
StaticClientConfig = new McpOauthRequiredDataStaticClientConfig
{
ClientId = " aryx-client ",
PublicClient = true,
},
},
});
Assert.Equal("mcp-oauth-required", oauthEvent.Type);
Assert.Equal("turn-1", oauthEvent.RequestId);
Assert.Equal("session-1", oauthEvent.SessionId);
Assert.Equal("oauth-request-1", oauthEvent.OauthRequestId);
Assert.Equal("agent-1", oauthEvent.AgentId);
Assert.Equal("Primary", oauthEvent.AgentName);
Assert.Equal("Example MCP", oauthEvent.ServerName);
Assert.Equal("https://example.com/mcp", oauthEvent.ServerUrl);
Assert.NotNull(oauthEvent.StaticClientConfig);
Assert.Equal("aryx-client", oauthEvent.StaticClientConfig!.ClientId);
Assert.True(oauthEvent.StaticClientConfig.PublicClient);
}
private static RunTurnCommandDto CreateCommand()
{
return new RunTurnCommandDto
{
RequestId = "turn-1",
SessionId = "session-1",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "MCP OAuth Pattern",
Mode = "single",
Availability = "available",
Agents =
[
new PatternAgentDefinitionDto
{
Id = "agent-1",
Name = "Primary",
Model = "gpt-5.4",
Instructions = "Help with the request.",
},
],
},
};
}
}
@@ -0,0 +1,304 @@
using System.Text.Json;
using Aryx.AgentHost.Contracts;
using Aryx.AgentHost.Services;
using GitHub.Copilot.SDK;
namespace Aryx.AgentHost.Tests;
public sealed class CopilotSessionHooksTests
{
[Fact]
public async Task Create_FileBasedPreToolUseDenyOverridesApprovalPolicy()
{
RunTurnCommandDto command = CreateCommandWithToolApproval();
RecordingHookCommandRunner runner = new(
[
"""{"permissionDecision":"deny","permissionDecisionReason":"Blocked by repository hook"}""",
]);
ResolvedHookSet configuredHooks = new()
{
PreToolUse =
[
CreateHookCommand("deny-pre-tool"),
],
};
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], configuredHooks, runner);
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
new PreToolUseHookInput
{
Timestamp = 1710000000000,
Cwd = command.ProjectPath,
ToolName = "view",
ToolArgs = JsonSerializer.SerializeToElement(new
{
path = "README.md",
}),
},
null!);
Assert.Equal("deny", decision?.PermissionDecision);
Assert.Equal("Blocked by repository hook", decision?.PermissionDecisionReason);
RecordedHookInvocation invocation = Assert.Single(runner.Invocations);
JsonDocument payload = JsonDocument.Parse(invocation.InputJson);
Assert.Equal("view", payload.RootElement.GetProperty("toolName").GetString());
Assert.Equal("{\"path\":\"README.md\"}", payload.RootElement.GetProperty("toolArgs").GetString());
Assert.Equal(command.ProjectPath, invocation.ProjectPath);
}
[Fact]
public async Task Create_PreToolUseFallsThroughWhenFileHooksDoNotDeny()
{
RunTurnCommandDto command = CreateCommandWithToolApproval();
RecordingHookCommandRunner runner = new(
[
"""{"permissionDecision":"allow"}""",
]);
ResolvedHookSet configuredHooks = new()
{
PreToolUse =
[
CreateHookCommand("allow-pre-tool"),
],
};
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], configuredHooks, runner);
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
new PreToolUseHookInput
{
ToolName = "view",
},
null!);
Assert.Equal("ask", decision?.PermissionDecision);
Assert.Single(runner.Invocations);
}
[Fact]
public async Task Create_PreToolUseIgnoresInvalidHookOutputAndFallsThrough()
{
RunTurnCommandDto command = CreateCommandWithToolApproval();
RecordingHookCommandRunner runner = new(
[
"not-json",
]);
ResolvedHookSet configuredHooks = new()
{
PreToolUse =
[
CreateHookCommand("invalid-pre-tool"),
],
};
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], configuredHooks, runner);
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
new PreToolUseHookInput
{
ToolName = "view",
},
null!);
Assert.Equal("ask", decision?.PermissionDecision);
Assert.Single(runner.Invocations);
}
[Fact]
public async Task Create_RunsConfiguredNonPreToolHooks()
{
RunTurnCommandDto command = CreateCommandWithoutApprovalRules();
RecordingHookCommandRunner runner = new();
ResolvedHookSet configuredHooks = new()
{
SessionStart = [CreateHookCommand("session-start-hook")],
UserPromptSubmitted = [CreateHookCommand("prompt-hook")],
PostToolUse = [CreateHookCommand("post-tool-hook")],
SessionEnd = [CreateHookCommand("session-end-hook")],
ErrorOccurred = [CreateHookCommand("error-hook")],
};
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], configuredHooks, runner);
await hooks.OnSessionStart!(
new SessionStartHookInput
{
Timestamp = 1,
Cwd = command.ProjectPath,
Source = "new",
InitialPrompt = "Create the feature",
},
null!);
await hooks.OnUserPromptSubmitted!(
new UserPromptSubmittedHookInput
{
Timestamp = 2,
Cwd = command.ProjectPath,
Prompt = "Refactor the API",
},
null!);
await hooks.OnPostToolUse!(
new PostToolUseHookInput
{
Timestamp = 3,
Cwd = command.ProjectPath,
ToolName = "view",
ToolArgs = JsonSerializer.SerializeToElement(new
{
path = "README.md",
}),
ToolResult = JsonSerializer.SerializeToElement(new
{
resultType = "success",
textResultForLlm = "Read 1 file",
}),
},
null!);
await hooks.OnSessionEnd!(
new SessionEndHookInput
{
Timestamp = 4,
Cwd = command.ProjectPath,
Reason = "complete",
FinalMessage = "Done",
},
null!);
await hooks.OnErrorOccurred!(
new ErrorOccurredHookInput
{
Timestamp = 5,
Cwd = command.ProjectPath,
Error = "Network timeout",
ErrorContext = "tool_execution",
Recoverable = true,
},
null!);
Assert.Equal(
["session-start-hook", "prompt-hook", "post-tool-hook", "session-end-hook", "error-hook"],
runner.Invocations.Select(invocation => GetCommandText(invocation.Hook)).ToArray());
JsonDocument postToolPayload = JsonDocument.Parse(runner.Invocations[2].InputJson);
Assert.Equal("view", postToolPayload.RootElement.GetProperty("toolName").GetString());
Assert.Equal("success", postToolPayload.RootElement.GetProperty("toolResult").GetProperty("resultType").GetString());
JsonDocument errorPayload = JsonDocument.Parse(runner.Invocations[4].InputJson);
Assert.Equal("Network timeout", errorPayload.RootElement.GetProperty("error").GetProperty("message").GetString());
Assert.Equal("tool_execution", errorPayload.RootElement.GetProperty("error").GetProperty("context").GetString());
Assert.True(errorPayload.RootElement.GetProperty("error").GetProperty("recoverable").GetBoolean());
}
[Fact]
public async Task Create_WithoutConfiguredFileHooksPreservesExistingApprovalBehavior()
{
RunTurnCommandDto command = CreateCommandWithoutApprovalRules();
SessionHooks hooks = CopilotSessionHooks.Create(command, command.Pattern.Agents[0], ResolvedHookSet.Empty, new RecordingHookCommandRunner());
PreToolUseHookOutput? decision = await hooks.OnPreToolUse!(
new PreToolUseHookInput
{
ToolName = "view",
},
null!);
Assert.Equal("allow", decision?.PermissionDecision);
}
private static RunTurnCommandDto CreateCommandWithToolApproval()
{
return new RunTurnCommandDto
{
RequestId = "turn-1",
SessionId = "session-1",
ProjectPath = @"C:\workspace\project",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "Pattern",
Mode = "single",
Availability = "available",
ApprovalPolicy = new ApprovalPolicyDto
{
Rules =
[
new ApprovalCheckpointRuleDto
{
Kind = "tool-call",
AgentIds = ["agent-1"],
},
],
},
Agents =
[
new PatternAgentDefinitionDto
{
Id = "agent-1",
Name = "Primary",
Model = "gpt-5.4",
Instructions = "Help.",
},
],
},
};
}
private static RunTurnCommandDto CreateCommandWithoutApprovalRules()
{
RunTurnCommandDto command = CreateCommandWithToolApproval();
return new RunTurnCommandDto
{
RequestId = command.RequestId,
SessionId = command.SessionId,
ProjectPath = command.ProjectPath,
Pattern = new PatternDefinitionDto
{
Id = command.Pattern.Id,
Name = command.Pattern.Name,
Mode = command.Pattern.Mode,
Availability = command.Pattern.Availability,
ApprovalPolicy = new ApprovalPolicyDto(),
Agents = command.Pattern.Agents,
},
};
}
private static HookCommandDefinition CreateHookCommand(string name)
=> new()
{
Type = "command",
Bash = name,
PowerShell = name,
};
private static string GetCommandText(HookCommandDefinition hook)
=> hook.PowerShell ?? hook.Bash ?? string.Empty;
private sealed class RecordingHookCommandRunner : IHookCommandRunner
{
private readonly Queue<string?> _outputs;
public List<RecordedHookInvocation> Invocations { get; } = [];
public RecordingHookCommandRunner(IEnumerable<string?>? outputs = null)
{
_outputs = outputs is null ? new Queue<string?>() : new Queue<string?>(outputs);
}
public Task<string?> RunAsync(
HookCommandDefinition hook,
string inputJson,
string projectPath,
CancellationToken cancellationToken)
{
Invocations.Add(new RecordedHookInvocation(hook, inputJson, projectPath));
return Task.FromResult(_outputs.Count > 0 ? _outputs.Dequeue() : string.Empty);
}
}
private sealed record RecordedHookInvocation(
HookCommandDefinition Hook,
string InputJson,
string ProjectPath);
}
@@ -0,0 +1,439 @@
using Aryx.AgentHost.Contracts;
using Aryx.AgentHost.Services;
using GitHub.Copilot.SDK;
namespace Aryx.AgentHost.Tests;
public sealed class CopilotTurnExecutionStateTests
{
[Fact]
public void ObserveSessionEvent_McpOauthRequired_SetsActiveAgent()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
new McpOauthRequiredEvent
{
Data = new McpOauthRequiredData
{
RequestId = "oauth-request-1",
ServerName = "Example MCP",
ServerUrl = "https://example.com/mcp",
},
});
Assert.True(state.ActiveAgent.HasValue);
Assert.Equal("agent-1", state.ActiveAgent.Value.AgentId);
Assert.Equal("Primary", state.ActiveAgent.Value.AgentName);
}
[Fact]
public void ObserveSessionEvent_AssistantMessageDelta_QueuesThinkingActivity()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "assistant.message_delta",
"data": {
"messageId": "msg-1",
"deltaContent": "Hello"
},
"id": "11111111-1111-1111-1111-111111111111",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
AgentActivityEventDto activity = Assert.Single(state.DrainPendingEvents().OfType<AgentActivityEventDto>());
Assert.Equal("thinking", activity.ActivityType);
Assert.Equal("agent-1", activity.AgentId);
Assert.Equal("Primary", activity.AgentName);
Assert.True(state.TryResolveObservedAgentForMessage("msg-1", out AgentIdentity observedAgent));
Assert.Equal("agent-1", observedAgent.AgentId);
}
[Fact]
public void ObserveSessionEvent_ToolExecutionStart_TracksToolNameByCallId()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "tool.execution_start",
"data": {
"toolCallId": "tool-call-1",
"toolName": "view"
},
"id": "33333333-3333-3333-3333-333333333333",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
Assert.True(state.ToolNamesByCallId.TryGetValue("tool-call-1", out string? toolName));
Assert.Equal("view", toolName);
}
[Fact]
public async Task EmitThinkingIfNeeded_DoesNotDuplicateQueuedThinkingActivity()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "assistant.reasoning_delta",
"data": {
"reasoningId": "reasoning-1",
"deltaContent": "Planning"
},
"id": "22222222-2222-2222-2222-222222222222",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
List<AgentActivityEventDto> activities = [.. state.DrainPendingEvents().OfType<AgentActivityEventDto>()];
await state.EmitThinkingIfNeeded(
new AgentIdentity("agent-1", "Primary"),
sidecarEvent =>
{
activities.Add(Assert.IsType<AgentActivityEventDto>(sidecarEvent));
return Task.CompletedTask;
});
AgentActivityEventDto thinking = Assert.Single(activities);
Assert.Equal("thinking", thinking.ActivityType);
Assert.Equal("agent-1", thinking.AgentId);
}
[Fact]
public void DrainPendingMcpOauthRequests_ReturnsQueuedRequestsAndClearsQueue()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
McpOauthRequiredEventDto request = new()
{
Type = "mcp-oauth-required",
RequestId = command.RequestId,
SessionId = command.SessionId,
OauthRequestId = "oauth-request-1",
ServerName = "Example MCP",
ServerUrl = "https://example.com/mcp",
};
state.EnqueuePendingMcpOauthRequest(request);
IReadOnlyList<McpOauthRequiredEventDto> firstDrain = state.DrainPendingMcpOauthRequests();
IReadOnlyList<McpOauthRequiredEventDto> secondDrain = state.DrainPendingMcpOauthRequests();
McpOauthRequiredEventDto drained = Assert.Single(firstDrain);
Assert.Equal("oauth-request-1", drained.OauthRequestId);
Assert.Empty(secondDrain);
}
[Fact]
public void ObserveSessionEvent_SubagentStarted_QueuesSubagentEvent()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "subagent.started",
"data": {
"toolCallId": "tool-call-1",
"agentName": "designer",
"agentDisplayName": "Designer",
"agentDescription": "Design specialist"
},
"id": "44444444-4444-4444-4444-444444444444",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
SubagentEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<SubagentEventDto>());
Assert.Equal("started", evt.EventKind);
Assert.Equal("tool-call-1", evt.ToolCallId);
Assert.Equal("designer", evt.CustomAgentName);
Assert.Equal("Designer", evt.CustomAgentDisplayName);
}
[Fact]
public void ObserveSessionEvent_SkillInvoked_QueuesSkillEvent()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "skill.invoked",
"data": {
"name": "reviewer",
"path": "C:\\skills\\reviewer\\SKILL.md",
"content": "# Reviewer",
"allowedTools": ["view"],
"pluginName": "aryx-plugin",
"pluginVersion": "1.0.0"
},
"id": "55555555-5555-5555-5555-555555555555",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
SkillInvokedEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<SkillInvokedEventDto>());
Assert.Equal("reviewer", evt.SkillName);
Assert.Equal(@"C:\skills\reviewer\SKILL.md", evt.Path);
Assert.Equal(["view"], evt.AllowedTools);
Assert.Equal("aryx-plugin", evt.PluginName);
}
[Fact]
public void ObserveSessionEvent_HookStart_QueuesHookLifecycleEvent()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(command.Pattern.Agents[0], CreateHookStartEvent());
HookLifecycleEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<HookLifecycleEventDto>());
Assert.Equal("start", evt.Phase);
Assert.Equal("postToolUse", evt.HookType);
Assert.Equal("hook-1", evt.HookInvocationId);
Assert.NotNull(evt.Input);
}
[Fact]
public void ObserveSessionEvent_HookEnd_QueuesHookLifecycleEvent()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(command.Pattern.Agents[0], CreateHookEndEvent());
HookLifecycleEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<HookLifecycleEventDto>());
Assert.Equal("end", evt.Phase);
Assert.Equal("postToolUse", evt.HookType);
Assert.Equal("hook-1", evt.HookInvocationId);
Assert.True(evt.Success);
}
[Fact]
public void ObserveSessionEvent_HookLifecycleEvents_AreSuppressedWhenConfigured()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command)
{
SuppressHookLifecycleEvents = true,
};
state.ObserveSessionEvent(command.Pattern.Agents[0], CreateHookStartEvent());
state.ObserveSessionEvent(command.Pattern.Agents[0], CreateHookEndEvent());
Assert.Empty(state.DrainPendingEvents());
}
[Fact]
public void ObserveSessionEvent_AssistantUsage_QueuesAssistantUsageEvent()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "assistant.usage",
"data": {
"model": "gpt-5.4",
"inputTokens": 1200,
"outputTokens": 300,
"cacheReadTokens": 50,
"cacheWriteTokens": 10,
"cost": 0.42,
"duration": 8200,
"quotaSnapshots": {
"premium_interactions": {
"entitlementRequests": 50,
"usedRequests": 12,
"remainingPercentage": 76,
"overage": 0,
"overageAllowedWithExhaustedQuota": true,
"resetDate": "2026-04-01T00:00:00Z"
}
},
"copilotUsage": {
"tokenDetails": [
{
"batchSize": 1,
"costPerBatch": 1,
"tokenCount": 1500,
"tokenType": "input"
}
],
"totalNanoAiu": 1200000000
}
},
"id": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
AssistantUsageEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<AssistantUsageEventDto>());
Assert.Equal("session-1", evt.SessionId);
Assert.Equal("agent-1", evt.AgentId);
Assert.Equal("Primary", evt.AgentName);
Assert.Equal("gpt-5.4", evt.Model);
Assert.Equal(1200, evt.InputTokens);
Assert.Equal(300, evt.OutputTokens);
Assert.Equal(0.42, evt.Cost);
Assert.Equal(8200, evt.Duration);
Assert.Equal(1200000000, evt.TotalNanoAiu);
QuotaSnapshotDto snapshot = Assert.Single(evt.QuotaSnapshots!.Values);
Assert.Equal(50, snapshot.EntitlementRequests);
Assert.Equal(12, snapshot.UsedRequests);
Assert.Equal(76, snapshot.RemainingPercentage);
}
[Fact]
public void ObserveSessionEvent_SessionCompactionComplete_QueuesCompactionEvent()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "session.compaction_complete",
"data": {
"success": true,
"preCompactionTokens": 1000,
"postCompactionTokens": 400,
"messagesRemoved": 8,
"tokensRemoved": 600,
"summaryContent": "Compacted summary",
"checkpointNumber": 2,
"checkpointPath": "C:\\Users\\me\\.copilot\\session-state\\checkpoint-2.json"
},
"id": "77777777-7777-7777-7777-777777777777",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
SessionCompactionEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<SessionCompactionEventDto>());
Assert.Equal("complete", evt.Phase);
Assert.True(evt.Success);
Assert.Equal(1000, evt.PreCompactionTokens);
Assert.Equal(400, evt.PostCompactionTokens);
Assert.Equal("Compacted summary", evt.SummaryContent);
}
[Fact]
public void ObserveSessionEvent_PendingMessagesModified_QueuesPendingMessageSignal()
{
RunTurnCommandDto command = CreateCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
command.Pattern.Agents[0],
SessionEvent.FromJson(
"""
{
"type": "pending_messages.modified",
"data": {},
"id": "88888888-8888-8888-8888-888888888888",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
PendingMessagesModifiedEventDto evt = Assert.Single(state.DrainPendingEvents().OfType<PendingMessagesModifiedEventDto>());
Assert.Equal("session-1", evt.SessionId);
Assert.Equal("agent-1", evt.AgentId);
}
private static SessionEvent CreateHookStartEvent()
{
return SessionEvent.FromJson(
"""
{
"type": "hook.start",
"data": {
"hookInvocationId": "hook-1",
"hookType": "postToolUse",
"input": {
"toolName": "view"
}
},
"id": "66666666-6666-6666-6666-666666666666",
"timestamp": "2026-03-27T00:00:00Z"
}
""");
}
private static SessionEvent CreateHookEndEvent()
{
return SessionEvent.FromJson(
"""
{
"type": "hook.end",
"data": {
"hookInvocationId": "hook-1",
"hookType": "postToolUse",
"success": true,
"output": {
"status": "ok"
}
},
"id": "99999999-9999-9999-9999-999999999999",
"timestamp": "2026-03-27T00:00:00Z"
}
""");
}
private static RunTurnCommandDto CreateCommand()
{
return new RunTurnCommandDto
{
RequestId = "turn-1",
SessionId = "session-1",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "MCP OAuth Pattern",
Mode = "single",
Availability = "available",
Agents =
[
new PatternAgentDefinitionDto
{
Id = "agent-1",
Name = "Primary",
Model = "gpt-5.4",
Instructions = "Help with the request.",
},
],
},
};
}
}
@@ -0,0 +1,109 @@
using Aryx.AgentHost.Contracts;
using Aryx.AgentHost.Services;
using GitHub.Copilot.SDK;
namespace Aryx.AgentHost.Tests;
public sealed class CopilotUserInputCoordinatorTests
{
[Fact]
public async Task RequestUserInputAsync_RaisesUserInputEventAndCompletesAfterResolution()
{
CopilotUserInputCoordinator coordinator = new();
UserInputRequestedEventDto? observedEvent = null;
RunTurnCommandDto command = CreateUserInputCommand();
Task<UserInputResponse> pending = coordinator.RequestUserInputAsync(
command,
command.Pattern.Agents[0],
new UserInputRequest
{
Question = "How should I proceed?",
Choices = ["Continue", "Stop"],
AllowFreeform = true,
},
new UserInputInvocation
{
SessionId = "copilot-session-1",
},
userInputEvent =>
{
observedEvent = userInputEvent;
return Task.CompletedTask;
},
CancellationToken.None);
Assert.False(pending.IsCompleted);
Assert.NotNull(observedEvent);
Assert.Equal("user-input-requested", observedEvent!.Type);
Assert.Equal("turn-1", observedEvent.RequestId);
Assert.Equal("session-1", observedEvent.SessionId);
Assert.Equal("agent-1", observedEvent.AgentId);
Assert.Equal("Primary", observedEvent.AgentName);
Assert.Equal("How should I proceed?", observedEvent.Question);
Assert.Equal(["Continue", "Stop"], observedEvent.Choices);
Assert.True(observedEvent.AllowFreeform);
await coordinator.ResolveUserInputAsync(
new ResolveUserInputCommandDto
{
UserInputId = observedEvent.UserInputId,
Answer = "Continue",
WasFreeform = false,
},
CancellationToken.None);
UserInputResponse response = await pending;
Assert.Equal("Continue", response.Answer);
Assert.False(response.WasFreeform);
}
[Fact]
public async Task ResolveUserInputAsync_RejectsUnknownUserInputIds()
{
CopilotUserInputCoordinator coordinator = new();
InvalidOperationException error = await Assert.ThrowsAsync<InvalidOperationException>(() =>
coordinator.ResolveUserInputAsync(
new ResolveUserInputCommandDto
{
UserInputId = "user-input-missing",
Answer = "Continue",
WasFreeform = false,
},
CancellationToken.None));
Assert.Contains("is not pending", error.Message);
}
private static PatternAgentDefinitionDto CreateAgent(string id, string name)
{
return new PatternAgentDefinitionDto
{
Id = id,
Name = name,
Model = "gpt-5.4",
Instructions = "Help with the request.",
};
}
private static RunTurnCommandDto CreateUserInputCommand()
{
return new RunTurnCommandDto
{
RequestId = "turn-1",
SessionId = "session-1",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "User Input Pattern",
Mode = "single",
Availability = "available",
Agents =
[
CreateAgent("agent-1", "Primary"),
],
},
};
}
}
@@ -1,12 +1,28 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using Aryx.AgentHost.Contracts;
using Aryx.AgentHost.Services;
using GitHub.Copilot.SDK;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.AI;
namespace Aryx.AgentHost.Tests;
public sealed class CopilotWorkflowRunnerTests
{
[Fact]
public void ConfigureHookLifecycleEventSuppression_SetsStateFromBundle()
{
RunTurnCommandDto command = CreateApprovalCommand();
CopilotTurnExecutionState state = new(command);
CopilotAgentBundle bundle = new(Array.Empty<AIAgent>(), hasConfiguredHooks: false);
CopilotWorkflowRunner.ConfigureHookLifecycleEventSuppression(state, bundle);
Assert.True(state.SuppressHookLifecycleEvents);
}
[Fact]
public void SelectNewOutputMessages_SkipsFullTranscriptPrefix()
{
@@ -156,6 +172,50 @@ public sealed class CopilotWorkflowRunnerTests
Assert.Equal("Hello", message.Content);
}
[Fact]
public void ProjectCompletedMessages_UsesFinalAssistantPayloadWhenStreamingTextIsMissing()
{
RunTurnCommandDto command = new()
{
RequestId = "turn-1",
SessionId = "session-1",
Pattern = new PatternDefinitionDto
{
Id = "pattern-single",
Name = "Single Agent",
Mode = "single",
Availability = "available",
Agents =
[
CreateAgent(id: "agent-single-primary", name: "Primary Agent"),
],
},
};
IReadOnlyList<ChatMessageDto> messages = WorkflowTranscriptProjector.ProjectCompletedMessages(
command,
[
new ChatMessage(ChatRole.Assistant, string.Empty)
{
MessageId = "msg-1",
RawRepresentation = new AssistantMessageEvent
{
Data = new AssistantMessageData
{
MessageId = "msg-1",
Content = "Hello from the final assistant payload.",
},
},
},
],
[]);
ChatMessageDto message = Assert.Single(messages);
Assert.Equal("msg-1", message.Id);
Assert.Equal("Primary Agent", message.AuthorName);
Assert.Equal("Hello from the final assistant payload.", message.Content);
}
[Fact]
public void ProjectCompletedMessages_PreservesSequentialConversationHistory()
{
@@ -645,6 +705,9 @@ public sealed class CopilotWorkflowRunnerTests
Assert.Equal("agent-handoff-ux", observedAgent.AgentId);
Assert.Equal("UX Specialist", observedAgent.AgentName);
Assert.Equal("agent-handoff-ux", state.ActiveAgent?.AgentId);
AgentActivityEventDto activity = Assert.Single(state.DrainPendingEvents().OfType<AgentActivityEventDto>());
Assert.Equal("thinking", activity.ActivityType);
Assert.Equal("agent-handoff-ux", activity.AgentId);
}
[Fact]
@@ -668,6 +731,71 @@ public sealed class CopilotWorkflowRunnerTests
Assert.Equal("agent-handoff-ux", state.ActiveAgent?.AgentId);
Assert.Equal("UX Specialist", state.ActiveAgent?.AgentName);
AgentActivityEventDto activity = Assert.Single(state.DrainPendingEvents().OfType<AgentActivityEventDto>());
Assert.Equal("thinking", activity.ActivityType);
Assert.Equal("agent-handoff-ux", activity.AgentId);
}
[Fact]
public async Task HandleWorkflowEventAsync_EmitsThinkingForHandoffTargets()
{
RunTurnCommandDto command = CreateHandoffCommand();
CopilotTurnExecutionState state = new(command);
state.ObserveSessionEvent(
CreateAgent("agent-handoff-triage", "Triage"),
SessionEvent.FromJson(
"""
{
"type": "assistant.reasoning_delta",
"data": {
"reasoningId": "reasoning-1",
"deltaContent": "Delegating."
},
"id": "33333333-3333-3333-3333-333333333333",
"timestamp": "2026-03-27T00:00:00Z"
}
"""));
_ = state.DrainPendingEvents();
RequestInfoEvent requestInfo = CreateRequestInfoEvent(
CreateHandoffTarget("agent-handoff-ux", "UX Specialist"));
List<AgentActivityEventDto> activities = [];
MethodInfo handleWorkflowEvent = typeof(CopilotWorkflowRunner).GetMethod(
"HandleWorkflowEventAsync",
BindingFlags.NonPublic | BindingFlags.Static)!;
Task<bool> handleTask = (Task<bool>)handleWorkflowEvent.Invoke(
null,
[
command,
requestInfo,
Array.Empty<ChatMessage>(),
state,
(Func<TurnDeltaEventDto, Task>)(_ => Task.CompletedTask),
(Func<SidecarEventDto, Task>)(sidecarEvent =>
{
activities.Add(Assert.IsType<AgentActivityEventDto>(sidecarEvent));
return Task.CompletedTask;
}),
])!;
bool shouldEndTurn = await handleTask;
Assert.False(shouldEndTurn);
Assert.Collection(
activities,
handoff =>
{
Assert.Equal("handoff", handoff.ActivityType);
Assert.Equal("agent-handoff-ux", handoff.AgentId);
Assert.Equal("UX Specialist", handoff.AgentName);
Assert.Equal("agent-handoff-triage", handoff.SourceAgentId);
},
thinking =>
{
Assert.Equal("thinking", thinking.ActivityType);
Assert.Equal("agent-handoff-ux", thinking.AgentId);
Assert.Equal("UX Specialist", thinking.AgentName);
});
}
[Fact]
@@ -694,7 +822,59 @@ public sealed class CopilotWorkflowRunnerTests
}
[Fact]
public void TryGetApprovalToolName_ReadsMcpCustomAndHookRequests()
public void RequiresToolCallApproval_HonorsRuntimeApprovalAliases()
{
ApprovalPolicyDto policy = new()
{
Rules =
[
new ApprovalCheckpointRuleDto
{
Kind = "tool-call",
AgentIds = ["agent-1"],
},
],
AutoApprovedToolNames = ["read", "store_memory"],
};
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "view", "read"));
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "remember_fact", "store_memory"));
Assert.True(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "write_file", "write"));
Assert.True(CopilotApprovalCoordinator.RequiresToolCallApproval(policy, "agent-1", "git.status"));
}
[Fact]
public void RequiresToolCallApproval_HonorsMcpServerLevelApprovalKey()
{
ApprovalPolicyDto policy = new()
{
Rules =
[
new ApprovalCheckpointRuleDto
{
Kind = "tool-call",
},
],
AutoApprovedToolNames = ["mcp_server:Git MCP"],
};
// Server-level key approves any tool from that server
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(
policy, "agent-1", "git.status", null, "mcp_server:Git MCP"));
Assert.False(CopilotApprovalCoordinator.RequiresToolCallApproval(
policy, "agent-1", "git.diff", null, "mcp_server:Git MCP"));
// Different server still requires approval
Assert.True(CopilotApprovalCoordinator.RequiresToolCallApproval(
policy, "agent-1", "fs.read", null, "mcp_server:Filesystem"));
// Non-MCP tools unaffected
Assert.True(CopilotApprovalCoordinator.RequiresToolCallApproval(
policy, "agent-1", "unknown_tool"));
}
[Fact]
public void TryGetApprovalToolName_ResolvesDirectNamesAndRuntimeFallbacks()
{
Assert.True(
CopilotApprovalCoordinator.TryGetApprovalToolName(
@@ -732,7 +912,7 @@ public sealed class CopilotWorkflowRunnerTests
out string? hookToolName));
Assert.Equal("web_fetch", hookToolName);
Assert.False(
Assert.True(
CopilotApprovalCoordinator.TryGetApprovalToolName(
new PermissionRequestShell
{
@@ -746,7 +926,49 @@ public sealed class CopilotWorkflowRunnerTests
CanOfferSessionApproval = false,
},
out string? shellToolName));
Assert.Null(shellToolName);
Assert.Equal("shell", shellToolName);
}
[Fact]
public void TryGetApprovalToolName_FallsBackToRuntimeApprovalAliasesWhenLookupMissing()
{
Assert.True(
CopilotApprovalCoordinator.TryGetApprovalToolName(
new PermissionRequestRead
{
Kind = "read",
ToolCallId = "tool-call-read",
Intention = "Inspect a file",
Path = "README.md",
},
out string? readToolName));
Assert.Equal("read", readToolName);
Assert.True(
CopilotApprovalCoordinator.TryGetApprovalToolName(
new PermissionRequestWrite
{
Kind = "write",
ToolCallId = "tool-call-write",
Intention = "Update a file",
FileName = "README.md",
Diff = "@@ -1 +1 @@",
},
out string? writeToolName));
Assert.Equal("write", writeToolName);
Assert.True(
CopilotApprovalCoordinator.TryGetApprovalToolName(
new PermissionRequestMemory
{
Kind = "memory",
ToolCallId = "tool-call-memory",
Subject = "repo conventions",
Fact = "Use Bun for script execution.",
Citations = "package.json",
},
out string? memoryToolName));
Assert.Equal("store_memory", memoryToolName);
}
[Fact]
@@ -876,6 +1098,9 @@ public sealed class CopilotWorkflowRunnerTests
Assert.Equal("lsp_ts_hover", approvalEvent.ToolName);
Assert.Equal("Approve lsp_ts_hover", approvalEvent.Title);
Assert.Contains("tool \"lsp_ts_hover\"", approvalEvent.Detail);
Assert.NotNull(approvalEvent.PermissionDetail);
Assert.Equal("custom-tool", approvalEvent.PermissionDetail!.Kind);
Assert.Equal("Hover information", approvalEvent.PermissionDetail.ToolDescription);
}
[Fact]
@@ -907,6 +1132,197 @@ public sealed class CopilotWorkflowRunnerTests
Assert.Contains("url permission", approvalEvent.Detail);
Assert.Contains("tool \"web_fetch\"", approvalEvent.Detail);
Assert.Contains("https://example.com/docs", approvalEvent.Detail);
Assert.NotNull(approvalEvent.PermissionDetail);
Assert.Equal("url", approvalEvent.PermissionDetail!.Kind);
Assert.Equal("Fetch the requested page", approvalEvent.PermissionDetail.Intention);
Assert.Equal("https://example.com/docs", approvalEvent.PermissionDetail.Url);
}
[Fact]
public void BuildPermissionDetail_ExtractsShellRequestData()
{
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
new PermissionRequestShell
{
Kind = "shell",
ToolCallId = "tool-call-shell",
FullCommandText = "curl https://example.com/docs > docs.json",
Intention = "Fetch documentation with curl",
Commands =
[
new PermissionRequestShellCommandsItem
{
Identifier = "curl",
ReadOnly = true,
},
],
PossiblePaths = ["docs.json"],
PossibleUrls =
[
new PermissionRequestShellPossibleUrlsItem
{
Url = "https://example.com/docs",
},
],
HasWriteFileRedirection = true,
CanOfferSessionApproval = false,
Warning = "Downloads remote content and writes it to disk.",
});
Assert.Equal("shell", detail.Kind);
Assert.Equal("curl https://example.com/docs > docs.json", detail.Command);
Assert.Equal("Fetch documentation with curl", detail.Intention);
Assert.Equal("Downloads remote content and writes it to disk.", detail.Warning);
Assert.Equal(["docs.json"], detail.PossiblePaths);
Assert.Equal(["https://example.com/docs"], detail.PossibleUrls);
Assert.True(detail.HasWriteFileRedirection);
}
[Fact]
public void BuildPermissionDetail_ExtractsWriteRequestData()
{
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
new PermissionRequestWrite
{
Kind = "write",
ToolCallId = "tool-call-write",
Intention = "Update README guidance",
FileName = "README.md",
Diff = "@@ -1 +1 @@\n-Hello\n+Hello world",
NewFileContents = "# README",
});
Assert.Equal("write", detail.Kind);
Assert.Equal("Update README guidance", detail.Intention);
Assert.Equal("README.md", detail.FileName);
Assert.Equal("@@ -1 +1 @@\n-Hello\n+Hello world", detail.Diff);
Assert.Equal("# README", detail.NewFileContents);
}
[Fact]
public void BuildPermissionDetail_ExtractsReadRequestData()
{
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
new PermissionRequestRead
{
Kind = "read",
ToolCallId = "tool-call-read",
Intention = "Inspect the README",
Path = "README.md",
});
Assert.Equal("read", detail.Kind);
Assert.Equal("Inspect the README", detail.Intention);
Assert.Equal("README.md", detail.Path);
}
[Fact]
public void BuildPermissionDetail_ExtractsMcpRequestData()
{
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
new PermissionRequestMcp
{
Kind = "mcp",
ToolCallId = "tool-call-mcp",
ServerName = "Git MCP",
ToolName = "git.status",
ToolTitle = "Git Status",
Args = new Dictionary<string, object?>
{
["path"] = ".",
},
ReadOnly = true,
});
Assert.Equal("mcp", detail.Kind);
Assert.Equal("Git MCP", detail.ServerName);
Assert.Equal("Git Status", detail.ToolTitle);
Assert.True(detail.ReadOnly);
Dictionary<string, object?> args = Assert.IsType<Dictionary<string, object?>>(detail.Args);
Assert.Equal(".", args["path"]);
}
[Fact]
public void BuildPermissionDetail_ExtractsUrlRequestData()
{
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
new PermissionRequestUrl
{
Kind = "url",
ToolCallId = "tool-call-url",
Intention = "Fetch the requested page",
Url = "https://example.com/docs",
});
Assert.Equal("url", detail.Kind);
Assert.Equal("Fetch the requested page", detail.Intention);
Assert.Equal("https://example.com/docs", detail.Url);
}
[Fact]
public void BuildPermissionDetail_ExtractsMemoryRequestData()
{
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
new PermissionRequestMemory
{
Kind = "memory",
ToolCallId = "tool-call-memory",
Subject = "repo conventions",
Fact = "Use Bun for script execution.",
Citations = "package.json",
});
Assert.Equal("memory", detail.Kind);
Assert.Equal("repo conventions", detail.Subject);
Assert.Equal("Use Bun for script execution.", detail.Fact);
Assert.Equal("package.json", detail.Citations);
}
[Fact]
public void BuildPermissionDetail_ExtractsCustomToolRequestData()
{
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
new PermissionRequestCustomTool
{
Kind = "custom tool",
ToolName = "lsp_ts_hover",
ToolDescription = "Hover information",
Args = new Dictionary<string, object?>
{
["file"] = "src/index.ts",
["line"] = 12,
},
});
Assert.Equal("custom-tool", detail.Kind);
Assert.Equal("Hover information", detail.ToolDescription);
Dictionary<string, object?> args = Assert.IsType<Dictionary<string, object?>>(detail.Args);
Assert.Equal("src/index.ts", args["file"]);
Assert.Equal(12, args["line"]);
}
[Fact]
public void BuildPermissionDetail_ExtractsHookRequestData()
{
PermissionDetailDto detail = CopilotApprovalCoordinator.BuildPermissionDetail(
new PermissionRequestHook
{
Kind = "hook",
ToolName = "web_fetch",
ToolArgs = new Dictionary<string, object?>
{
["url"] = "https://example.com",
},
HookMessage = "Review required before fetch",
});
Assert.Equal("hook", detail.Kind);
Assert.Equal("Review required before fetch", detail.HookMessage);
Dictionary<string, object?> args = Assert.IsType<Dictionary<string, object?>>(detail.Args);
Assert.Equal("https://example.com", args["url"]);
}
[Fact]
@@ -984,6 +1400,170 @@ public sealed class CopilotWorkflowRunnerTests
Assert.Equal(PermissionRequestResultKind.Approved, result.Kind);
}
[Fact]
public async Task RequestApprovalAsync_AlwaysApproveCachesRuntimeApprovalForCurrentTurn()
{
CopilotApprovalCoordinator coordinator = new();
ApprovalRequestedEventDto? firstApproval = null;
RunTurnCommandDto command = CreateApprovalCommand();
Task<PermissionRequestResult> firstPending = coordinator.RequestApprovalAsync(
command,
command.Pattern.Agents[0],
new PermissionRequestRead
{
Kind = "read",
ToolCallId = "tool-call-read-1",
Intention = "Inspect README guidance",
Path = "README.md",
},
new PermissionInvocation
{
SessionId = "copilot-session-1",
},
new Dictionary<string, string>(StringComparer.Ordinal)
{
["tool-call-read-1"] = "view",
},
approval =>
{
firstApproval = approval;
return Task.CompletedTask;
},
CancellationToken.None);
Assert.False(firstPending.IsCompleted);
Assert.NotNull(firstApproval);
await coordinator.ResolveApprovalAsync(
new ResolveApprovalCommandDto
{
ApprovalId = firstApproval!.ApprovalId,
Decision = "approved",
AlwaysApprove = true,
},
CancellationToken.None);
PermissionRequestResult firstResult = await firstPending;
Assert.Equal(PermissionRequestResultKind.Approved, firstResult.Kind);
bool sawSecondApproval = false;
PermissionRequestResult secondResult = await coordinator.RequestApprovalAsync(
command,
command.Pattern.Agents[0],
new PermissionRequestRead
{
Kind = "read",
ToolCallId = "tool-call-read-2",
Intention = "Inspect docs guidance",
Path = "docs\\guide.md",
},
new PermissionInvocation
{
SessionId = "copilot-session-1",
},
new Dictionary<string, string>(StringComparer.Ordinal)
{
["tool-call-read-2"] = "grep",
},
approval =>
{
sawSecondApproval = true;
return Task.CompletedTask;
},
CancellationToken.None);
Assert.False(sawSecondApproval);
Assert.Equal(PermissionRequestResultKind.Approved, secondResult.Kind);
}
[Fact]
public async Task RequestApprovalAsync_AlwaysApproveCacheDoesNotCarryAcrossTurnRequests()
{
CopilotApprovalCoordinator coordinator = new();
ApprovalRequestedEventDto? firstApproval = null;
RunTurnCommandDto firstCommand = CreateApprovalCommand();
Task<PermissionRequestResult> firstPending = coordinator.RequestApprovalAsync(
firstCommand,
firstCommand.Pattern.Agents[0],
new PermissionRequestRead
{
Kind = "read",
ToolCallId = "tool-call-read-1",
Intention = "Inspect README guidance",
Path = "README.md",
},
new PermissionInvocation
{
SessionId = "copilot-session-1",
},
new Dictionary<string, string>(StringComparer.Ordinal)
{
["tool-call-read-1"] = "view",
},
approval =>
{
firstApproval = approval;
return Task.CompletedTask;
},
CancellationToken.None);
Assert.NotNull(firstApproval);
await coordinator.ResolveApprovalAsync(
new ResolveApprovalCommandDto
{
ApprovalId = firstApproval!.ApprovalId,
Decision = "approved",
AlwaysApprove = true,
},
CancellationToken.None);
await firstPending;
ApprovalRequestedEventDto? secondApproval = null;
RunTurnCommandDto secondCommand = CreateApprovalCommand(requestId: "turn-2");
Task<PermissionRequestResult> secondPending = coordinator.RequestApprovalAsync(
secondCommand,
secondCommand.Pattern.Agents[0],
new PermissionRequestRead
{
Kind = "read",
ToolCallId = "tool-call-read-2",
Intention = "Inspect docs guidance",
Path = "docs\\guide.md",
},
new PermissionInvocation
{
SessionId = "copilot-session-1",
},
new Dictionary<string, string>(StringComparer.Ordinal)
{
["tool-call-read-2"] = "grep",
},
approval =>
{
secondApproval = approval;
return Task.CompletedTask;
},
CancellationToken.None);
Assert.False(secondPending.IsCompleted);
Assert.NotNull(secondApproval);
await coordinator.ResolveApprovalAsync(
new ResolveApprovalCommandDto
{
ApprovalId = secondApproval!.ApprovalId,
Decision = "approved",
},
CancellationToken.None);
PermissionRequestResult secondResult = await secondPending;
Assert.Equal(PermissionRequestResultKind.Approved, secondResult.Kind);
}
[Fact]
public async Task ResolveApprovalAsync_RejectsUnknownApprovalIds()
{
@@ -1033,11 +1613,38 @@ public sealed class CopilotWorkflowRunnerTests
};
}
private static RunTurnCommandDto CreateApprovalCommand()
private static RequestInfoEvent CreateRequestInfoEvent(object payload)
{
RequestPort port = RequestPort.Create<object, object>("test-port");
ExternalRequest request = ExternalRequest.Create(port, payload, "request-1");
return new RequestInfoEvent(request);
}
private static object CreateHandoffTarget(string id, string name)
{
Type type = Type.GetType(
"Microsoft.Agents.AI.Workflows.Specialized.HandoffTarget, Microsoft.Agents.AI.Workflows",
throwOnError: true)!;
return Activator.CreateInstance(type, CreateChatClientAgent(id, name), "Handle the UX work.")!;
}
private static ChatClientAgent CreateChatClientAgent(string id, string name)
{
return new ChatClientAgent(
new StubChatClient(),
id,
name,
"Stub agent for handoff tests.",
[],
null!,
null!);
}
private static RunTurnCommandDto CreateApprovalCommand(string requestId = "turn-1")
{
return new RunTurnCommandDto
{
RequestId = "turn-1",
RequestId = requestId,
SessionId = "session-1",
Pattern = new PatternDefinitionDto
{
@@ -1064,4 +1671,33 @@ public sealed class CopilotWorkflowRunnerTests
},
};
}
private sealed class StubChatClient : IChatClient
{
public Task<ChatResponse> GetResponseAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options,
CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
IEnumerable<ChatMessage> messages,
ChatOptions? options,
[EnumeratorCancellation]
CancellationToken cancellationToken)
{
yield break;
}
public object? GetService(Type serviceType, object? serviceKey)
{
return null;
}
public void Dispose()
{
}
}
}
@@ -0,0 +1,127 @@
using Aryx.AgentHost.Contracts;
using Aryx.AgentHost.Services;
namespace Aryx.AgentHost.Tests;
public sealed class HookCommandRunnerTests
{
[Fact]
public async Task RunAsync_PipesJsonIntoHookStandardInput()
{
HookCommandRunner runner = new();
using TestDirectory project = new();
HookCommandDefinition hook = CreatePlatformHook(
OperatingSystem.IsWindows()
? "$payload = [Console]::In.ReadToEnd(); Write-Output $payload"
: "payload=$(cat); printf '%s' \"$payload\"");
string input = """{"toolName":"view","toolArgs":"{\"path\":\"README.md\"}"}""";
string? output = await runner.RunAsync(hook, input, project.Path, CancellationToken.None);
Assert.Equal(input, output?.Trim());
}
[Fact]
public async Task RunAsync_ReturnsNullWhenHookTimesOut()
{
HookCommandRunner runner = new();
using TestDirectory project = new();
HookCommandDefinition hook = CreatePlatformHook(
OperatingSystem.IsWindows() ? "Start-Sleep -Seconds 5" : "sleep 5",
timeoutSec: 1);
string? output = await runner.RunAsync(hook, "{}", project.Path, CancellationToken.None);
Assert.Null(output);
}
[Fact]
public async Task RunAsync_ReturnsNullWhenHookFails()
{
HookCommandRunner runner = new();
using TestDirectory project = new();
HookCommandDefinition hook = CreatePlatformHook(
OperatingSystem.IsWindows() ? "Write-Error 'boom'; exit 1" : "echo boom >&2; exit 1");
string? output = await runner.RunAsync(hook, "{}", project.Path, CancellationToken.None);
Assert.Null(output);
}
[Fact]
public async Task RunAsync_ReturnsNullWhenCurrentPlatformCommandIsMissing()
{
HookCommandRunner runner = new();
using TestDirectory project = new();
HookCommandDefinition hook = OperatingSystem.IsWindows()
? new HookCommandDefinition { Type = "command", Bash = "echo unsupported" }
: new HookCommandDefinition { Type = "command", PowerShell = "Write-Output unsupported" };
string? output = await runner.RunAsync(hook, "{}", project.Path, CancellationToken.None);
Assert.Null(output);
}
[Fact]
public async Task RunAsync_UsesConfiguredWorkingDirectoryAndEnvironment()
{
HookCommandRunner runner = new();
using TestDirectory project = new();
string hooksDirectory = Directory.CreateDirectory(Path.Combine(project.Path, "scripts")).FullName;
await File.WriteAllTextAsync(Path.Combine(hooksDirectory, "cwd-marker.txt"), "marker");
HookCommandDefinition hook = CreatePlatformHook(
OperatingSystem.IsWindows()
? "$null = [Console]::In.ReadToEnd(); if (Test-Path -LiteralPath './cwd-marker.txt') { $status = 'present' } else { $status = 'missing' }; Write-Output ($status + '|' + $env:HOOK_TEST_ENV)"
: "cat >/dev/null; if [ -f ./cwd-marker.txt ]; then status=present; else status=missing; fi; printf '%s|%s' \"$status\" \"$HOOK_TEST_ENV\"",
cwd: "scripts",
env: new Dictionary<string, string>
{
["HOOK_TEST_ENV"] = "configured",
});
string? output = await runner.RunAsync(hook, "{}", project.Path, CancellationToken.None);
Assert.Equal("present|configured", output?.Trim());
}
private static HookCommandDefinition CreatePlatformHook(
string command,
int? timeoutSec = null,
string? cwd = null,
IReadOnlyDictionary<string, string>? env = null)
{
return OperatingSystem.IsWindows()
? new HookCommandDefinition
{
Type = "command",
PowerShell = command,
TimeoutSec = timeoutSec,
Cwd = cwd,
Env = env,
}
: new HookCommandDefinition
{
Type = "command",
Bash = command,
TimeoutSec = timeoutSec,
Cwd = cwd,
Env = env,
};
}
private sealed class TestDirectory : IDisposable
{
private readonly DirectoryInfo _directory = Directory.CreateTempSubdirectory("aryx-hooks-runner-");
public string Path => _directory.FullName;
public void Dispose()
{
if (_directory.Exists)
{
_directory.Delete(recursive: true);
}
}
}
}
@@ -0,0 +1,204 @@
using Aryx.AgentHost.Contracts;
using Aryx.AgentHost.Services;
namespace Aryx.AgentHost.Tests;
public sealed class HookConfigLoaderTests
{
[Fact]
public async Task LoadAsync_ParsesSupportedHookTypes()
{
using TestDirectory project = new();
string hooksDirectory = Directory.CreateDirectory(Path.Combine(project.Path, ".github", "hooks")).FullName;
await File.WriteAllTextAsync(
Path.Combine(hooksDirectory, "hooks.json"),
"""
{
"version": 1,
"hooks": {
"sessionStart": [
{
"type": "command",
"bash": "echo session-start",
"powershell": "Write-Output session-start",
"cwd": ".",
"env": { "HOOK_MODE": "audit" },
"timeoutSec": 15
}
],
"preToolUse": [
{
"type": "command",
"bash": "echo pre-tool",
"powershell": "Write-Output pre-tool"
}
],
"errorOccurred": [
{
"type": "command",
"bash": "echo error-hook",
"powershell": "Write-Output error-hook"
}
]
}
}
""");
ResolvedHookSet hooks = await HookConfigLoader.LoadAsync(project.Path, CancellationToken.None);
HookCommandDefinition sessionStart = Assert.Single(hooks.SessionStart);
Assert.Equal("command", sessionStart.Type);
Assert.Equal("echo session-start", sessionStart.Bash);
Assert.Equal("Write-Output session-start", sessionStart.PowerShell);
Assert.Equal(".", sessionStart.Cwd);
Assert.Equal(15, sessionStart.TimeoutSec);
Assert.NotNull(sessionStart.Env);
Assert.Equal("audit", sessionStart.Env["HOOK_MODE"]);
Assert.Single(hooks.PreToolUse);
Assert.Single(hooks.ErrorOccurred);
Assert.False(hooks.IsEmpty);
}
[Fact]
public async Task LoadAsync_MergesHookFilesInFileNameOrder()
{
using TestDirectory project = new();
string hooksDirectory = Directory.CreateDirectory(Path.Combine(project.Path, ".github", "hooks")).FullName;
await File.WriteAllTextAsync(
Path.Combine(hooksDirectory, "20-second.json"),
"""
{
"version": 1,
"hooks": {
"preToolUse": [
{
"type": "command",
"bash": "echo second",
"powershell": "Write-Output second"
}
]
}
}
""");
await File.WriteAllTextAsync(
Path.Combine(hooksDirectory, "10-first.json"),
"""
{
"version": 1,
"hooks": {
"preToolUse": [
{
"type": "command",
"bash": "echo first",
"powershell": "Write-Output first"
}
]
}
}
""");
ResolvedHookSet hooks = await HookConfigLoader.LoadAsync(project.Path, CancellationToken.None);
string[] commands = hooks.PreToolUse.Select(GetCommandText).ToArray();
Assert.Equal(2, commands.Length);
Assert.Contains("first", commands[0], StringComparison.Ordinal);
Assert.Contains("second", commands[1], StringComparison.Ordinal);
}
[Fact]
public async Task LoadAsync_ReturnsEmptyWhenHooksDirectoryIsMissing()
{
using TestDirectory project = new();
ResolvedHookSet hooks = await HookConfigLoader.LoadAsync(project.Path, CancellationToken.None);
Assert.Same(ResolvedHookSet.Empty, hooks);
}
[Fact]
public async Task LoadAsync_SkipsInvalidFilesAndUnsupportedVersions()
{
using TestDirectory project = new();
string hooksDirectory = Directory.CreateDirectory(Path.Combine(project.Path, ".github", "hooks")).FullName;
await File.WriteAllTextAsync(Path.Combine(hooksDirectory, "00-invalid.json"), "{ not-json");
await File.WriteAllTextAsync(
Path.Combine(hooksDirectory, "10-unsupported.json"),
"""
{
"version": 2,
"hooks": {
"sessionStart": [
{
"type": "command",
"bash": "echo unsupported",
"powershell": "Write-Output unsupported"
}
]
}
}
""");
await File.WriteAllTextAsync(
Path.Combine(hooksDirectory, "20-valid.json"),
"""
{
"version": 1,
"hooks": {
"sessionEnd": [
{
"type": "command",
"bash": "echo valid",
"powershell": "Write-Output valid"
}
]
}
}
""");
ResolvedHookSet hooks = await HookConfigLoader.LoadAsync(project.Path, CancellationToken.None);
HookCommandDefinition valid = Assert.Single(hooks.SessionEnd);
Assert.Contains("valid", GetCommandText(valid), StringComparison.Ordinal);
Assert.Empty(hooks.SessionStart);
}
[Fact]
public async Task LoadAsync_ReturnsEmptyForEmptyHooksObject()
{
using TestDirectory project = new();
string hooksDirectory = Directory.CreateDirectory(Path.Combine(project.Path, ".github", "hooks")).FullName;
await File.WriteAllTextAsync(
Path.Combine(hooksDirectory, "hooks.json"),
"""
{
"version": 1,
"hooks": {}
}
""");
ResolvedHookSet hooks = await HookConfigLoader.LoadAsync(project.Path, CancellationToken.None);
Assert.Same(ResolvedHookSet.Empty, hooks);
}
private static string GetCommandText(HookCommandDefinition hook)
=> hook.PowerShell ?? hook.Bash ?? string.Empty;
private sealed class TestDirectory : IDisposable
{
private readonly DirectoryInfo _directory = Directory.CreateTempSubdirectory("aryx-hooks-loader-");
public string Path => _directory.FullName;
public void Dispose()
{
if (_directory.Exists)
{
_directory.Delete(recursive: true);
}
}
}
}
@@ -1,6 +1,7 @@
using System.Text.Json;
using Aryx.AgentHost.Contracts;
using Aryx.AgentHost.Services;
using GitHub.Copilot.SDK.Rpc;
namespace Aryx.AgentHost.Tests;
@@ -112,7 +113,7 @@ public sealed class SidecarProtocolHostTests
{
SidecarProtocolHost host = new(
new PatternValidator(),
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, cancellationToken) =>
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
{
await onActivity(new AgentActivityEventDto
{
@@ -231,12 +232,49 @@ public sealed class SidecarProtocolHostTests
});
}
[Fact]
public async Task RunTurnCommand_DeserializesInteractionMode()
{
string? capturedMode = null;
SidecarProtocolHost host = new(
new PatternValidator(),
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
{
capturedMode = command.Mode;
return [];
}));
await RunHostAsync(
new RunTurnCommandDto
{
Type = "run-turn",
RequestId = "turn-plan",
SessionId = "session-1",
ProjectPath = "C:\\workspace\\project",
Mode = "plan",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "Single Agent",
Mode = "single",
Availability = "available",
Agents =
[
CreateAgent(name: "Primary"),
],
},
},
host);
Assert.Equal("plan", capturedMode);
}
[Fact]
public async Task RunTurnCommand_ReturnsApprovalEvents()
{
SidecarProtocolHost host = new(
new PatternValidator(),
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, cancellationToken) =>
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
{
await onApproval(new ApprovalRequestedEventDto
{
@@ -249,6 +287,13 @@ public sealed class SidecarProtocolHostTests
AgentName = "Primary",
PermissionKind = "tool access",
Title = "Approve tool access",
PermissionDetail = new PermissionDetailDto
{
Kind = "shell",
Command = "git status",
Intention = "Inspect repository state",
PossiblePaths = ["README.md"],
},
});
return [];
@@ -284,6 +329,11 @@ public sealed class SidecarProtocolHostTests
Assert.Equal("approval-1", approvalEvent.GetProperty("approvalId").GetString());
Assert.Equal("tool-call", approvalEvent.GetProperty("approvalKind").GetString());
Assert.Equal("Approve tool access", approvalEvent.GetProperty("title").GetString());
JsonElement permissionDetail = approvalEvent.GetProperty("permissionDetail");
Assert.Equal("shell", permissionDetail.GetProperty("kind").GetString());
Assert.Equal("git status", permissionDetail.GetProperty("command").GetString());
Assert.Equal("Inspect repository state", permissionDetail.GetProperty("intention").GetString());
Assert.Equal("README.md", Assert.Single(permissionDetail.GetProperty("possiblePaths").EnumerateArray()).GetString());
},
completionEvent =>
{
@@ -297,12 +347,218 @@ public sealed class SidecarProtocolHostTests
});
}
[Fact]
public async Task RunTurnCommand_ReturnsUserInputEvents()
{
SidecarProtocolHost host = new(
new PatternValidator(),
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
{
await onUserInput(new UserInputRequestedEventDto
{
Type = "user-input-requested",
RequestId = command.RequestId,
SessionId = command.SessionId,
UserInputId = "user-input-1",
AgentId = "agent-1",
AgentName = "Primary",
Question = "What should I do next?",
Choices = ["Continue", "Stop"],
AllowFreeform = true,
});
return [];
}));
IReadOnlyList<JsonElement> events = await RunHostAsync(
new RunTurnCommandDto
{
Type = "run-turn",
RequestId = "turn-user-input",
SessionId = "session-1",
ProjectPath = "C:\\workspace\\project",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "Single Agent",
Mode = "single",
Availability = "available",
Agents =
[
CreateAgent(name: "Primary"),
],
},
},
host);
Assert.Collection(
events,
userInputEvent =>
{
Assert.Equal("user-input-requested", userInputEvent.GetProperty("type").GetString());
Assert.Equal("turn-user-input", userInputEvent.GetProperty("requestId").GetString());
Assert.Equal("session-1", userInputEvent.GetProperty("sessionId").GetString());
Assert.Equal("user-input-1", userInputEvent.GetProperty("userInputId").GetString());
Assert.Equal("Primary", userInputEvent.GetProperty("agentName").GetString());
Assert.Equal("What should I do next?", userInputEvent.GetProperty("question").GetString());
string[] choices = userInputEvent.GetProperty("choices")
.EnumerateArray()
.Select(choice => choice.GetString() ?? string.Empty)
.ToArray();
Assert.Equal(["Continue", "Stop"], choices);
Assert.True(userInputEvent.GetProperty("allowFreeform").GetBoolean());
},
completionEvent =>
{
Assert.Equal("turn-complete", completionEvent.GetProperty("type").GetString());
Assert.False(completionEvent.GetProperty("cancelled").GetBoolean());
},
commandCompleteEvent =>
{
Assert.Equal("command-complete", commandCompleteEvent.GetProperty("type").GetString());
Assert.Equal("turn-user-input", commandCompleteEvent.GetProperty("requestId").GetString());
});
}
[Fact]
public async Task RunTurnCommand_ReturnsMcpOauthRequiredEvents()
{
SidecarProtocolHost host = new(
new PatternValidator(),
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
{
await onMcpOAuthRequired(new McpOauthRequiredEventDto
{
Type = "mcp-oauth-required",
RequestId = command.RequestId,
SessionId = command.SessionId,
OauthRequestId = "oauth-request-1",
AgentId = "agent-1",
AgentName = "Primary",
ServerName = "Example MCP",
ServerUrl = "https://example.com/mcp",
StaticClientConfig = new McpOauthStaticClientConfigDto
{
ClientId = "aryx-client",
PublicClient = true,
},
});
return [];
}));
IReadOnlyList<JsonElement> events = await RunHostAsync(
CreateRunTurnCommand(requestId: "turn-mcp-oauth"),
host);
Assert.Collection(
events,
oauthEvent =>
{
Assert.Equal("mcp-oauth-required", oauthEvent.GetProperty("type").GetString());
Assert.Equal("turn-mcp-oauth", oauthEvent.GetProperty("requestId").GetString());
Assert.Equal("session-1", oauthEvent.GetProperty("sessionId").GetString());
Assert.Equal("oauth-request-1", oauthEvent.GetProperty("oauthRequestId").GetString());
Assert.Equal("Primary", oauthEvent.GetProperty("agentName").GetString());
Assert.Equal("Example MCP", oauthEvent.GetProperty("serverName").GetString());
Assert.Equal("https://example.com/mcp", oauthEvent.GetProperty("serverUrl").GetString());
JsonElement staticClientConfig = oauthEvent.GetProperty("staticClientConfig");
Assert.Equal("aryx-client", staticClientConfig.GetProperty("clientId").GetString());
Assert.True(staticClientConfig.GetProperty("publicClient").GetBoolean());
},
completionEvent =>
{
Assert.Equal("turn-complete", completionEvent.GetProperty("type").GetString());
Assert.False(completionEvent.GetProperty("cancelled").GetBoolean());
},
commandCompleteEvent =>
{
Assert.Equal("command-complete", commandCompleteEvent.GetProperty("type").GetString());
Assert.Equal("turn-mcp-oauth", commandCompleteEvent.GetProperty("requestId").GetString());
});
}
[Fact]
public async Task RunTurnCommand_ReturnsExitPlanModeEvents()
{
SidecarProtocolHost host = new(
new PatternValidator(),
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
{
await onExitPlanMode(new ExitPlanModeRequestedEventDto
{
Type = "exit-plan-mode-requested",
RequestId = command.RequestId,
SessionId = command.SessionId,
ExitPlanId = "exit-plan-1",
AgentId = "agent-1",
AgentName = "Primary",
Summary = "Proposed implementation plan",
PlanContent = "1. Inspect\n2. Change\n3. Validate",
Actions = ["interactive", "autopilot"],
RecommendedAction = "interactive",
});
return [];
}));
IReadOnlyList<JsonElement> events = await RunHostAsync(
new RunTurnCommandDto
{
Type = "run-turn",
RequestId = "turn-plan-mode",
SessionId = "session-1",
ProjectPath = "C:\\workspace\\project",
Mode = "plan",
Pattern = new PatternDefinitionDto
{
Id = "pattern-1",
Name = "Single Agent",
Mode = "single",
Availability = "available",
Agents =
[
CreateAgent(name: "Primary"),
],
},
},
host);
Assert.Collection(
events,
exitPlanEvent =>
{
Assert.Equal("exit-plan-mode-requested", exitPlanEvent.GetProperty("type").GetString());
Assert.Equal("turn-plan-mode", exitPlanEvent.GetProperty("requestId").GetString());
Assert.Equal("exit-plan-1", exitPlanEvent.GetProperty("exitPlanId").GetString());
Assert.Equal("Primary", exitPlanEvent.GetProperty("agentName").GetString());
Assert.Equal("Proposed implementation plan", exitPlanEvent.GetProperty("summary").GetString());
Assert.Equal("1. Inspect\n2. Change\n3. Validate", exitPlanEvent.GetProperty("planContent").GetString());
string[] actions = exitPlanEvent.GetProperty("actions")
.EnumerateArray()
.Select(action => action.GetString() ?? string.Empty)
.ToArray();
Assert.Equal(["interactive", "autopilot"], actions);
Assert.Equal("interactive", exitPlanEvent.GetProperty("recommendedAction").GetString());
},
completionEvent =>
{
Assert.Equal("turn-complete", completionEvent.GetProperty("type").GetString());
Assert.False(completionEvent.GetProperty("cancelled").GetBoolean());
},
commandCompleteEvent =>
{
Assert.Equal("command-complete", commandCompleteEvent.GetProperty("type").GetString());
Assert.Equal("turn-plan-mode", commandCompleteEvent.GetProperty("requestId").GetString());
});
}
[Fact]
public async Task CancelTurnCommand_CancelsInProgressTurnAndCompletesBothCommands()
{
SidecarProtocolHost host = new(
new PatternValidator(),
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, cancellationToken) =>
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
{
await Task.Delay(Timeout.Infinite, cancellationToken);
return [];
@@ -350,7 +606,7 @@ public sealed class SidecarProtocolHostTests
{
SidecarProtocolHost host = new(
new PatternValidator(),
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, cancellationToken) => []));
new FakeWorkflowRunner(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => []));
await RunHostAsync(CreateRunTurnCommand(requestId: "turn-completed"), host);
@@ -373,7 +629,7 @@ public sealed class SidecarProtocolHostTests
SidecarProtocolHost host = new(
new PatternValidator(),
new FakeWorkflowRunner(
handler: async (command, onDelta, onActivity, onApproval, cancellationToken) => [],
handler: async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => [],
resolveApprovalHandler: (command, cancellationToken) =>
{
captured = command;
@@ -387,6 +643,7 @@ public sealed class SidecarProtocolHostTests
RequestId = "approval-command-1",
ApprovalId = "approval-1",
Decision = "approved",
AlwaysApprove = true,
},
host);
@@ -395,6 +652,93 @@ public sealed class SidecarProtocolHostTests
Assert.Equal("approval-command-1", completionEvent.GetProperty("requestId").GetString());
Assert.Equal("approval-1", captured?.ApprovalId);
Assert.Equal("approved", captured?.Decision);
Assert.True(captured?.AlwaysApprove ?? false);
}
[Fact]
public async Task ResolveUserInputCommand_DelegatesToWorkflowRunnerAndCompletes()
{
ResolveUserInputCommandDto? captured = null;
SidecarProtocolHost host = new(
new PatternValidator(),
new FakeWorkflowRunner(
handler: async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) => [],
resolveUserInputHandler: (command, cancellationToken) =>
{
captured = command;
return Task.CompletedTask;
}));
IReadOnlyList<JsonElement> events = await RunHostAsync(
new ResolveUserInputCommandDto
{
Type = "resolve-user-input",
RequestId = "user-input-command-1",
UserInputId = "user-input-1",
Answer = "Continue",
WasFreeform = false,
},
host);
JsonElement completionEvent = Assert.Single(events);
Assert.Equal("command-complete", completionEvent.GetProperty("type").GetString());
Assert.Equal("user-input-command-1", completionEvent.GetProperty("requestId").GetString());
Assert.Equal("user-input-1", captured?.UserInputId);
Assert.Equal("Continue", captured?.Answer);
Assert.False(captured?.WasFreeform);
}
[Fact]
public void MapRuntimeTools_ExcludesOnlyInternalMetaToolsAndDeduplicatesByName()
{
IReadOnlyList<SidecarRuntimeToolDto> runtimeTools = SidecarProtocolHost.MapRuntimeTools(
[
new Tool
{
Name = "ask_user",
Description = "Ask the user a question.",
},
new Tool
{
Name = "report_intent",
Description = "Report current intent.",
},
new Tool
{
Name = "task_complete",
Description = "Signal task completion.",
},
new Tool
{
Name = "exit_plan_mode",
Description = "Exit plan mode.",
},
new Tool
{
Name = " web_fetch ",
Description = " Fetch content from the web. ",
},
new Tool
{
Name = "WEB_FETCH",
Description = "Duplicate entry",
},
]);
Assert.Collection(
runtimeTools,
exitPlanTool =>
{
Assert.Equal("exit_plan_mode", exitPlanTool.Id);
Assert.Equal("exit_plan_mode", exitPlanTool.Label);
Assert.Equal("Exit plan mode.", exitPlanTool.Description);
},
runtimeTool =>
{
Assert.Equal("web_fetch", runtimeTool.Id);
Assert.Equal("web_fetch", runtimeTool.Label);
Assert.Equal("Fetch content from the web.", runtimeTool.Description);
});
}
[Fact]
@@ -436,6 +780,147 @@ public sealed class SidecarProtocolHostTests
Assert.False(string.IsNullOrWhiteSpace(diagnostics.CheckedAt));
}
[Fact]
public async Task ListSessionsCommand_ReturnsSessionsListedEvent()
{
SidecarProtocolHost host = new(
new PatternValidator(),
sessionManager: new FakeSessionManager
{
Sessions =
[
new CopilotSessionInfoDto
{
CopilotSessionId = "aryx::session-1::agent-1",
ManagedByAryx = true,
SessionId = "session-1",
AgentId = "agent-1",
Summary = "Review session",
},
],
});
IReadOnlyList<JsonElement> events = await RunHostAsync(
new ListSessionsCommandDto
{
Type = "list-sessions",
RequestId = "list-1",
},
host);
JsonElement listedEvent = AssertSingleEvent(events, "sessions-listed", "list-1");
JsonElement session = Assert.Single(listedEvent.GetProperty("sessions").EnumerateArray());
Assert.Equal("aryx::session-1::agent-1", session.GetProperty("copilotSessionId").GetString());
Assert.Equal("session-1", session.GetProperty("sessionId").GetString());
}
[Fact]
public async Task DeleteSessionCommand_ReturnsDeletedSessionsEvent()
{
FakeSessionManager sessionManager = new()
{
DeletedSessions =
[
new CopilotSessionInfoDto
{
CopilotSessionId = "aryx::session-1::agent-1",
ManagedByAryx = true,
SessionId = "session-1",
AgentId = "agent-1",
},
],
};
SidecarProtocolHost host = new(
new PatternValidator(),
sessionManager: sessionManager);
IReadOnlyList<JsonElement> events = await RunHostAsync(
new DeleteSessionCommandDto
{
Type = "delete-session",
RequestId = "delete-1",
SessionId = "session-1",
},
host);
JsonElement deletedEvent = AssertSingleEvent(events, "sessions-deleted", "delete-1");
JsonElement session = Assert.Single(deletedEvent.GetProperty("sessions").EnumerateArray());
Assert.Equal("session-1", deletedEvent.GetProperty("sessionId").GetString());
Assert.Equal("aryx::session-1::agent-1", session.GetProperty("copilotSessionId").GetString());
Assert.Equal("session-1", sessionManager.DeletedAryxSessionId);
}
[Fact]
public async Task GetQuotaCommand_ReturnsQuotaResultEvent()
{
SidecarProtocolHost host = new(
new PatternValidator(),
sessionManager: new FakeSessionManager
{
QuotaSnapshots = new Dictionary<string, QuotaSnapshotDto>(StringComparer.Ordinal)
{
["premium_interactions"] = new()
{
EntitlementRequests = 50,
UsedRequests = 12,
RemainingPercentage = 76,
Overage = 0,
OverageAllowedWithExhaustedQuota = true,
ResetDate = "2026-04-01T00:00:00Z",
},
},
});
IReadOnlyList<JsonElement> events = await RunHostAsync(
new GetQuotaCommandDto
{
Type = "get-quota",
RequestId = "quota-1",
},
host);
JsonElement quotaEvent = AssertSingleEvent(events, "quota-result", "quota-1");
JsonElement snapshot = quotaEvent.GetProperty("quotaSnapshots").GetProperty("premium_interactions");
Assert.Equal(50, snapshot.GetProperty("entitlementRequests").GetDouble());
Assert.Equal(12, snapshot.GetProperty("usedRequests").GetDouble());
Assert.Equal(76, snapshot.GetProperty("remainingPercentage").GetDouble());
Assert.True(snapshot.GetProperty("overageAllowedWithExhaustedQuota").GetBoolean());
Assert.Equal("2026-04-01T00:00:00Z", snapshot.GetProperty("resetDate").GetString());
}
[Fact]
public async Task DisconnectSessionCommand_CancelsActiveTurnsForSession()
{
FakeWorkflowRunner runner = new(async (command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken) =>
{
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
return [];
});
SidecarProtocolHost host = new(new PatternValidator(), runner);
IReadOnlyList<JsonElement> events = await RunHostAsync(
[
CreateRunTurnCommand(requestId: "turn-1", sessionId: "session-1"),
new DisconnectSessionCommandDto
{
Type = "disconnect-session",
RequestId = "disconnect-1",
SessionId = "session-1",
},
],
host);
JsonElement disconnectedEvent = AssertSingleEvent(events, "session-disconnected", "disconnect-1");
string[] cancelledRequestIds = disconnectedEvent.GetProperty("cancelledRequestIds")
.EnumerateArray()
.Select(value => value.GetString() ?? string.Empty)
.ToArray();
Assert.Equal(["turn-1"], cancelledRequestIds);
JsonElement turnComplete = AssertSingleEvent(events, "turn-complete", "turn-1");
Assert.True(turnComplete.GetProperty("cancelled").GetBoolean());
}
private static async Task<IReadOnlyList<JsonElement>> RunHostAsync(
object command,
SidecarProtocolHost? host = null)
@@ -464,9 +949,9 @@ public sealed class SidecarProtocolHostTests
string eventType,
string requestId)
{
return Assert.Single(events.Where(evt =>
return Assert.Single(events, evt =>
evt.GetProperty("type").GetString() == eventType
&& evt.GetProperty("requestId").GetString() == requestId));
&& evt.GetProperty("requestId").GetString() == requestId);
}
private static SidecarProtocolHost CreateHostForTests()
@@ -605,34 +1090,46 @@ public sealed class SidecarProtocolHostTests
private readonly Func<
RunTurnCommandDto,
Func<TurnDeltaEventDto, Task>,
Func<AgentActivityEventDto, Task>,
Func<SidecarEventDto, Task>,
Func<ApprovalRequestedEventDto, Task>,
Func<UserInputRequestedEventDto, Task>,
Func<McpOauthRequiredEventDto, Task>,
Func<ExitPlanModeRequestedEventDto, Task>,
CancellationToken,
Task<IReadOnlyList<ChatMessageDto>>> _handler;
private readonly Func<ResolveApprovalCommandDto, CancellationToken, Task> _resolveApprovalHandler;
private readonly Func<ResolveUserInputCommandDto, CancellationToken, Task> _resolveUserInputHandler;
public FakeWorkflowRunner(
Func<
RunTurnCommandDto,
Func<TurnDeltaEventDto, Task>,
Func<AgentActivityEventDto, Task>,
Func<SidecarEventDto, Task>,
Func<ApprovalRequestedEventDto, Task>,
Func<UserInputRequestedEventDto, Task>,
Func<McpOauthRequiredEventDto, Task>,
Func<ExitPlanModeRequestedEventDto, Task>,
CancellationToken,
Task<IReadOnlyList<ChatMessageDto>>> handler,
Func<ResolveApprovalCommandDto, CancellationToken, Task>? resolveApprovalHandler = null)
Func<ResolveApprovalCommandDto, CancellationToken, Task>? resolveApprovalHandler = null,
Func<ResolveUserInputCommandDto, CancellationToken, Task>? resolveUserInputHandler = null)
{
_handler = handler;
_resolveApprovalHandler = resolveApprovalHandler ?? ((_, _) => Task.CompletedTask);
_resolveUserInputHandler = resolveUserInputHandler ?? ((_, _) => Task.CompletedTask);
}
public Task<IReadOnlyList<ChatMessageDto>> RunTurnAsync(
RunTurnCommandDto command,
Func<TurnDeltaEventDto, Task> onDelta,
Func<AgentActivityEventDto, Task> onActivity,
Func<SidecarEventDto, Task> onActivity,
Func<ApprovalRequestedEventDto, Task> onApproval,
Func<UserInputRequestedEventDto, Task> onUserInput,
Func<McpOauthRequiredEventDto, Task> onMcpOAuthRequired,
Func<ExitPlanModeRequestedEventDto, Task> onExitPlanMode,
CancellationToken cancellationToken)
{
return _handler(command, onDelta, onActivity, onApproval, cancellationToken);
return _handler(command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, cancellationToken);
}
public Task ResolveApprovalAsync(
@@ -641,5 +1138,49 @@ public sealed class SidecarProtocolHostTests
{
return _resolveApprovalHandler(command, cancellationToken);
}
public Task ResolveUserInputAsync(
ResolveUserInputCommandDto command,
CancellationToken cancellationToken)
{
return _resolveUserInputHandler(command, cancellationToken);
}
}
private sealed class FakeSessionManager : ICopilotSessionManager
{
public IReadOnlyList<CopilotSessionInfoDto> Sessions { get; init; } = [];
public IReadOnlyList<CopilotSessionInfoDto> DeletedSessions { get; init; } = [];
public IReadOnlyDictionary<string, QuotaSnapshotDto> QuotaSnapshots { get; init; }
= new Dictionary<string, QuotaSnapshotDto>(StringComparer.Ordinal);
public string? DeletedAryxSessionId { get; private set; }
public string? DeletedCopilotSessionId { get; private set; }
public Task<IReadOnlyList<CopilotSessionInfoDto>> ListSessionsAsync(
CopilotSessionListFilterDto? filter,
CancellationToken cancellationToken)
{
return Task.FromResult(Sessions);
}
public Task<IReadOnlyList<CopilotSessionInfoDto>> DeleteSessionsAsync(
string? aryxSessionId,
string? copilotSessionId,
CancellationToken cancellationToken)
{
DeletedAryxSessionId = aryxSessionId;
DeletedCopilotSessionId = copilotSessionId;
return Task.FromResult(DeletedSessions);
}
public Task<IReadOnlyDictionary<string, QuotaSnapshotDto>> GetQuotaAsync(
CancellationToken cancellationToken)
{
return Task.FromResult(QuotaSnapshots);
}
}
}
+1115 -37
View File
File diff suppressed because it is too large Load Diff
+66 -5
View File
@@ -5,22 +5,32 @@ import { ipcChannels } from '@shared/contracts/channels';
import type {
CancelSessionTurnInput,
CreateSessionInput,
ResolveProjectDiscoveredToolingInput,
ResolveWorkspaceDiscoveredToolingInput,
DismissSessionMcpAuthInput,
DismissSessionPlanReviewInput,
DeleteSessionInput,
StartSessionMcpAuthInput,
DuplicateSessionInput,
RenameSessionInput,
RescanProjectConfigsInput,
RescanProjectCustomizationInput,
ResolveProjectDiscoveredToolingInput,
ResolveSessionApprovalInput,
ResolveSessionUserInputInput,
ResolveWorkspaceDiscoveredToolingInput,
SaveLspProfileInput,
SaveMcpServerInput,
SavePatternInput,
SendSessionMessageInput,
SetPatternFavoriteInput,
SetProjectAgentProfileEnabledInput,
SetSessionArchivedInput,
SetSessionInteractionModeInput,
SetSessionPinnedInput,
SetTerminalHeightInput,
ResizeTerminalInput,
UpdateSessionModelConfigInput,
UpdateSessionApprovalSettingsInput,
UpdateSessionToolingInput,
UpdateSessionModelConfigInput,
} from '@shared/contracts/ipc';
import type { QuerySessionsInput } from '@shared/domain/sessionLibrary';
import type { AppearanceTheme } from '@shared/domain/tooling';
@@ -47,11 +57,21 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
ipcMain.handle(ipcChannels.rescanProjectConfigs, (_event, input: RescanProjectConfigsInput) =>
service.rescanProjectConfigs(input.projectId),
);
ipcMain.handle(
ipcChannels.rescanProjectCustomization,
(_event, input: RescanProjectCustomizationInput) =>
service.rescanProjectCustomization(input.projectId),
);
ipcMain.handle(
ipcChannels.resolveProjectDiscoveredTooling,
(_event, input: ResolveProjectDiscoveredToolingInput) =>
service.resolveProjectDiscoveredTooling(input.projectId, input.serverIds, input.resolution),
);
ipcMain.handle(
ipcChannels.setProjectAgentProfileEnabled,
(_event, input: SetProjectAgentProfileEnabledInput) =>
service.setProjectAgentProfileEnabled(input.projectId, input.agentProfileId, input.enabled),
);
ipcMain.handle(ipcChannels.savePattern, (_event, input: SavePatternInput) => service.savePattern(input.pattern));
ipcMain.handle(ipcChannels.deletePattern, (_event, patternId: string) => service.deletePattern(patternId));
ipcMain.handle(ipcChannels.setPatternFavorite, (_event, input: SetPatternFavoriteInput) =>
@@ -62,6 +82,10 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
applyTitleBarTheme(window, theme);
return result;
});
ipcMain.handle(
ipcChannels.setTerminalHeight,
(_event, input: SetTerminalHeightInput) => service.setTerminalHeight(input.height),
);
ipcMain.handle(ipcChannels.saveMcpServer, (_event, input: SaveMcpServerInput) =>
service.saveMcpServer(input.server),
);
@@ -74,6 +98,16 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
ipcMain.handle(ipcChannels.deleteLspProfile, (_event, profileId: string) =>
service.deleteLspProfile(profileId),
);
ipcMain.handle(ipcChannels.describeTerminal, () => service.describeTerminal());
ipcMain.handle(ipcChannels.createTerminal, () => service.createTerminal());
ipcMain.handle(ipcChannels.restartTerminal, () => service.restartTerminal());
ipcMain.handle(ipcChannels.killTerminal, () => service.killTerminal());
ipcMain.on(ipcChannels.writeTerminal, (_event, data: string) => {
service.writeTerminal(data);
});
ipcMain.on(ipcChannels.resizeTerminal, (_event, input: ResizeTerminalInput) => {
service.resizeTerminal(input.cols, input.rows);
});
ipcMain.handle(ipcChannels.updateSessionTooling, (_event, input: UpdateSessionToolingInput) =>
service.updateSessionTooling(
input.sessionId,
@@ -101,14 +135,32 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
ipcMain.handle(ipcChannels.setSessionArchived, (_event, input: SetSessionArchivedInput) =>
service.setSessionArchived(input.sessionId, input.isArchived),
);
ipcMain.handle(ipcChannels.deleteSession, (_event, input: DeleteSessionInput) =>
service.deleteSession(input.sessionId),
);
ipcMain.handle(ipcChannels.sendSessionMessage, (_event, input: SendSessionMessageInput) =>
service.sendSessionMessage(input.sessionId, input.content),
service.sendSessionMessage(input.sessionId, input.content, input.attachments, input.messageMode),
);
ipcMain.handle(ipcChannels.cancelSessionTurn, (_event, input: CancelSessionTurnInput) =>
service.cancelSessionTurn(input.sessionId),
);
ipcMain.handle(ipcChannels.resolveSessionApproval, (_event, input: ResolveSessionApprovalInput) =>
service.resolveSessionApproval(input.sessionId, input.approvalId, input.decision),
service.resolveSessionApproval(input.sessionId, input.approvalId, input.decision, input.alwaysApprove),
);
ipcMain.handle(ipcChannels.resolveSessionUserInput, (_event, input: ResolveSessionUserInputInput) =>
service.resolveSessionUserInput(input.sessionId, input.userInputId, input.answer, input.wasFreeform),
);
ipcMain.handle(ipcChannels.setSessionInteractionMode, (_event, input: SetSessionInteractionModeInput) =>
service.setSessionInteractionMode(input.sessionId, input.mode),
);
ipcMain.handle(ipcChannels.dismissSessionPlanReview, (_event, input: DismissSessionPlanReviewInput) =>
service.dismissSessionPlanReview(input.sessionId),
);
ipcMain.handle(ipcChannels.dismissSessionMcpAuth, (_event, input: DismissSessionMcpAuthInput) =>
service.dismissSessionMcpAuth(input.sessionId),
);
ipcMain.handle(ipcChannels.startSessionMcpAuth, (_event, input: StartSessionMcpAuthInput) =>
service.startSessionMcpAuth(input.sessionId),
);
ipcMain.handle(
ipcChannels.updateSessionModelConfig,
@@ -121,6 +173,7 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
ipcMain.handle(ipcChannels.selectSession, (_event, sessionId?: string) => service.selectSession(sessionId));
ipcMain.handle(ipcChannels.openAppDataFolder, () => service.openAppDataFolder());
ipcMain.handle(ipcChannels.resetLocalWorkspace, () => service.resetLocalWorkspace());
ipcMain.handle(ipcChannels.getQuota, () => service.getQuota());
service.on('workspace-updated', (workspace) => {
window.webContents.send(ipcChannels.workspaceUpdated, workspace);
@@ -129,4 +182,12 @@ export function registerIpcHandlers(window: BrowserWindow, service: AryxAppServi
service.on('session-event', (event) => {
window.webContents.send(ipcChannels.sessionEvent, event);
});
service.on('terminal-data', (data) => {
window.webContents.send(ipcChannels.terminalData, data);
});
service.on('terminal-exit', (info) => {
window.webContents.send(ipcChannels.terminalExit, info);
});
}
+4
View File
@@ -10,3 +10,7 @@ export function getWorkspaceFilePath(): string {
export function getScratchpadDirectoryPath(): string {
return join(app.getPath('userData'), 'scratchpad');
}
export function getScratchpadSessionPath(sessionId: string): string {
return join(getScratchpadDirectoryPath(), sessionId);
}
+34 -13
View File
@@ -2,9 +2,11 @@ import { mkdir } from 'node:fs/promises';
import { createBuiltinPatterns, resolvePatternGraph } from '@shared/domain/pattern';
import type { PatternDefinition } from '@shared/domain/pattern';
import { mergeScratchpadProject } from '@shared/domain/project';
import { isScratchpadProject, mergeScratchpadProject } from '@shared/domain/project';
import { normalizeDiscoveredToolingState } from '@shared/domain/discoveredTooling';
import { normalizeProjectCustomizationState } from '@shared/domain/projectCustomization';
import { normalizeSessionRunRecords } from '@shared/domain/runTimeline';
import type { SessionRecord } from '@shared/domain/session';
import {
normalizeSessionToolingSelection,
normalizeWorkspaceSettings,
@@ -17,7 +19,11 @@ import {
import { createWorkspaceSeed, type WorkspaceState } from '@shared/domain/workspace';
import { nowIso } from '@shared/utils/ids';
import { getScratchpadDirectoryPath, getWorkspaceFilePath } from '@main/persistence/appPaths';
import {
getScratchpadDirectoryPath,
getScratchpadSessionPath,
getWorkspaceFilePath,
} from '@main/persistence/appPaths';
import { readJsonFile, writeJsonFile } from '@main/persistence/jsonStore';
function mergePatterns(existingPatterns: PatternDefinition[]): PatternDefinition[] {
@@ -68,9 +74,32 @@ export class WorkspaceRepository {
(stored.projects ?? []).map((project) => ({
...project,
discoveredTooling: normalizeDiscoveredToolingState(project.discoveredTooling),
customization: normalizeProjectCustomizationState(project.customization),
})),
this.scratchpadPath,
);
const sessions = await Promise.all((stored.sessions ?? []).map(async (session): Promise<SessionRecord> => {
const normalizedSession: SessionRecord = {
...session,
runs: normalizeSessionRunRecords(session.runs),
tooling: normalizeSessionToolingSelection(session.tooling),
approvalSettings: normalizeSessionApprovalSettings(session.approvalSettings),
...normalizePendingApprovalState({
pendingApproval: session.pendingApproval,
pendingApprovalQueue: session.pendingApprovalQueue,
}),
};
if (!isScratchpadProject(normalizedSession.projectId)) {
return normalizedSession;
}
const cwd = normalizedSession.cwd ?? getScratchpadSessionPath(normalizedSession.id);
await mkdir(cwd, { recursive: true });
return {
...normalizedSession,
cwd,
};
}));
const settings = normalizeWorkspaceSettings(stored.settings);
const workspace: WorkspaceState = {
@@ -81,16 +110,7 @@ export class WorkspaceRepository {
graph: resolvePatternGraph(pattern),
})),
projects,
sessions: (stored.sessions ?? []).map((session) => ({
...session,
runs: normalizeSessionRunRecords(session.runs),
tooling: normalizeSessionToolingSelection(session.tooling),
approvalSettings: normalizeSessionApprovalSettings(session.approvalSettings),
...normalizePendingApprovalState({
pendingApproval: session.pendingApproval,
pendingApprovalQueue: session.pendingApprovalQueue,
}),
})),
sessions,
settings,
selectedProjectId: projects.some((project) => project.id === stored.selectedProjectId)
? stored.selectedProjectId
@@ -103,8 +123,9 @@ export class WorkspaceRepository {
}
async save(workspace: WorkspaceState): Promise<void> {
const { mcpProbingServerIds: _mcpProbingServerIds, ...persistedWorkspace } = workspace;
await writeJsonFile(this.filePath, {
...workspace,
...persistedWorkspace,
lastUpdatedAt: nowIso(),
});
}
+370
View File
@@ -0,0 +1,370 @@
import { readdir, readFile } from 'node:fs/promises';
import { basename, join, relative } from 'node:path';
import { parse as parseYaml } from 'yaml';
import {
mergeProjectCustomizationState,
normalizeProjectCustomizationState,
type ProjectAgentProfile,
type ProjectCustomizationState,
type ProjectInstructionFile,
type ProjectPromptFile,
type ProjectPromptVariable,
} from '@shared/domain/projectCustomization';
import { nowIso } from '@shared/utils/ids';
const promptVariablePattern = /\$\{input:([a-zA-Z0-9_-]+):([^}]+)\}/g;
export class ProjectCustomizationScanner {
async scanProject(
projectPath: string,
current?: ProjectCustomizationState,
): Promise<ProjectCustomizationState> {
const previous = normalizeProjectCustomizationState(current);
const instructions = await this.scanInstructionFiles(projectPath, previous);
const agentProfiles = await this.scanAgentProfiles(projectPath, previous);
const promptFiles = await this.scanPromptFiles(projectPath, previous);
return mergeProjectCustomizationState(
previous,
{
instructions,
agentProfiles,
promptFiles,
},
nowIso(),
);
}
private async scanInstructionFiles(
projectPath: string,
previous: ProjectCustomizationState,
): Promise<ProjectInstructionFile[]> {
const previousByPath = new Map(previous.instructions.map((instruction) => [instruction.sourcePath, instruction]));
const sourcePaths = ['.github\\copilot-instructions.md', 'AGENTS.md'] as const;
const instructions: ProjectInstructionFile[] = [];
for (const sourcePath of sourcePaths) {
const filePath = join(projectPath, ...sourcePath.split('\\'));
const contents = await this.readProjectFile(filePath);
if (contents.kind === 'missing') {
continue;
}
if (contents.kind === 'retain-previous') {
const existing = previousByPath.get(sourcePath);
if (existing) {
instructions.push(existing);
}
continue;
}
const content = contents.value.trim();
if (!content) {
continue;
}
instructions.push({
id: buildProjectCustomizationItemId('instruction', sourcePath),
sourcePath,
content,
});
}
return instructions;
}
private async scanAgentProfiles(
projectPath: string,
previous: ProjectCustomizationState,
): Promise<ProjectAgentProfile[]> {
const previousByPath = new Map(previous.agentProfiles.map((profile) => [profile.sourcePath, profile]));
const filePaths = await this.listProjectFiles(join(projectPath, '.github', 'agents'), '.agent.md');
const profiles: ProjectAgentProfile[] = [];
for (const filePath of filePaths) {
const sourcePath = toProjectSourcePath(projectPath, filePath);
const contents = await this.readProjectFile(filePath);
if (contents.kind === 'retain-previous') {
const existing = previousByPath.get(sourcePath);
if (existing) {
profiles.push(existing);
}
continue;
}
if (contents.kind === 'missing') {
continue;
}
const parsedFile = parseProjectFrontmatter(contents.value, sourcePath);
if (!parsedFile) {
const existing = previousByPath.get(sourcePath);
if (existing) {
profiles.push(existing);
}
continue;
}
const name = readOptionalString(parsedFile.attributes, ['name'])
?? basename(filePath, '.agent.md');
const prompt = parsedFile.body.trim();
if (!name || !prompt) {
continue;
}
profiles.push({
id: buildProjectCustomizationItemId('agent', sourcePath),
name,
displayName: readOptionalString(parsedFile.attributes, ['displayName', 'display-name']),
description: readOptionalString(parsedFile.attributes, ['description']),
tools: readOptionalStringArray(parsedFile.attributes.tools),
prompt,
mcpServers: readOptionalNamedObjectMap(parsedFile.attributes['mcp-servers']),
infer: typeof parsedFile.attributes.infer === 'boolean' ? parsedFile.attributes.infer : undefined,
sourcePath,
enabled: previousByPath.get(sourcePath)?.enabled ?? true,
});
}
return profiles;
}
private async scanPromptFiles(
projectPath: string,
previous: ProjectCustomizationState,
): Promise<ProjectPromptFile[]> {
const previousByPath = new Map(previous.promptFiles.map((promptFile) => [promptFile.sourcePath, promptFile]));
const filePaths = await this.listProjectFiles(join(projectPath, '.github', 'prompts'), '.prompt.md');
const promptFiles: ProjectPromptFile[] = [];
for (const filePath of filePaths) {
const sourcePath = toProjectSourcePath(projectPath, filePath);
const contents = await this.readProjectFile(filePath);
if (contents.kind === 'retain-previous') {
const existing = previousByPath.get(sourcePath);
if (existing) {
promptFiles.push(existing);
}
continue;
}
if (contents.kind === 'missing') {
continue;
}
const parsedFile = parseProjectFrontmatter(contents.value, sourcePath);
if (!parsedFile) {
const existing = previousByPath.get(sourcePath);
if (existing) {
promptFiles.push(existing);
}
continue;
}
const template = parsedFile.body.trim();
if (!template) {
continue;
}
promptFiles.push({
id: buildProjectCustomizationItemId('prompt', sourcePath),
name: basename(filePath, '.prompt.md'),
description: readOptionalString(parsedFile.attributes, ['description']),
agent: readOptionalString(parsedFile.attributes, ['agent']),
template,
variables: extractPromptVariables(template),
sourcePath,
});
}
return promptFiles;
}
private async listProjectFiles(directoryPath: string, suffix: string): Promise<string[]> {
try {
const entries = await readdir(directoryPath, { withFileTypes: true });
return entries
.filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith(suffix))
.map((entry) => join(directoryPath, entry.name))
.sort((left, right) => left.localeCompare(right));
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return [];
}
console.warn(`[aryx customization] Failed to read directory ${directoryPath}:`, error);
return [];
}
}
private async readProjectFile(filePath: string): Promise<
| { kind: 'success'; value: string }
| { kind: 'missing' }
| { kind: 'retain-previous' }
> {
try {
return {
kind: 'success',
value: await readFile(filePath, 'utf8'),
};
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return { kind: 'missing' };
}
console.warn(`[aryx customization] Failed to read ${filePath}:`, error);
return { kind: 'retain-previous' };
}
}
}
function parseProjectFrontmatter(
contents: string,
sourcePath: string,
): { attributes: Record<string, unknown>; body: string } | undefined {
const match = /^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)([\s\S]*)$/u.exec(contents);
if (!match) {
return {
attributes: {},
body: contents,
};
}
try {
const parsed = parseYaml(match[1]);
if (!isPlainObject(parsed) && parsed !== null && parsed !== undefined) {
console.warn(`[aryx customization] Ignoring non-object frontmatter in ${sourcePath}.`);
return undefined;
}
return {
attributes: isPlainObject(parsed) ? parsed : {},
body: match[2],
};
} catch (error) {
console.warn(`[aryx customization] Failed to parse frontmatter in ${sourcePath}:`, error);
return undefined;
}
}
function extractPromptVariables(template: string): ProjectPromptVariable[] {
const variables: ProjectPromptVariable[] = [];
const seenNames = new Set<string>();
let match: RegExpExecArray | null;
while ((match = promptVariablePattern.exec(template))) {
const name = match[1]?.trim();
if (!name || seenNames.has(name)) {
continue;
}
seenNames.add(name);
variables.push({
name,
placeholder: match[2]?.trim() ?? '',
});
}
promptVariablePattern.lastIndex = 0;
return variables;
}
function buildProjectCustomizationItemId(kind: 'instruction' | 'agent' | 'prompt', sourcePath: string): string {
return `project_customization_${kind}_${normalizeIdentifierSegment(sourcePath)}`;
}
function toProjectSourcePath(projectPath: string, filePath: string): string {
const relativePath = relative(projectPath, filePath).trim();
return relativePath ? relativePath.replaceAll('/', '\\') : basename(filePath);
}
function normalizeIdentifierSegment(value: string): string {
const normalized = value
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '');
return normalized.length > 0 ? normalized : 'item';
}
function readOptionalString(
record: Record<string, unknown>,
keys: ReadonlyArray<string>,
): string | undefined {
for (const key of keys) {
const value = record[key];
if (typeof value !== 'string') {
continue;
}
const trimmed = value.trim();
if (trimmed.length > 0) {
return trimmed;
}
}
return undefined;
}
function readOptionalStringArray(value: unknown): string[] | undefined {
if (value === undefined) {
return undefined;
}
if (typeof value === 'string') {
const trimmed = value.trim();
return trimmed.length > 0 ? [trimmed] : [];
}
if (!Array.isArray(value)) {
return undefined;
}
return [...new Set(value
.filter((entry): entry is string => typeof entry === 'string')
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0))];
}
function readOptionalNamedObjectMap(
value: unknown,
): Record<string, Record<string, unknown>> | undefined {
if (!isPlainObject(value)) {
return undefined;
}
const entries = Object.entries(value)
.map(([name, config]) => [name.trim(), normalizeYamlValue(config)] as const)
.filter(([name, config]) => name.length > 0 && isPlainObject(config))
.sort(([leftName], [rightName]) => leftName.localeCompare(rightName));
if (entries.length === 0) {
return undefined;
}
return Object.fromEntries(entries.map(([name, config]) => [name, config as Record<string, unknown>]));
}
function normalizeYamlValue(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map((entry) => normalizeYamlValue(entry));
}
if (!isPlainObject(value)) {
return typeof value === 'string' ? value.trim() : value;
}
return Object.fromEntries(
Object.entries(value)
.map(([key, nestedValue]) => [key.trim(), normalizeYamlValue(nestedValue)] as const)
.filter(([key]) => key.length > 0)
.sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)),
);
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value);
}
+563
View File
@@ -0,0 +1,563 @@
import { randomBytes, createHash } from 'node:crypto';
import { createServer, type Server, type IncomingMessage, type ServerResponse } from 'node:http';
import electron from 'electron';
import type { McpOauthStaticClientConfig } from '@shared/domain/mcpAuth';
import { storeToken, buildWellKnownUrl, buildWellKnownUrlFallback, buildWellKnownUrlOriginOnly, type McpOAuthToken } from './mcpTokenStore';
const { shell } = electron;
/* ── Public API ──────────────────────────────────────────────── */
export interface McpOAuthFlowOptions {
serverUrl: string;
staticClientConfig?: McpOauthStaticClientConfig;
onStatusChange?: (status: 'discovering' | 'awaiting-consent' | 'exchanging') => void;
}
export interface McpOAuthFlowResult {
success: boolean;
token?: McpOAuthToken;
error?: string;
}
const VSCODE_REDIRECT_URI = 'https://vscode.dev/redirect';
interface KnownOAuthProvider {
id: 'github' | 'entra';
clientId: string;
redirectMode: 'vscode-dev';
authorizationEndpoint?: string;
tokenEndpoint?: string;
scopes?: readonly string[];
authorizationParams?: Readonly<Record<string, string>>;
includeOfflineAccess?: boolean;
}
interface KnownOAuthProviderConfig extends KnownOAuthProvider {
matches: (url: URL) => boolean;
}
const GITHUB_PROVIDER_SCOPES = [
'codespace',
'gist',
'notifications',
'project',
'read:org',
'read:packages',
'read:project',
'read:user',
'repo',
'user:email',
'workflow',
'write:packages',
] as const;
const knownOAuthProviders: readonly KnownOAuthProviderConfig[] = [
{
id: 'github',
clientId: '01ab8ac9400c4e429b23',
redirectMode: 'vscode-dev',
authorizationEndpoint: 'https://github.com/login/oauth/authorize',
tokenEndpoint: 'https://github.com/login/oauth/access_token',
scopes: GITHUB_PROVIDER_SCOPES,
authorizationParams: { prompt: 'select_account' },
includeOfflineAccess: false,
matches: (url) => url.hostname === 'github.com',
},
{
id: 'entra',
clientId: 'aebc6443-996d-45c2-90f0-388ff96faa56',
redirectMode: 'vscode-dev',
includeOfflineAccess: true,
matches: (url) => url.hostname === 'login.microsoftonline.com',
},
] as const;
export function resolveKnownProvider(authServerUrl: string): KnownOAuthProvider | undefined {
try {
const parsed = new URL(authServerUrl);
const match = knownOAuthProviders.find((candidate) => candidate.matches(parsed));
if (!match) {
return undefined;
}
const { matches: _matches, ...provider } = match;
return provider;
} catch {
return undefined;
}
}
/**
* Probes an MCP server URL to determine if it requires OAuth authentication.
* Returns true if the server responds with 401 and has discoverable OAuth metadata.
*/
export async function requiresOAuth(serverUrl: string): Promise<boolean> {
try {
const metadata = await fetchWellKnownMetadata(serverUrl, 'oauth-protected-resource');
if (!metadata) {
console.log(`[aryx oauth] No PRM found for ${serverUrl}`);
return false;
}
const hasAuthServers = Array.isArray(metadata.authorization_servers) && metadata.authorization_servers.length > 0;
console.log(`[aryx oauth] PRM found for ${serverUrl}: authorization_servers=${hasAuthServers}`);
return hasAuthServers;
} catch (err) {
console.warn(`[aryx oauth] Probe failed for ${serverUrl}:`, err instanceof Error ? err.message : err);
return false;
}
}
/**
* Performs the full MCP OAuth 2.1 + PKCE flow:
* 1. Discover protected resource metadata (RFC 9728)
* 2. Fetch authorization server metadata (RFC 8414)
* 3. Resolve client ID (static config or dynamic registration per RFC 7591)
* 4. PKCE code verifier + challenge
* 5. Open browser for user consent
* 6. Local callback server receives auth code
* 7. Exchange code for token
*/
export async function performMcpOAuthFlow(options: McpOAuthFlowOptions): Promise<McpOAuthFlowResult> {
const { serverUrl, staticClientConfig, onStatusChange } = options;
try {
onStatusChange?.('discovering');
const prm = await discoverProtectedResource(serverUrl);
const knownProvider = resolveKnownProvider(prm.authorizationServer);
const { verifier, challenge } = generatePkceChallenge();
const {
localRedirectUri,
hostedRedirectState,
waitForCallback,
close,
} = await startCallbackServer();
try {
const metadata = await resolveAuthServerMetadata(prm.authorizationServer, knownProvider);
const clientId = staticClientConfig?.clientId
?? knownProvider?.clientId
?? await dynamicClientRegistration(metadata, localRedirectUri, serverUrl);
const usesHostedRedirect = knownProvider?.redirectMode === 'vscode-dev';
const scopes = buildScopes(knownProvider, prm.resourceScopes, metadata.scopes_supported);
const redirectUri = usesHostedRedirect ? VSCODE_REDIRECT_URI : localRedirectUri;
const state = usesHostedRedirect ? hostedRedirectState : randomBytes(16).toString('hex');
const authUrl = buildAuthorizationUrl(metadata.authorization_endpoint, {
clientId,
redirectUri,
codeChallenge: challenge,
scope: scopes,
state,
extraParams: knownProvider?.authorizationParams,
});
onStatusChange?.('awaiting-consent');
await shell.openExternal(authUrl);
const code = await waitForCallback();
onStatusChange?.('exchanging');
const token = await exchangeCodeForToken(metadata.token_endpoint, {
code,
clientId,
redirectUri,
codeVerifier: verifier,
});
storeToken(serverUrl, token);
return { success: true, token };
} finally {
close();
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
return { success: false, error: message };
}
}
/**
* Builds the OAuth scope string.
* Priority: provider-specific scopes > PRM resource scopes > auth server scopes.
* `offline_access` is only appended when the provider supports/needs it.
*/
export function buildScopes(
knownProvider: KnownOAuthProvider | undefined,
resourceScopes?: string[],
authServerScopes?: string[],
): string {
const scopes = knownProvider?.scopes ?? resourceScopes ?? authServerScopes ?? [];
if (scopes.length === 0) {
return '';
}
const set = new Set(scopes);
if (knownProvider?.includeOfflineAccess ?? true) {
set.add('offline_access');
}
return [...set].join(' ');
}
/* ── Discovery ───────────────────────────────────────────────── */
interface ProtectedResourceMetadata {
resource: string;
authorization_servers?: string[];
scopes_supported?: string[];
}
interface AuthServerMetadata {
issuer: string;
authorization_endpoint: string;
token_endpoint: string;
registration_endpoint?: string;
scopes_supported?: string[];
}
/**
* Tries to fetch a well-known metadata document from a base URL.
* Attempts the RFC 9728 compliant path first (inserted after origin),
* then falls back to the appended path (used by some servers).
* Returns the parsed JSON or undefined if neither endpoint responds.
*/
async function fetchWellKnownMetadata(baseUrl: string, suffix: string): Promise<Record<string, unknown> | undefined> {
const rfcUrl = buildWellKnownUrl(baseUrl, suffix);
const fallbackUrl = buildWellKnownUrlFallback(baseUrl, suffix);
const originOnlyUrl = buildWellKnownUrlOriginOnly(baseUrl, suffix);
// Deduplicate: RFC path, appended fallback, then origin-only (for servers
// that serve metadata at the origin without the resource path suffix).
const seen = new Set<string>();
const urls: string[] = [];
for (const url of [rfcUrl, fallbackUrl, originOnlyUrl]) {
if (!seen.has(url)) {
seen.add(url);
urls.push(url);
}
}
for (const url of urls) {
try {
console.log(`[aryx oauth] Trying well-known at ${url}`);
const response = await fetch(url, { signal: AbortSignal.timeout(5_000) });
if (response.ok) {
const data = await response.json();
console.log(`[aryx oauth] Found well-known metadata at ${url}`);
return data;
}
console.log(`[aryx oauth] ${url} returned ${response.status}`);
} catch {
console.log(`[aryx oauth] ${url} unreachable`);
}
}
return undefined;
}
interface PrmDiscoveryResult {
authorizationServer: string;
resourceScopes?: string[];
}
async function discoverProtectedResource(serverUrl: string): Promise<PrmDiscoveryResult> {
const metadata = await fetchWellKnownMetadata(serverUrl, 'oauth-protected-resource');
if (!metadata) {
throw new Error('Protected Resource Metadata discovery failed: no well-known endpoint found');
}
const prm = metadata as unknown as ProtectedResourceMetadata;
const authServer = prm.authorization_servers?.[0];
if (!authServer) {
throw new Error('No authorization server found in Protected Resource Metadata');
}
return { authorizationServer: authServer, resourceScopes: prm.scopes_supported };
}
async function fetchAuthServerMetadata(authServerUrl: string): Promise<AuthServerMetadata> {
// RFC 8414 suffix first, then OpenID Connect Discovery suffix (used by Entra ID, Google, etc.)
const metadata =
(await fetchWellKnownMetadata(authServerUrl, 'oauth-authorization-server')) ??
(await fetchWellKnownMetadata(authServerUrl, 'openid-configuration'));
if (!metadata) {
throw new Error('Authorization Server Metadata fetch failed: no well-known endpoint found');
}
const asMeta = metadata as unknown as AuthServerMetadata;
if (!asMeta.authorization_endpoint || !asMeta.token_endpoint) {
throw new Error('Authorization server metadata is missing required endpoints');
}
return asMeta;
}
async function resolveAuthServerMetadata(
authServerUrl: string,
knownProvider: KnownOAuthProvider | undefined,
): Promise<AuthServerMetadata> {
if (knownProvider?.authorizationEndpoint && knownProvider?.tokenEndpoint) {
return {
issuer: authServerUrl,
authorization_endpoint: knownProvider.authorizationEndpoint,
token_endpoint: knownProvider.tokenEndpoint,
scopes_supported: knownProvider.scopes ? [...knownProvider.scopes] : undefined,
};
}
return fetchAuthServerMetadata(authServerUrl);
}
/* ── Dynamic Client Registration (RFC 7591) ──────────────────── */
async function dynamicClientRegistration(
metadata: AuthServerMetadata,
redirectUri: string,
serverUrl: string,
): Promise<string> {
if (!metadata.registration_endpoint) {
throw new Error(
'No static client ID provided and the authorization server does not support dynamic client registration',
);
}
const response = await fetch(metadata.registration_endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
client_name: 'Aryx',
redirect_uris: [redirectUri],
grant_types: ['authorization_code'],
response_types: ['code'],
token_endpoint_auth_method: 'none',
scope: metadata.scopes_supported?.join(' ') ?? '',
}),
});
if (!response.ok) {
throw new Error(`Dynamic client registration failed: ${response.status} ${response.statusText}`);
}
const registration = await response.json();
if (!registration.client_id) {
throw new Error('Dynamic client registration response is missing client_id');
}
return registration.client_id;
}
/* ── PKCE ────────────────────────────────────────────────────── */
function generatePkceChallenge(): { verifier: string; challenge: string } {
const verifier = randomBytes(32).toString('base64url');
const challenge = createHash('sha256').update(verifier).digest('base64url');
return { verifier, challenge };
}
/* ── Authorization URL ───────────────────────────────────────── */
function buildAuthorizationUrl(
authorizationEndpoint: string,
params: {
clientId: string;
redirectUri: string;
codeChallenge: string;
scope: string;
state: string;
extraParams?: Readonly<Record<string, string>>;
},
): string {
const url = new URL(authorizationEndpoint);
url.searchParams.set('response_type', 'code');
url.searchParams.set('client_id', params.clientId);
url.searchParams.set('redirect_uri', params.redirectUri);
url.searchParams.set('code_challenge', params.codeChallenge);
url.searchParams.set('code_challenge_method', 'S256');
if (params.scope) {
url.searchParams.set('scope', params.scope);
}
url.searchParams.set('state', params.state);
for (const [key, value] of Object.entries(params.extraParams ?? {})) {
url.searchParams.set(key, value);
}
return url.toString();
}
/* ── Local callback server ───────────────────────────────────── */
interface CallbackServerHandle {
port: number;
localRedirectUri: string;
hostedRedirectState: string;
waitForCallback: () => Promise<string>;
close: () => void;
}
function startCallbackServer(): Promise<CallbackServerHandle> {
return new Promise((resolve, reject) => {
let settled = false;
let callbackResolve: (code: string) => void;
let callbackReject: (err: Error) => void;
const callbackPromise = new Promise<string>((res, rej) => {
callbackResolve = res;
callbackReject = rej;
});
const server: Server = createServer((req: IncomingMessage, res: ServerResponse) => {
const url = new URL(req.url ?? '/', `http://127.0.0.1`);
const code = url.searchParams.get('code');
const error = url.searchParams.get('error');
const errorDescription = url.searchParams.get('error_description');
// Ignore requests without code or error (e.g. favicon)
if (!code && !error) {
res.writeHead(404);
res.end();
return;
}
res.writeHead(200, { 'Content-Type': 'text/html' });
if (code) {
res.end('<html><body><h2>Authentication successful</h2><p>You can close this tab.</p></body></html>');
callbackResolve(code);
} else {
const msg = errorDescription ?? error ?? 'Unknown error';
res.end(`<html><body><h2>Authentication failed</h2><p>${escapeHtml(msg)}</p></body></html>`);
callbackReject(new Error(`OAuth callback error: ${msg}`));
}
});
server.on('error', (err) => {
if (!settled) {
settled = true;
reject(err);
}
});
server.listen(0, '127.0.0.1', () => {
settled = true;
const addr = server.address();
if (!addr || typeof addr === 'string') {
reject(new Error('Failed to bind callback server'));
return;
}
resolve({
port: addr.port,
localRedirectUri: `http://127.0.0.1:${addr.port}/callback`,
hostedRedirectState: buildHostedRedirectState(`http://127.0.0.1:${addr.port}/callback`),
waitForCallback: () => callbackPromise,
close: () => server.close(),
});
});
setTimeout(() => {
if (!settled) {
settled = true;
server.close();
reject(new Error('Callback server start timed out'));
}
}, 5_000);
});
}
function buildHostedRedirectState(localRedirectUri: string): string {
const stateUrl = new URL(localRedirectUri);
stateUrl.searchParams.set('nonce', randomBytes(16).toString('base64url'));
return stateUrl.toString();
}
/* ── Token exchange ──────────────────────────────────────────── */
async function exchangeCodeForToken(
tokenEndpoint: string,
params: {
code: string;
clientId: string;
redirectUri: string;
codeVerifier: string;
},
): Promise<McpOAuthToken> {
const body = new URLSearchParams({
grant_type: 'authorization_code',
code: params.code,
client_id: params.clientId,
redirect_uri: params.redirectUri,
code_verifier: params.codeVerifier,
});
const response = await fetch(tokenEndpoint, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: body.toString(),
});
const data = parseTokenResponseBody(await response.text(), response.headers.get('content-type'));
if (!response.ok) {
const errorMessage =
typeof data.error_description === 'string'
? data.error_description
: typeof data.error === 'string'
? data.error
: `${response.status} ${response.statusText}`;
throw new Error(`Token exchange failed: ${errorMessage}`);
}
const accessToken = typeof data.access_token === 'string' ? data.access_token : undefined;
const tokenType = typeof data.token_type === 'string' ? data.token_type : 'Bearer';
const scope = typeof data.scope === 'string' ? data.scope : undefined;
const refreshToken = typeof data.refresh_token === 'string' ? data.refresh_token : undefined;
if (!accessToken) {
throw new Error('Token response is missing access_token');
}
const token: McpOAuthToken = {
accessToken,
tokenType,
scope,
};
if (data.expires_in && typeof data.expires_in === 'number') {
token.expiresAt = Date.now() + data.expires_in * 1_000;
}
if (refreshToken) {
token.refreshToken = refreshToken;
}
return token;
}
export function parseTokenResponseBody(body: string, contentType?: string | null): Record<string, unknown> {
const normalizedContentType = contentType?.toLowerCase() ?? '';
if (normalizedContentType.includes('application/json') || body.trim().startsWith('{')) {
const parsed = JSON.parse(body) as unknown;
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return parsed as Record<string, unknown>;
}
return {};
}
return Object.fromEntries(new URLSearchParams(body).entries());
}
/* ── Utilities ───────────────────────────────────────────────── */
function escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
+73
View File
@@ -0,0 +1,73 @@
/**
* In-memory OAuth token store keyed by MCP server URL.
* Tokens are lost on app restart by design (phase 1).
*/
export interface McpOAuthToken {
accessToken: string;
tokenType: string;
expiresAt?: number;
refreshToken?: string;
scope?: string;
}
const tokens = new Map<string, McpOAuthToken>();
export function getStoredToken(serverUrl: string): McpOAuthToken | undefined {
const token = tokens.get(normalizeUrl(serverUrl));
if (!token) {
return undefined;
}
if (token.expiresAt && Date.now() >= token.expiresAt) {
tokens.delete(normalizeUrl(serverUrl));
return undefined;
}
return token;
}
export function storeToken(serverUrl: string, token: McpOAuthToken): void {
tokens.set(normalizeUrl(serverUrl), token);
}
export function clearToken(serverUrl: string): void {
tokens.delete(normalizeUrl(serverUrl));
}
export function clearAllTokens(): void {
tokens.clear();
}
function normalizeUrl(url: string): string {
try {
const parsed = new URL(url);
return parsed.origin + parsed.pathname.replace(/\/+$/, '');
} catch {
return url.toLowerCase().replace(/\/+$/, '');
}
}
/**
* Constructs well-known URL candidates for a given base URL.
* Returns the RFC 9728 compliant URL first (inserted after origin),
* then the appended fallback (some servers use this instead).
*
* RFC 9728: `https://example.com/.well-known/oauth-protected-resource/mcp/`
* Fallback: `https://example.com/mcp/.well-known/oauth-protected-resource`
*/
export function buildWellKnownUrl(baseUrl: string, wellKnownSuffix: string): string {
const parsed = new URL(baseUrl);
const path = parsed.pathname === '/' ? '' : parsed.pathname;
return `${parsed.origin}/.well-known/${wellKnownSuffix}${path}`;
}
export function buildWellKnownUrlFallback(baseUrl: string, wellKnownSuffix: string): string {
const base = baseUrl.replace(/\/+$/, '');
return `${base}/.well-known/${wellKnownSuffix}`;
}
export function buildWellKnownUrlOriginOnly(baseUrl: string, wellKnownSuffix: string): string {
const parsed = new URL(baseUrl);
return `${parsed.origin}/.well-known/${wellKnownSuffix}`;
}
+237
View File
@@ -0,0 +1,237 @@
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
import type { McpServerDefinition } from '@shared/domain/tooling';
export interface McpProbedTool {
name: string;
description?: string;
}
export interface McpProbeResult {
serverId: string;
serverName: string;
tools: McpProbedTool[];
status: 'success' | 'failed';
error?: string;
}
const CLIENT_INFO = { name: 'aryx', version: '1.0.0' };
const DEFAULT_TIMEOUT_MS = 30_000;
const MAX_CONCURRENCY = 5;
export async function probeServers(
servers: ReadonlyArray<McpServerDefinition>,
tokenLookup?: (serverUrl: string) => string | undefined,
onResult?: (result: McpProbeResult) => void | Promise<void>,
): Promise<McpProbeResult[]> {
if (servers.length === 0) {
return [];
}
const results = new Array<McpProbeResult>(servers.length);
let nextIndex = 0;
const workerCount = Math.min(MAX_CONCURRENCY, servers.length);
async function worker(): Promise<void> {
while (true) {
const index = nextIndex;
nextIndex += 1;
const server = servers[index];
if (!server) {
return;
}
const result = await probeServer(server, tokenLookup);
results[index] = result;
await onResult?.(result);
}
}
await Promise.all(Array.from({ length: workerCount }, () => worker()));
return results;
}
export async function probeServer(
server: McpServerDefinition,
tokenLookup?: (serverUrl: string) => string | undefined,
): Promise<McpProbeResult> {
const timeoutMs = server.timeoutMs ?? DEFAULT_TIMEOUT_MS;
try {
const tools = await withTimeout(
probeServerCore(server, tokenLookup),
timeoutMs,
`Probe timed out after ${timeoutMs}ms`,
);
console.log(`[aryx mcp-probe] ${server.name}: discovered ${tools.length} tool(s)`);
return {
serverId: server.id,
serverName: server.name,
tools,
status: 'success',
};
} catch (error) {
const message = formatProbeError(error);
console.warn(`[aryx mcp-probe] ${server.name}: failed — ${message}`);
return {
serverId: server.id,
serverName: server.name,
tools: [],
status: 'failed',
error: message,
};
}
}
async function probeServerCore(
server: McpServerDefinition,
tokenLookup?: (serverUrl: string) => string | undefined,
): Promise<McpProbedTool[]> {
if (server.transport === 'local' || server.transport === 'sse') {
return probeWithTransport(createTransport(server, tokenLookup));
}
// For HTTP servers, try Streamable HTTP first, then fall back to SSE.
// Many MCP servers only support SSE despite being configured as generic HTTP.
const headers = buildHeaders(server.url, server.headers, tokenLookup);
const headerOpts = headers ? { requestInit: { headers } } : undefined;
try {
return await probeWithTransport(
new StreamableHTTPClientTransport(new URL(server.url), headerOpts),
);
} catch (streamableError) {
try {
return await probeWithTransport(
new SSEClientTransport(new URL(server.url), headerOpts),
);
} catch (sseError) {
// SSE 405 means the server IS Streamable HTTP — surface the original error.
const sseCode = (sseError as { code?: number }).code;
if (sseCode === 405) throw streamableError;
throw sseError;
}
}
}
async function probeWithTransport(
transport: InstanceType<typeof StdioClientTransport> | InstanceType<typeof SSEClientTransport> | InstanceType<typeof StreamableHTTPClientTransport>,
): Promise<McpProbedTool[]> {
const client = new Client(CLIENT_INFO, { capabilities: {} });
try {
await client.connect(transport);
// Use listTools() which validates schemas. If a tool has a complex
// outputSchema with $ref that the SDK can't resolve, fall back to
// a raw JSON-RPC request that skips schema compilation.
let rawTools: Array<{ name?: string; description?: string }>;
try {
const result = await client.listTools();
rawTools = result.tools ?? [];
} catch {
// listTools failed (likely schema validation of outputSchema $ref).
// Send raw JSON-RPC and extract tool names without validation.
const response = await new Promise<{ tools?: Array<{ name?: string; description?: string }> }>((resolve, reject) => {
const id = Math.random().toString(36).slice(2);
const onMessage = (msg: { id?: string; result?: unknown; error?: unknown }) => {
if (msg.id !== id) return;
transport.onmessage = undefined;
if (msg.error) reject(new Error(JSON.stringify(msg.error)));
else resolve((msg.result ?? {}) as { tools?: Array<{ name?: string; description?: string }> });
};
const prevHandler = transport.onmessage;
transport.onmessage = (msg) => {
onMessage(msg as { id?: string; result?: unknown; error?: unknown });
if (prevHandler) (prevHandler as (msg: unknown) => void)(msg);
};
transport.send({ jsonrpc: '2.0', id, method: 'tools/list', params: {} }).catch(reject);
});
rawTools = response.tools ?? [];
}
return rawTools
.filter((tool) => typeof tool.name === 'string' && tool.name.trim().length > 0)
.map((tool) => ({
name: tool.name!.trim(),
description: typeof tool.description === 'string' && tool.description.trim().length > 0
? tool.description.trim()
: undefined,
}));
} finally {
try {
await client.close();
} catch {
// Ignore close errors — connection may already be closed
}
}
}
function createTransport(
server: McpServerDefinition,
tokenLookup?: (serverUrl: string) => string | undefined,
) {
if (server.transport === 'local') {
return new StdioClientTransport({
command: server.command,
args: server.args.length > 0 ? server.args : undefined,
env: server.env
? Object.fromEntries(
Object.entries({ ...process.env, ...server.env })
.filter((entry): entry is [string, string] => entry[1] !== undefined),
)
: undefined,
cwd: server.cwd,
stderr: 'ignore',
});
}
const headers = buildHeaders(server.url, server.headers, tokenLookup);
return new SSEClientTransport(
new URL(server.url),
headers ? { requestInit: { headers } } : undefined,
);
}
function buildHeaders(
serverUrl: string,
configHeaders?: Record<string, string>,
tokenLookup?: (serverUrl: string) => string | undefined,
): Record<string, string> | undefined {
const bearerToken = tokenLookup?.(serverUrl);
if (!bearerToken && !configHeaders) {
return undefined;
}
return {
...(configHeaders ?? {}),
...(bearerToken ? { Authorization: `Bearer ${bearerToken}` } : {}),
};
}
function formatProbeError(error: unknown): string {
if (!(error instanceof Error)) return String(error);
const httpCode = (error as { code?: number }).code;
const base = error.message;
if (typeof httpCode === 'number' && httpCode >= 100) {
return `HTTP ${httpCode}: ${base}`;
}
return base;
}
function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(message)), ms);
promise.then(
(value) => { clearTimeout(timer); resolve(value); },
(error) => { clearTimeout(timer); reject(error); },
);
});
}
+352
View File
@@ -0,0 +1,352 @@
import { EventEmitter } from 'node:events';
import { constants as fsConstants } from 'node:fs';
import { access, stat } from 'node:fs/promises';
import { basename, delimiter, isAbsolute, join } from 'node:path';
import type { TerminalExitInfo, TerminalSnapshot } from '@shared/domain/terminal';
const DEFAULT_COLS = 80;
const DEFAULT_ROWS = 24;
const DEFAULT_TERMINAL_NAME = 'xterm-256color';
const DEFAULT_UNIX_SHELL = '/bin/bash';
const DEFAULT_WINDOWS_FALLBACK_SHELL = 'cmd.exe';
type Disposable = {
dispose(): void;
};
interface ManagedPty {
readonly pid: number;
write(data: string): void;
resize(cols: number, rows: number): void;
kill(signal?: string): void;
onData(listener: (data: string) => void): Disposable;
onExit(listener: (event: TerminalExitInfo) => void): Disposable;
}
type PtySpawnOptions = {
name: string;
cols: number;
rows: number;
cwd: string;
env: Record<string, string>;
};
type PtySpawn = (
file: string,
args: string[],
options: PtySpawnOptions,
) => ManagedPty | Promise<ManagedPty>;
type CommandExists = (
command: string,
env: NodeJS.ProcessEnv,
platform: NodeJS.Platform,
) => Promise<boolean>;
type ActiveTerminal = {
pty: ManagedPty;
snapshot: TerminalSnapshot;
dataSubscription: Disposable;
exitSubscription: Disposable;
};
type PtyManagerEvents = {
data: [string];
exit: [TerminalExitInfo];
};
export interface PtyManagerOptions {
platform?: NodeJS.Platform;
env?: NodeJS.ProcessEnv;
spawnPty?: PtySpawn;
commandExists?: CommandExists;
}
export class PtyManager extends EventEmitter<PtyManagerEvents> {
private readonly platform: NodeJS.Platform;
private readonly env: NodeJS.ProcessEnv;
private readonly spawnPty: PtySpawn;
private readonly commandExists: CommandExists;
private activeTerminal?: ActiveTerminal;
constructor(options: PtyManagerOptions = {}) {
super();
this.platform = options.platform ?? process.platform;
this.env = options.env ?? process.env;
this.spawnPty = options.spawnPty ?? defaultSpawnPty;
this.commandExists = options.commandExists ?? commandExistsOnPath;
}
get isRunning(): boolean {
return this.activeTerminal !== undefined;
}
getSnapshot(): TerminalSnapshot | undefined {
return this.activeTerminal ? { ...this.activeTerminal.snapshot } : undefined;
}
async create(cwd: string, cols = DEFAULT_COLS, rows = DEFAULT_ROWS): Promise<TerminalSnapshot> {
if (this.activeTerminal) {
return { ...this.activeTerminal.snapshot };
}
return this.spawnTerminal(cwd, cols, rows);
}
async restart(
cwd: string,
cols = this.activeTerminal?.snapshot.cols ?? DEFAULT_COLS,
rows = this.activeTerminal?.snapshot.rows ?? DEFAULT_ROWS,
): Promise<TerminalSnapshot> {
this.disposeActiveTerminal();
return this.spawnTerminal(cwd, cols, rows);
}
write(data: string): void {
if (!data) {
return;
}
if (!this.activeTerminal) {
console.warn('[aryx terminal] Ignoring terminal write because no terminal is running.');
return;
}
this.activeTerminal.pty.write(data);
}
resize(cols: number, rows: number): void {
if (!this.activeTerminal) {
console.warn('[aryx terminal] Ignoring terminal resize because no terminal is running.');
return;
}
const nextCols = normalizeDimension(cols, DEFAULT_COLS);
const nextRows = normalizeDimension(rows, DEFAULT_ROWS);
this.activeTerminal.pty.resize(nextCols, nextRows);
this.activeTerminal.snapshot.cols = nextCols;
this.activeTerminal.snapshot.rows = nextRows;
}
kill(): void {
this.activeTerminal?.pty.kill();
}
dispose(): void {
this.disposeActiveTerminal();
}
private async spawnTerminal(cwd: string, cols: number, rows: number): Promise<TerminalSnapshot> {
await assertDirectory(cwd);
const nextCols = normalizeDimension(cols, DEFAULT_COLS);
const nextRows = normalizeDimension(rows, DEFAULT_ROWS);
const shell = await resolveShellCommand(this.platform, this.env, this.commandExists);
const pty = await this.spawnPty(shell.command, shell.args, {
name: DEFAULT_TERMINAL_NAME,
cols: nextCols,
rows: nextRows,
cwd,
env: sanitizeEnvironment(this.env),
});
const snapshot: TerminalSnapshot = {
cwd,
shell: shell.label,
pid: pty.pid,
cols: nextCols,
rows: nextRows,
};
const active: ActiveTerminal = {
pty,
snapshot,
dataSubscription: { dispose() {} },
exitSubscription: { dispose() {} },
};
active.dataSubscription = pty.onData((data) => {
if (this.activeTerminal?.pty !== pty) {
return;
}
this.emit('data', data);
});
active.exitSubscription = pty.onExit((event) => {
if (this.activeTerminal?.pty !== pty) {
return;
}
this.activeTerminal = undefined;
active.dataSubscription.dispose();
active.exitSubscription.dispose();
this.emit('exit', event);
});
this.activeTerminal = active;
return { ...snapshot };
}
private disposeActiveTerminal(): void {
const active = this.activeTerminal;
if (!active) {
return;
}
this.activeTerminal = undefined;
active.dataSubscription.dispose();
active.exitSubscription.dispose();
try {
active.pty.kill();
} catch (error) {
console.warn('[aryx terminal] Failed to stop terminal during cleanup.', error);
}
}
}
async function defaultSpawnPty(
file: string,
args: string[],
options: PtySpawnOptions,
): Promise<ManagedPty> {
const { spawn } = await import('node-pty');
return spawn(file, args, options) as ManagedPty;
}
async function resolveShellCommand(
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv,
commandExists: CommandExists,
): Promise<{ command: string; args: string[]; label: string }> {
if (platform === 'win32') {
const windowsPowerShellPath = resolveWindowsPowerShellPath(env);
const candidates = [
{ command: 'pwsh.exe', args: ['-NoLogo'], label: 'PowerShell' },
{ command: windowsPowerShellPath, args: ['-NoLogo'], label: 'PowerShell' },
...(env.COMSPEC || env.ComSpec
? [{
command: env.COMSPEC ?? env.ComSpec ?? DEFAULT_WINDOWS_FALLBACK_SHELL,
args: [],
label: resolveShellLabel(env.COMSPEC ?? env.ComSpec ?? DEFAULT_WINDOWS_FALLBACK_SHELL),
}]
: []),
{ command: DEFAULT_WINDOWS_FALLBACK_SHELL, args: [], label: 'Command Prompt' },
] satisfies Array<{ command: string; args: string[]; label: string }>;
for (const candidate of candidates) {
if (await commandExists(candidate.command, env, platform)) {
return candidate;
}
}
return candidates[candidates.length - 1]!;
}
const configuredShell = env.SHELL?.trim();
if (configuredShell && await commandExists(configuredShell, env, platform)) {
return { command: configuredShell, args: [], label: resolveShellLabel(configuredShell) };
}
return { command: DEFAULT_UNIX_SHELL, args: [], label: resolveShellLabel(DEFAULT_UNIX_SHELL) };
}
async function commandExistsOnPath(
command: string,
env: NodeJS.ProcessEnv,
platform: NodeJS.Platform,
): Promise<boolean> {
if (isAbsolute(command)) {
return fileExists(command, platform);
}
const searchPath = env.PATH ?? env.Path ?? '';
const pathEntries = searchPath.split(delimiter).filter((entry) => entry.length > 0);
const commandNames = platform === 'win32'
? expandWindowsCommandCandidates(command)
: [command];
for (const entry of pathEntries) {
for (const candidate of commandNames) {
if (await fileExists(join(entry, candidate), platform)) {
return true;
}
}
}
return false;
}
async function fileExists(path: string, platform: NodeJS.Platform): Promise<boolean> {
try {
await access(path, platform === 'win32' ? fsConstants.F_OK : fsConstants.X_OK);
return true;
} catch {
return false;
}
}
function expandWindowsCommandCandidates(command: string): string[] {
if (command.includes('.')) {
return [command];
}
return [
`${command}.exe`,
`${command}.cmd`,
`${command}.bat`,
command,
];
}
function resolveWindowsPowerShellPath(env: NodeJS.ProcessEnv): string {
const systemRoot = env.SystemRoot ?? env.SYSTEMROOT ?? 'C:\\Windows';
return join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
}
function resolveShellLabel(command: string): string {
const baseName = basename(command).replace(/\.(exe|cmd|bat)$/i, '');
if (baseName === 'pwsh' || baseName === 'powershell') {
return 'PowerShell';
}
if (baseName === 'cmd') {
return 'Command Prompt';
}
return baseName;
}
function sanitizeEnvironment(env: NodeJS.ProcessEnv): Record<string, string> {
return Object.fromEntries(
Object.entries({
...env,
TERM: DEFAULT_TERMINAL_NAME,
}).filter((entry): entry is [string, string] => typeof entry[1] === 'string'),
);
}
function normalizeDimension(value: number, fallback: number): number {
if (!Number.isFinite(value)) {
return fallback;
}
const normalized = Math.round(value);
return normalized >= 1 ? normalized : fallback;
}
async function assertDirectory(path: string): Promise<void> {
try {
const entry = await stat(path);
if (!entry.isDirectory()) {
throw new Error(`Terminal working directory "${path}" is not a directory.`);
}
} catch (error) {
if (error instanceof Error) {
throw new Error(`Terminal working directory "${path}" is unavailable.`, { cause: error });
}
throw error;
}
}
+18 -1
View File
@@ -30,6 +30,7 @@ export function validateSessionToolingSelectionIds(
export function buildRunTurnToolingConfig(
tooling: WorkspaceToolingSettings,
selection: SessionToolingSelection,
tokenLookup?: (serverUrl: string) => string | undefined,
): RunTurnToolingConfig | undefined {
const mcpServersById = new Map<string, McpServerDefinition>(
tooling.mcpServers.map((server) => [server.id, server]),
@@ -68,7 +69,7 @@ export function buildRunTurnToolingConfig(
tools: [...server.tools],
timeoutMs: server.timeoutMs,
url: server.url,
headers: server.headers ? { ...server.headers } : undefined,
headers: mergeAuthorizationHeader(server.url, server.headers, tokenLookup),
},
];
});
@@ -100,3 +101,19 @@ export function buildRunTurnToolingConfig(
lspProfiles,
};
}
function mergeAuthorizationHeader(
serverUrl: string,
configHeaders: Record<string, string> | undefined,
tokenLookup: ((serverUrl: string) => string | undefined) | undefined,
): Record<string, string> | undefined {
const bearerToken = tokenLookup?.(serverUrl);
if (!bearerToken) {
return configHeaders ? { ...configHeaders } : undefined;
}
return {
...(configHeaders ?? {}),
Authorization: `Bearer ${bearerToken}`,
};
}
+28 -1
View File
@@ -1,6 +1,29 @@
import type { AgentActivityEvent, ApprovalRequestedEvent, TurnDeltaEvent } from '@shared/contracts/sidecar';
import type {
AgentActivityEvent,
ApprovalRequestedEvent,
ExitPlanModeRequestedEvent,
McpOauthRequiredEvent,
TurnDeltaEvent,
UserInputRequestedEvent,
SubagentEvent,
SkillInvokedEvent,
HookLifecycleEvent,
SessionUsageEvent,
SessionCompactionEvent,
PendingMessagesModifiedEvent,
AssistantUsageEvent,
} from '@shared/contracts/sidecar';
import type { ChatMessageRecord } from '@shared/domain/session';
export type TurnScopedEvent =
| SubagentEvent
| SkillInvokedEvent
| HookLifecycleEvent
| SessionUsageEvent
| SessionCompactionEvent
| PendingMessagesModifiedEvent
| AssistantUsageEvent;
export interface RunTurnPendingCommand {
kind: 'run-turn';
resolve: (messages: ChatMessageRecord[]) => void;
@@ -8,6 +31,10 @@ export interface RunTurnPendingCommand {
onDelta: (event: TurnDeltaEvent) => void | Promise<void>;
onActivity: (event: AgentActivityEvent) => void | Promise<void>;
onApproval: (event: ApprovalRequestedEvent) => void | Promise<void>;
onUserInput: (event: UserInputRequestedEvent) => void | Promise<void>;
onMcpOAuthRequired: (event: McpOauthRequiredEvent) => void | Promise<void>;
onExitPlanMode: (event: ExitPlanModeRequestedEvent) => void | Promise<void>;
onTurnScopedEvent: (event: TurnScopedEvent) => void | Promise<void>;
errored: boolean;
}
+180 -3
View File
@@ -9,8 +9,14 @@ import type {
SidecarCapabilities,
SidecarEvent,
TurnDeltaEvent,
UserInputRequestedEvent,
McpOauthRequiredEvent,
ExitPlanModeRequestedEvent,
ValidatePatternCommand,
RunTurnCommand,
CopilotSessionListFilter,
CopilotSessionInfo,
QuotaSnapshot,
} from '@shared/contracts/sidecar';
import type { ApprovalDecision } from '@shared/domain/approval';
import type { ChatMessageRecord } from '@shared/domain/session';
@@ -19,6 +25,7 @@ import {
markRunTurnPendingErrored,
shouldHandleRunTurnEvent,
type RunTurnPendingCommand,
type TurnScopedEvent,
} from '@main/sidecar/runTurnPending';
import { TurnCancelledError } from '@main/sidecar/turnCancelledError';
import { resolveSidecarProcess } from '@main/sidecar/sidecarRuntime';
@@ -44,12 +51,42 @@ type PendingCommand =
resolve: () => void;
reject: (error: Error) => void;
})
| ({
processId: number;
kind: 'resolve-user-input';
resolve: () => void;
reject: (error: Error) => void;
})
| ({
processId: number;
kind: 'cancel-turn';
resolve: () => void;
reject: (error: Error) => void;
})
| ({
processId: number;
kind: 'list-sessions';
resolve: (sessions: CopilotSessionInfo[]) => void;
reject: (error: Error) => void;
})
| ({
processId: number;
kind: 'delete-session';
resolve: (sessions: CopilotSessionInfo[]) => void;
reject: (error: Error) => void;
})
| ({
processId: number;
kind: 'disconnect-session';
resolve: () => void;
reject: (error: Error) => void;
})
| ({
processId: number;
kind: 'get-quota';
resolve: (snapshots: Record<string, QuotaSnapshot>) => void;
reject: (error: Error) => void;
})
| ({
processId: number;
} & RunTurnPendingCommand);
@@ -94,16 +131,31 @@ export class SidecarClient {
onDelta: (event: TurnDeltaEvent) => void | Promise<void>,
onActivity: (event: AgentActivityEvent) => void | Promise<void>,
onApproval: (event: ApprovalRequestedEvent) => void | Promise<void>,
onUserInput: (event: UserInputRequestedEvent) => void | Promise<void>,
onMcpOAuthRequired: (event: McpOauthRequiredEvent) => void | Promise<void>,
onExitPlanMode: (event: ExitPlanModeRequestedEvent) => void | Promise<void>,
onTurnScopedEvent: (event: TurnScopedEvent) => void | Promise<void>,
): Promise<ChatMessageRecord[]> {
return this.dispatch<ChatMessageRecord[]>(command, onDelta, onActivity, onApproval);
return this.dispatch<ChatMessageRecord[]>(command, onDelta, onActivity, onApproval, onUserInput, onMcpOAuthRequired, onExitPlanMode, onTurnScopedEvent);
}
async resolveApproval(approvalId: string, decision: ApprovalDecision): Promise<void> {
async resolveUserInput(userInputId: string, answer: string, wasFreeform: boolean): Promise<void> {
return this.dispatch<void>({
type: 'resolve-user-input',
requestId: `user-input-${Date.now()}`,
userInputId,
answer,
wasFreeform,
});
}
async resolveApproval(approvalId: string, decision: ApprovalDecision, alwaysApprove?: boolean): Promise<void> {
return this.dispatch<void>({
type: 'resolve-approval',
requestId: `approval-${Date.now()}`,
approvalId,
decision,
alwaysApprove: alwaysApprove ?? false,
});
}
@@ -115,6 +167,38 @@ export class SidecarClient {
} satisfies CancelTurnCommand);
}
async listSessions(filter?: CopilotSessionListFilter): Promise<CopilotSessionInfo[]> {
return this.dispatch<CopilotSessionInfo[]>({
type: 'list-sessions',
requestId: `list-sessions-${Date.now()}`,
filter,
});
}
async deleteSession(sessionId?: string, copilotSessionId?: string): Promise<CopilotSessionInfo[]> {
return this.dispatch<CopilotSessionInfo[]>({
type: 'delete-session',
requestId: `delete-session-${Date.now()}`,
sessionId,
copilotSessionId,
});
}
async disconnectSession(sessionId: string): Promise<void> {
return this.dispatch<void>({
type: 'disconnect-session',
requestId: `disconnect-session-${Date.now()}`,
sessionId,
});
}
async getQuota(): Promise<Record<string, QuotaSnapshot>> {
return this.dispatch<Record<string, QuotaSnapshot>>({
type: 'get-quota',
requestId: `get-quota-${Date.now()}`,
});
}
async dispose(): Promise<void> {
const state = this.processState;
if (!state) {
@@ -199,6 +283,10 @@ export class SidecarClient {
onDelta?: (event: TurnDeltaEvent) => void | Promise<void>,
onActivity?: (event: AgentActivityEvent) => void | Promise<void>,
onApproval?: (event: ApprovalRequestedEvent) => void | Promise<void>,
onUserInput?: (event: UserInputRequestedEvent) => void | Promise<void>,
onMcpOAuthRequired?: (event: McpOauthRequiredEvent) => void | Promise<void>,
onExitPlanMode?: (event: ExitPlanModeRequestedEvent) => void | Promise<void>,
onTurnScopedEvent?: (event: TurnScopedEvent) => void | Promise<void>,
): Promise<TResult> {
const state = await this.ensureProcess();
@@ -212,6 +300,10 @@ export class SidecarClient {
onDelta: onDelta ?? (() => undefined),
onActivity: onActivity ?? (() => undefined),
onApproval: onApproval ?? (() => undefined),
onUserInput: onUserInput ?? (() => undefined),
onMcpOAuthRequired: onMcpOAuthRequired ?? (() => undefined),
onExitPlanMode: onExitPlanMode ?? (() => undefined),
onTurnScopedEvent: onTurnScopedEvent ?? (() => undefined),
errored: false,
});
} else if (command.type === 'validate-pattern') {
@@ -228,6 +320,13 @@ export class SidecarClient {
resolve: resolve as () => void,
reject,
});
} else if (command.type === 'resolve-user-input') {
this.pending.set(command.requestId, {
processId: state.id,
kind: 'resolve-user-input',
resolve: resolve as () => void,
reject,
});
} else if (command.type === 'cancel-turn') {
this.pending.set(command.requestId, {
processId: state.id,
@@ -235,6 +334,34 @@ export class SidecarClient {
resolve: resolve as () => void,
reject,
});
} else if (command.type === 'list-sessions') {
this.pending.set(command.requestId, {
processId: state.id,
kind: 'list-sessions',
resolve: resolve as (sessions: CopilotSessionInfo[]) => void,
reject,
});
} else if (command.type === 'delete-session') {
this.pending.set(command.requestId, {
processId: state.id,
kind: 'delete-session',
resolve: resolve as (sessions: CopilotSessionInfo[]) => void,
reject,
});
} else if (command.type === 'disconnect-session') {
this.pending.set(command.requestId, {
processId: state.id,
kind: 'disconnect-session',
resolve: resolve as () => void,
reject,
});
} else if (command.type === 'get-quota') {
this.pending.set(command.requestId, {
processId: state.id,
kind: 'get-quota',
resolve: resolve as (snapshots: Record<string, QuotaSnapshot>) => void,
reject,
});
} else {
this.pending.set(command.requestId, {
processId: state.id,
@@ -297,6 +424,56 @@ export class SidecarClient {
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onApproval(event));
}
return;
case 'user-input-requested':
if (pending.kind === 'run-turn' && shouldHandleRunTurnEvent(pending)) {
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onUserInput(event));
}
return;
case 'mcp-oauth-required':
if (pending.kind === 'run-turn' && shouldHandleRunTurnEvent(pending)) {
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onMcpOAuthRequired(event));
}
return;
case 'exit-plan-mode-requested':
if (pending.kind === 'run-turn' && shouldHandleRunTurnEvent(pending)) {
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onExitPlanMode(event));
}
return;
case 'subagent-event':
case 'skill-invoked':
case 'hook-lifecycle':
case 'session-usage':
case 'session-compaction':
case 'pending-messages-modified':
case 'assistant-usage':
if (pending.kind === 'run-turn' && shouldHandleRunTurnEvent(pending)) {
this.invokeRunTurnHandler(event.requestId, pending, () => pending.onTurnScopedEvent(event));
}
return;
case 'quota-result':
if (pending.kind === 'get-quota') {
pending.resolve(event.quotaSnapshots);
this.pending.delete(event.requestId);
}
return;
case 'sessions-listed':
if (pending.kind === 'list-sessions') {
pending.resolve(event.sessions);
this.pending.delete(event.requestId);
}
return;
case 'sessions-deleted':
if (pending.kind === 'delete-session') {
pending.resolve(event.sessions);
this.pending.delete(event.requestId);
}
return;
case 'session-disconnected':
if (pending.kind === 'disconnect-session') {
pending.resolve();
this.pending.delete(event.requestId);
}
return;
case 'turn-complete':
if (pending.kind === 'run-turn') {
if (shouldHandleRunTurnEvent(pending)) {
@@ -318,7 +495,7 @@ export class SidecarClient {
this.pending.delete(event.requestId);
return;
case 'command-complete':
if (pending.kind === 'resolve-approval' || pending.kind === 'cancel-turn') {
if (pending.kind === 'resolve-approval' || pending.kind === 'resolve-user-input' || pending.kind === 'cancel-turn') {
pending.resolve();
this.pending.delete(event.requestId);
} else if (pending.kind !== 'run-turn' || pending.errored) {
+36
View File
@@ -15,16 +15,31 @@ const api: ElectronApi = {
ipcRenderer.invoke(ipcChannels.resolveWorkspaceDiscoveredTooling, input),
refreshProjectGitContext: (projectId) => ipcRenderer.invoke(ipcChannels.refreshProjectGitContext, projectId),
rescanProjectConfigs: (input) => ipcRenderer.invoke(ipcChannels.rescanProjectConfigs, input),
rescanProjectCustomization: (input) =>
ipcRenderer.invoke(ipcChannels.rescanProjectCustomization, input),
resolveProjectDiscoveredTooling: (input) =>
ipcRenderer.invoke(ipcChannels.resolveProjectDiscoveredTooling, input),
setProjectAgentProfileEnabled: (input) =>
ipcRenderer.invoke(ipcChannels.setProjectAgentProfileEnabled, input),
savePattern: (input) => ipcRenderer.invoke(ipcChannels.savePattern, input),
deletePattern: (patternId) => ipcRenderer.invoke(ipcChannels.deletePattern, patternId),
setPatternFavorite: (input) => ipcRenderer.invoke(ipcChannels.setPatternFavorite, input),
setTheme: (theme) => ipcRenderer.invoke(ipcChannels.setTheme, theme),
setTerminalHeight: (input) => ipcRenderer.invoke(ipcChannels.setTerminalHeight, input),
saveMcpServer: (input) => ipcRenderer.invoke(ipcChannels.saveMcpServer, input),
deleteMcpServer: (serverId) => ipcRenderer.invoke(ipcChannels.deleteMcpServer, serverId),
saveLspProfile: (input) => ipcRenderer.invoke(ipcChannels.saveLspProfile, input),
deleteLspProfile: (profileId) => ipcRenderer.invoke(ipcChannels.deleteLspProfile, profileId),
describeTerminal: () => ipcRenderer.invoke(ipcChannels.describeTerminal),
createTerminal: () => ipcRenderer.invoke(ipcChannels.createTerminal),
restartTerminal: () => ipcRenderer.invoke(ipcChannels.restartTerminal),
killTerminal: () => ipcRenderer.invoke(ipcChannels.killTerminal),
writeTerminal: (data) => {
ipcRenderer.send(ipcChannels.writeTerminal, data);
},
resizeTerminal: (input) => {
ipcRenderer.send(ipcChannels.resizeTerminal, input);
},
updateSessionTooling: (input) => ipcRenderer.invoke(ipcChannels.updateSessionTooling, input),
updateSessionApprovalSettings: (input) =>
ipcRenderer.invoke(ipcChannels.updateSessionApprovalSettings, input),
@@ -33,9 +48,15 @@ const api: ElectronApi = {
renameSession: (input) => ipcRenderer.invoke(ipcChannels.renameSession, input),
setSessionPinned: (input) => ipcRenderer.invoke(ipcChannels.setSessionPinned, input),
setSessionArchived: (input) => ipcRenderer.invoke(ipcChannels.setSessionArchived, input),
deleteSession: (input) => ipcRenderer.invoke(ipcChannels.deleteSession, input),
sendSessionMessage: (input) => ipcRenderer.invoke(ipcChannels.sendSessionMessage, input),
cancelSessionTurn: (input) => ipcRenderer.invoke(ipcChannels.cancelSessionTurn, input),
resolveSessionApproval: (input) => ipcRenderer.invoke(ipcChannels.resolveSessionApproval, input),
resolveSessionUserInput: (input) => ipcRenderer.invoke(ipcChannels.resolveSessionUserInput, input),
setSessionInteractionMode: (input) => ipcRenderer.invoke(ipcChannels.setSessionInteractionMode, input),
dismissSessionPlanReview: (input) => ipcRenderer.invoke(ipcChannels.dismissSessionPlanReview, input),
dismissSessionMcpAuth: (input) => ipcRenderer.invoke(ipcChannels.dismissSessionMcpAuth, input),
startSessionMcpAuth: (input) => ipcRenderer.invoke(ipcChannels.startSessionMcpAuth, input),
updateSessionModelConfig: (input) =>
ipcRenderer.invoke(ipcChannels.updateSessionModelConfig, input),
querySessions: (input) => ipcRenderer.invoke(ipcChannels.querySessions, input),
@@ -44,6 +65,21 @@ const api: ElectronApi = {
selectSession: (sessionId) => ipcRenderer.invoke(ipcChannels.selectSession, sessionId),
openAppDataFolder: () => ipcRenderer.invoke(ipcChannels.openAppDataFolder),
resetLocalWorkspace: () => ipcRenderer.invoke(ipcChannels.resetLocalWorkspace),
getQuota: () => ipcRenderer.invoke(ipcChannels.getQuota),
onTerminalData: (listener) => {
const handler = (_event: Electron.IpcRendererEvent, data: Parameters<typeof listener>[0]) =>
listener(data);
ipcRenderer.on(ipcChannels.terminalData, handler);
return () => ipcRenderer.off(ipcChannels.terminalData, handler);
},
onTerminalExit: (listener) => {
const handler = (_event: Electron.IpcRendererEvent, info: Parameters<typeof listener>[0]) =>
listener(info);
ipcRenderer.on(ipcChannels.terminalExit, handler);
return () => ipcRenderer.off(ipcChannels.terminalExit, handler);
},
onWorkspaceUpdated:(listener) => {
const handler = (_event: Electron.IpcRendererEvent, workspace: Awaited<ReturnType<ElectronApi['loadWorkspace']>>) =>
listener(workspace);
+191 -10
View File
@@ -5,14 +5,26 @@ import { ActivityPanel } from '@renderer/components/ActivityPanel';
import { ChatPane } from '@renderer/components/ChatPane';
import { DiscoveredToolingModal } from '@renderer/components/DiscoveredToolingModal';
import { NewSessionModal } from '@renderer/components/NewSessionModal';
import { ProjectSettingsPanel } from '@renderer/components/ProjectSettingsPanel';
import { SettingsPanel } from '@renderer/components/SettingsPanel';
import { Sidebar } from '@renderer/components/Sidebar';
import { TerminalPanel, DEFAULT_HEIGHT as DEFAULT_TERMINAL_HEIGHT, MIN_HEIGHT as MIN_TERMINAL_HEIGHT } from '@renderer/components/TerminalPanel';
import { resolveChatToolingSettings } from '@renderer/lib/chatTooling';
import {
applySessionEventActivity,
applySessionUsageEvent,
applyAssistantUsageEvent,
applyTurnEventLog,
pruneSessionActivities,
pruneSessionUsage,
pruneSessionRequestUsage,
pruneTurnEventLogs,
type SessionActivityMap,
type SessionUsageMap,
type SessionRequestUsageMap,
type TurnEventLogMap,
} from '@renderer/lib/sessionActivity';
import { applySubagentEvent, pruneSubagentMap, type ActiveSubagentMap } from '@renderer/lib/subagentTracker';
import { applySessionEventWorkspace } from '@renderer/lib/sessionWorkspace';
import { WelcomePane } from '@renderer/components/WelcomePane';
import { getElectronApi } from '@renderer/lib/electronApi';
@@ -91,11 +103,23 @@ export default function App() {
const [error, setError] = useState<string>();
const { capabilities: sidecarCapabilities, isRefreshing: isRefreshingCapabilities, refresh: refreshCapabilities } = useSidecarCapabilities(api);
const [sessionActivities, setSessionActivities] = useState<SessionActivityMap>({});
const [sessionUsage, setSessionUsage] = useState<SessionUsageMap>({});
const [sessionRequestUsage, setSessionRequestUsage] = useState<SessionRequestUsageMap>({});
const [turnEventLogs, setTurnEventLogs] = useState<TurnEventLogMap>({});
const [activeSubagents, setActiveSubagents] = useState<ActiveSubagentMap>({});
const [showSettings, setShowSettings] = useState(false);
const [projectSettingsId, setProjectSettingsId] = useState<string>();
const [newSessionProjectId, setNewSessionProjectId] = useState<string>();
const [showDiscoveryModal, setShowDiscoveryModal] = useState(false);
// Terminal state
const [terminalOpen, setTerminalOpen] = useState(false);
const [terminalHeight, setTerminalHeight] = useState(
() => workspace?.settings.terminalHeight ?? DEFAULT_TERMINAL_HEIGHT,
);
const [terminalRunning, setTerminalRunning] = useState(false);
// Load workspace on mount
useEffect(() => {
let disposed = false;
@@ -114,11 +138,39 @@ export default function App() {
ws.sessions.map((session) => session.id),
),
);
setSessionUsage((current) =>
pruneSessionUsage(
current,
ws.sessions.map((session) => session.id),
),
);
setSessionRequestUsage((current) =>
pruneSessionRequestUsage(
current,
ws.sessions.map((session) => session.id),
),
);
setTurnEventLogs((current) =>
pruneTurnEventLogs(
current,
ws.sessions.map((session) => session.id),
),
);
setActiveSubagents((current) =>
pruneSubagentMap(
current,
ws.sessions.map((session) => session.id),
),
);
});
const offSessionEvent = api.onSessionEvent((event) => {
setWorkspace((current) => applySessionEventWorkspace(current, event));
setSessionActivities((current) => applySessionEventActivity(current, event));
setSessionUsage((current) => applySessionUsageEvent(current, event));
setSessionRequestUsage((current) => applyAssistantUsageEvent(current, event));
setTurnEventLogs((current) => applyTurnEventLog(current, event));
setActiveSubagents((current) => applySubagentEvent(current, event));
});
return () => {
@@ -169,6 +221,22 @@ export default function App() {
() => (selectedSession ? sessionActivities[selectedSession.id] : undefined),
[selectedSession, sessionActivities],
);
const usageForSession = useMemo(
() => (selectedSession ? sessionUsage[selectedSession.id] : undefined),
[selectedSession, sessionUsage],
);
const requestUsageForSession = useMemo(
() => (selectedSession ? sessionRequestUsage[selectedSession.id] : undefined),
[selectedSession, sessionRequestUsage],
);
const subagentsForSession = useMemo(
() => (selectedSession ? activeSubagents[selectedSession.id] : undefined),
[selectedSession, activeSubagents],
);
const turnEventsForSession = useMemo(
() => (selectedSession ? turnEventLogs[selectedSession.id] : undefined),
[selectedSession, turnEventLogs],
);
const hasUserProjects = useMemo(
() => (workspace?.projects.some((project) => !isScratchpadProject(project)) ?? false),
[workspace?.projects],
@@ -196,6 +264,46 @@ export default function App() {
if (hasPendingDiscoveries) setShowDiscoveryModal(true);
}, [hasPendingDiscoveries]);
// Terminal: Ctrl+` toggle + track running state
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.ctrlKey && e.key === '`') {
e.preventDefault();
setTerminalOpen((prev) => !prev);
}
};
window.addEventListener('keydown', handleKeyDown);
// Track terminal running state via exit events
const offExit = api.onTerminalExit(() => setTerminalRunning(false));
return () => {
window.removeEventListener('keydown', handleKeyDown);
offExit();
};
}, [api]);
// Sync terminalHeight from workspace settings when workspace loads
useEffect(() => {
if (workspace?.settings.terminalHeight) {
setTerminalHeight(workspace.settings.terminalHeight);
}
}, [workspace?.settings.terminalHeight]);
const handleTerminalHeightChange = useCallback((newHeight: number) => {
const clamped = Math.max(MIN_TERMINAL_HEIGHT, Math.round(newHeight));
setTerminalHeight(clamped);
void api.setTerminalHeight({ height: clamped });
}, [api]);
const handleTerminalClose = useCallback(() => {
setTerminalOpen(false);
}, []);
const handleTerminalToggle = useCallback(() => {
setTerminalOpen((prev) => !prev);
}, []);
const jumpToMessage = useCallback((messageId: string) => {
const element = document.querySelector(`[data-message-id="${CSS.escape(messageId)}"]`);
if (element) {
@@ -221,6 +329,16 @@ export default function App() {
}
}, [api, workspace]);
const projectForSettings = useMemo(
() => workspace?.projects.find((p) => p.id === projectSettingsId),
[workspace?.projects, projectSettingsId],
);
// Close project settings if the project was removed
useEffect(() => {
if (projectSettingsId && !projectForSettings) setProjectSettingsId(undefined);
}, [projectSettingsId, projectForSettings]);
// Loading state
if (!workspace) {
return (
@@ -245,11 +363,31 @@ export default function App() {
} else if (selectedSession && patternForSession && projectForSession) {
content = (
<ChatPane
onSend={(c) => api.sendSessionMessage({ sessionId: selectedSession.id, content: c })}
onSend={(c, attachments, messageMode) => api.sendSessionMessage({
sessionId: selectedSession.id,
content: c,
attachments: attachments?.length ? attachments : undefined,
messageMode,
})}
onCancelTurn={() => { void api.cancelSessionTurn({ sessionId: selectedSession.id }); }}
onResolveApproval={(approvalId, decision) =>
api.resolveSessionApproval({ sessionId: selectedSession.id, approvalId, decision })
onResolveApproval={(approvalId, decision, alwaysApprove) =>
api.resolveSessionApproval({ sessionId: selectedSession.id, approvalId, decision, alwaysApprove })
}
onResolveUserInput={(userInputId, answer, wasFreeform) =>
api.resolveSessionUserInput({ sessionId: selectedSession.id, userInputId, answer, wasFreeform })
}
onSetInteractionMode={(mode) => {
void api.setSessionInteractionMode({ sessionId: selectedSession.id, mode });
}}
onDismissPlanReview={() => {
void api.dismissSessionPlanReview({ sessionId: selectedSession.id });
}}
onDismissMcpAuth={() => {
void api.dismissSessionMcpAuth({ sessionId: selectedSession.id });
}}
onAuthenticateMcp={() => {
void api.startSessionMcpAuth({ sessionId: selectedSession.id });
}}
onUpdateSessionModelConfig={(config) =>
api.updateSessionModelConfig({
sessionId: selectedSession.id,
@@ -271,10 +409,16 @@ export default function App() {
});
}}
availableModels={availableModels}
mcpProbingServerIds={workspace.mcpProbingServerIds}
onTerminalToggle={handleTerminalToggle}
pattern={patternForSession}
project={projectForSession}
runtimeTools={sidecarCapabilities?.runtimeTools}
session={selectedSession}
sessionUsage={usageForSession}
activeSubagents={subagentsForSession}
terminalOpen={terminalOpen}
terminalRunning={terminalRunning}
toolingSettings={chatToolingSettings ?? workspace.settings.tooling}
/>
);
@@ -284,6 +428,8 @@ export default function App() {
onJumpToMessage={jumpToMessage}
pattern={patternForSession}
session={selectedSession}
sessionRequestUsage={requestUsageForSession}
turnEvents={turnEventsForSession}
/>
);
} else {
@@ -335,22 +481,20 @@ export default function App() {
onSetTheme={(theme) => void api.setTheme(theme)}
onOpenAppDataFolder={() => void api.openAppDataFolder()}
onResetLocalWorkspace={async () => {
await api.resetLocalWorkspace();
const fresh = await api.resetLocalWorkspace();
setWorkspace(fresh);
setSessionActivities({});
setShowSettings(false);
}}
patterns={workspace.patterns}
sidecarCapabilities={sidecarCapabilities}
theme={workspace.settings.theme}
toolingSettings={workspace.settings.tooling}
discoveredUserTooling={workspace.settings.discoveredUserTooling}
discoveredProjectTooling={selectedProject?.discoveredTooling}
selectedProjectName={selectedProject?.name}
onRescanProjectConfigs={selectedProject ? () => void api.rescanProjectConfigs({ projectId: selectedProject.id }) : undefined}
onResolveUserDiscoveredTooling={(serverIds, resolution) => {
void api.resolveWorkspaceDiscoveredTooling({ serverIds, resolution });
}}
onResolveProjectDiscoveredTooling={selectedProject ? (serverIds, resolution) => {
void api.resolveProjectDiscoveredTooling({ projectId: selectedProject.id, serverIds, resolution });
} : undefined}
onGetQuota={() => api.getQuota()}
/>
) : null;
@@ -360,6 +504,16 @@ export default function App() {
content={content}
detailPanel={detailPanel}
overlay={overlay}
terminalPanel={
terminalOpen ? (
<TerminalPanel
height={terminalHeight}
onHeightChange={handleTerminalHeightChange}
onClose={handleTerminalClose}
onMinimize={handleTerminalClose}
/>
) : undefined
}
sidebar={
<Sidebar
onAddProject={() => void api.addProject()}
@@ -368,6 +522,7 @@ export default function App() {
setNewSessionProjectId(projectId);
}}
onOpenSettings={() => setShowSettings(true)}
onOpenProjectSettings={(projectId) => setProjectSettingsId(projectId)}
onProjectSelect={(projectId) => {
void api.selectProject(projectId);
}}
@@ -386,6 +541,9 @@ export default function App() {
onSetSessionArchived={(sessionId, isArchived) => {
void api.setSessionArchived({ sessionId, isArchived });
}}
onDeleteSession={(sessionId) => {
void api.deleteSession({ sessionId });
}}
onRefreshGitContext={(projectId) => {
void api.refreshProjectGitContext(projectId);
}}
@@ -426,6 +584,29 @@ export default function App() {
userDiscoveredTooling={workspace.settings.discoveredUserTooling}
/>
)}
{projectForSettings && (
<ProjectSettingsPanel
project={projectForSettings}
onClose={() => setProjectSettingsId(undefined)}
onRescanConfigs={() => {
void api.rescanProjectConfigs({ projectId: projectForSettings.id });
}}
onRescanCustomization={() => {
void api.rescanProjectCustomization({ projectId: projectForSettings.id });
}}
onResolveDiscoveredTooling={(serverIds, resolution) => {
void api.resolveProjectDiscoveredTooling({ projectId: projectForSettings.id, serverIds, resolution });
}}
onSetAgentProfileEnabled={(agentProfileId, enabled) => {
void api.setProjectAgentProfileEnabled({ projectId: projectForSettings.id, agentProfileId, enabled });
}}
onRemoveProject={() => {
void api.removeProject(projectForSettings.id);
setProjectSettingsId(undefined);
}}
/>
)}
</>
);
}
+152 -10
View File
@@ -1,13 +1,19 @@
import { useMemo, type ReactNode } from 'react';
import { Activity, Clock, ShieldAlert, Sparkles, Users } from 'lucide-react';
import { Activity, ArrowRight, BarChart3, CheckCircle2, Clock, Cog, ShieldAlert, Sparkles, Users, Zap } from 'lucide-react';
import {
buildAgentActivityRows,
formatAgentActivityLabel,
formatDuration,
formatNanoAiu,
formatTokenCount,
isAgentActivityActive,
isAgentActivityCompleted,
type AgentActivityRow,
type AgentUsageAccumulator,
type SessionActivityState,
type SessionRequestUsageState,
type TurnEventLog,
} from '@renderer/lib/sessionActivity';
import { RunTimeline } from '@renderer/components/RunTimeline';
import { inferProvider } from '@shared/domain/models';
@@ -69,11 +75,13 @@ function AgentRow({
agent,
accent,
isLast,
agentUsage,
}: {
row: AgentActivityRow;
agent?: PatternAgentDefinition;
accent: (typeof modeAccent)[OrchestrationMode];
isLast: boolean;
agentUsage?: AgentUsageAccumulator;
}) {
const isActive = isAgentActivityActive(row.activity);
const isCompleted = isAgentActivityCompleted(row.activity);
@@ -140,11 +148,61 @@ function AgentRow({
{formatAgentActivityLabel(row.activity)}
</span>
</div>
{/* Per-agent usage summary */}
{agentUsage && agentUsage.requestCount > 0 && (
<div className="mt-0.5 flex items-center gap-1 text-[10px] text-zinc-600">
<span className="tabular-nums">{formatTokenCount(agentUsage.inputTokens)} in</span>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{formatTokenCount(agentUsage.outputTokens)} out</span>
{agentUsage.cost > 0 && (
<>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{agentUsage.cost.toFixed(2)} cost</span>
</>
)}
{agentUsage.durationMs > 0 && (
<>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{formatDuration(agentUsage.durationMs)}</span>
</>
)}
</div>
)}
</div>
</div>
);
}
/* ── Turn event helpers ─────────────────────────────────────── */
import type { SessionEventKind } from '@shared/domain/event';
function TurnEventIcon({ kind, phase, success }: { kind: SessionEventKind; phase?: string; success?: boolean }) {
const base = 'size-3';
switch (kind) {
case 'subagent':
return <ArrowRight className={`${base} ${success === false ? 'text-red-400' : 'text-sky-400'}`} />;
case 'hook-lifecycle':
return <Cog className={`${base} ${phase === 'start' ? 'animate-spin text-amber-400' : success === false ? 'text-red-400' : 'text-emerald-400'}`} />;
case 'skill-invoked':
return <Sparkles className={`${base} text-violet-400`} />;
case 'session-compaction':
return <CheckCircle2 className={`${base} ${phase === 'start' ? 'animate-pulse text-amber-400' : 'text-emerald-400'}`} />;
default:
return <Zap className={`${base} text-zinc-500`} />;
}
}
function formatTurnEventTimestamp(iso: string): string {
try {
const d = new Date(iso);
return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
} catch {
return '';
}
}
/* ── ActivityPanel ─────────────────────────────────────────── */
interface ActivityPanelProps {
@@ -152,6 +210,8 @@ interface ActivityPanelProps {
onJumpToMessage?: (messageId: string) => void;
pattern: PatternDefinition;
session: SessionRecord;
sessionRequestUsage?: SessionRequestUsageState;
turnEvents?: TurnEventLog;
}
export function ActivityPanel({
@@ -159,6 +219,8 @@ export function ActivityPanel({
onJumpToMessage,
pattern,
session,
sessionRequestUsage,
turnEvents,
}: ActivityPanelProps) {
const activityRows = useMemo(
() => buildAgentActivityRows(activity, pattern.agents),
@@ -209,21 +271,68 @@ export function ActivityPanel({
{activityRows.length > 0 ? (
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40 px-3">
{activityRows.map((row, index) => (
<AgentRow
accent={accent}
agent={pattern.agents[index]}
isLast={index === activityRows.length - 1}
key={row.key}
row={row}
/>
))}
{activityRows.map((row, index) => {
const agentKey = row.activity?.agentId ?? row.key;
const agentUsage = sessionRequestUsage?.perAgent[agentKey]
?? sessionRequestUsage?.perAgent[row.agentName];
return (
<AgentRow
accent={accent}
agent={pattern.agents[index]}
agentUsage={agentUsage}
isLast={index === activityRows.length - 1}
key={row.key}
row={row}
/>
);
})}
</div>
) : (
<p className="py-4 text-center text-[11px] text-zinc-600">No agents configured</p>
)}
</div>
{/* ── Session usage section ──────────────────────────── */}
{sessionRequestUsage && sessionRequestUsage.requestCount > 0 && (
<div className="mb-4">
<SectionHeader>
<BarChart3 className="size-3" />
<span>Session Usage</span>
</SectionHeader>
<div className="rounded-lg border border-zinc-800 bg-zinc-900/40 px-3 py-2.5">
<div className="flex flex-wrap items-center gap-1.5 text-[11px] text-zinc-400">
<span className="font-medium tabular-nums">
{sessionRequestUsage.requestCount} premium request{sessionRequestUsage.requestCount === 1 ? '' : 's'}
</span>
{sessionRequestUsage.totalNanoAiu > 0 && (
<>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{formatNanoAiu(sessionRequestUsage.totalNanoAiu)} AIU</span>
</>
)}
</div>
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-[10px] text-zinc-500">
<span className="tabular-nums">{formatTokenCount(sessionRequestUsage.totalInputTokens)} in</span>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{formatTokenCount(sessionRequestUsage.totalOutputTokens)} out</span>
{sessionRequestUsage.totalCost > 0 && (
<>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{sessionRequestUsage.totalCost.toFixed(2)} cost</span>
</>
)}
{sessionRequestUsage.totalDurationMs > 0 && (
<>
<span className="text-zinc-700">·</span>
<span className="tabular-nums">{formatDuration(sessionRequestUsage.totalDurationMs)} total</span>
</>
)}
</div>
</div>
</div>
)}
{/* ── Run timeline section ─────────────────────────── */}
<div className="mb-4">
<SectionHeader>
@@ -239,6 +348,39 @@ export function ActivityPanel({
<RunTimeline onJumpToMessage={onJumpToMessage} runs={session.runs} />
</div>
{/* ── Turn events section ─────────────────────────── */}
{turnEvents && turnEvents.length > 0 && (
<div className="mb-4">
<SectionHeader>
<Zap className="size-3" />
<span>Events</span>
<span className="rounded-full bg-zinc-800 px-1.5 py-0.5 text-[9px] tabular-nums text-zinc-500">
{turnEvents.length}
</span>
</SectionHeader>
<div className="space-y-0.5 rounded-lg border border-zinc-800 bg-zinc-900/40 px-3 py-2">
{turnEvents.slice().reverse().map((entry, index) => (
<div key={index} className="flex items-start gap-2 py-1">
<div className="mt-0.5 shrink-0">
<TurnEventIcon kind={entry.kind} phase={entry.phase} success={entry.success} />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<span className="text-[11px] font-medium text-zinc-300">{entry.label}</span>
<span className="ml-auto shrink-0 text-[9px] tabular-nums text-zinc-700">
{formatTurnEventTimestamp(entry.occurredAt)}
</span>
</div>
{entry.detail && (
<p className="text-[10px] leading-snug text-zinc-600">{entry.detail}</p>
)}
</div>
</div>
))}
</div>
</div>
)}
</div>
</div>
+6 -2
View File
@@ -4,10 +4,11 @@ interface AppShellProps {
sidebar: ReactNode;
content: ReactNode;
detailPanel?: ReactNode;
terminalPanel?: ReactNode;
overlay?: ReactNode;
}
export function AppShell({ sidebar, content, detailPanel, overlay }: AppShellProps) {
export function AppShell({ sidebar, content, detailPanel, terminalPanel, overlay }: AppShellProps) {
return (
<div className="relative flex h-screen bg-[var(--color-surface-0)] text-zinc-100">
{/* Full-width drag region matching the title bar overlay height */}
@@ -16,7 +17,10 @@ export function AppShell({ sidebar, content, detailPanel, overlay }: AppShellPro
<aside className="flex w-72 shrink-0 flex-col border-r border-[var(--color-border)] bg-[var(--color-surface-1)]">
{sidebar}
</aside>
<main className="relative min-w-0 flex-1">{content}</main>
<main className="relative flex min-w-0 flex-1 flex-col">
<div className="min-h-0 flex-1">{content}</div>
{terminalPanel}
</main>
{detailPanel && (
<aside className="flex w-64 shrink-0 flex-col border-l border-[var(--color-border)] bg-[var(--color-surface-1)]">
{detailPanel}
+361 -42
View File
@@ -1,13 +1,23 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { AlertCircle, ArrowUp, Bot, Circle, GitBranch, Loader2, ShieldAlert, Square, User } from 'lucide-react';
import { AlertCircle, ArrowUp, Bot, Circle, ClipboardList, GitBranch, Loader2, MessageCircleQuestion, Paperclip, ShieldAlert, Square, User, X } from 'lucide-react';
import { MarkdownContent } from '@renderer/components/MarkdownContent';
import { MarkdownComposer, type MarkdownComposerHandle } from '@renderer/components/MarkdownComposer';
import { ApprovalBanner, QueuedApprovalsList } from '@renderer/components/chat/ApprovalBanner';
import { InlineApprovalPill, InlineModelPill, InlineThinkingPill, InlineToolsPill } from '@renderer/components/chat/InlinePills';
import { PlanReviewBanner } from '@renderer/components/chat/PlanReviewBanner';
import { McpAuthBanner } from '@renderer/components/chat/McpAuthBanner';
import { UserInputBanner } from '@renderer/components/chat/UserInputBanner';
import { InlineApprovalPill, InlineModelPill, InlineTerminalPill, InlineThinkingPill, InlineToolsPill } from '@renderer/components/chat/InlinePills';
import { InlinePromptPill } from '@renderer/components/chat/InlinePromptPill';
import { ThinkingDots } from '@renderer/components/chat/ThinkingDots';
import { SubagentActivityList } from '@renderer/components/chat/SubagentActivityCard';
import { getAssistantMessagePhase } from '@renderer/lib/messagePhase';
import type { ApprovalDecision } from '@shared/domain/approval';
import type { InteractionMode, MessageMode } from '@shared/contracts/sidecar';
import type { ChatMessageAttachment } from '@shared/domain/attachment';
import { getAttachmentDisplayName, isImageAttachment } from '@shared/domain/attachment';
import type { SessionUsageState } from '@renderer/lib/sessionActivity';
import type { ActiveSubagent } from '@renderer/lib/subagentTracker';
import {
findModel,
getSupportedReasoningEfforts,
@@ -18,6 +28,7 @@ import { type PatternDefinition, type ReasoningEffort } from '@shared/domain/pat
import { isScratchpadProject, type ProjectRecord } from '@shared/domain/project';
import { resolveSessionToolingSelection, type SessionRecord } from '@shared/domain/session';
import {
groupApprovalToolsByProvider,
listApprovalToolDefinitions,
type RuntimeToolDefinition,
type SessionToolingSelection,
@@ -32,10 +43,21 @@ interface ChatPaneProps {
session: SessionRecord;
availableModels: ReadonlyArray<ModelDefinition>;
toolingSettings: WorkspaceToolingSettings;
mcpProbingServerIds?: string[];
runtimeTools?: ReadonlyArray<RuntimeToolDefinition>;
onSend: (content: string) => Promise<void>;
sessionUsage?: SessionUsageState;
activeSubagents?: ReadonlyArray<ActiveSubagent>;
terminalOpen?: boolean;
terminalRunning?: boolean;
onSend: (content: string, attachments?: ChatMessageAttachment[], messageMode?: MessageMode) => Promise<void>;
onCancelTurn?: () => void;
onResolveApproval?: (approvalId: string, decision: ApprovalDecision) => Promise<unknown>;
onResolveApproval?: (approvalId: string, decision: ApprovalDecision, alwaysApprove?: boolean) => Promise<unknown>;
onResolveUserInput?: (userInputId: string, answer: string, wasFreeform: boolean) => Promise<unknown>;
onSetInteractionMode?: (mode: InteractionMode) => void;
onDismissPlanReview?: () => void;
onDismissMcpAuth?: () => void;
onAuthenticateMcp?: () => void;
onTerminalToggle?: () => void;
onUpdateSessionModelConfig?: (config: {
model: string;
reasoningEffort?: ReasoningEffort;
@@ -50,10 +72,21 @@ export function ChatPane({
session,
availableModels,
toolingSettings,
mcpProbingServerIds,
runtimeTools,
sessionUsage,
activeSubagents,
terminalOpen,
terminalRunning,
onSend,
onCancelTurn,
onResolveApproval,
onResolveUserInput,
onSetInteractionMode,
onDismissPlanReview,
onDismissMcpAuth,
onAuthenticateMcp,
onTerminalToggle,
onUpdateSessionModelConfig,
onUpdateSessionTooling,
onUpdateSessionApprovalSettings,
@@ -62,6 +95,7 @@ export function ChatPane({
const [configError, setConfigError] = useState<string>();
const [approvalError, setApprovalError] = useState<string>();
const [isResolvingApproval, setIsResolvingApproval] = useState(false);
const [isSubmittingUserInput, setIsSubmittingUserInput] = useState(false);
const [isUpdatingSessionModelConfig, setIsUpdatingSessionModelConfig] = useState(false);
const transcriptRef = useRef<HTMLDivElement>(null);
const composerRef = useRef<MarkdownComposerHandle>(null);
@@ -70,14 +104,24 @@ export function ChatPane({
const pendingApproval = session.pendingApproval?.status === 'pending' ? session.pendingApproval : undefined;
const queuedApprovals = (session.pendingApprovalQueue ?? []).filter((a) => a.status === 'pending');
const totalPendingCount = (pendingApproval ? 1 : 0) + queuedApprovals.length;
const pendingUserInput = session.pendingUserInput?.status === 'pending' ? session.pendingUserInput : undefined;
const pendingPlanReview = session.pendingPlanReview?.status === 'pending' ? session.pendingPlanReview : undefined;
const pendingMcpAuth = session.pendingMcpAuth?.status === 'pending' || session.pendingMcpAuth?.status === 'authenticating'
|| session.pendingMcpAuth?.status === 'failed'
? session.pendingMcpAuth
: undefined;
const interactionMode: InteractionMode = session.interactionMode ?? 'interactive';
const isPlanMode = interactionMode === 'plan';
const isScratchpad = isScratchpadProject(project);
const isSingleAgent = pattern.agents.length === 1;
const primaryAgent = pattern.agents[0];
const selectedModel = primaryAgent ? findModel(primaryAgent.model, availableModels) : undefined;
const supportedEfforts = getSupportedReasoningEfforts(selectedModel);
const sessionReasoningEffort = resolveReasoningEffort(selectedModel, primaryAgent?.reasoningEffort);
const isComposerDisabled = isSessionBusy || isUpdatingSessionModelConfig;
const isComposerDisabled = isUpdatingSessionModelConfig;
const canSubmitInput = hasComposerContent && !isComposerDisabled;
const [pendingAttachments, setPendingAttachments] = useState<ChatMessageAttachment[]>([]);
const promptFiles = useMemo(() => project.customization?.promptFiles ?? [], [project.customization?.promptFiles]);
const toolSelection = useMemo(() => resolveSessionToolingSelection(session), [session]);
const mcpServers = toolingSettings.mcpServers;
@@ -97,6 +141,22 @@ export function ChatPane({
),
[isApprovalOverridden, session.approvalSettings, pattern.approvalPolicy],
);
const effectiveAutoApprovedCount = useMemo(() => {
const groups = groupApprovalToolsByProvider(approvalTools, toolingSettings);
const counted = new Set<string>();
for (const group of groups) {
if (group.serverApprovalKey && effectiveAutoApproved.has(group.serverApprovalKey)) {
for (const tool of group.tools) counted.add(tool.id);
} else {
for (const tool of group.tools) {
if (effectiveAutoApproved.has(tool.id)) counted.add(tool.id);
}
}
}
return counted.size;
}, [approvalTools, effectiveAutoApproved, toolingSettings]);
const isProbingMcp = (mcpProbingServerIds?.length ?? 0) > 0;
const hasApprovalContent = approvalTools.length > 0 || isProbingMcp;
useEffect(() => {
transcriptRef.current?.scrollTo({
@@ -113,7 +173,22 @@ export function ChatPane({
}, [session.id]);
function handleComposerSubmit(content: string) {
void onSend(content);
const attachments = pendingAttachments.length > 0 ? [...pendingAttachments] : undefined;
const messageMode: MessageMode | undefined = isSessionBusy ? 'immediate' : undefined;
setPendingAttachments([]);
void onSend(content, attachments, messageMode);
}
function handleDismissPlan() {
onDismissPlanReview?.();
}
function handleDismissMcpAuth() {
onDismissMcpAuth?.();
}
function handleAuthenticateMcp() {
onAuthenticateMcp?.();
}
async function handleSessionModelConfigChange(config: {
@@ -143,14 +218,14 @@ export function ChatPane({
}
}
async function handleResolveApproval(decision: ApprovalDecision) {
async function handleResolveApproval(decision: ApprovalDecision, alwaysApprove?: boolean) {
if (!pendingApproval || !onResolveApproval || isResolvingApproval) return;
setApprovalError(undefined);
setIsResolvingApproval(true);
try {
await onResolveApproval(pendingApproval.id, decision);
await onResolveApproval(pendingApproval.id, decision, alwaysApprove);
} catch (error) {
setApprovalError(error instanceof Error ? error.message : String(error));
} finally {
@@ -158,6 +233,20 @@ export function ChatPane({
}
}
async function handleResolveUserInput(answer: string, wasFreeform: boolean) {
if (!pendingUserInput || !onResolveUserInput || isSubmittingUserInput) return;
setIsSubmittingUserInput(true);
try {
await onResolveUserInput(pendingUserInput.id, answer, wasFreeform);
} catch {
// User input errors are non-critical; the turn will fail and show the error status
} finally {
setIsSubmittingUserInput(false);
}
}
return (
<div className="flex h-full flex-col">
{/* Header — extra top padding clears the title bar overlay zone */}
@@ -194,14 +283,20 @@ export function ChatPane({
)}
</div>
)}
{isSessionBusy && !pendingApproval && <span className="size-2 animate-pulse rounded-full bg-blue-400" />}
{pendingUserInput && !pendingApproval && (
<div className="flex items-center gap-1.5 text-[12px] font-medium text-blue-400">
<MessageCircleQuestion className="size-3.5" />
Awaiting your input
</div>
)}
{isSessionBusy && !pendingApproval && !pendingUserInput && <span className="size-2 animate-pulse rounded-full bg-blue-400" />}
{session.status === 'error' && (
<div className="flex items-center gap-1.5 text-[12px] text-red-400">
<AlertCircle className="size-3.5" />
Error
</div>
)}
{session.status === 'idle' && !pendingApproval && session.messages.length > 0 && (
{session.status === 'idle' && !pendingApproval && !pendingUserInput && session.messages.length > 0 && (
<span className="text-[12px] text-zinc-600">
{session.messages.length} message{session.messages.length === 1 ? '' : 's'}
</span>
@@ -277,6 +372,29 @@ export function ChatPane({
: `rounded-xl border px-4 py-3 text-[14px] leading-relaxed text-zinc-200 ${assistantContainerClass}`
}
>
{/* Attachment thumbnails */}
{isUser && message.attachments && message.attachments.length > 0 && (
<div className="mb-2 flex flex-wrap gap-2">
{message.attachments.map((att, attIdx) =>
isImageAttachment(att) ? (
<img
key={attIdx}
alt={getAttachmentDisplayName(att)}
className="max-h-48 max-w-xs rounded-lg border border-zinc-700 object-cover"
src={`data:${att.mimeType};base64,${att.data}`}
/>
) : (
<div
key={attIdx}
className="flex items-center gap-1.5 rounded-lg border border-zinc-700 bg-zinc-800 px-2 py-1 text-[11px] text-zinc-400"
>
<Paperclip className="size-3" />
{getAttachmentDisplayName(att)}
</div>
),
)}
</div>
)}
{!isUser && message.pending ? (
<div className="whitespace-pre-wrap break-words text-[14px] leading-relaxed text-zinc-200">
{message.content}
@@ -295,6 +413,11 @@ export function ChatPane({
);
})}
</div>
{activeSubagents && activeSubagents.length > 0 && (
<div className="px-6 py-1">
<SubagentActivityList subagents={activeSubagents} />
</div>
)}
</div>
)}
</div>
@@ -329,7 +452,7 @@ export function ChatPane({
<ApprovalBanner
approval={pendingApproval}
isResolving={isResolvingApproval}
onResolve={(decision) => void handleResolveApproval(decision)}
onResolve={(decision, alwaysApprove) => void handleResolveApproval(decision, alwaysApprove)}
position={totalPendingCount > 1 ? 1 : undefined}
total={totalPendingCount > 1 ? totalPendingCount : undefined}
/>
@@ -339,6 +462,38 @@ export function ChatPane({
</div>
)}
{/* Pending user input banner */}
{pendingUserInput && (
<div className="mb-3">
<UserInputBanner
isSubmitting={isSubmittingUserInput}
onSubmit={(answer, wasFreeform) => void handleResolveUserInput(answer, wasFreeform)}
userInput={pendingUserInput}
/>
</div>
)}
{/* Plan review banner */}
{pendingPlanReview && (
<div className="mb-3">
<PlanReviewBanner
onDismiss={handleDismissPlan}
planReview={pendingPlanReview}
/>
</div>
)}
{/* MCP auth required banner */}
{pendingMcpAuth && (
<div className="mb-3">
<McpAuthBanner
mcpAuth={pendingMcpAuth}
onAuthenticate={handleAuthenticateMcp}
onDismiss={handleDismissMcpAuth}
/>
</div>
)}
{/* Session config pills — tools/approval left, model/reasoning right */}
{isSingleAgent && (
<div className="mb-2 flex items-center gap-2">
@@ -351,13 +506,16 @@ export function ChatPane({
selection={toolSelection}
/>
)}
{hasToolCallApproval && onUpdateSessionApprovalSettings && approvalTools.length > 0 && (
{hasToolCallApproval && onUpdateSessionApprovalSettings && hasApprovalContent && (
<InlineApprovalPill
approvalTools={approvalTools}
disabled={isComposerDisabled}
effectiveAutoApproved={effectiveAutoApproved}
effectiveAutoApprovedCount={effectiveAutoApprovedCount}
isOverridden={isApprovalOverridden}
mcpProbingServerIds={mcpProbingServerIds}
onUpdate={onUpdateSessionApprovalSettings}
toolingSettings={toolingSettings}
/>
)}
{primaryAgent && (
@@ -405,18 +563,44 @@ export function ChatPane({
selection={toolSelection}
/>
)}
{hasToolCallApproval && onUpdateSessionApprovalSettings && approvalTools.length > 0 && (
{hasToolCallApproval && onUpdateSessionApprovalSettings && hasApprovalContent && (
<InlineApprovalPill
approvalTools={approvalTools}
disabled={isComposerDisabled}
effectiveAutoApproved={effectiveAutoApproved}
effectiveAutoApprovedCount={effectiveAutoApprovedCount}
isOverridden={isApprovalOverridden}
mcpProbingServerIds={mcpProbingServerIds}
onUpdate={onUpdateSessionApprovalSettings}
toolingSettings={toolingSettings}
/>
)}
</div>
)}
{/* Attachment preview */}
{pendingAttachments.length > 0 && (
<div className="flex flex-wrap gap-2 px-1 pb-2">
{pendingAttachments.map((attachment, index) => (
<div
key={index}
className="flex items-center gap-1.5 rounded-lg border border-zinc-700 bg-zinc-800 px-2.5 py-1.5 text-[11px] text-zinc-300"
>
<Paperclip className="size-3 text-zinc-500" />
<span className="max-w-[160px] truncate">{getAttachmentDisplayName(attachment)}</span>
<button
aria-label="Remove attachment"
className="ml-1 rounded p-0.5 text-zinc-500 hover:bg-zinc-700 hover:text-zinc-300"
onClick={() => setPendingAttachments((prev) => prev.filter((_, i) => i !== index))}
type="button"
>
<X className="size-3" />
</button>
</div>
))}
</div>
)}
<div className="rounded-xl border border-zinc-700 bg-zinc-900 transition-colors focus-within:border-indigo-500/50">
<MarkdownComposer
ref={composerRef}
@@ -426,40 +610,175 @@ export function ChatPane({
placeholder={
pendingApproval
? 'Awaiting approval...'
: isSessionBusy
? 'Waiting for response...'
: isUpdatingSessionModelConfig
? 'Saving model settings...'
: 'Message...'
: pendingUserInput
? 'Awaiting your input above...'
: pendingPlanReview
? 'Review the plan above...'
: pendingMcpAuth
? 'MCP server requires authentication...'
: isSessionBusy
? 'Steer the agent (sends immediately)...'
: isUpdatingSessionModelConfig
? 'Saving model settings...'
: isPlanMode
? 'Describe what to plan...'
: 'Message...'
}
>
<button
className={`absolute bottom-2 right-2 flex size-8 items-center justify-center rounded-lg transition ${
isSessionBusy
? 'bg-red-600/80 text-white hover:bg-red-500'
: canSubmitInput
? 'bg-indigo-600 text-white hover:bg-indigo-500'
: 'bg-zinc-800 text-zinc-600'
}`}
disabled={!canSubmitInput && !isSessionBusy}
onClick={() => {
if (isSessionBusy) {
onCancelTurn?.();
} else {
composerRef.current?.submit();
}
}}
type="button"
aria-label={isSessionBusy ? 'Stop generating' : 'Send message'}
>
{isSessionBusy ? (
<Square className="size-3.5" fill="currentColor" />
) : (
<ArrowUp className="size-4" />
{/* Bottom action bar: left = shortcuts, right = buttons */}
<div className="flex items-center justify-between px-2 pb-2">
{/* Left: quick actions */}
<div className="flex items-center gap-1.5">
{onTerminalToggle && (
<InlineTerminalPill
disabled={false}
isOpen={!!terminalOpen}
isRunning={!!terminalRunning}
onToggle={onTerminalToggle}
/>
)}
{!isScratchpad && promptFiles.length > 0 && (
<InlinePromptPill
disabled={isComposerDisabled}
onSubmit={(content) => void onSend(content)}
promptFiles={promptFiles}
/>
)}
</div>
{/* Right: attach, plan mode, send */}
<div className="flex items-center gap-1">
{/* Attachment picker */}
<button
aria-label="Attach image"
className="flex size-8 items-center justify-center rounded-lg text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
disabled={isComposerDisabled}
onClick={() => {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/jpeg,image/png,image/gif,image/webp';
input.multiple = true;
input.onchange = () => {
if (!input.files) return;
const newAttachments: ChatMessageAttachment[] = [];
for (const file of input.files) {
const reader = new FileReader();
reader.onload = () => {
const base64 = (reader.result as string).split(',')[1];
setPendingAttachments((prev) => [
...prev,
{ type: 'blob', data: base64, mimeType: file.type, displayName: file.name },
]);
};
reader.readAsDataURL(file);
}
};
input.click();
}}
type="button"
>
<Paperclip className="size-3.5" />
</button>
{/* Plan mode toggle */}
{onSetInteractionMode && !isSessionBusy && (
<button
aria-label={isPlanMode ? 'Switch to interactive mode' : 'Switch to plan mode'}
aria-pressed={isPlanMode}
className={`flex size-8 items-center justify-center rounded-lg transition ${
isPlanMode
? 'bg-emerald-600/20 text-emerald-400 hover:bg-emerald-600/30'
: 'text-zinc-500 hover:bg-zinc-800 hover:text-zinc-300'
}`}
disabled={isComposerDisabled}
onClick={() => onSetInteractionMode(isPlanMode ? 'interactive' : 'plan')}
type="button"
>
<ClipboardList className="size-3.5" />
</button>
)}
</button>
{/* Send / Stop / Steer button */}
<button
className={`flex size-8 items-center justify-center rounded-lg transition ${
isSessionBusy && !hasComposerContent && pendingAttachments.length === 0
? 'bg-red-600/80 text-white hover:bg-red-500'
: canSubmitInput || pendingAttachments.length > 0
? isSessionBusy
? 'bg-amber-600 text-white hover:bg-amber-500'
: isPlanMode
? 'bg-emerald-600 text-white hover:bg-emerald-500'
: 'bg-indigo-600 text-white hover:bg-indigo-500'
: 'bg-zinc-800 text-zinc-600'
}`}
disabled={!canSubmitInput && !isSessionBusy && pendingAttachments.length === 0}
onClick={() => {
if (isSessionBusy && !hasComposerContent && pendingAttachments.length === 0) {
onCancelTurn?.();
} else {
composerRef.current?.submit();
}
}}
type="button"
aria-label={
isSessionBusy && !hasComposerContent && pendingAttachments.length === 0
? 'Stop generating'
: isSessionBusy
? 'Steer agent'
: isPlanMode
? 'Send as plan request'
: 'Send message'
}
>
{isSessionBusy && !hasComposerContent && pendingAttachments.length === 0 ? (
<Square className="size-3.5" fill="currentColor" />
) : (
<ArrowUp className="size-4" />
)}
</button>
</div>
</div>
</MarkdownComposer>
{isPlanMode && !isSessionBusy && (
<div className="flex items-center gap-1.5 px-3 pb-1.5 pt-0.5">
<div className="size-1.5 rounded-full bg-emerald-500" />
<span className="text-[10px] font-medium text-emerald-400/80">
Plan mode the agent will propose a plan instead of implementing
</span>
</div>
)}
{isSessionBusy && (hasComposerContent || pendingAttachments.length > 0) && (
<div className="flex items-center gap-1.5 px-3 pb-1.5 pt-0.5">
<div className="size-1.5 rounded-full bg-amber-500" />
<span className="text-[10px] font-medium text-amber-400/80">
Steering your message will be injected into the current turn
</span>
</div>
)}
</div>
{/* Session usage bar */}
{sessionUsage && sessionUsage.tokenLimit > 0 && (
<div className="px-1 pt-1.5">
<div className="flex items-center gap-2 text-[10px] text-zinc-500">
<div className="h-1 flex-1 overflow-hidden rounded-full bg-zinc-800">
<div
className={`h-full rounded-full transition-all ${
sessionUsage.currentTokens / sessionUsage.tokenLimit > 0.9
? 'bg-red-500'
: sessionUsage.currentTokens / sessionUsage.tokenLimit > 0.7
? 'bg-amber-500'
: 'bg-indigo-500/60'
}`}
style={{ width: `${Math.min(100, (sessionUsage.currentTokens / sessionUsage.tokenLimit) * 100)}%` }}
/>
</div>
<span className="tabular-nums">
{Math.round((sessionUsage.currentTokens / sessionUsage.tokenLimit) * 100)}% context
</span>
</div>
</div>
)}
</div>
</div>
</div>
+150 -1
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useEffect, useState } from 'react';
import {
CheckCircle2,
XCircle,
@@ -12,12 +12,15 @@ import {
ArrowUpCircle,
User,
Building2,
BarChart3,
Loader2,
} from 'lucide-react';
import type {
SidecarConnectionDiagnostics,
SidecarConnectionStatus,
SidecarCopilotCliVersionStatus,
QuotaSnapshot,
} from '@shared/contracts/sidecar';
interface CopilotStatusCardProps {
@@ -25,6 +28,7 @@ interface CopilotStatusCardProps {
modelCount: number;
isRefreshing: boolean;
onRefresh: () => void;
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
}
interface StatusConfig {
@@ -125,6 +129,137 @@ function VersionBadge({ status, installedVersion }: { status: SidecarCopilotCliV
}
}
const quotaTypeLabels: Record<string, string> = {
premium_interactions: 'Premium Requests',
chat: 'Chat',
completions: 'Completions',
};
function formatQuotaTypeLabel(key: string): string {
return quotaTypeLabels[key] ?? key.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());
}
function formatResetDate(iso: string): string {
try {
const date = new Date(iso);
const now = new Date();
const diffMs = date.getTime() - now.getTime();
const diffDays = Math.ceil(diffMs / 86_400_000);
if (diffDays <= 0) return 'Today';
if (diffDays === 1) return 'Tomorrow';
if (diffDays <= 30) return `In ${diffDays} day${diffDays === 1 ? '' : 's'}`;
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
} catch {
return iso;
}
}
function QuotaSection({
onGetQuota,
}: {
onGetQuota: () => Promise<Record<string, QuotaSnapshot>>;
}) {
const [quotaData, setQuotaData] = useState<Record<string, QuotaSnapshot>>();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string>();
useEffect(() => {
let cancelled = false;
setLoading(true);
setError(undefined);
void onGetQuota()
.then((data) => { if (!cancelled) setQuotaData(data); })
.catch((err: unknown) => {
if (!cancelled) setError(err instanceof Error ? err.message : String(err));
})
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
}, [onGetQuota]);
if (loading) {
return (
<div className="flex items-center gap-2 py-2">
<Loader2 className="size-3.5 animate-spin text-zinc-500" />
<span className="text-[12px] text-zinc-500">Loading quota</span>
</div>
);
}
if (error) {
return (
<div className="flex items-center gap-2 py-2">
<XCircle className="size-3.5 text-red-400" />
<span className="text-[12px] text-zinc-500">Could not load quota</span>
</div>
);
}
if (!quotaData || Object.keys(quotaData).length === 0) {
return (
<div className="py-2">
<span className="text-[12px] text-zinc-600">No quota data available</span>
</div>
);
}
return (
<div className="space-y-3">
{Object.entries(quotaData).map(([key, snapshot]) => {
const usedPct = snapshot.entitlementRequests > 0
? (snapshot.usedRequests / snapshot.entitlementRequests) * 100
: 0;
const barColor = usedPct > 90
? 'bg-red-500'
: usedPct > 70
? 'bg-amber-500'
: 'bg-indigo-500/60';
return (
<div key={key} className="space-y-1.5">
<div className="flex items-center justify-between">
<span className="text-[12px] font-medium text-zinc-300">
{formatQuotaTypeLabel(key)}
</span>
<span className="text-[11px] tabular-nums text-zinc-500">
{Math.round(snapshot.remainingPercentage)}% remaining
</span>
</div>
<div className="h-1.5 overflow-hidden rounded-full bg-zinc-800">
<div
className={`h-full rounded-full transition-all ${barColor}`}
style={{ width: `${Math.min(100, usedPct)}%` }}
/>
</div>
<div className="flex items-center gap-1.5 text-[10px] text-zinc-500">
<span className="tabular-nums">
{Math.round(snapshot.usedRequests)} of {Math.round(snapshot.entitlementRequests)} used
</span>
{snapshot.overage > 0 && (
<>
<span className="text-zinc-700">·</span>
<span className="tabular-nums text-amber-400">
{Math.round(snapshot.overage)} overage
</span>
</>
)}
{snapshot.resetDate && (
<>
<span className="text-zinc-700">·</span>
<span>Resets {formatResetDate(snapshot.resetDate)}</span>
</>
)}
</div>
</div>
);
})}
</div>
);
}
function AccountSection({ connection }: { connection: SidecarConnectionDiagnostics }) {
const { account } = connection;
if (!account) return null;
@@ -182,6 +317,7 @@ export function CopilotStatusCard({
modelCount,
isRefreshing,
onRefresh,
onGetQuota,
}: CopilotStatusCardProps) {
const [showDetails, setShowDetails] = useState(false);
@@ -242,6 +378,19 @@ export function CopilotStatusCard({
<AccountSection connection={connection} />
)}
{/* Usage & Quota (when healthy and callback provided) */}
{isHealthy && onGetQuota && (
<div className="space-y-2">
<div className="flex items-center gap-1.5 text-[11px] font-medium text-zinc-400">
<BarChart3 className="size-3" />
<span>Usage &amp; Quota</span>
</div>
<div className="rounded-lg border border-zinc-800/60 bg-zinc-900/40 px-3 py-2.5">
<QuotaSection onGetQuota={onGetQuota} />
</div>
</div>
)}
{/* Action hint for non-ready states */}
{!isHealthy && config.actionLabel && (
<div className="flex items-start gap-2 rounded-lg border border-zinc-800 bg-zinc-900/60 px-3 py-2.5">
+5 -55
View File
@@ -24,7 +24,6 @@ import {
$isCodeNode,
$createCodeNode,
$createCodeHighlightNode,
$isCodeHighlightNode,
CodeNode,
CodeHighlightNode,
} from '@lexical/code';
@@ -44,9 +43,7 @@ import {
$getNodeByKey,
$getRoot,
$getSelection,
$isLineBreakNode,
$isRangeSelection,
$isTextNode,
CLEAR_EDITOR_COMMAND,
COMMAND_PRIORITY_HIGH,
FORMAT_TEXT_COMMAND,
@@ -63,6 +60,8 @@ import {
markdownEditorNamespace,
markdownEditorNodes,
markdownEditorTransformers,
getCodeNodeAbsoluteOffset,
restoreCodeNodeSelection,
} from '@renderer/lib/markdownEditor';
import { prepareChatMessageContent } from '@shared/utils/chatMessage';
@@ -295,55 +294,6 @@ function parseHljsHtml(html: string): HljsToken[] {
/* ── Code highlight plugin ────────────────────────────── */
function getAbsoluteOffset(
codeNode: ReturnType<typeof $getNodeByKey>,
point: { key: string; offset: number },
): number {
if (!codeNode || !('getChildren' in codeNode)) return 0;
let offset = 0;
for (const child of (codeNode as CodeNode).getChildren()) {
if (child.getKey() === point.key) return offset + point.offset;
offset += $isLineBreakNode(child) ? 1 : child.getTextContentSize();
}
return offset;
}
function restoreSelectionFromOffsets(codeNode: CodeNode, anchorOff: number, focusOff: number) {
const children = codeNode.getChildren();
function findPoint(target: number) {
let offset = 0;
for (const child of children) {
const size = $isLineBreakNode(child) ? 1 : child.getTextContentSize();
if (offset + size > target || (offset + size === target && $isTextNode(child))) {
return {
key: child.getKey(),
offset: target - offset,
type: ($isTextNode(child) || $isCodeHighlightNode(child) ? 'text' : 'element') as 'text' | 'element',
};
}
offset += size;
}
const last = children[children.length - 1];
if (last) {
return {
key: last.getKey(),
offset: $isLineBreakNode(last) ? 0 : last.getTextContentSize(),
type: ($isTextNode(last) || $isCodeHighlightNode(last) ? 'text' : 'element') as 'text' | 'element',
};
}
return { key: codeNode.getKey(), offset: 0, type: 'element' as const };
}
const anchor = findPoint(anchorOff);
const focus = findPoint(focusOff);
const selection = $getSelection();
if ($isRangeSelection(selection)) {
selection.anchor.set(anchor.key, anchor.offset, anchor.type);
selection.focus.set(focus.key, focus.offset, focus.type);
}
}
/** Enables highlight.js-based syntax highlighting inside CodeNodes. */
function CodeHighlightPlugin() {
const [editor] = useLexicalComposerContext();
@@ -369,8 +319,8 @@ function CodeHighlightPlugin() {
let anchorOff: number | undefined;
let focusOff: number | undefined;
if ($isRangeSelection(sel)) {
anchorOff = getAbsoluteOffset(current, sel.anchor);
focusOff = getAbsoluteOffset(current, sel.focus);
anchorOff = getCodeNodeAbsoluteOffset(current, sel.anchor);
focusOff = getCodeNodeAbsoluteOffset(current, sel.focus);
}
// Build new children from tokens
@@ -392,7 +342,7 @@ function CodeHighlightPlugin() {
// Restore cursor
if (anchorOff !== undefined && focusOff !== undefined) {
restoreSelectionFromOffsets(current, anchorOff, focusOff);
restoreCodeNodeSelection(current, anchorOff, focusOff);
}
});
queueMicrotask(() => highlightingKeys.delete(nodeKey));
+11 -4
View File
@@ -18,6 +18,8 @@ import {
import type { ApprovalCheckpointKind, ApprovalPolicy } from '@shared/domain/approval';
import type { ModelDefinition } from '@shared/domain/models';
import {
addAgentToGraph,
removeAgentFromGraph,
resolvePatternGraph,
syncPatternGraph,
validatePatternDefinition,
@@ -35,7 +37,6 @@ import {
} from '@shared/domain/tooling';
import { ToggleSwitch } from '@renderer/components/ui';
import { addAgentNodeToGraph } from '@renderer/lib/patternGraph';
import { PatternGraphCanvas } from './pattern-graph/PatternGraphCanvas';
import { PatternGraphInspector } from './pattern-graph/PatternGraphInspector';
@@ -143,6 +144,10 @@ export function PatternEditor({
const graph = resolvePatternGraph(pattern);
function emitChange(nextPattern: PatternDefinition) {
onChange({ ...nextPattern, graph: resolvePatternGraph(nextPattern) });
}
function emitModeChange(nextPattern: PatternDefinition) {
onChange(syncPatternGraph(nextPattern));
}
@@ -159,7 +164,7 @@ export function PatternEditor({
model: 'gpt-5.4',
reasoningEffort: 'high',
};
const updatedGraph = addAgentNodeToGraph(graph, newAgent);
const updatedGraph = addAgentToGraph(graph, pattern.mode, newAgent);
onChange({ ...pattern, agents: [...pattern.agents, newAgent], graph: updatedGraph });
}
@@ -175,9 +180,11 @@ export function PatternEditor({
return;
}
emitChange({
const updatedGraph = removeAgentFromGraph(graph, pattern.mode, agentId);
onChange({
...pattern,
agents: pattern.agents.filter((a) => a.id !== agentId),
graph: updatedGraph,
});
setSelectedNodeId(null);
}
@@ -374,7 +381,7 @@ export function PatternEditor({
}`}
disabled={disabled}
key={mode}
onClick={() => emitChange({ ...pattern, mode })}
onClick={() => emitModeChange({ ...pattern, mode })}
type="button"
>
<div className="flex items-center gap-1.5">
@@ -0,0 +1,786 @@
import { useCallback, useMemo, useState, type ReactNode } from 'react';
import { ChevronDown, ChevronLeft, FileCode2, FileText, FolderOpen, GitBranch, RefreshCw, Server, Sparkles, Trash2, AlertTriangle, Circle } from 'lucide-react';
import { ToggleSwitch } from '@renderer/components/ui';
import type { ProjectRecord, ProjectGitContext } from '@shared/domain/project';
import type { DiscoveredMcpServer } from '@shared/domain/discoveredTooling';
import { listAcceptedDiscoveredMcpServers, listPendingDiscoveredMcpServers } from '@shared/domain/discoveredTooling';
import type { ProjectAgentProfile, ProjectInstructionFile, ProjectPromptFile } from '@shared/domain/projectCustomization';
/* ── Types ────────────────────────────────────────────────── */
type ProjectSettingsSection = 'overview' | 'instructions' | 'agents' | 'prompts' | 'mcp-servers' | 'danger-zone';
interface NavItem {
id: ProjectSettingsSection;
label: string;
icon: ReactNode;
}
interface NavGroup {
label: string;
items: NavItem[];
}
interface ProjectSettingsPanelProps {
project: ProjectRecord;
onClose: () => void;
onRescanConfigs: () => void;
onRescanCustomization: () => void;
onResolveDiscoveredTooling: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
onSetAgentProfileEnabled: (agentProfileId: string, enabled: boolean) => void;
onRemoveProject: () => void;
}
/* ── Main component ───────────────────────────────────────── */
export function ProjectSettingsPanel({
project,
onClose,
onRescanConfigs,
onRescanCustomization,
onResolveDiscoveredTooling,
onSetAgentProfileEnabled,
onRemoveProject,
}: ProjectSettingsPanelProps) {
const [activeSection, setActiveSection] = useState<ProjectSettingsSection>('overview');
const [confirmingRemove, setConfirmingRemove] = useState(false);
const acceptedServers = useMemo(() => listAcceptedDiscoveredMcpServers(project.discoveredTooling), [project.discoveredTooling]);
const pendingServers = useMemo(() => listPendingDiscoveredMcpServers(project.discoveredTooling), [project.discoveredTooling]);
const instructions = project.customization?.instructions ?? [];
const agentProfiles = project.customization?.agentProfiles ?? [];
const promptFiles = project.customization?.promptFiles ?? [];
const enabledAgentCount = agentProfiles.filter((a) => a.enabled).length;
const handleRemove = useCallback(() => {
if (!confirmingRemove) {
setConfirmingRemove(true);
return;
}
onRemoveProject();
}, [confirmingRemove, onRemoveProject]);
const navGroups: NavGroup[] = [
{
label: 'Project',
items: [
{ id: 'overview', label: 'Overview', icon: <FolderOpen className="size-3.5" /> },
],
},
{
label: 'Copilot',
items: [
{ id: 'instructions', label: 'Instructions', icon: <FileCode2 className="size-3.5" /> },
{ id: 'agents', label: 'Custom Agents', icon: <Sparkles className="size-3.5" /> },
{ id: 'prompts', label: 'Prompt Files', icon: <FileText className="size-3.5" /> },
],
},
{
label: 'Tooling',
items: [
{ id: 'mcp-servers', label: 'MCP Servers', icon: <Server className="size-3.5" /> },
],
},
];
function sectionBadge(section: ProjectSettingsSection): ReactNode {
switch (section) {
case 'instructions':
return instructions.length > 0
? <CountBadge count={instructions.length} />
: null;
case 'agents':
return agentProfiles.length > 0
? <CountBadge count={enabledAgentCount} total={agentProfiles.length} />
: null;
case 'prompts':
return promptFiles.length > 0
? <CountBadge count={promptFiles.length} />
: null;
case 'mcp-servers': {
if (pendingServers.length > 0) {
return <PendingBadge count={pendingServers.length} />;
}
const totalServers = acceptedServers.length + pendingServers.length;
return totalServers > 0 ? <CountBadge count={totalServers} /> : null;
}
default:
return null;
}
}
return (
<div className="fixed inset-0 z-50 flex flex-col bg-[var(--color-surface-0)]">
{/* Header */}
<div className="drag-region flex items-center gap-3 border-b border-[var(--color-border)] px-5 pb-3 pt-3">
<button
className="no-drag flex size-8 items-center justify-center rounded-lg text-zinc-400 transition hover:bg-zinc-800 hover:text-zinc-200"
onClick={onClose}
type="button"
>
<ChevronLeft className="size-4" />
</button>
<h2 className="text-[13px] font-semibold text-zinc-100">
Project Settings
<span className="ml-2 font-normal text-zinc-500">·</span>
<span className="ml-2 font-normal text-zinc-400">{project.name}</span>
</h2>
</div>
{/* Sidebar + Content */}
<div className="flex min-h-0 flex-1">
{/* Navigation sidebar */}
<nav className="w-52 shrink-0 border-r border-[var(--color-border)] bg-[var(--color-surface-1)] p-3">
<div className="space-y-4">
{navGroups.map((group) => (
<div key={group.label}>
<span className="mb-1 block px-3 text-[10px] font-semibold uppercase tracking-wider text-zinc-600">
{group.label}
</span>
<div className="space-y-0.5">
{group.items.map((item) => {
const isActive = item.id === activeSection;
const badge = sectionBadge(item.id);
return (
<button
className={`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-[13px] transition ${
isActive
? 'bg-zinc-800 font-medium text-zinc-100'
: 'text-zinc-400 hover:bg-zinc-800/50 hover:text-zinc-300'
}`}
key={item.id}
onClick={() => {
setActiveSection(item.id);
setConfirmingRemove(false);
}}
type="button"
>
<span className={isActive ? 'text-zinc-300' : 'text-zinc-500'}>{item.icon}</span>
<span className="flex-1 truncate">{item.label}</span>
{badge}
</button>
);
})}
</div>
</div>
))}
{/* Danger zone at the bottom */}
<div className="border-t border-zinc-800 pt-3">
<div className="space-y-0.5">
<button
className={`flex w-full items-center gap-2.5 rounded-lg px-3 py-2 text-left text-[13px] transition ${
activeSection === 'danger-zone'
? 'bg-zinc-800 font-medium text-red-400'
: 'text-zinc-500 hover:bg-zinc-800/50 hover:text-red-400'
}`}
onClick={() => {
setActiveSection('danger-zone');
setConfirmingRemove(false);
}}
type="button"
>
<Trash2 className="size-3.5" />
<span className="flex-1 truncate">Danger Zone</span>
</button>
</div>
</div>
</div>
</nav>
{/* Content panel */}
<div className="flex-1 overflow-y-auto">
<div className="mx-auto max-w-2xl px-8 py-6">
{activeSection === 'overview' && (
<OverviewContent project={project} />
)}
{activeSection === 'instructions' && (
<InstructionsContent
instructions={instructions}
onRescan={onRescanCustomization}
/>
)}
{activeSection === 'agents' && (
<AgentsContent
agents={agentProfiles}
onRescan={onRescanCustomization}
onSetEnabled={onSetAgentProfileEnabled}
/>
)}
{activeSection === 'prompts' && (
<PromptsContent
onRescan={onRescanCustomization}
promptFiles={promptFiles}
/>
)}
{activeSection === 'mcp-servers' && (
<McpServersContent
accepted={acceptedServers}
onRescan={onRescanConfigs}
onResolve={onResolveDiscoveredTooling}
pending={pendingServers}
/>
)}
{activeSection === 'danger-zone' && (
<DangerZoneContent
confirmingRemove={confirmingRemove}
onCancelRemove={() => setConfirmingRemove(false)}
onRemove={handleRemove}
/>
)}
</div>
</div>
</div>
</div>
);
}
/* ── Nav badges ───────────────────────────────────────────── */
function CountBadge({ count, total }: { count: number; total?: number }) {
return (
<span className="rounded-full bg-zinc-800 px-1.5 py-0.5 text-[10px] font-medium text-zinc-500">
{total !== undefined ? `${count}/${total}` : count}
</span>
);
}
function PendingBadge({ count }: { count: number }) {
return (
<span className="rounded-full bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-400">
{count} new
</span>
);
}
/* ── Overview ─────────────────────────────────────────────── */
function OverviewContent({ project }: { project: ProjectRecord }) {
return (
<div>
<SectionHeader
description="Project details and git status."
title="Overview"
/>
<div className="rounded-xl border border-zinc-800 bg-zinc-900/40 px-5 py-4 space-y-3">
<div className="flex items-center gap-3">
<FolderOpen className="size-5 shrink-0 text-indigo-400" />
<div className="min-w-0">
<div className="text-[13px] font-medium text-zinc-200">{project.name}</div>
<div className="mt-0.5 truncate text-[12px] text-zinc-500">{project.path}</div>
</div>
</div>
{project.git && <ProjectGitInfo git={project.git} />}
</div>
</div>
);
}
function ProjectGitInfo({ git }: { git: ProjectGitContext }) {
if (git.status === 'not-repository') {
return (
<div className="flex items-center gap-2 text-[12px] text-zinc-600">
<GitBranch className="size-3.5" />
Not a git repository
</div>
);
}
if (git.status === 'git-missing') {
return (
<div className="flex items-center gap-2 text-[12px] text-amber-500/70">
<AlertTriangle className="size-3.5" />
Git is not installed
</div>
);
}
if (git.status === 'error') {
return (
<div className="flex items-center gap-2 text-[12px] text-red-400/70">
<AlertTriangle className="size-3.5" />
{git.errorMessage ?? 'Git error'}
</div>
);
}
const branchLabel = git.branch ?? git.head?.shortHash ?? 'HEAD';
const parts: string[] = [];
if (git.isDirty && git.changedFileCount) parts.push(`${git.changedFileCount} changed`);
if (git.ahead) parts.push(`${git.ahead} ahead`);
if (git.behind) parts.push(`${git.behind} behind`);
return (
<div className="flex items-center gap-2 text-[12px] text-zinc-400">
<GitBranch className="size-3.5 shrink-0" />
<span>{branchLabel}</span>
{git.isDirty && <Circle className="size-1.5 shrink-0 fill-amber-500 text-amber-500" />}
{parts.length > 0 && (
<span className="text-zinc-600">· {parts.join(' · ')}</span>
)}
</div>
);
}
/* ── Instructions ─────────────────────────────────────────── */
function InstructionsContent({
instructions,
onRescan,
}: {
instructions: ProjectInstructionFile[];
onRescan: () => void;
}) {
return (
<div>
<SectionHeader
description="Repository instructions automatically included in every session. Discovered from .github/copilot-instructions.md and AGENTS.md."
title="Instructions"
>
<RescanButton onClick={onRescan} />
</SectionHeader>
{instructions.length === 0 ? (
<EmptyState>
No instruction files found. Add a <code className="text-zinc-400">.github/copilot-instructions.md</code> or <code className="text-zinc-400">AGENTS.md</code> file to your project root.
</EmptyState>
) : (
<div className="space-y-3">
{instructions.map((instruction) => (
<InstructionCard key={instruction.id} instruction={instruction} />
))}
</div>
)}
</div>
);
}
function InstructionCard({ instruction }: { instruction: ProjectInstructionFile }) {
const [expanded, setExpanded] = useState(false);
const isLong = instruction.content.length > 300;
return (
<div className="rounded-xl border border-zinc-800 bg-zinc-900/40">
<button
className="flex w-full items-center gap-3 px-5 py-3.5 text-left transition hover:bg-zinc-900/60"
onClick={() => setExpanded(!expanded)}
type="button"
>
<FileCode2 className="size-4 shrink-0 text-indigo-400" />
<span className="flex-1 text-[13px] font-medium text-zinc-200">{instruction.sourcePath}</span>
<ChevronDown
className={`size-3.5 shrink-0 text-zinc-500 transition-transform ${expanded ? 'rotate-180' : ''}`}
/>
</button>
{expanded && (
<div className="border-t border-zinc-800 px-5 py-4">
<pre className="whitespace-pre-wrap text-[11px] leading-relaxed text-zinc-400">
{instruction.content}
</pre>
</div>
)}
{!expanded && (
<div className="px-5 pb-3">
<p className={`text-[11px] leading-relaxed text-zinc-500 ${isLong ? 'line-clamp-2' : ''}`}>
{instruction.content}
</p>
</div>
)}
</div>
);
}
/* ── Custom Agents ────────────────────────────────────────── */
function AgentsContent({
agents,
onRescan,
onSetEnabled,
}: {
agents: ProjectAgentProfile[];
onRescan: () => void;
onSetEnabled: (agentProfileId: string, enabled: boolean) => void;
}) {
const enabledCount = agents.filter((a) => a.enabled).length;
return (
<div>
<SectionHeader
description="Custom agent profiles discovered from .github/agents/*.agent.md. Enable or disable individual agents."
title="Custom Agents"
>
<RescanButton onClick={onRescan} />
</SectionHeader>
{agents.length === 0 ? (
<EmptyState>
No custom agents found. Add <code className="text-zinc-400">.agent.md</code> files to <code className="text-zinc-400">.github/agents/</code> in your project.
</EmptyState>
) : (
<>
{agents.length > 1 && (
<div className="mb-3 text-[11px] text-zinc-500">
{enabledCount} of {agents.length} agent{agents.length === 1 ? '' : 's'} enabled
</div>
)}
<div className="space-y-2">
{agents.map((agent) => (
<AgentCard
key={agent.id}
agent={agent}
onToggle={() => onSetEnabled(agent.id, !agent.enabled)}
/>
))}
</div>
</>
)}
</div>
);
}
function AgentCard({
agent,
onToggle,
}: {
agent: ProjectAgentProfile;
onToggle: () => void;
}) {
return (
<div className={`rounded-xl border px-5 py-4 transition ${
agent.enabled
? 'border-zinc-800 bg-zinc-900/40'
: 'border-zinc-800/50 bg-zinc-900/20 opacity-60'
}`}>
<div className="flex items-start gap-3">
<Sparkles className={`mt-0.5 size-4 shrink-0 ${agent.enabled ? 'text-amber-400' : 'text-zinc-600'}`} />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-[13px] font-medium text-zinc-200">
{agent.displayName ?? agent.name}
</span>
{agent.tools && agent.tools.length > 0 && (
<span className="rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium text-zinc-500">
{agent.tools.length} tool{agent.tools.length === 1 ? '' : 's'}
</span>
)}
</div>
{agent.description && (
<p className="mt-1 text-[12px] leading-relaxed text-zinc-500">{agent.description}</p>
)}
<p className="mt-1 text-[11px] text-zinc-600">{agent.sourcePath}</p>
</div>
<button
aria-label={agent.enabled ? `Disable ${agent.name}` : `Enable ${agent.name}`}
aria-pressed={agent.enabled}
className="mt-0.5 shrink-0"
onClick={onToggle}
type="button"
>
<ToggleSwitch enabled={agent.enabled} size="sm" />
</button>
</div>
</div>
);
}
/* ── Prompt Files ─────────────────────────────────────────── */
function PromptsContent({
promptFiles,
onRescan,
}: {
promptFiles: ProjectPromptFile[];
onRescan: () => void;
}) {
return (
<div>
<SectionHeader
description="Reusable prompt templates discovered from .github/prompts/*.prompt.md. Use them from the Prompts pill in the chat input."
title="Prompt Files"
>
<RescanButton onClick={onRescan} />
</SectionHeader>
{promptFiles.length === 0 ? (
<EmptyState>
No prompt files found. Add <code className="text-zinc-400">.prompt.md</code> files to <code className="text-zinc-400">.github/prompts/</code> in your project.
</EmptyState>
) : (
<div className="space-y-2">
{promptFiles.map((prompt) => (
<PromptCard key={prompt.id} prompt={prompt} />
))}
</div>
)}
</div>
);
}
function PromptCard({ prompt }: { prompt: ProjectPromptFile }) {
return (
<div className="rounded-xl border border-zinc-800 bg-zinc-900/40 px-5 py-4">
<div className="flex items-start gap-3">
<FileText className="mt-0.5 size-4 shrink-0 text-emerald-400" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-[13px] font-medium text-zinc-200">{prompt.name}</span>
{prompt.variables.length > 0 && (
<span className="rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium text-zinc-500">
{prompt.variables.length} variable{prompt.variables.length === 1 ? '' : 's'}
</span>
)}
</div>
{prompt.description && (
<p className="mt-1 text-[12px] leading-relaxed text-zinc-500">{prompt.description}</p>
)}
{prompt.variables.length > 0 && (
<div className="mt-2 flex flex-wrap gap-1.5">
{prompt.variables.map((v) => (
<span
key={v.name}
className="rounded-md bg-zinc-800 px-2 py-0.5 text-[10px] font-medium text-zinc-400"
title={v.placeholder}
>
{v.name}
</span>
))}
</div>
)}
<p className="mt-1.5 text-[11px] text-zinc-600">{prompt.sourcePath}</p>
</div>
</div>
</div>
);
}
/* ── MCP Servers ──────────────────────────────────────────── */
function McpServersContent({
accepted,
pending,
onRescan,
onResolve,
}: {
accepted: DiscoveredMcpServer[];
pending: DiscoveredMcpServer[];
onRescan: () => void;
onResolve: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
}) {
const hasServers = accepted.length + pending.length > 0;
return (
<div>
<SectionHeader
description="MCP servers discovered from project config files (.vscode/mcp.json, .mcp.json, .copilot/mcp.json)."
title="MCP Servers"
>
<RescanButton label={hasServers ? 'Re-scan' : 'Scan'} onClick={onRescan} />
</SectionHeader>
{!hasServers ? (
<EmptyState>
No MCP servers discovered. Click Scan to check project config files.
</EmptyState>
) : (
<>
<div className="space-y-1">
{accepted.map((server) => (
<DiscoveredServerRow
key={server.id}
onDismiss={() => onResolve([server.id], 'dismiss')}
server={server}
status="accepted"
/>
))}
{pending.map((server) => (
<DiscoveredServerRow
key={server.id}
onAccept={() => onResolve([server.id], 'accept')}
onDismiss={() => onResolve([server.id], 'dismiss')}
server={server}
status="pending"
/>
))}
</div>
{pending.length > 1 && (
<div className="mt-3 flex items-center gap-2">
<button
className="rounded-lg bg-emerald-500/10 px-3 py-1.5 text-[12px] font-medium text-emerald-400 transition hover:bg-emerald-500/20"
onClick={() => onResolve(pending.map((s) => s.id), 'accept')}
type="button"
>
Accept all ({pending.length})
</button>
<button
className="rounded-lg px-3 py-1.5 text-[12px] font-medium text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
onClick={() => onResolve(pending.map((s) => s.id), 'dismiss')}
type="button"
>
Dismiss all
</button>
</div>
)}
</>
)}
</div>
);
}
function DiscoveredServerRow({
server,
status,
onAccept,
onDismiss,
}: {
server: DiscoveredMcpServer;
status: 'accepted' | 'pending';
onAccept?: () => void;
onDismiss?: () => void;
}) {
const detail =
server.transport === 'local'
? server.command || 'No command'
: server.url || 'No URL';
const statusBadge = status === 'accepted'
? 'bg-emerald-500/10 text-emerald-400'
: 'bg-amber-500/10 text-amber-400';
return (
<div className="flex items-center gap-3 rounded-xl border border-transparent px-4 py-3 hover:border-zinc-800 hover:bg-zinc-900">
<Server className="size-4 shrink-0 text-zinc-600" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="truncate text-[13px] font-medium text-zinc-200">{server.name}</span>
<span className="rounded-full bg-zinc-800 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-zinc-400">
{server.transport}
</span>
<span className={`rounded-full px-2 py-0.5 text-[10px] font-medium ${statusBadge}`}>
{status}
</span>
</div>
<p className="mt-0.5 truncate text-[12px] text-zinc-500">
{detail}
<span className="ml-2 text-zinc-700">· {server.sourceLabel}</span>
</p>
</div>
<div className="flex items-center gap-1">
{onAccept && (
<button
className="rounded-lg px-2.5 py-1 text-[12px] font-medium text-emerald-400 transition hover:bg-emerald-500/10"
onClick={onAccept}
type="button"
>
Accept
</button>
)}
{onDismiss && (
<button
className="rounded-lg px-2.5 py-1 text-[12px] font-medium text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
onClick={onDismiss}
type="button"
>
{status === 'accepted' ? 'Remove' : 'Dismiss'}
</button>
)}
</div>
</div>
);
}
/* ── Danger Zone ──────────────────────────────────────────── */
function DangerZoneContent({
confirmingRemove,
onRemove,
onCancelRemove,
}: {
confirmingRemove: boolean;
onRemove: () => void;
onCancelRemove: () => void;
}) {
return (
<div>
<SectionHeader
description="Irreversible actions for this project."
title="Danger Zone"
/>
<div className="rounded-xl border border-red-500/20 bg-red-500/5 px-5 py-5">
<h4 className="text-[13px] font-semibold text-zinc-200">Remove project</h4>
<p className="mt-1 text-[12px] text-zinc-500">
Removing a project deletes all its sessions and discovered tooling from Aryx.
Your project files on disk are not affected.
</p>
<div className="mt-4 flex items-center gap-3">
<button
className={`flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] font-medium transition ${
confirmingRemove
? 'bg-red-600 text-white hover:bg-red-500'
: 'bg-red-500/10 text-red-400 hover:bg-red-500/20'
}`}
onClick={onRemove}
type="button"
>
<Trash2 className="size-3.5" />
{confirmingRemove ? 'Confirm removal' : 'Remove project'}
</button>
{confirmingRemove && (
<button
className="rounded-lg px-3 py-1.5 text-[13px] font-medium text-zinc-400 transition hover:bg-zinc-800 hover:text-zinc-200"
onClick={onCancelRemove}
type="button"
>
Cancel
</button>
)}
</div>
</div>
</div>
);
}
/* ── Shared helpers ──────────────────────────────────────── */
function SectionHeader({
title,
description,
children,
}: {
title: string;
description: string;
children?: ReactNode;
}) {
return (
<div className="mb-4 flex items-center justify-between gap-3">
<div>
<h3 className="text-[13px] font-semibold text-zinc-200">{title}</h3>
<p className="mt-0.5 text-[12px] text-zinc-500">{description}</p>
</div>
{children}
</div>
);
}
function RescanButton({ onClick, label = 'Re-scan' }: { onClick: () => void; label?: string }) {
return (
<button
className="flex items-center gap-1.5 rounded-lg bg-zinc-800 px-3 py-1.5 text-[13px] font-medium text-zinc-200 transition hover:bg-zinc-700"
onClick={onClick}
title={label === 'Scan' ? 'Scan for files' : 'Re-scan for changes'}
type="button"
>
<RefreshCw className="size-3.5" />
{label}
</button>
);
}
function EmptyState({ children }: { children: ReactNode }) {
return (
<div className="rounded-xl border border-dashed border-zinc-800 bg-zinc-900/20 px-5 py-8 text-center text-[12px] leading-relaxed text-zinc-500">
{children}
</div>
);
}
+19 -61
View File
@@ -1,12 +1,12 @@
import { useState, type ReactNode } from 'react';
import { ChevronLeft, ChevronRight, Code, Cpu, FolderOpen, Palette, Plus, RefreshCw, Server, TriangleAlert, Workflow, Wrench } from 'lucide-react';
import { ChevronLeft, ChevronRight, Code, Cpu, FolderOpen, Palette, Plus, Server, TriangleAlert, Workflow, Wrench } from 'lucide-react';
import { CopilotStatusCard } from '@renderer/components/CopilotStatusCard';
import { PatternEditor } from '@renderer/components/PatternEditor';
import { LspProfileEditor } from '@renderer/components/settings/LspProfileEditor';
import { McpServerEditor } from '@renderer/components/settings/McpServerEditor';
import type { SidecarCapabilities } from '@shared/contracts/sidecar';
import type { DiscoveredMcpServer, DiscoveredToolingState, ProjectDiscoveredTooling } from '@shared/domain/discoveredTooling';
import type { SidecarCapabilities, QuotaSnapshot } from '@shared/contracts/sidecar';
import type { DiscoveredMcpServer, DiscoveredToolingState } from '@shared/domain/discoveredTooling';
import { listAcceptedDiscoveredMcpServers, listPendingDiscoveredMcpServers } from '@shared/domain/discoveredTooling';
import type { ModelDefinition } from '@shared/domain/models';
import type { PatternDefinition } from '@shared/domain/pattern';
@@ -26,8 +26,6 @@ interface SettingsPanelProps {
theme: AppearanceTheme;
toolingSettings: WorkspaceToolingSettings;
discoveredUserTooling: DiscoveredToolingState;
discoveredProjectTooling?: ProjectDiscoveredTooling;
selectedProjectName?: string;
isRefreshingCapabilities: boolean;
onRefreshCapabilities: () => void;
onClose: () => void;
@@ -43,9 +41,8 @@ interface SettingsPanelProps {
onSetTheme: (theme: AppearanceTheme) => void;
onOpenAppDataFolder: () => void;
onResetLocalWorkspace: () => Promise<void>;
onRescanProjectConfigs?: () => void;
onResolveUserDiscoveredTooling?: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
onResolveProjectDiscoveredTooling?: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
}
type SettingsSection = 'appearance' | 'connection' | 'patterns' | 'mcp-servers' | 'lsp-profiles' | 'troubleshooting';
@@ -107,8 +104,6 @@ export function SettingsPanel({
theme,
toolingSettings,
discoveredUserTooling,
discoveredProjectTooling,
selectedProjectName,
isRefreshingCapabilities,
onRefreshCapabilities,
onClose,
@@ -124,9 +119,8 @@ export function SettingsPanel({
onSetTheme,
onOpenAppDataFolder,
onResetLocalWorkspace,
onRescanProjectConfigs,
onResolveUserDiscoveredTooling,
onResolveProjectDiscoveredTooling,
onGetQuota,
}: SettingsPanelProps) {
const [activeSection, setActiveSection] = useState<SettingsSection>('appearance');
const [editingPattern, setEditingPattern] = useState<PatternDefinition | null>(null);
@@ -269,6 +263,7 @@ export function SettingsPanel({
isRefreshing={isRefreshingCapabilities}
modelCount={sidecarCapabilities?.models.length ?? 0}
onRefresh={onRefreshCapabilities}
onGetQuota={onGetQuota}
/>
)}
{activeSection === 'patterns' && (
@@ -287,12 +282,8 @@ export function SettingsPanel({
)}
{activeSection === 'mcp-servers' && (
<DiscoveredMcpSection
discoveredProjectTooling={discoveredProjectTooling}
discoveredUserTooling={discoveredUserTooling}
onRescanProjectConfigs={onRescanProjectConfigs}
onResolveProjectDiscoveredTooling={onResolveProjectDiscoveredTooling}
onResolveUserDiscoveredTooling={onResolveUserDiscoveredTooling}
selectedProjectName={selectedProjectName}
/>
)}
{activeSection === 'lsp-profiles' && (
@@ -377,11 +368,13 @@ function ConnectionSection({
modelCount,
isRefreshing,
onRefresh,
onGetQuota,
}: {
connection?: SidecarCapabilities['connection'];
modelCount: number;
isRefreshing: boolean;
onRefresh: () => void;
onGetQuota?: () => Promise<Record<string, QuotaSnapshot>>;
}) {
return (
<div>
@@ -396,6 +389,7 @@ function ConnectionSection({
connection={connection}
isRefreshing={isRefreshing}
modelCount={modelCount}
onGetQuota={onGetQuota}
onRefresh={onRefresh}
/>
</div>
@@ -607,68 +601,32 @@ function EmptyState({ children }: { children: ReactNode }) {
function DiscoveredMcpSection({
discoveredUserTooling,
discoveredProjectTooling,
selectedProjectName,
onRescanProjectConfigs,
onResolveUserDiscoveredTooling,
onResolveProjectDiscoveredTooling,
}: {
discoveredUserTooling: DiscoveredToolingState;
discoveredProjectTooling?: ProjectDiscoveredTooling;
selectedProjectName?: string;
onRescanProjectConfigs?: () => void;
onResolveUserDiscoveredTooling?: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
onResolveProjectDiscoveredTooling?: (serverIds: string[], resolution: 'accept' | 'dismiss') => void;
}) {
const acceptedUser = listAcceptedDiscoveredMcpServers(discoveredUserTooling);
const pendingUser = listPendingDiscoveredMcpServers(discoveredUserTooling);
const acceptedProject = listAcceptedDiscoveredMcpServers(discoveredProjectTooling);
const pendingProject = listPendingDiscoveredMcpServers(discoveredProjectTooling);
const hasAny = acceptedUser.length + pendingUser.length + acceptedProject.length + pendingProject.length > 0;
const hasAny = acceptedUser.length + pendingUser.length > 0;
if (!hasAny) return null;
return (
<div className="mt-8">
<SectionHeader
description="MCP servers discovered from project and user config files. Accepted servers are available for session tooling."
description="MCP servers discovered from user config files. Accepted servers are available for session tooling."
title="Discovered MCP Servers"
>
{onRescanProjectConfigs && (
<button
className="flex items-center gap-1.5 rounded-lg bg-zinc-800 px-3 py-1.5 text-[13px] font-medium text-zinc-200 transition hover:bg-zinc-700"
onClick={onRescanProjectConfigs}
title="Re-scan project config files"
type="button"
>
<RefreshCw className="size-3.5" />
Re-scan
</button>
)}
</SectionHeader>
/>
{/* User-level discovered */}
{(acceptedUser.length > 0 || pendingUser.length > 0) && (
<DiscoveredSubSection
label="User-level"
description="From ~/.copilot/mcp.json"
accepted={acceptedUser}
pending={pendingUser}
onResolve={onResolveUserDiscoveredTooling}
/>
)}
{/* Project-level discovered */}
{(acceptedProject.length > 0 || pendingProject.length > 0) && (
<DiscoveredSubSection
label={selectedProjectName ? `Project: ${selectedProjectName}` : 'Project-level'}
description="From .vscode/mcp.json, .mcp.json, or .copilot/mcp.json"
accepted={acceptedProject}
pending={pendingProject}
onResolve={onResolveProjectDiscoveredTooling}
/>
)}
<DiscoveredSubSection
label="User-level"
description="From ~/.copilot/mcp.json"
accepted={acceptedUser}
pending={pendingUser}
onResolve={onResolveUserDiscoveredTooling}
/>
</div>
);
}
+40 -3
View File
@@ -21,6 +21,7 @@ import {
RefreshCw,
Search,
Settings,
Trash2,
Users,
X,
type LucideIcon,
@@ -41,10 +42,12 @@ interface SidebarProps {
onProjectSelect: (projectId?: string) => void;
onSessionSelect: (sessionId: string) => void;
onOpenSettings: () => void;
onOpenProjectSettings: (projectId: string) => void;
onRenameSession: (sessionId: string, title: string) => void;
onDuplicateSession: (sessionId: string) => void;
onSetSessionPinned: (sessionId: string, isPinned: boolean) => void;
onSetSessionArchived: (sessionId: string, isArchived: boolean) => void;
onDeleteSession: (sessionId: string) => void;
onRefreshGitContext: (projectId: string) => void;
}
@@ -128,14 +131,16 @@ function ActionMenuItem({
icon: Icon,
label,
onClick,
className,
}: {
icon: LucideIcon;
label: string;
onClick: () => void;
className?: string;
}) {
return (
<button
className="flex w-full items-center gap-2 px-3 py-1.5 text-[12px] text-zinc-300 transition hover:bg-zinc-800"
className={`flex w-full items-center gap-2 px-3 py-1.5 text-[12px] transition hover:bg-zinc-800 ${className ?? 'text-zinc-300'}`}
onClick={onClick}
role="menuitem"
type="button"
@@ -324,6 +329,7 @@ function ProjectGroup({
onRenameSubmit,
onRenameCancel,
onRefreshGitContext,
onOpenProjectSettings,
onNewSession,
newSessionLabel,
}: {
@@ -337,6 +343,7 @@ function ProjectGroup({
onRenameSubmit: (sessionId: string, title: string) => void;
onRenameCancel: () => void;
onRefreshGitContext?: (projectId: string) => void;
onOpenProjectSettings?: (projectId: string) => void;
onNewSession?: () => void;
newSessionLabel?: string;
}){
@@ -390,6 +397,19 @@ function ProjectGroup({
)}
<div className="ml-auto flex items-center gap-1.5">
{!isScratchpad && onOpenProjectSettings && (
<span
className="flex size-5 items-center justify-center rounded text-zinc-600 opacity-0 transition hover:bg-zinc-700 hover:text-zinc-300 group-hover:opacity-100"
onClick={(e) => {
e.stopPropagation();
onOpenProjectSettings(project.id);
}}
role="button"
title="Project settings"
>
<Settings className="size-3" />
</span>
)}
{!isScratchpad && onRefreshGitContext && (
<span
className="flex size-5 items-center justify-center rounded text-zinc-600 opacity-0 transition hover:bg-zinc-700 hover:text-zinc-300 group-hover:opacity-100"
@@ -411,8 +431,13 @@ function ProjectGroup({
)}
{pendingDiscoveryCount > 0 && (
<span
className="flex items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-400"
title={`${pendingDiscoveryCount} MCP server${pendingDiscoveryCount === 1 ? '' : 's'} discovered`}
className="flex cursor-pointer items-center gap-1 rounded-full bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-400 transition hover:bg-amber-500/20"
onClick={(e) => {
e.stopPropagation();
onOpenProjectSettings?.(project.id);
}}
role="button"
title={`${pendingDiscoveryCount} MCP server${pendingDiscoveryCount === 1 ? '' : 's'} discovered — click to review`}
>
{pendingDiscoveryCount} new
</span>
@@ -471,10 +496,12 @@ export function Sidebar({
onProjectSelect,
onSessionSelect,
onOpenSettings,
onOpenProjectSettings,
onRenameSession,
onDuplicateSession,
onSetSessionPinned,
onSetSessionArchived,
onDeleteSession,
onRefreshGitContext,
}: SidebarProps) {
const scratchpadProject = workspace.projects.find((project) => isScratchpadProject(project));
@@ -673,6 +700,7 @@ export function Sidebar({
onRenameSubmit={handleRenameSubmit}
onRenameCancel={() => setRenamingSessionId(undefined)}
onRefreshGitContext={onRefreshGitContext}
onOpenProjectSettings={onOpenProjectSettings}
renamingSessionId={renamingSessionId}
patterns={workspace.patterns}
project={project}
@@ -742,6 +770,15 @@ export function Sidebar({
closeMenu();
}}
/>
<ActionMenuItem
className="text-red-400 hover:bg-red-500/10"
icon={Trash2}
label="Delete"
onClick={() => {
onDeleteSession(menuState.sessionId);
closeMenu();
}}
/>
</div>
</>
)}
+284
View File
@@ -0,0 +1,284 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { RotateCcw, Minus, X } from 'lucide-react';
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import '@xterm/xterm/css/xterm.css';
import { getElectronApi } from '@renderer/lib/electronApi';
import type { TerminalSnapshot } from '@shared/domain/terminal';
import type { TerminalExitInfo } from '@shared/domain/terminal';
/* ── Theme ────────────────────────────────────────────────── */
const terminalTheme = {
background: '#09090b', // zinc-950
foreground: '#e4e4e7', // zinc-200
cursor: '#818cf8', // indigo-400
cursorAccent: '#09090b',
selectionBackground: '#6366f14d', // indigo-500/30
selectionForeground: '#e4e4e7',
black: '#27272a', // zinc-800
red: '#f87171', // red-400
green: '#4ade80', // green-400
yellow: '#facc15', // yellow-400
blue: '#60a5fa', // blue-400
magenta: '#c084fc', // purple-400
cyan: '#22d3ee', // cyan-400
white: '#e4e4e7', // zinc-200
brightBlack: '#52525b', // zinc-600
brightRed: '#fca5a5', // red-300
brightGreen: '#86efac', // green-300
brightYellow: '#fde047', // yellow-300
brightBlue: '#93c5fd', // blue-300
brightMagenta: '#d8b4fe',// purple-300
brightCyan: '#67e8f9', // cyan-300
brightWhite: '#fafafa', // zinc-50
};
/* ── Constants ────────────────────────────────────────────── */
const MIN_HEIGHT = 120;
const MAX_HEIGHT_FRACTION = 0.7;
const DEFAULT_HEIGHT = 280;
/* ── TerminalPanel ────────────────────────────────────────── */
interface TerminalPanelProps {
height: number;
onHeightChange: (height: number) => void;
onClose: () => void;
onMinimize: () => void;
}
export function TerminalPanel({
height,
onHeightChange,
onClose,
onMinimize,
}: TerminalPanelProps) {
const api = getElectronApi();
const containerRef = useRef<HTMLDivElement>(null);
const terminalRef = useRef<Terminal | null>(null);
const fitAddonRef = useRef<FitAddon | null>(null);
const [snapshot, setSnapshot] = useState<TerminalSnapshot>();
const [isRunning, setIsRunning] = useState(false);
const [isDragging, setIsDragging] = useState(false);
const dragStartRef = useRef<{ y: number; height: number } | null>(null);
// Create or recover terminal on mount
useEffect(() => {
let disposed = false;
void api.describeTerminal().then((existing) => {
if (disposed) return;
if (existing) {
setSnapshot(existing);
setIsRunning(true);
} else {
void api.createTerminal().then((created) => {
if (disposed) return;
setSnapshot(created);
setIsRunning(true);
});
}
});
return () => {
disposed = true;
};
}, [api]);
// Initialize xterm.js
useEffect(() => {
if (!containerRef.current) return;
const terminal = new Terminal({
theme: terminalTheme,
fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',
fontSize: 13,
lineHeight: 1.4,
cursorBlink: true,
cursorStyle: 'bar',
scrollback: 5000,
allowProposedApi: true,
});
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
terminal.open(containerRef.current);
terminalRef.current = terminal;
fitAddonRef.current = fitAddon;
// Send keystrokes to the backend
const dataDisposable = terminal.onData((data) => {
api.writeTerminal(data);
});
// Initial fit
requestAnimationFrame(() => {
fitAddon.fit();
api.resizeTerminal({ cols: terminal.cols, rows: terminal.rows });
});
return () => {
dataDisposable.dispose();
terminal.dispose();
terminalRef.current = null;
fitAddonRef.current = null;
};
}, [api]);
// Subscribe to terminal data and exit events
useEffect(() => {
const offData = api.onTerminalData((data) => {
terminalRef.current?.write(data);
});
const offExit = api.onTerminalExit((_info: TerminalExitInfo) => {
setIsRunning(false);
terminalRef.current?.write('\r\n\x1b[90m[Process exited]\x1b[0m\r\n');
});
return () => {
offData();
offExit();
};
}, [api]);
// Refit on height changes
useEffect(() => {
if (!fitAddonRef.current || !terminalRef.current) return;
requestAnimationFrame(() => {
fitAddonRef.current?.fit();
const terminal = terminalRef.current;
if (terminal) {
api.resizeTerminal({ cols: terminal.cols, rows: terminal.rows });
}
});
}, [height, api]);
// ResizeObserver for container width changes
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const observer = new ResizeObserver(() => {
requestAnimationFrame(() => {
fitAddonRef.current?.fit();
const terminal = terminalRef.current;
if (terminal) {
api.resizeTerminal({ cols: terminal.cols, rows: terminal.rows });
}
});
});
observer.observe(container);
return () => observer.disconnect();
}, [api]);
// Drag-to-resize
const handleDragStart = useCallback((e: React.MouseEvent) => {
e.preventDefault();
dragStartRef.current = { y: e.clientY, height };
setIsDragging(true);
const handleDragMove = (moveEvent: MouseEvent) => {
if (!dragStartRef.current) return;
const maxHeight = window.innerHeight * MAX_HEIGHT_FRACTION;
const delta = dragStartRef.current.y - moveEvent.clientY;
const nextHeight = Math.max(MIN_HEIGHT, Math.min(maxHeight, dragStartRef.current.height + delta));
onHeightChange(nextHeight);
};
const handleDragEnd = () => {
setIsDragging(false);
dragStartRef.current = null;
document.removeEventListener('mousemove', handleDragMove);
document.removeEventListener('mouseup', handleDragEnd);
};
document.addEventListener('mousemove', handleDragMove);
document.addEventListener('mouseup', handleDragEnd);
}, [height, onHeightChange]);
const handleRestart = useCallback(() => {
void api.restartTerminal().then((restarted) => {
setSnapshot(restarted);
setIsRunning(true);
terminalRef.current?.clear();
});
}, [api]);
const handleClose = useCallback(() => {
void api.killTerminal();
onClose();
}, [api, onClose]);
return (
<div
className="flex flex-col border-t border-[var(--color-border)] bg-[#09090b]"
style={{ height, minHeight: MIN_HEIGHT }}
>
{/* Resize handle */}
<div
className={`h-1 shrink-0 cursor-row-resize transition-colors ${isDragging ? 'bg-indigo-500/40' : 'hover:bg-zinc-700/60'}`}
onMouseDown={handleDragStart}
role="separator"
aria-orientation="horizontal"
aria-label="Resize terminal"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'ArrowUp') {
e.preventDefault();
onHeightChange(Math.min(window.innerHeight * MAX_HEIGHT_FRACTION, height + 20));
} else if (e.key === 'ArrowDown') {
e.preventDefault();
onHeightChange(Math.max(MIN_HEIGHT, height - 20));
}
}}
/>
{/* Header bar */}
<div className="flex h-7 shrink-0 items-center gap-2 border-b border-zinc-800/60 px-3">
<span className={`size-1.5 shrink-0 rounded-full ${isRunning ? 'bg-emerald-400' : 'bg-zinc-600'}`} />
<span className="min-w-0 flex-1 truncate text-[11px] text-zinc-500">
{snapshot ? `${snapshot.shell}${snapshot.cwd}` : 'Terminal'}
</span>
<div className="flex items-center gap-0.5">
<button
aria-label="Restart terminal"
className="rounded p-0.5 text-zinc-600 transition hover:bg-zinc-800 hover:text-zinc-400"
onClick={handleRestart}
type="button"
>
<RotateCcw className="size-3" />
</button>
<button
aria-label="Minimize terminal"
className="rounded p-0.5 text-zinc-600 transition hover:bg-zinc-800 hover:text-zinc-400"
onClick={onMinimize}
type="button"
>
<Minus className="size-3" />
</button>
<button
aria-label="Close terminal"
className="rounded p-0.5 text-zinc-600 transition hover:bg-zinc-800 hover:text-red-400"
onClick={handleClose}
type="button"
>
<X className="size-3" />
</button>
</div>
</div>
{/* Terminal body */}
<div
className="min-h-0 flex-1 px-1 py-0.5"
ref={containerRef}
role="application"
aria-label="Terminal"
/>
</div>
);
}
export { DEFAULT_HEIGHT, MIN_HEIGHT };
@@ -1,8 +1,11 @@
import { useState } from 'react';
import { Bot, Check, ChevronDown, Loader2, ShieldAlert, ShieldCheck, X } from 'lucide-react';
import { Bot, Check, ChevronDown, Loader2, ShieldAlert, ShieldBan, ShieldCheck, X } from 'lucide-react';
import { MarkdownContent } from '@renderer/components/MarkdownContent';
import { permissionDetailSummary, PermissionDetailView } from '@renderer/components/chat/PermissionDetailView';
import { resolveApprovalToolKey } from '@shared/domain/approval';
import type { ApprovalDecision, PendingApprovalRecord } from '@shared/domain/approval';
import { resolveToolLabel } from '@shared/domain/tooling';
/* ── ApprovalBanner ────────────────────────────────────────── */
@@ -14,7 +17,7 @@ export function ApprovalBanner({
total,
}: {
approval: PendingApprovalRecord;
onResolve: (decision: ApprovalDecision) => void;
onResolve: (decision: ApprovalDecision, alwaysApprove?: boolean) => void;
isResolving: boolean;
position?: number;
total?: number;
@@ -22,6 +25,9 @@ export function ApprovalBanner({
const kindLabel = approval.kind === 'final-response' ? 'Final response review' : 'Tool call approval';
const hasMessages = approval.messages && approval.messages.length > 0;
const showPosition = position !== undefined && total !== undefined && total > 1;
const approvalToolKey = resolveApprovalToolKey(approval.toolName, approval.permissionKind);
const canAlwaysApprove = approval.kind === 'tool-call' && !!approvalToolKey;
const approvalToolLabel = approvalToolKey ? resolveToolLabel(approvalToolKey) : undefined;
return (
<div className="rounded-xl border border-amber-500/30 bg-amber-500/5 px-4 py-3" role="alert">
@@ -47,9 +53,11 @@ export function ApprovalBanner({
{approval.permissionKind && <span>Permission: <span className="text-zinc-300">{approval.permissionKind}</span></span>}
</div>
{approval.detail && (
<p className="mt-1.5 text-[12px] leading-relaxed text-zinc-400">{approval.detail}</p>
)}
{approval.permissionDetail
? <PermissionDetailView detail={approval.permissionDetail} />
: approval.detail && (
<p className="mt-1.5 text-[12px] leading-relaxed text-zinc-400">{approval.detail}</p>
)}
</div>
</div>
@@ -84,6 +92,19 @@ export function ApprovalBanner({
{isResolving ? <Loader2 className="size-3 animate-spin" /> : <Check className="size-3" />}
Approve
</button>
{canAlwaysApprove && (
<button
aria-label={`Always approve ${approvalToolLabel}`}
className="inline-flex items-center gap-1.5 rounded-lg bg-emerald-600/20 px-3.5 py-1.5 text-[12px] font-medium text-emerald-300 transition hover:bg-emerald-600/30 disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResolving}
onClick={() => onResolve('approved', true)}
title={`Auto-approve "${approvalToolLabel}" for the rest of this session`}
type="button"
>
<ShieldBan className="size-3" />
Always approve
</button>
)}
<button
className="inline-flex items-center gap-1.5 rounded-lg bg-zinc-800 px-3.5 py-1.5 text-[12px] font-medium text-zinc-300 transition hover:bg-zinc-700 hover:text-white disabled:cursor-not-allowed disabled:opacity-50"
disabled={isResolving}
@@ -134,7 +155,9 @@ export function QueuedApprovalsList({ approvals }: { approvals: PendingApprovalR
key={approval.id}
>
<ShieldAlert className="size-3 shrink-0 text-zinc-600" />
<span className="min-w-0 flex-1 truncate text-[11px] text-zinc-400">{approval.title}</span>
<span className="min-w-0 flex-1 truncate text-[11px] text-zinc-400">
{(approval.permissionDetail && permissionDetailSummary(approval.permissionDetail)) || approval.title}
</span>
<span className="shrink-0 rounded-full bg-zinc-800 px-1.5 py-0.5 text-[8px] font-semibold uppercase tracking-wider text-zinc-500">
{kindLabel}
</span>
+301 -56
View File
@@ -1,10 +1,11 @@
import { useState } from 'react';
import { ChevronDown, Sparkles } from 'lucide-react';
import { useMemo, useState } from 'react';
import { ChevronDown, ChevronRight, Loader2, Minus, Search, Sparkles, TerminalSquare } from 'lucide-react';
import { ProviderIcon } from '@renderer/components/ProviderIcons';
import { PopoverToggleRow } from '@renderer/components/ui';
import { useClickOutside } from '@renderer/hooks/useClickOutside';
import type { ApprovalToolDefinition, ApprovalToolKind, LspProfileDefinition, McpServerDefinition, SessionToolingSelection } from '@shared/domain/tooling';
import type { ApprovalToolDefinition, LspProfileDefinition, McpServerDefinition, SessionToolingSelection, WorkspaceToolingSettings } from '@shared/domain/tooling';
import { groupApprovalToolsByProvider, type ApprovalToolGroup } from '@shared/domain/tooling';
import { findModel, inferProvider, providerMeta, type ModelDefinition } from '@shared/domain/models';
import { reasoningEffortOptions, type ReasoningEffort } from '@shared/domain/pattern';
import { RotateCcw, Server, ShieldCheck } from 'lucide-react';
@@ -337,29 +338,64 @@ function McpServerGroup({
/* ── InlineApprovalPill ────────────────────────────────────── */
const approvalKindOrder: ApprovalToolKind[] = ['builtin', 'mcp', 'lsp', 'mixed'];
const approvalKindLabels: Record<ApprovalToolKind, string> = {
builtin: 'Built-in',
mcp: 'MCP Servers',
lsp: 'Language Servers',
mixed: 'Other',
};
const SEARCH_THRESHOLD = 10;
export function InlineApprovalPill({
approvalTools,
toolingSettings,
effectiveAutoApproved,
effectiveAutoApprovedCount,
isOverridden,
disabled,
mcpProbingServerIds,
onUpdate,
}: {
approvalTools: ApprovalToolDefinition[];
toolingSettings: WorkspaceToolingSettings;
effectiveAutoApproved: Set<string>;
effectiveAutoApprovedCount: number;
isOverridden: boolean;
disabled: boolean;
mcpProbingServerIds?: string[];
onUpdate: (settings: { autoApprovedToolNames?: string[] }) => void;
}) {
}){
const [open, setOpen] = useState(false);
const ref = useClickOutside<HTMLDivElement>(() => setOpen(false), open);
const [search, setSearch] = useState('');
const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set());
const ref = useClickOutside<HTMLDivElement>(() => { setOpen(false); setSearch(''); }, open);
const probingSet = useMemo(
() => new Set(mcpProbingServerIds ?? []),
[mcpProbingServerIds],
);
const isProbingAny = probingSet.size > 0;
const groups = useMemo(
() => groupApprovalToolsByProvider(approvalTools, toolingSettings),
[approvalTools, toolingSettings],
);
const totalItemCount = groups.reduce(
(sum, g) => sum + Math.max(g.tools.length, g.serverApprovalKey ? 1 : 0),
0,
);
const showSearch = totalItemCount > SEARCH_THRESHOLD;
const searchLower = search.toLowerCase().trim();
const filteredGroups = useMemo(() => {
if (!searchLower) return groups;
return groups
.map((group) => ({
...group,
tools: group.tools.filter(
(t) =>
t.label.toLowerCase().includes(searchLower)
|| t.id.toLowerCase().includes(searchLower)
|| group.label.toLowerCase().includes(searchLower),
),
}))
.filter((g) => g.tools.length > 0 || g.label.toLowerCase().includes(searchLower));
}, [groups, searchLower]);
function toggleTool(toolId: string) {
const next = new Set(effectiveAutoApproved);
@@ -371,10 +407,68 @@ export function InlineApprovalPill({
onUpdate({ autoApprovedToolNames: [...next] });
}
const groups = approvalKindOrder
.map((kind) => ({ kind, tools: approvalTools.filter((t) => t.kind === kind) }))
.filter((g) => g.tools.length > 0);
const showHeaders = groups.length > 1;
function toggleGroup(group: ApprovalToolGroup) {
const next = new Set(effectiveAutoApproved);
if (group.serverApprovalKey) {
// MCP servers use server-level approval key
if (next.has(group.serverApprovalKey)) {
next.delete(group.serverApprovalKey);
} else {
next.add(group.serverApprovalKey);
}
// Also remove individual tool entries when toggling server-level
for (const tool of group.tools) {
next.delete(tool.id);
}
} else {
// Non-MCP groups: toggle individual tools
const allApproved = group.tools.every((t) => next.has(t.id));
for (const tool of group.tools) {
if (allApproved) {
next.delete(tool.id);
} else {
next.add(tool.id);
}
}
}
onUpdate({ autoApprovedToolNames: [...next] });
}
function isGroupApproved(group: ApprovalToolGroup): 'all' | 'some' | 'none' {
if (group.serverApprovalKey && effectiveAutoApproved.has(group.serverApprovalKey)) {
return 'all';
}
if (group.tools.length === 0) return 'none';
const approvedCount = group.tools.filter((t) => effectiveAutoApproved.has(t.id)).length;
if (approvedCount === group.tools.length) return 'all';
if (approvedCount > 0) return 'some';
return 'none';
}
function isGroupProbing(group: ApprovalToolGroup): boolean {
if (group.kind !== 'mcp') return false;
const serverId = group.id.replace(/^mcp:/, '');
return probingSet.has(serverId);
}
function toggleExpanded(groupId: string) {
setExpandedGroups((prev) => {
const next = new Set(prev);
if (next.has(groupId)) {
next.delete(groupId);
} else {
next.add(groupId);
}
return next;
});
}
function isGroupExpanded(groupId: string): boolean {
if (searchLower) return true;
return expandedGroups.has(groupId);
}
return (
<div className="relative" ref={ref}>
@@ -392,58 +486,209 @@ export function InlineApprovalPill({
onClick={() => setOpen(!open)}
type="button"
>
<ShieldCheck className="size-2.5" />
<span>{effectiveAutoApproved.size}/{approvalTools.length} auto-approved</span>
{isProbingAny ? (
<Loader2 className="size-2.5 animate-spin" aria-label="Probing MCP servers" />
) : (
<ShieldCheck className="size-2.5" />
)}
<span>
{effectiveAutoApprovedCount}/{totalItemCount} auto-approved
{isProbingAny && <span className="text-zinc-500"> · probing</span>}
</span>
<ChevronDown className={`size-2.5 transition ${open ? 'rotate-180' : ''}`} />
</button>
{open && !disabled && (
<div className="absolute bottom-full left-0 z-40 mb-1.5 max-h-80 w-72 overflow-y-auto rounded-lg border border-zinc-700 bg-zinc-900 shadow-2xl">
<div className="flex items-center gap-2 border-b border-zinc-800 px-3 py-2">
<span className={`rounded-full px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider ${
isOverridden
? 'bg-amber-500/15 text-amber-400'
: 'bg-zinc-800 text-zinc-500'
}`}>
{isOverridden ? 'Session override' : 'Pattern defaults'}
</span>
{isOverridden && (
<button
className="flex items-center gap-1 rounded-full px-2 py-0.5 text-[9px] font-medium text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
onClick={() => onUpdate({})}
type="button"
>
<RotateCcw className="size-2.5" />
Reset
</button>
<div className="absolute bottom-full left-0 z-40 mb-1.5 max-h-[28rem] w-80 overflow-y-auto rounded-lg border border-zinc-700 bg-zinc-900 shadow-2xl">
{/* Header: session override / pattern defaults */}
<div className="sticky top-0 z-10 border-b border-zinc-800 bg-zinc-900">
<div className="flex items-center gap-2 px-3 py-2">
<span className={`rounded-full px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider ${
isOverridden
? 'bg-amber-500/15 text-amber-400'
: 'bg-zinc-800 text-zinc-500'
}`}>
{isOverridden ? 'Session override' : 'Pattern defaults'}
</span>
{isOverridden && (
<button
className="flex items-center gap-1 rounded-full px-2 py-0.5 text-[9px] font-medium text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
onClick={() => onUpdate({})}
type="button"
>
<RotateCcw className="size-2.5" />
Reset
</button>
)}
</div>
{/* Search */}
{showSearch && (
<div className="border-t border-zinc-800/50 px-3 py-1.5">
<div className="flex items-center gap-2 rounded border border-zinc-800 bg-zinc-800/30 px-2 py-1">
<Search className="size-3 shrink-0 text-zinc-600" />
<input
autoFocus
className="w-full bg-transparent text-[12px] text-zinc-300 placeholder-zinc-600 outline-none"
onChange={(e) => setSearch(e.target.value)}
placeholder="Filter tools…"
type="text"
value={search}
/>
</div>
</div>
)}
</div>
{/* Tool groups */}
<div className="py-1">
{groups.map((group, i) => (
<div key={group.kind}>
{showHeaders && (
<div className={`px-3 pb-1 ${i > 0 ? 'pt-2' : 'pt-1'} text-[9px] font-semibold uppercase tracking-wider text-zinc-600`}>
{approvalKindLabels[group.kind]}
</div>
)}
{group.tools.map((tool) => {
const detail = tool.description || (tool.providerNames.length > 0 ? tool.providerNames.join(', ') : undefined);
return (
<PopoverToggleRow
detail={detail}
enabled={effectiveAutoApproved.has(tool.id)}
key={tool.id}
label={tool.label}
onToggle={() => toggleTool(tool.id)}
/>
);
})}
{filteredGroups.map((group, groupIdx) => {
const isBuiltin = group.kind === 'builtin';
const isCollapsible = !isBuiltin;
const expanded = isBuiltin || isGroupExpanded(group.id);
const probing = isGroupProbing(group);
const groupState = isGroupApproved(group);
const allApproved = groupState === 'all';
const someApproved = groupState === 'some';
const approvedLabel = group.serverApprovalKey && allApproved
? 'all'
: `${group.tools.filter((t) => effectiveAutoApproved.has(t.id)).length}/${group.tools.length}`;
return (
<div key={group.id}>
{/* Group header */}
{isBuiltin ? (
<div className={`px-3 pb-1 ${groupIdx > 0 ? 'pt-2.5' : 'pt-1'} text-[9px] font-semibold uppercase tracking-wider text-zinc-600`}>
{group.label}
</div>
) : (
<div
className={`flex w-full cursor-pointer items-center gap-1.5 px-2.5 py-1.5 text-left transition hover:bg-zinc-800/60 ${groupIdx > 0 ? 'mt-0.5' : ''}`}
onClick={() => toggleExpanded(group.id)}
onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggleExpanded(group.id); } }}
role="button"
tabIndex={0}
>
{probing ? (
<Loader2 className="size-3 shrink-0 animate-spin text-indigo-400" aria-label="Probing server" />
) : group.tools.length > 0 ? (
<ChevronRight className={`size-3 shrink-0 text-zinc-600 transition ${expanded ? 'rotate-90' : ''}`} />
) : (
<Server className="size-3 shrink-0 text-zinc-600" />
)}
<span className="min-w-0 flex-1 truncate text-[12px] font-medium text-zinc-300">{group.label}</span>
{probing ? (
<span className="shrink-0 rounded-full bg-indigo-500/10 px-1.5 py-px text-[9px] font-medium text-indigo-400">
probing
</span>
) : (
<span className="shrink-0 rounded-full bg-zinc-800/80 px-1.5 py-px text-[9px] font-medium tabular-nums text-zinc-500">
{approvedLabel}
</span>
)}
{!probing && (
<GroupToggle
allApproved={allApproved}
someApproved={someApproved}
onToggle={(e) => { e.stopPropagation(); toggleGroup(group); }}
/>
)}
</div>
)}
{/* Group tools */}
{expanded && group.tools.map((tool) => {
const detail = tool.description || (
!isBuiltin && tool.providerNames.length > 1
? tool.providerNames.join(', ')
: undefined
);
return (
<div key={tool.id} className={isCollapsible ? 'pl-3' : ''}>
<PopoverToggleRow
detail={detail}
enabled={effectiveAutoApproved.has(tool.id)}
label={tool.label}
onToggle={() => toggleTool(tool.id)}
/>
</div>
);
})}
</div>
);
})}
{filteredGroups.length === 0 && searchLower && (
<div className="px-3 py-4 text-center text-[12px] text-zinc-600">
No tools match "{search}"
</div>
))}
)}
</div>
</div>
)}
</div>
);
}
function GroupToggle({
allApproved,
someApproved,
onToggle,
}: {
allApproved: boolean;
someApproved: boolean;
onToggle: (e: React.MouseEvent) => void;
}) {
return (
<button
aria-pressed={allApproved}
className={`relative inline-flex h-[16px] w-[28px] shrink-0 items-center rounded-full transition-colors ${
allApproved ? 'bg-indigo-500' : someApproved ? 'bg-zinc-600' : 'bg-zinc-700'
}`}
onClick={onToggle}
type="button"
>
{someApproved ? (
<Minus className="absolute left-1/2 size-2 -translate-x-1/2 text-zinc-300" strokeWidth={3} />
) : (
<span
className={`inline-block size-[12px] rounded-full bg-white shadow transition-transform ${
allApproved ? 'translate-x-[13px]' : 'translate-x-[2px]'
}`}
/>
)}
</button>
);
}
/* ── InlineTerminalPill ────────────────────────────────────── */
export function InlineTerminalPill({
disabled,
isRunning,
isOpen,
onToggle,
}: {
disabled: boolean;
isRunning: boolean;
isOpen: boolean;
onToggle: () => void;
}) {
return (
<button
aria-pressed={isOpen}
className={`inline-flex items-center gap-1 rounded-lg px-2 py-1 text-[11px] font-medium transition ${
isOpen
? 'bg-indigo-500/15 text-indigo-300 hover:bg-indigo-500/20'
: 'text-zinc-500 hover:bg-zinc-800 hover:text-zinc-300'
} disabled:cursor-not-allowed disabled:opacity-50`}
disabled={disabled}
onClick={onToggle}
type="button"
>
{isRunning && <span className="size-1.5 shrink-0 rounded-full bg-emerald-400" />}
<TerminalSquare className="size-3" />
<span>Terminal</span>
</button>
);
}
@@ -0,0 +1,253 @@
import { useCallback, useMemo, useState } from 'react';
import { ArrowUp, FileText, X } from 'lucide-react';
import { useClickOutside } from '@renderer/hooks/useClickOutside';
import type { ProjectPromptFile, ProjectPromptVariable } from '@shared/domain/projectCustomization';
const promptVariablePattern = /\$\{input:([a-zA-Z0-9_-]+):[^}]+\}/g;
function resolvePromptTemplate(template: string, values: Record<string, string>): string {
return template.replace(promptVariablePattern, (_match, name: string) => {
return values[name] ?? '';
});
}
export function InlinePromptPill({
promptFiles,
disabled,
onSubmit,
}: {
promptFiles: ReadonlyArray<ProjectPromptFile>;
disabled: boolean;
onSubmit: (resolvedContent: string) => void;
}) {
const [open, setOpen] = useState(false);
const [selectedPrompt, setSelectedPrompt] = useState<ProjectPromptFile | null>(null);
const [variableValues, setVariableValues] = useState<Record<string, string>>({});
const ref = useClickOutside<HTMLDivElement>(() => handleClose(), open);
const handleClose = useCallback(() => {
setOpen(false);
setSelectedPrompt(null);
setVariableValues({});
}, []);
const handleSelectPrompt = useCallback((prompt: ProjectPromptFile) => {
if (prompt.variables.length === 0) {
onSubmit(prompt.template.trim());
handleClose();
} else {
setSelectedPrompt(prompt);
setVariableValues({});
}
}, [onSubmit, handleClose]);
const handleSubmitWithVariables = useCallback(() => {
if (!selectedPrompt) return;
const resolved = resolvePromptTemplate(selectedPrompt.template, variableValues).trim();
if (!resolved) return;
onSubmit(resolved);
handleClose();
}, [selectedPrompt, variableValues, onSubmit, handleClose]);
const handleVariableChange = useCallback((name: string, value: string) => {
setVariableValues((prev) => ({ ...prev, [name]: value }));
}, []);
const allVariablesFilled = useMemo(() => {
if (!selectedPrompt) return false;
return selectedPrompt.variables.every((v) => (variableValues[v.name] ?? '').trim().length > 0);
}, [selectedPrompt, variableValues]);
if (promptFiles.length === 0) return null;
return (
<div className="relative" ref={ref}>
<button
aria-expanded={open}
aria-haspopup="listbox"
className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-[11px] font-medium text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
disabled={disabled}
onClick={() => setOpen(!open)}
type="button"
>
<FileText className="size-3" />
Prompts
<span className="text-zinc-600">({promptFiles.length})</span>
</button>
{open && !disabled && (
<div
className="absolute bottom-full left-0 z-40 mb-1.5 w-80 rounded-lg border border-zinc-700 bg-zinc-900 shadow-xl"
role="listbox"
>
{selectedPrompt ? (
<PromptVariableForm
onBack={() => {
setSelectedPrompt(null);
setVariableValues({});
}}
onSubmit={handleSubmitWithVariables}
onVariableChange={handleVariableChange}
prompt={selectedPrompt}
submitDisabled={!allVariablesFilled}
values={variableValues}
/>
) : (
<PromptList
onSelect={handleSelectPrompt}
promptFiles={promptFiles}
/>
)}
</div>
)}
</div>
);
}
function PromptList({
promptFiles,
onSelect,
}: {
promptFiles: ReadonlyArray<ProjectPromptFile>;
onSelect: (prompt: ProjectPromptFile) => void;
}) {
return (
<div className="max-h-64 overflow-y-auto py-1">
<div className="px-3 py-2 text-[10px] font-semibold uppercase tracking-wider text-zinc-500">
Prompt files
</div>
{promptFiles.map((prompt) => (
<button
key={prompt.id}
className="flex w-full items-start gap-2.5 px-3 py-2 text-left transition hover:bg-zinc-800"
onClick={() => onSelect(prompt)}
role="option"
type="button"
>
<FileText className="mt-0.5 size-3.5 shrink-0 text-zinc-500" />
<div className="min-w-0 flex-1">
<div className="truncate text-[12px] font-medium text-zinc-200">
{prompt.name}
</div>
{prompt.description && (
<div className="mt-0.5 truncate text-[11px] text-zinc-500">
{prompt.description}
</div>
)}
{prompt.variables.length > 0 && (
<div className="mt-1 flex flex-wrap gap-1">
{prompt.variables.map((v) => (
<span
key={v.name}
className="rounded bg-zinc-800 px-1.5 py-0.5 text-[10px] text-zinc-500"
>
{v.name}
</span>
))}
</div>
)}
</div>
</button>
))}
</div>
);
}
function PromptVariableForm({
prompt,
values,
submitDisabled,
onVariableChange,
onSubmit,
onBack,
}: {
prompt: ProjectPromptFile;
values: Record<string, string>;
submitDisabled: boolean;
onVariableChange: (name: string, value: string) => void;
onSubmit: () => void;
onBack: () => void;
}) {
return (
<div className="p-3">
<div className="mb-3 flex items-center gap-2">
<button
className="flex size-5 items-center justify-center rounded text-zinc-500 transition hover:bg-zinc-800 hover:text-zinc-300"
onClick={onBack}
type="button"
aria-label="Back to prompt list"
>
<X className="size-3" />
</button>
<div className="min-w-0 flex-1">
<div className="truncate text-[12px] font-medium text-zinc-200">
{prompt.name}
</div>
{prompt.description && (
<div className="truncate text-[10px] text-zinc-500">{prompt.description}</div>
)}
</div>
</div>
<div className="space-y-2.5">
{prompt.variables.map((variable) => (
<PromptVariableInput
key={variable.name}
onChange={(value) => onVariableChange(variable.name, value)}
onSubmit={!submitDisabled ? onSubmit : undefined}
value={values[variable.name] ?? ''}
variable={variable}
/>
))}
</div>
<button
className={`mt-3 flex w-full items-center justify-center gap-1.5 rounded-lg px-3 py-2 text-[12px] font-medium transition ${
submitDisabled
? 'bg-zinc-800 text-zinc-600'
: 'bg-indigo-600 text-white hover:bg-indigo-500'
}`}
disabled={submitDisabled}
onClick={onSubmit}
type="button"
>
<ArrowUp className="size-3.5" />
Send prompt
</button>
</div>
);
}
function PromptVariableInput({
variable,
value,
onChange,
onSubmit,
}: {
variable: ProjectPromptVariable;
value: string;
onChange: (value: string) => void;
onSubmit?: () => void;
}) {
return (
<div>
<label className="mb-1 block text-[11px] font-medium text-zinc-400">
{variable.name}
</label>
<input
className="w-full rounded-lg border border-zinc-700 bg-zinc-800 px-2.5 py-1.5 text-[12px] text-zinc-200 placeholder-zinc-600 transition focus:border-indigo-500/50 focus:outline-none"
onChange={(e) => onChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && onSubmit) {
e.preventDefault();
onSubmit();
}
}}
placeholder={variable.placeholder}
type="text"
value={value}
/>
</div>
);
}
@@ -0,0 +1,88 @@
import { useCallback } from 'react';
import { KeyRound, Loader2, X } from 'lucide-react';
import type { PendingMcpAuthRecord } from '@shared/domain/mcpAuth';
export function McpAuthBanner({
mcpAuth,
onAuthenticate,
onDismiss,
}: {
mcpAuth: PendingMcpAuthRecord;
onAuthenticate: () => void;
onDismiss: () => void;
}) {
const handleAuthenticate = useCallback(() => {
onAuthenticate();
}, [onAuthenticate]);
const handleDismiss = useCallback(() => {
onDismiss();
}, [onDismiss]);
const isAuthenticating = mcpAuth.status === 'authenticating';
const hasFailed = mcpAuth.status === 'failed';
return (
<div className="rounded-xl border border-amber-500/30 bg-amber-500/5 px-4 py-3" role="alert">
<div className="flex items-start gap-2.5">
<KeyRound className="mt-0.5 size-4 shrink-0 text-amber-400" />
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<span className="text-[13px] font-semibold text-amber-200">Authentication required</span>
<span className="rounded-full bg-amber-500/15 px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-amber-400">
MCP
</span>
</div>
<button
aria-label="Dismiss authentication prompt"
className="rounded p-0.5 text-zinc-500 transition hover:bg-zinc-700/50 hover:text-zinc-300"
onClick={handleDismiss}
type="button"
>
<X className="size-3.5" />
</button>
</div>
<p className="mt-2 text-[13px] leading-relaxed text-zinc-200">
The MCP server{' '}
<span className="font-medium text-amber-200">{mcpAuth.serverName}</span>{' '}
requires OAuth authentication to connect.
</p>
<p className="mt-1 text-[11px] text-zinc-500">{mcpAuth.serverUrl}</p>
{hasFailed && mcpAuth.errorMessage && (
<p className="mt-2 text-[12px] text-red-400">{mcpAuth.errorMessage}</p>
)}
<div className="mt-3 flex items-center gap-3">
<button
className="inline-flex items-center gap-1.5 rounded-lg bg-amber-500/20 px-3 py-1.5 text-[12px] font-medium text-amber-200 transition hover:bg-amber-500/30 disabled:opacity-50"
disabled={isAuthenticating}
onClick={handleAuthenticate}
type="button"
>
{isAuthenticating ? (
<>
<Loader2 className="size-3.5 animate-spin" />
Authenticating
</>
) : hasFailed ? (
'Retry authentication'
) : (
'Authenticate in browser'
)}
</button>
<span className="text-[11px] text-zinc-500">
{isAuthenticating
? 'Waiting for consent in the browser…'
: 'Opens your browser for OAuth consent. Token is stored for this session only.'}
</span>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,295 @@
import { useState } from 'react';
import {
AlertTriangle,
BookOpen,
ChevronDown,
ExternalLink,
FileEdit,
FileText,
Globe,
Server,
Terminal,
} from 'lucide-react';
import type { PermissionDetail } from '@shared/contracts/sidecar';
export function PermissionDetailView({ detail }: { detail: PermissionDetail }) {
switch (detail.kind) {
case 'shell':
return <ShellDetail detail={detail} />;
case 'write':
return <WriteDetail detail={detail} />;
case 'read':
return <ReadDetail detail={detail} />;
case 'mcp':
return <McpDetail detail={detail} />;
case 'url':
return <UrlDetail detail={detail} />;
case 'memory':
return <MemoryDetail detail={detail} />;
case 'custom-tool':
return <CustomToolDetail detail={detail} />;
case 'hook':
return <HookDetail detail={detail} />;
default:
return null;
}
}
export function permissionDetailSummary(detail: PermissionDetail): string | undefined {
switch (detail.kind) {
case 'shell':
return detail.command ? truncate(detail.command, 80) : undefined;
case 'write':
return detail.fileName;
case 'read':
return detail.path;
case 'url':
return detail.url;
case 'mcp':
return detail.serverName
? `${detail.serverName}${detail.toolTitle ?? ''}`
: detail.toolTitle;
case 'memory':
return detail.subject;
case 'custom-tool':
return detail.toolDescription ? truncate(detail.toolDescription, 80) : undefined;
case 'hook':
return detail.hookMessage ? truncate(detail.hookMessage, 80) : undefined;
default:
return undefined;
}
}
/* ── Kind-specific renderers ────────────────────────────────── */
function ShellDetail({ detail }: { detail: PermissionDetail }) {
return (
<div className="mt-2.5 space-y-2">
{detail.intention && <IntentionLine text={detail.intention} />}
{detail.warning && (
<div className="flex items-start gap-1.5 rounded-md bg-red-500/10 px-2.5 py-1.5 text-[11px] text-red-300">
<AlertTriangle className="mt-0.5 size-3 shrink-0" />
<span>{detail.warning}</span>
</div>
)}
{detail.command && <CommandBlock text={detail.command} />}
{detail.possiblePaths && detail.possiblePaths.length > 0 && (
<MetaList label="Paths" items={detail.possiblePaths} />
)}
{detail.possibleUrls && detail.possibleUrls.length > 0 && (
<MetaList label="URLs" items={detail.possibleUrls} />
)}
</div>
);
}
function WriteDetail({ detail }: { detail: PermissionDetail }) {
return (
<div className="mt-2.5 space-y-2">
{detail.intention && <IntentionLine text={detail.intention} />}
{detail.fileName && (
<div className="flex items-center gap-1.5 text-[11px] text-zinc-300">
<FileEdit className="size-3 shrink-0 text-zinc-500" />
<code className="font-mono">{detail.fileName}</code>
</div>
)}
{detail.diff && <DiffBlock text={detail.diff} />}
{!detail.diff && detail.newFileContents && (
<CollapsibleCode label="New file contents" text={detail.newFileContents} />
)}
</div>
);
}
function ReadDetail({ detail }: { detail: PermissionDetail }) {
return (
<div className="mt-2.5 space-y-2">
{detail.intention && <IntentionLine text={detail.intention} />}
{detail.path && (
<div className="flex items-center gap-1.5 text-[11px] text-zinc-300">
<FileText className="size-3 shrink-0 text-zinc-500" />
<code className="font-mono">{detail.path}</code>
</div>
)}
</div>
);
}
function McpDetail({ detail }: { detail: PermissionDetail }) {
return (
<div className="mt-2.5 space-y-2">
<div className="flex flex-wrap items-center gap-2 text-[11px]">
{detail.serverName && (
<span className="inline-flex items-center gap-1 rounded-full bg-indigo-500/15 px-2 py-0.5 text-indigo-300">
<Server className="size-2.5" />
{detail.serverName}
</span>
)}
{detail.toolTitle && <span className="text-zinc-300">{detail.toolTitle}</span>}
{detail.readOnly && (
<span className="rounded-full bg-emerald-500/15 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-emerald-400">
read-only
</span>
)}
</div>
{detail.args && Object.keys(detail.args).length > 0 && (
<CollapsibleCode label="Arguments" text={JSON.stringify(detail.args, null, 2)} />
)}
</div>
);
}
function UrlDetail({ detail }: { detail: PermissionDetail }) {
return (
<div className="mt-2.5 space-y-2">
{detail.intention && <IntentionLine text={detail.intention} />}
{detail.url && (
<div className="flex items-center gap-1.5 rounded-md bg-zinc-800/60 px-2.5 py-1.5 text-[11px] text-blue-300">
<Globe className="size-3 shrink-0" />
<code className="min-w-0 flex-1 break-all font-mono">{detail.url}</code>
<ExternalLink className="size-3 shrink-0 text-zinc-500" />
</div>
)}
</div>
);
}
function MemoryDetail({ detail }: { detail: PermissionDetail }) {
return (
<div className="mt-2.5 space-y-1.5">
{detail.subject && (
<div className="flex items-center gap-1.5 text-[11px]">
<BookOpen className="size-3 shrink-0 text-zinc-500" />
<span className="font-medium text-zinc-300">{detail.subject}</span>
</div>
)}
{detail.fact && (
<p className="rounded-md bg-zinc-800/60 px-2.5 py-1.5 text-[11px] leading-relaxed text-zinc-300">
{detail.fact}
</p>
)}
{detail.citations && (
<p className="text-[10px] text-zinc-500">
Source: <span className="text-zinc-400">{detail.citations}</span>
</p>
)}
</div>
);
}
function CustomToolDetail({ detail }: { detail: PermissionDetail }) {
return (
<div className="mt-2.5 space-y-2">
{detail.toolDescription && (
<p className="text-[11px] text-zinc-400">{detail.toolDescription}</p>
)}
{detail.args && Object.keys(detail.args).length > 0 && (
<CollapsibleCode label="Arguments" text={JSON.stringify(detail.args, null, 2)} />
)}
</div>
);
}
function HookDetail({ detail }: { detail: PermissionDetail }) {
return (
<div className="mt-2.5 space-y-2">
{detail.hookMessage && (
<div className="flex items-start gap-1.5 rounded-md bg-amber-500/10 px-2.5 py-1.5 text-[11px] text-amber-200">
<AlertTriangle className="mt-0.5 size-3 shrink-0" />
<span>{detail.hookMessage}</span>
</div>
)}
{detail.args && Object.keys(detail.args).length > 0 && (
<CollapsibleCode label="Arguments" text={JSON.stringify(detail.args, null, 2)} />
)}
</div>
);
}
/* ── Shared primitives ──────────────────────────────────────── */
function IntentionLine({ text }: { text: string }) {
return <p className="text-[11px] italic text-zinc-400">{text}</p>;
}
function CommandBlock({ text }: { text: string }) {
return (
<pre className="overflow-x-auto rounded-md bg-zinc-900/80 px-3 py-2 font-mono text-[11px] leading-relaxed text-emerald-300">
{text}
</pre>
);
}
function DiffBlock({ text }: { text: string }) {
const lines = text.split('\n');
return (
<CollapsibleCode label="Diff" text={text} defaultExpanded>
<pre className="max-h-48 overflow-auto rounded-md bg-zinc-900/80 px-3 py-2 font-mono text-[10px] leading-relaxed">
{lines.map((line, i) => {
let color = 'text-zinc-400';
if (line.startsWith('+')) color = 'text-emerald-400';
else if (line.startsWith('-')) color = 'text-red-400';
else if (line.startsWith('@@')) color = 'text-blue-400';
return (
<div className={color} key={i}>
{line}
</div>
);
})}
</pre>
</CollapsibleCode>
);
}
function CollapsibleCode({
label,
text,
children,
defaultExpanded = false,
}: {
label: string;
text: string;
children?: React.ReactNode;
defaultExpanded?: boolean;
}) {
const [expanded, setExpanded] = useState(defaultExpanded);
return (
<div className="rounded-md border border-zinc-800/60 bg-zinc-900/40">
<button
aria-expanded={expanded}
className="flex w-full items-center gap-1.5 px-2.5 py-1.5 text-left text-[10px] font-medium text-zinc-500 hover:text-zinc-400"
onClick={() => setExpanded(!expanded)}
type="button"
>
<ChevronDown
className={`size-2.5 transition-transform ${expanded ? 'rotate-180' : ''}`}
/>
{label}
</button>
{expanded && (
<div className="border-t border-zinc-800/40 px-2.5 py-1.5">
{children ?? (
<pre className="max-h-48 overflow-auto font-mono text-[10px] leading-relaxed text-zinc-300">
{text}
</pre>
)}
</div>
)}
</div>
);
}
function MetaList({ label, items }: { label: string; items: string[] }) {
return (
<div className="text-[10px] text-zinc-500">
<span className="font-medium">{label}:</span>{' '}
<span className="text-zinc-400">{items.join(', ')}</span>
</div>
);
}
function truncate(text: string, maxLength: number): string {
return text.length <= maxLength ? text : `${text.slice(0, maxLength)}`;
}
@@ -0,0 +1,71 @@
import { useCallback } from 'react';
import { ClipboardList, X } from 'lucide-react';
import { MarkdownContent } from '@renderer/components/MarkdownContent';
import type { PendingPlanReviewRecord } from '@shared/domain/planReview';
export function PlanReviewBanner({
planReview,
onDismiss,
}: {
planReview: PendingPlanReviewRecord;
onDismiss: (planReview: PendingPlanReviewRecord) => void;
}) {
const handleDismiss = useCallback(() => {
onDismiss(planReview);
}, [planReview, onDismiss]);
return (
<div className="rounded-xl border border-emerald-500/30 bg-emerald-500/5 px-4 py-3" role="alert">
{/* Header */}
<div className="flex items-start gap-2.5">
<ClipboardList className="mt-0.5 size-4 shrink-0 text-emerald-400" />
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<span className="text-[13px] font-semibold text-emerald-200">Plan ready for review</span>
<span className="rounded-full bg-emerald-500/15 px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-emerald-400">
Plan mode
</span>
</div>
<button
aria-label="Dismiss plan"
className="rounded p-0.5 text-zinc-500 transition hover:bg-zinc-700/50 hover:text-zinc-300"
onClick={handleDismiss}
type="button"
>
<X className="size-3.5" />
</button>
</div>
{planReview.agentName && (
<div className="mt-1 text-[11px] text-zinc-400">
Agent: <span className="text-zinc-300">{planReview.agentName}</span>
</div>
)}
{/* Summary */}
{planReview.summary && (
<p className="mt-2 text-[13px] leading-relaxed text-zinc-200">
{planReview.summary}
</p>
)}
{/* Plan content (rendered markdown) */}
{planReview.planContent && (
<div className="mt-3 max-h-80 overflow-y-auto rounded-lg border border-zinc-700/50 bg-zinc-900/60 p-3">
<MarkdownContent content={planReview.planContent} />
</div>
)}
{/* Guidance */}
<p className="mt-3 text-[12px] leading-relaxed text-zinc-400">
Send a follow-up message to proceed e.g.{' '}
<span className="text-zinc-300">&quot;implement the plan&quot;</span>,{' '}
<span className="text-zinc-300">&quot;adjust step 3&quot;</span>, or ask for a different approach.
</p>
</div>
</div>
</div>
);
}
@@ -0,0 +1,89 @@
import { useEffect, useState } from 'react';
import { Bot, CheckCircle2, Loader2, XCircle } from 'lucide-react';
import type { ActiveSubagent } from '@renderer/lib/subagentTracker';
function formatElapsed(startedAt: string): string {
const seconds = Math.floor((Date.now() - new Date(startedAt).getTime()) / 1000);
if (seconds < 60) return `${seconds}s`;
const minutes = Math.floor(seconds / 60);
const remainder = seconds % 60;
return `${minutes}m ${remainder}s`;
}
function StatusIcon({ status }: { status: ActiveSubagent['status'] }) {
switch (status) {
case 'running':
return <Loader2 className="size-3.5 animate-spin text-sky-400" aria-label="Running" />;
case 'completed':
return <CheckCircle2 className="size-3.5 text-emerald-400" aria-label="Completed" />;
case 'failed':
return <XCircle className="size-3.5 text-red-400" aria-label="Failed" />;
}
}
function ElapsedTimer({ startedAt }: { startedAt: string }) {
const [elapsed, setElapsed] = useState(() => formatElapsed(startedAt));
useEffect(() => {
const id = setInterval(() => setElapsed(formatElapsed(startedAt)), 1000);
return () => clearInterval(id);
}, [startedAt]);
return (
<span className="ml-auto shrink-0 text-[10px] tabular-nums text-zinc-600">{elapsed}</span>
);
}
interface SubagentActivityCardProps {
subagent: ActiveSubagent;
}
function SubagentActivityCard({ subagent }: SubagentActivityCardProps) {
const borderClass =
subagent.status === 'running'
? 'border-sky-500/20'
: subagent.status === 'failed'
? 'border-red-500/20'
: 'border-emerald-500/20';
return (
<div
className={`flex items-center gap-2 rounded-lg border bg-zinc-900/60 px-3 py-1.5 ${borderClass}`}
role="status"
aria-label={`Sub-agent ${subagent.name}: ${subagent.activityLabel}`}
>
<StatusIcon status={subagent.status} />
<Bot className="size-3 text-zinc-500" />
<span className="text-[11px] font-medium text-zinc-300">{subagent.name}</span>
<span className="text-[10px] text-zinc-600"></span>
<span className="text-[10px] text-zinc-500">{subagent.activityLabel}</span>
{subagent.status === 'running' && <ElapsedTimer startedAt={subagent.startedAt} />}
{subagent.error && (
<span className="truncate text-[10px] text-red-400" title={subagent.error}>
{subagent.error}
</span>
)}
</div>
);
}
interface SubagentActivityListProps {
subagents: ReadonlyArray<ActiveSubagent>;
}
export function SubagentActivityList({ subagents }: SubagentActivityListProps) {
if (subagents.length === 0) return null;
// Only show running subagents in the chat stream
const visible = subagents.filter((s) => s.status === 'running');
if (visible.length === 0) return null;
return (
<div className="flex flex-col gap-1 py-1" aria-label="Active sub-agents">
{visible.map((subagent) => (
<SubagentActivityCard key={subagent.toolCallId} subagent={subagent} />
))}
</div>
);
}
@@ -0,0 +1,113 @@
import { useState, useCallback } from 'react';
import { Loader2, MessageCircleQuestion, Send } from 'lucide-react';
import type { PendingUserInputRecord } from '@shared/domain/userInput';
export function UserInputBanner({
userInput,
onSubmit,
isSubmitting,
}: {
userInput: PendingUserInputRecord;
onSubmit: (answer: string, wasFreeform: boolean) => void;
isSubmitting: boolean;
}) {
const [freeformText, setFreeformText] = useState('');
const hasChoices = userInput.choices && userInput.choices.length > 0;
const handleChoiceClick = useCallback(
(choice: string) => {
if (!isSubmitting) {
onSubmit(choice, false);
}
},
[isSubmitting, onSubmit],
);
const handleFreeformSubmit = useCallback(() => {
const trimmed = freeformText.trim();
if (trimmed && !isSubmitting) {
onSubmit(trimmed, true);
}
}, [freeformText, isSubmitting, onSubmit]);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleFreeformSubmit();
}
},
[handleFreeformSubmit],
);
return (
<div className="rounded-xl border border-blue-500/30 bg-blue-500/5 px-4 py-3" role="alert">
{/* Header */}
<div className="flex items-start gap-2.5">
<MessageCircleQuestion className="mt-0.5 size-4 shrink-0 text-blue-400" />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-[13px] font-semibold text-blue-200">Agent question</span>
<span className="rounded-full bg-blue-500/15 px-2 py-0.5 text-[9px] font-semibold uppercase tracking-wider text-blue-400">
User input
</span>
</div>
{userInput.agentName && (
<div className="mt-1 text-[11px] text-zinc-400">
Agent: <span className="text-zinc-300">{userInput.agentName}</span>
</div>
)}
<p className="mt-2 text-[13px] leading-relaxed text-zinc-200 whitespace-pre-wrap">
{userInput.question}
</p>
</div>
</div>
{/* Choices */}
{hasChoices && (
<div className="mt-3 flex flex-wrap gap-2">
{userInput.choices!.map((choice) => (
<button
className="rounded-lg border border-blue-500/30 bg-blue-500/10 px-3.5 py-1.5 text-[12px] font-medium text-blue-200 transition hover:border-blue-400/50 hover:bg-blue-500/20 hover:text-white disabled:cursor-not-allowed disabled:opacity-50"
disabled={isSubmitting}
key={choice}
onClick={() => handleChoiceClick(choice)}
type="button"
>
{choice}
</button>
))}
</div>
)}
{/* Freeform input */}
{userInput.allowFreeform && (
<div className="mt-3 flex items-center gap-2">
<input
aria-label="Type your answer"
className="min-w-0 flex-1 rounded-lg border border-zinc-700 bg-zinc-900/60 px-3 py-1.5 text-[13px] text-zinc-200 placeholder-zinc-500 outline-none transition focus:border-blue-500/50 focus:ring-1 focus:ring-blue-500/30 disabled:cursor-not-allowed disabled:opacity-50"
disabled={isSubmitting}
onChange={(e) => setFreeformText(e.target.value)}
onKeyDown={handleKeyDown}
placeholder={hasChoices ? 'Or type your own answer…' : 'Type your answer…'}
type="text"
value={freeformText}
/>
<button
aria-label="Submit answer"
className="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-3.5 py-1.5 text-[12px] font-medium text-white transition hover:bg-blue-500 disabled:cursor-not-allowed disabled:opacity-50"
disabled={isSubmitting || !freeformText.trim()}
onClick={handleFreeformSubmit}
type="button"
>
{isSubmitting ? <Loader2 className="size-3 animate-spin" /> : <Send className="size-3" />}
Send
</button>
</div>
)}
</div>
);
}
+79 -2
View File
@@ -1,9 +1,16 @@
import { CodeHighlightNode, CodeNode } from '@lexical/code';
import { $isCodeHighlightNode, CodeHighlightNode, CodeNode } from '@lexical/code';
import { AutoLinkNode, LinkNode } from '@lexical/link';
import { type Transformer, TRANSFORMERS } from '@lexical/markdown';
import { ListItemNode, ListNode } from '@lexical/list';
import { HeadingNode, QuoteNode } from '@lexical/rich-text';
import { type Klass, type LexicalNode } from 'lexical';
import {
$getSelection,
$isLineBreakNode,
$isRangeSelection,
$isTextNode,
type Klass,
type LexicalNode,
} from 'lexical';
import { normalizeChatMessageLineEndings } from '@shared/utils/chatMessage';
@@ -96,3 +103,73 @@ export function inspectMarkdownPaste(text: string): MarkdownPasteInspection {
export function shouldImportMarkdownPaste(text: string): boolean {
return inspectMarkdownPaste(text).shouldImportMarkdown;
}
/* ── Code-node selection helpers ──────────────────────── */
/**
* Returns the absolute character offset of a selection point within a CodeNode.
* LineBreakNodes count as 1 character; all other children use their text content size.
*/
export function getCodeNodeAbsoluteOffset(
codeNode: CodeNode,
point: { key: string; offset: number },
): number {
let offset = 0;
for (const child of codeNode.getChildren()) {
if (child.getKey() === point.key) return offset + point.offset;
offset += $isLineBreakNode(child) ? 1 : child.getTextContentSize();
}
return offset;
}
/**
* Converts an absolute character offset within a CodeNode into a valid Lexical
* selection point (node key, local offset, and point type).
*
* The returned point always targets either a text-like child (`type: 'text'`)
* or the parent CodeNode itself (`type: 'element'`). It never targets a
* LineBreakNode directly — doing so would crash Lexical because LineBreakNode
* is not an ElementNode.
*/
export function findCodeNodeSelectionPoint(
codeNode: CodeNode,
target: number,
): { key: string; offset: number; type: 'text' | 'element' } {
const children = codeNode.getChildren();
let offset = 0;
for (let i = 0; i < children.length; i++) {
const child = children[i];
const size = $isLineBreakNode(child) ? 1 : child.getTextContentSize();
if (offset + size > target || (offset + size === target && $isTextNode(child))) {
if ($isTextNode(child) || $isCodeHighlightNode(child)) {
return { key: child.getKey(), offset: target - offset, type: 'text' as const };
}
// Non-text child (e.g. LineBreakNode): target the parent CodeNode at this child index
return { key: codeNode.getKey(), offset: i, type: 'element' as const };
}
offset += size;
}
const last = children.length > 0 ? children[children.length - 1] : undefined;
if (last && ($isTextNode(last) || $isCodeHighlightNode(last))) {
return { key: last.getKey(), offset: last.getTextContentSize(), type: 'text' as const };
}
return { key: codeNode.getKey(), offset: children.length, type: 'element' as const };
}
/**
* Restores a range selection within a CodeNode from absolute character offsets.
* Must be called inside an editor update or read context.
*/
export function restoreCodeNodeSelection(
codeNode: CodeNode,
anchorOff: number,
focusOff: number,
): void {
const anchor = findCodeNodeSelectionPoint(codeNode, anchorOff);
const focus = findCodeNodeSelectionPoint(codeNode, focusOff);
const selection = $getSelection();
if ($isRangeSelection(selection)) {
selection.anchor.set(anchor.key, anchor.offset, anchor.type);
selection.focus.set(focus.key, focus.offset, focus.type);
}
}
-26
View File
@@ -246,32 +246,6 @@ export function removeEdge(graph: PatternGraph, removeEdgeId: string): PatternGr
return { ...graph, edges: graph.edges.filter((e) => e.id !== removeEdgeId) };
}
/* ── Add disconnected agent node ───────────────────────────── */
export function addAgentNodeToGraph(
graph: PatternGraph,
agent: PatternAgentDefinition,
): PatternGraph {
const existingAgentNodes = graph.nodes.filter((n) => n.kind === 'agent');
const nextOrder = existingAgentNodes.length;
// Place new node below existing agent nodes
const maxY = existingAgentNodes.reduce((max, n) => Math.max(max, n.position.y), 0);
const avgX = existingAgentNodes.length > 0
? Math.round(existingAgentNodes.reduce((sum, n) => sum + n.position.x, 0) / existingAgentNodes.length)
: 400;
const newNode: PatternGraphNode = {
id: `agent-node-${agent.id}`,
kind: 'agent',
agentId: agent.id,
order: nextOrder,
position: { x: avgX, y: maxY + 120 },
};
return { ...graph, nodes: [...graph.nodes, newNode] };
}
/* ── Sequential reorder ────────────────────────────────────── */
export function swapSequentialOrder(
+268
View File
@@ -1,5 +1,6 @@
import type { PatternDefinition } from '@shared/domain/pattern';
import type { SessionEventRecord } from '@shared/domain/event';
import type { QuotaSnapshot } from '@shared/contracts/sidecar';
export interface AgentActivityState {
agentId: string;
@@ -8,8 +9,15 @@ export interface AgentActivityState {
toolName?: string;
}
export interface SessionUsageState {
tokenLimit: number;
currentTokens: number;
messagesLength: number;
}
export type SessionActivityState = Record<string, AgentActivityState>;
export type SessionActivityMap = Record<string, SessionActivityState | undefined>;
export type SessionUsageMap = Record<string, SessionUsageState | undefined>;
export interface AgentActivityRow {
key: string;
@@ -184,3 +192,263 @@ function clearActiveSessionActivity(
function resolveAgentKey(event: SessionEventRecord): string | undefined {
return event.agentId?.trim() || event.agentName?.trim();
}
export function applySessionUsageEvent(
current: SessionUsageMap,
event: SessionEventRecord,
): SessionUsageMap {
if (event.kind !== 'session-usage' || event.tokenLimit === undefined || event.currentTokens === undefined) {
return current;
}
return {
...current,
[event.sessionId]: {
tokenLimit: event.tokenLimit,
currentTokens: event.currentTokens,
messagesLength: event.messagesLength ?? 0,
},
};
}
export function pruneSessionUsage(
current: SessionUsageMap,
sessionIds: Iterable<string>,
): SessionUsageMap {
const allowed = new Set(sessionIds);
const next: SessionUsageMap = {};
let changed = false;
for (const [sessionId, usage] of Object.entries(current)) {
if (!allowed.has(sessionId)) {
changed = true;
continue;
}
next[sessionId] = usage;
}
return changed || Object.keys(next).length !== Object.keys(current).length ? next : current;
}
/* ── Turn-scoped event log ──────────────────────────────── */
const TURN_EVENT_LOG_LIMIT = 50;
export interface TurnEventEntry {
kind: SessionEventRecord['kind'];
occurredAt: string;
label: string;
detail?: string;
phase?: 'start' | 'end' | 'complete';
success?: boolean;
}
export type TurnEventLog = readonly TurnEventEntry[];
export type TurnEventLogMap = Record<string, TurnEventLog | undefined>;
const hookTypeLabels: Record<string, string> = {
sessionStart: 'Session start',
sessionEnd: 'Session end',
userPromptSubmitted: 'Prompt submitted',
preToolUse: 'Pre-tool use',
postToolUse: 'Post-tool use',
errorOccurred: 'Error occurred',
};
function formatHookType(hookType: string | undefined): string {
if (!hookType) return 'Unknown';
return hookTypeLabels[hookType] ?? hookType;
}
function formatTurnEventEntry(event: SessionEventRecord): TurnEventEntry | undefined {
switch (event.kind) {
case 'subagent':
return {
kind: event.kind,
occurredAt: event.occurredAt,
label: `Sub-agent ${event.subagentEventKind ?? 'update'}: ${event.customAgentDisplayName ?? event.customAgentName ?? 'unknown'}`,
detail: event.agentName ? `from ${event.agentName}` : undefined,
phase: event.subagentEventKind === 'started' ? 'start' : event.subagentEventKind === 'completed' ? 'end' : undefined,
success: event.subagentEventKind === 'completed' ? true : event.subagentEventKind === 'failed' ? false : undefined,
};
case 'hook-lifecycle': {
const hookLabel = formatHookType(event.hookType);
const phaseLabel = event.hookPhase === 'start' ? 'started' : event.hookPhase === 'end' ? 'completed' : undefined;
return {
kind: event.kind,
occurredAt: event.occurredAt,
label: phaseLabel ? `${hookLabel} hook ${phaseLabel}` : `${hookLabel} hook`,
phase: event.hookPhase,
success: event.hookSuccess,
};
}
case 'skill-invoked':
return {
kind: event.kind,
occurredAt: event.occurredAt,
label: `Skill: ${event.skillName ?? 'unknown'}`,
detail: event.pluginName ? `via ${event.pluginName}` : undefined,
};
case 'session-compaction':
return {
kind: event.kind,
occurredAt: event.occurredAt,
label: event.compactionPhase === 'start' ? 'Context compaction started' : 'Context compaction complete',
detail: event.compactionPhase === 'complete' && event.tokensRemoved
? `${event.tokensRemoved.toLocaleString()} tokens freed`
: undefined,
phase: event.compactionPhase,
success: event.compactionSuccess,
};
default:
return undefined;
}
}
export function applyTurnEventLog(
current: TurnEventLogMap,
event: SessionEventRecord,
): TurnEventLogMap {
const entry = formatTurnEventEntry(event);
if (!entry) return current;
const existing = current[event.sessionId] ?? [];
const next = [...existing, entry].slice(-TURN_EVENT_LOG_LIMIT);
return { ...current, [event.sessionId]: next };
}
export function pruneTurnEventLogs(
current: TurnEventLogMap,
sessionIds: Iterable<string>,
): TurnEventLogMap {
const allowed = new Set(sessionIds);
const next: TurnEventLogMap = {};
let changed = false;
for (const [sessionId, log] of Object.entries(current)) {
if (!allowed.has(sessionId)) {
changed = true;
continue;
}
next[sessionId] = log;
}
return changed || Object.keys(next).length !== Object.keys(current).length ? next : current;
}
/* ── Assistant usage accumulator ────────────────────────────── */
export interface AgentUsageAccumulator {
inputTokens: number;
outputTokens: number;
cost: number;
durationMs: number;
requestCount: number;
}
export interface SessionRequestUsageState {
totalInputTokens: number;
totalOutputTokens: number;
totalCost: number;
totalDurationMs: number;
totalNanoAiu: number;
requestCount: number;
perAgent: Record<string, AgentUsageAccumulator>;
latestQuotaSnapshots?: Record<string, QuotaSnapshot>;
}
export type SessionRequestUsageMap = Record<string, SessionRequestUsageState | undefined>;
function createEmptyUsageAccumulator(): AgentUsageAccumulator {
return { inputTokens: 0, outputTokens: 0, cost: 0, durationMs: 0, requestCount: 0 };
}
export function applyAssistantUsageEvent(
current: SessionRequestUsageMap,
event: SessionEventRecord,
): SessionRequestUsageMap {
if (event.kind !== 'assistant-usage') {
return current;
}
const prev = current[event.sessionId] ?? {
totalInputTokens: 0,
totalOutputTokens: 0,
totalCost: 0,
totalDurationMs: 0,
totalNanoAiu: 0,
requestCount: 0,
perAgent: {},
};
const inputTokens = event.usageInputTokens ?? 0;
const outputTokens = event.usageOutputTokens ?? 0;
const cost = event.usageCost ?? 0;
const durationMs = event.usageDuration ?? 0;
const nanoAiu = event.usageTotalNanoAiu ?? 0;
const next: SessionRequestUsageState = {
totalInputTokens: prev.totalInputTokens + inputTokens,
totalOutputTokens: prev.totalOutputTokens + outputTokens,
totalCost: prev.totalCost + cost,
totalDurationMs: prev.totalDurationMs + durationMs,
totalNanoAiu: nanoAiu > 0 ? nanoAiu : prev.totalNanoAiu,
requestCount: prev.requestCount + 1,
perAgent: { ...prev.perAgent },
latestQuotaSnapshots: event.usageQuotaSnapshots ?? prev.latestQuotaSnapshots,
};
const agentKey = event.agentId?.trim() || event.agentName?.trim();
if (agentKey) {
const agentPrev = next.perAgent[agentKey] ?? createEmptyUsageAccumulator();
next.perAgent[agentKey] = {
inputTokens: agentPrev.inputTokens + inputTokens,
outputTokens: agentPrev.outputTokens + outputTokens,
cost: agentPrev.cost + cost,
durationMs: agentPrev.durationMs + durationMs,
requestCount: agentPrev.requestCount + 1,
};
}
return { ...current, [event.sessionId]: next };
}
export function pruneSessionRequestUsage(
current: SessionRequestUsageMap,
sessionIds: Iterable<string>,
): SessionRequestUsageMap {
const allowed = new Set(sessionIds);
const next: SessionRequestUsageMap = {};
let changed = false;
for (const [sessionId, usage] of Object.entries(current)) {
if (!allowed.has(sessionId)) {
changed = true;
continue;
}
next[sessionId] = usage;
}
return changed || Object.keys(next).length !== Object.keys(current).length ? next : current;
}
/* ── Formatting helpers ─────────────────────────────────────── */
export function formatTokenCount(tokens: number): string {
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1)}M`;
if (tokens >= 1_000) return `${(tokens / 1_000).toFixed(1)}k`;
return String(tokens);
}
export function formatNanoAiu(nanoAiu: number): string {
const aiu = nanoAiu / 1e9;
if (aiu >= 100) return aiu.toFixed(0);
if (aiu >= 10) return aiu.toFixed(1);
return aiu.toFixed(2);
}
export function formatDuration(ms: number): string {
if (ms >= 60_000) return `${(ms / 60_000).toFixed(1)}m`;
return `${(ms / 1_000).toFixed(1)}s`;
}
+9 -1
View File
@@ -112,10 +112,18 @@ function applyMessageDeltaEvent(session: SessionRecord, event: SessionEventRecor
};
}
// Auto-complete any previously pending assistant messages so only
// the new message shows the "Thinking" indicator.
const completedMessages = session.messages.map((message) =>
message.pending && message.role === 'assistant'
? { ...message, pending: false }
: message,
);
return {
...session,
messages: [
...session.messages,
...completedMessages,
{
id: event.messageId,
role: 'assistant',
+162
View File
@@ -0,0 +1,162 @@
import type { SessionEventRecord, SubagentEventKind } from '@shared/domain/event';
export interface ActiveSubagent {
toolCallId: string;
name: string;
description?: string;
model?: string;
activityLabel: string;
startedAt: string;
status: 'running' | 'completed' | 'failed';
error?: string;
}
export type ActiveSubagentMap = Record<string, ReadonlyArray<ActiveSubagent> | undefined>;
function subagentKey(event: SessionEventRecord): string {
return event.subagentToolCallId ?? event.customAgentName ?? 'unknown';
}
function subagentDisplayName(event: SessionEventRecord): string {
return event.customAgentDisplayName ?? event.customAgentName ?? 'Sub-agent';
}
function activityLabelForKind(kind: SubagentEventKind | undefined): string {
switch (kind) {
case 'started':
return 'Starting…';
case 'selected':
return 'Selected';
case 'completed':
return 'Completed';
case 'failed':
return 'Failed';
case 'deselected':
return 'Deselected';
default:
return 'Working…';
}
}
export function applySubagentEvent(
current: ActiveSubagentMap,
event: SessionEventRecord,
): ActiveSubagentMap {
if (event.kind !== 'subagent') {
// Clear all subagents when session goes idle
if (event.kind === 'status' && event.status === 'idle') {
if (!current[event.sessionId]?.length) return current;
const next = { ...current };
delete next[event.sessionId];
return next;
}
// Update running subagent activity from agent-activity events
if (event.kind === 'agent-activity' && event.agentName) {
const existing = current[event.sessionId];
if (!existing?.length) return current;
const agentName = event.agentName.trim();
const hasMatch = existing.some(
(s) => s.status === 'running' && s.name === agentName,
);
if (!hasMatch) return current;
let label: string;
switch (event.activityType) {
case 'tool-calling':
label = `Using ${event.toolName?.trim() || 'a tool'}`;
break;
case 'thinking':
label = 'Thinking…';
break;
case 'handoff':
label = 'Handling handoff…';
break;
default:
return current;
}
return {
...current,
[event.sessionId]: existing.map((s) =>
s.status === 'running' && s.name === agentName
? { ...s, activityLabel: label }
: s,
),
};
}
return current;
}
const key = subagentKey(event);
const existing = current[event.sessionId] ?? [];
switch (event.subagentEventKind) {
case 'started': {
const entry: ActiveSubagent = {
toolCallId: key,
name: subagentDisplayName(event),
description: event.customAgentDescription,
model: event.subagentModel,
activityLabel: activityLabelForKind('started'),
startedAt: event.occurredAt,
status: 'running',
};
return {
...current,
[event.sessionId]: [...existing.filter((s) => s.toolCallId !== key), entry],
};
}
case 'completed': {
return {
...current,
[event.sessionId]: existing.map((s) =>
s.toolCallId === key
? { ...s, status: 'completed' as const, activityLabel: activityLabelForKind('completed') }
: s,
),
};
}
case 'failed': {
return {
...current,
[event.sessionId]: existing.map((s) =>
s.toolCallId === key
? {
...s,
status: 'failed' as const,
activityLabel: activityLabelForKind('failed'),
error: event.subagentError,
}
: s,
),
};
}
default:
return current;
}
}
export function pruneSubagentMap(
current: ActiveSubagentMap,
sessionIds: Iterable<string>,
): ActiveSubagentMap {
const allowed = new Set(sessionIds);
const next: ActiveSubagentMap = {};
let changed = false;
for (const [sessionId, subagents] of Object.entries(current)) {
if (!allowed.has(sessionId)) {
changed = true;
continue;
}
next[sessionId] = subagents;
}
return changed || Object.keys(next).length !== Object.keys(current).length ? next : current;
}
+1 -1
View File
@@ -145,7 +145,7 @@ body {
min-height: 52px;
max-height: 200px;
overflow-y: auto;
padding: 10px 48px 10px 16px;
padding: 10px 16px 4px 16px;
font-size: 14px;
line-height: 1.6;
color: #f4f4f5;
+18
View File
@@ -7,15 +7,24 @@ export const ipcChannels = {
resolveWorkspaceDiscoveredTooling: 'workspace:resolve-discovered-tooling',
refreshProjectGitContext: 'projects:refresh-git-context',
rescanProjectConfigs: 'project:rescan-configs',
rescanProjectCustomization: 'project:rescan-customization',
resolveProjectDiscoveredTooling: 'project:resolve-discovered-tooling',
setProjectAgentProfileEnabled: 'project:set-agent-profile-enabled',
savePattern: 'patterns:save',
deletePattern: 'patterns:delete',
setPatternFavorite: 'patterns:set-favorite',
setTheme: 'settings:set-theme',
setTerminalHeight: 'settings:set-terminal-height',
saveMcpServer: 'tooling:mcp:save',
deleteMcpServer: 'tooling:mcp:delete',
saveLspProfile: 'tooling:lsp:save',
deleteLspProfile: 'tooling:lsp:delete',
describeTerminal: 'terminal:describe',
createTerminal: 'terminal:create',
restartTerminal: 'terminal:restart',
writeTerminal: 'terminal:write',
resizeTerminal: 'terminal:resize',
killTerminal: 'terminal:kill',
updateSessionTooling: 'sessions:update-tooling',
updateSessionApprovalSettings: 'sessions:update-approval-settings',
createSession: 'sessions:create',
@@ -23,9 +32,15 @@ export const ipcChannels = {
renameSession: 'sessions:rename',
setSessionPinned: 'sessions:set-pinned',
setSessionArchived: 'sessions:set-archived',
deleteSession: 'sessions:delete',
sendSessionMessage: 'sessions:send-message',
cancelSessionTurn: 'sessions:cancel-turn',
resolveSessionApproval: 'sessions:resolve-approval',
resolveSessionUserInput: 'sessions:resolve-user-input',
setSessionInteractionMode: 'sessions:set-interaction-mode',
dismissSessionPlanReview: 'sessions:dismiss-plan-review',
dismissSessionMcpAuth: 'sessions:dismiss-mcp-auth',
startSessionMcpAuth: 'sessions:start-mcp-auth',
querySessions: 'sessions:query',
updateSessionModelConfig: 'sessions:update-model-config',
selectProject: 'selection:project',
@@ -33,6 +48,9 @@ export const ipcChannels = {
selectSession: 'selection:session',
openAppDataFolder: 'troubleshooting:open-app-data-folder',
resetLocalWorkspace: 'troubleshooting:reset-local-workspace',
terminalData: 'terminal:data',
terminalExit: 'terminal:exit',
workspaceUpdated: 'workspace:updated',
sessionEvent: 'sessions:event',
getQuota: 'sidecar:get-quota',
} as const;
+71 -1
View File
@@ -1,9 +1,10 @@
import type { ApprovalDecision } from '@shared/domain/approval';
import type { SidecarCapabilities } from '@shared/contracts/sidecar';
import type { SidecarCapabilities, InteractionMode, MessageMode, QuotaSnapshot } from '@shared/contracts/sidecar';
import type { PatternDefinition, ReasoningEffort } from '@shared/domain/pattern';
import type { ProjectRecord } from '@shared/domain/project';
import type { QuerySessionsInput, SessionQueryResult } from '@shared/domain/sessionLibrary';
import type { SessionEventRecord } from '@shared/domain/event';
import type { TerminalExitInfo, TerminalSnapshot } from '@shared/domain/terminal';
import type {
LspProfileDefinition,
McpServerDefinition,
@@ -11,6 +12,7 @@ import type {
AppearanceTheme,
} from '@shared/domain/tooling';
import type { WorkspaceState } from '@shared/domain/workspace';
import type { ChatMessageAttachment } from '@shared/domain/attachment';
export interface CreateSessionInput {
projectId: string;
@@ -24,6 +26,8 @@ export interface SavePatternInput {
export interface SendSessionMessageInput {
sessionId: string;
content: string;
attachments?: ChatMessageAttachment[];
messageMode?: MessageMode;
}
export interface CancelSessionTurnInput {
@@ -34,6 +38,14 @@ export interface ResolveSessionApprovalInput {
sessionId: string;
approvalId: string;
decision: ApprovalDecision;
alwaysApprove?: boolean;
}
export interface ResolveSessionUserInputInput {
sessionId: string;
userInputId: string;
answer: string;
wasFreeform: boolean;
}
export interface UpdateSessionModelConfigInput {
@@ -80,12 +92,22 @@ export interface RescanProjectConfigsInput {
projectId: string;
}
export interface RescanProjectCustomizationInput {
projectId: string;
}
export interface ResolveProjectDiscoveredToolingInput {
projectId: string;
serverIds: string[];
resolution: DiscoveredToolingResolution;
}
export interface SetProjectAgentProfileEnabledInput {
projectId: string;
agentProfileId: string;
enabled: boolean;
}
export interface ResolveWorkspaceDiscoveredToolingInput {
serverIds: string[];
resolution: DiscoveredToolingResolution;
@@ -100,6 +122,36 @@ export interface UpdateSessionApprovalSettingsInput {
autoApprovedToolNames?: string[];
}
export interface SetSessionInteractionModeInput {
sessionId: string;
mode: InteractionMode;
}
export interface DismissSessionPlanReviewInput {
sessionId: string;
}
export interface DismissSessionMcpAuthInput {
sessionId: string;
}
export interface StartSessionMcpAuthInput {
sessionId: string;
}
export interface DeleteSessionInput {
sessionId: string;
}
export interface ResizeTerminalInput {
cols: number;
rows: number;
}
export interface SetTerminalHeightInput {
height?: number;
}
export interface ElectronApi {
describeSidecarCapabilities(): Promise<SidecarCapabilities>;
refreshSidecarCapabilities(): Promise<SidecarCapabilities>;
@@ -109,7 +161,9 @@ export interface ElectronApi {
resolveWorkspaceDiscoveredTooling(input: ResolveWorkspaceDiscoveredToolingInput): Promise<WorkspaceState>;
refreshProjectGitContext(projectId?: string): Promise<WorkspaceState>;
rescanProjectConfigs(input: RescanProjectConfigsInput): Promise<WorkspaceState>;
rescanProjectCustomization(input: RescanProjectCustomizationInput): Promise<WorkspaceState>;
resolveProjectDiscoveredTooling(input: ResolveProjectDiscoveredToolingInput): Promise<WorkspaceState>;
setProjectAgentProfileEnabled(input: SetProjectAgentProfileEnabledInput): Promise<WorkspaceState>;
savePattern(input: SavePatternInput): Promise<WorkspaceState>;
deletePattern(patternId: string): Promise<WorkspaceState>;
saveMcpServer(input: SaveMcpServerInput): Promise<WorkspaceState>;
@@ -123,9 +177,15 @@ export interface ElectronApi {
renameSession(input: RenameSessionInput): Promise<WorkspaceState>;
setSessionPinned(input: SetSessionPinnedInput): Promise<WorkspaceState>;
setSessionArchived(input: SetSessionArchivedInput): Promise<WorkspaceState>;
deleteSession(input: DeleteSessionInput): Promise<WorkspaceState>;
sendSessionMessage(input: SendSessionMessageInput): Promise<void>;
cancelSessionTurn(input: CancelSessionTurnInput): Promise<void>;
resolveSessionApproval(input: ResolveSessionApprovalInput): Promise<WorkspaceState>;
resolveSessionUserInput(input: ResolveSessionUserInputInput): Promise<WorkspaceState>;
setSessionInteractionMode(input: SetSessionInteractionModeInput): Promise<WorkspaceState>;
dismissSessionPlanReview(input: DismissSessionPlanReviewInput): Promise<WorkspaceState>;
dismissSessionMcpAuth(input: DismissSessionMcpAuthInput): Promise<WorkspaceState>;
startSessionMcpAuth(input: StartSessionMcpAuthInput): Promise<WorkspaceState>;
updateSessionModelConfig(input: UpdateSessionModelConfigInput): Promise<WorkspaceState>;
querySessions(input: QuerySessionsInput): Promise<SessionQueryResult[]>;
selectProject(projectId?: string): Promise<WorkspaceState>;
@@ -133,8 +193,18 @@ export interface ElectronApi {
selectSession(sessionId?: string): Promise<WorkspaceState>;
setPatternFavorite(input: SetPatternFavoriteInput): Promise<WorkspaceState>;
setTheme(theme: AppearanceTheme): Promise<WorkspaceState>;
setTerminalHeight(input: SetTerminalHeightInput): Promise<WorkspaceState>;
describeTerminal(): Promise<TerminalSnapshot | undefined>;
createTerminal(): Promise<TerminalSnapshot>;
restartTerminal(): Promise<TerminalSnapshot>;
killTerminal(): Promise<void>;
writeTerminal(data: string): void;
resizeTerminal(input: ResizeTerminalInput): void;
openAppDataFolder(): Promise<void>;
resetLocalWorkspace(): Promise<WorkspaceState>;
getQuota(): Promise<Record<string, QuotaSnapshot>>;
onTerminalData(listener: (data: string) => void): () => void;
onTerminalExit(listener: (info: TerminalExitInfo) => void): () => void;
onWorkspaceUpdated(listener: (workspace: WorkspaceState) => void): () => void;
onSessionEvent(listener: (event: SessionEventRecord) => void): () => void;
}
+322 -1
View File
@@ -2,6 +2,7 @@ import type { PatternDefinition, PatternValidationIssue, ReasoningEffort } from
import type { ApprovalCheckpointKind, ApprovalDecision } from '@shared/domain/approval';
import type { ChatMessageRecord } from '@shared/domain/session';
import type { RuntimeToolDefinition } from '@shared/domain/tooling';
import type { ChatMessageAttachment } from '@shared/domain/attachment';
export interface SidecarModeCapability {
available: boolean;
@@ -68,14 +69,21 @@ export interface ValidatePatternCommand {
pattern: PatternDefinition;
}
export type InteractionMode = 'interactive' | 'plan';
export type MessageMode = 'enqueue' | 'immediate';
export interface RunTurnCommand {
type: 'run-turn';
requestId: string;
sessionId: string;
projectPath: string;
workspaceKind?: 'project' | 'scratchpad';
mode?: InteractionMode;
messageMode?: MessageMode;
projectInstructions?: string;
pattern: PatternDefinition;
messages: ChatMessageRecord[];
attachments?: ChatMessageAttachment[];
tooling?: RunTurnToolingConfig;
}
@@ -90,6 +98,41 @@ export interface ResolveApprovalCommand {
requestId: string;
approvalId: string;
decision: ApprovalDecision;
alwaysApprove: boolean;
}
export interface ResolveUserInputCommand {
type: 'resolve-user-input';
requestId: string;
userInputId: string;
answer: string;
wasFreeform: boolean;
}
export interface ListSessionsCommand {
type: 'list-sessions';
requestId: string;
filter?: CopilotSessionListFilter;
}
export interface DeleteSessionCommand {
type: 'delete-session';
requestId: string;
sessionId?: string;
copilotSessionId?: string;
}
export interface DisconnectSessionCommand {
type: 'disconnect-session';
requestId: string;
sessionId: string;
}
export interface CopilotSessionListFilter {
cwd?: string;
gitRoot?: string;
repository?: string;
branch?: string;
}
export type SidecarCommand =
@@ -97,7 +140,12 @@ export type SidecarCommand =
| ValidatePatternCommand
| RunTurnCommand
| CancelTurnCommand
| ResolveApprovalCommand;
| ResolveApprovalCommand
| ResolveUserInputCommand
| ListSessionsCommand
| DeleteSessionCommand
| DisconnectSessionCommand
| GetQuotaCommand;
export interface RunTurnLocalMcpServerConfig {
id: string;
@@ -137,6 +185,30 @@ export interface RunTurnToolingConfig {
lspProfiles: RunTurnLspProfileConfig[];
}
export interface RunTurnCustomAgentConfig {
name: string;
displayName?: string;
description?: string;
tools?: string[];
prompt: string;
mcpServers?: RunTurnMcpServerConfig[];
infer?: boolean;
}
export interface RunTurnInfiniteSessionsConfig {
enabled?: boolean;
backgroundCompactionThreshold?: number;
bufferExhaustionThreshold?: number;
}
export interface PatternAgentCopilotConfig {
customAgents?: RunTurnCustomAgentConfig[];
agent?: string;
skillDirectories?: string[];
disabledSkills?: string[];
infiniteSessions?: RunTurnInfiniteSessionsConfig;
}
export interface CapabilitiesEvent {
type: 'capabilities';
requestId: string;
@@ -181,6 +253,161 @@ export interface AgentActivityEvent {
toolName?: string;
}
export type SubagentEventKind = 'started' | 'completed' | 'failed' | 'selected' | 'deselected';
export interface SubagentEvent {
type: 'subagent-event';
requestId: string;
sessionId: string;
eventKind: SubagentEventKind;
agentId?: string;
agentName?: string;
toolCallId?: string;
customAgentName?: string;
customAgentDisplayName?: string;
customAgentDescription?: string;
error?: string;
model?: string;
totalToolCalls?: number;
totalTokens?: number;
durationMs?: number;
tools?: string[];
}
export interface SkillInvokedEvent {
type: 'skill-invoked';
requestId: string;
sessionId: string;
agentId?: string;
agentName?: string;
skillName: string;
path: string;
content: string;
allowedTools?: string[];
pluginName?: string;
pluginVersion?: string;
description?: string;
}
export interface HookLifecycleEvent {
type: 'hook-lifecycle';
requestId: string;
sessionId: string;
agentId?: string;
agentName?: string;
hookInvocationId: string;
hookType: string;
phase: 'start' | 'end';
success?: boolean;
input?: unknown;
output?: unknown;
error?: string;
}
export interface SessionUsageEvent {
type: 'session-usage';
requestId: string;
sessionId: string;
agentId?: string;
agentName?: string;
tokenLimit: number;
currentTokens: number;
messagesLength: number;
systemTokens?: number;
conversationTokens?: number;
toolDefinitionsTokens?: number;
isInitial?: boolean;
}
export interface SessionCompactionEvent {
type: 'session-compaction';
requestId: string;
sessionId: string;
agentId?: string;
agentName?: string;
phase: 'start' | 'complete';
success?: boolean;
error?: string;
systemTokens?: number;
conversationTokens?: number;
toolDefinitionsTokens?: number;
preCompactionTokens?: number;
postCompactionTokens?: number;
preCompactionMessagesLength?: number;
messagesRemoved?: number;
tokensRemoved?: number;
summaryContent?: string;
checkpointNumber?: number;
checkpointPath?: string;
}
export interface PendingMessagesModifiedEvent {
type: 'pending-messages-modified';
requestId: string;
sessionId: string;
agentId?: string;
agentName?: string;
}
export interface CopilotSessionInfo {
copilotSessionId: string;
managedByAryx: boolean;
sessionId?: string;
agentId?: string;
startTime: string;
modifiedTime: string;
summary?: string;
isRemote: boolean;
cwd?: string;
gitRoot?: string;
repository?: string;
branch?: string;
}
export interface SessionsListedEvent {
type: 'sessions-listed';
requestId: string;
sessions: CopilotSessionInfo[];
}
export interface SessionsDeletedEvent {
type: 'sessions-deleted';
requestId: string;
sessionId?: string;
sessions: CopilotSessionInfo[];
}
export interface SessionDisconnectedEvent {
type: 'session-disconnected';
requestId: string;
sessionId: string;
cancelledRequestIds: string[];
}
export interface PermissionDetail {
kind: string;
intention?: string;
command?: string;
warning?: string;
possiblePaths?: string[];
possibleUrls?: string[];
hasWriteFileRedirection?: boolean;
fileName?: string;
diff?: string;
newFileContents?: string;
path?: string;
serverName?: string;
toolTitle?: string;
args?: Record<string, unknown>;
readOnly?: boolean;
url?: string;
subject?: string;
fact?: string;
citations?: string;
toolDescription?: string;
hookMessage?: string;
}
export interface ApprovalRequestedEvent {
type: 'approval-requested';
requestId: string;
@@ -193,6 +420,49 @@ export interface ApprovalRequestedEvent {
permissionKind?: string;
title: string;
detail?: string;
permissionDetail?: PermissionDetail;
}
export interface UserInputRequestedEvent {
type: 'user-input-requested';
requestId: string;
sessionId: string;
userInputId: string;
agentId?: string;
agentName?: string;
question: string;
choices?: string[];
allowFreeform?: boolean;
}
export interface McpOauthStaticClientConfigEvent {
clientId: string;
publicClient?: boolean;
}
export interface McpOauthRequiredEvent {
type: 'mcp-oauth-required';
requestId: string;
sessionId: string;
oauthRequestId: string;
agentId?: string;
agentName?: string;
serverName: string;
serverUrl: string;
staticClientConfig?: McpOauthStaticClientConfigEvent;
}
export interface ExitPlanModeRequestedEvent {
type: 'exit-plan-mode-requested';
requestId: string;
sessionId: string;
exitPlanId: string;
agentId?: string;
agentName?: string;
summary: string;
planContent: string;
actions?: string[];
recommendedAction?: string;
}
export interface CommandErrorEvent {
@@ -201,6 +471,43 @@ export interface CommandErrorEvent {
message: string;
}
export interface AssistantUsageEvent {
type: 'assistant-usage';
requestId: string;
sessionId: string;
agentId?: string;
agentName?: string;
model: string;
inputTokens?: number;
outputTokens?: number;
cacheReadTokens?: number;
cacheWriteTokens?: number;
cost?: number;
duration?: number;
totalNanoAiu?: number;
quotaSnapshots?: Record<string, QuotaSnapshot>;
}
export interface QuotaSnapshot {
entitlementRequests: number;
usedRequests: number;
remainingPercentage: number;
overage: number;
overageAllowedWithExhaustedQuota: boolean;
resetDate?: string;
}
export interface GetQuotaCommand {
type: 'get-quota';
requestId: string;
}
export interface QuotaResultEvent {
type: 'quota-result';
requestId: string;
quotaSnapshots: Record<string, QuotaSnapshot>;
}
export interface CommandCompleteEvent {
type: 'command-complete';
requestId: string;
@@ -212,6 +519,20 @@ export type SidecarEvent =
| TurnDeltaEvent
| TurnCompleteEvent
| AgentActivityEvent
| SubagentEvent
| SkillInvokedEvent
| HookLifecycleEvent
| SessionUsageEvent
| SessionCompactionEvent
| PendingMessagesModifiedEvent
| ApprovalRequestedEvent
| UserInputRequestedEvent
| McpOauthRequiredEvent
| ExitPlanModeRequestedEvent
| SessionsListedEvent
| SessionsDeletedEvent
| SessionDisconnectedEvent
| AssistantUsageEvent
| QuotaResultEvent
| CommandErrorEvent
| CommandCompleteEvent;
+26
View File
@@ -1,3 +1,5 @@
import type { PermissionDetail } from '@shared/contracts/sidecar';
export type ApprovalCheckpointKind = 'tool-call' | 'final-response';
export type ApprovalStatus = 'pending' | 'approved' | 'rejected';
export type ApprovalDecision = Exclude<ApprovalStatus, 'pending'>;
@@ -35,6 +37,7 @@ export interface PendingApprovalRecord {
title: string;
detail?: string;
messages?: PendingApprovalMessageRecord[];
permissionDetail?: PermissionDetail;
}
export interface PendingApprovalState {
@@ -190,6 +193,28 @@ export function approvalPolicyRequiresCheckpoint(
return rule.agentIds.includes(normalizedAgentId);
}
const runtimePermissionKinds: ReadonlySet<string> = new Set(['read', 'write', 'shell', 'memory', 'url']);
/**
* Resolves the canonical approval key for a pending approval.
*
* Runtime tools always use their permission-kind category (`read`, `write`, `shell`)
* mapped to the corresponding approval-tool id. MCP/custom/hook tools use their
* specific tool name.
*/
export function resolveApprovalToolKey(
toolName: string | undefined,
permissionKind: string | undefined,
): string | undefined {
if (permissionKind && runtimePermissionKinds.has(permissionKind)) {
if (permissionKind === 'memory') return 'store_memory';
if (permissionKind === 'url') return 'web_fetch';
return permissionKind;
}
return toolName;
}
export function approvalPolicyAutoApprovesTool(
policy: ApprovalPolicy | undefined,
toolName?: string,
@@ -290,6 +315,7 @@ export function normalizePendingApproval(
title,
detail: normalizeOptionalString(approval?.detail),
messages: normalizePendingApprovalMessages(approval?.messages),
permissionDetail: approval?.permissionDetail,
};
}
+42
View File
@@ -0,0 +1,42 @@
export type ChatMessageAttachmentType = 'file' | 'blob';
export interface ChatMessageAttachment {
type: ChatMessageAttachmentType;
path?: string;
data?: string;
mimeType?: string;
displayName?: string;
}
const supportedImageMimeTypes = new Set([
'image/jpeg',
'image/png',
'image/gif',
'image/webp',
]);
export function isImageAttachment(attachment: ChatMessageAttachment): boolean {
if (attachment.mimeType) {
return supportedImageMimeTypes.has(attachment.mimeType);
}
if (attachment.path) {
const ext = attachment.path.split('.').pop()?.toLowerCase();
return ext === 'jpg' || ext === 'jpeg' || ext === 'png' || ext === 'gif' || ext === 'webp';
}
return false;
}
export function getAttachmentDisplayName(attachment: ChatMessageAttachment): string {
if (attachment.displayName) {
return attachment.displayName;
}
if (attachment.path) {
const parts = attachment.path.replace(/\\/g, '/').split('/');
return parts[parts.length - 1] || attachment.path;
}
return attachment.mimeType ?? 'Attachment';
}
+2
View File
@@ -7,6 +7,7 @@ export interface BaseDiscoveredMcpServer {
name: string;
transport: DiscoveredMcpServerTransport;
tools: string[];
probedTools?: { name: string; description?: string }[];
timeoutMs?: number;
scope: DiscoveredToolingScope;
scannerId: string;
@@ -121,6 +122,7 @@ export function mergeDiscoveredToolingState(
return {
...server,
status: existing.status,
probedTools: existing.probedTools,
} satisfies DiscoveredMcpServer;
}
+55 -1
View File
@@ -1,5 +1,7 @@
import type { SessionRunRecord } from '@shared/domain/runTimeline';
import type { QuotaSnapshot } from '@shared/contracts/sidecar';
export type SessionActivityType = 'thinking' | 'tool-calling' | 'handoff' | 'completed';
export type SessionEventKind =
@@ -8,7 +10,16 @@ export type SessionEventKind =
| 'message-complete'
| 'agent-activity'
| 'run-updated'
| 'error';
| 'error'
| 'subagent'
| 'skill-invoked'
| 'hook-lifecycle'
| 'session-usage'
| 'session-compaction'
| 'pending-messages-modified'
| 'assistant-usage';
export type SubagentEventKind = 'started' | 'completed' | 'failed' | 'selected' | 'deselected';
export interface SessionEventRecord {
sessionId: string;
@@ -27,4 +38,47 @@ export interface SessionEventRecord {
toolName?: string;
run?: SessionRunRecord;
error?: string;
// Subagent event fields
subagentEventKind?: SubagentEventKind;
customAgentName?: string;
customAgentDisplayName?: string;
customAgentDescription?: string;
subagentError?: string;
subagentToolCallId?: string;
subagentModel?: string;
// Skill invoked fields
skillName?: string;
skillPath?: string;
pluginName?: string;
// Hook lifecycle fields
hookInvocationId?: string;
hookType?: string;
hookPhase?: 'start' | 'end';
hookSuccess?: boolean;
// Session usage fields
tokenLimit?: number;
currentTokens?: number;
messagesLength?: number;
// Session compaction fields
compactionPhase?: 'start' | 'complete';
compactionSuccess?: boolean;
preCompactionTokens?: number;
postCompactionTokens?: number;
tokensRemoved?: number;
// Assistant usage fields
usageModel?: string;
usageInputTokens?: number;
usageOutputTokens?: number;
usageCacheReadTokens?: number;
usageCacheWriteTokens?: number;
usageCost?: number;
usageDuration?: number;
usageTotalNanoAiu?: number;
usageQuotaSnapshots?: Record<string, QuotaSnapshot>;
}
+19
View File
@@ -0,0 +1,19 @@
export type McpAuthStatus = 'pending' | 'authenticating' | 'authenticated' | 'failed';
export interface McpOauthStaticClientConfig {
clientId: string;
publicClient?: boolean;
}
export interface PendingMcpAuthRecord {
id: string;
status: McpAuthStatus;
agentId?: string;
agentName?: string;
serverName: string;
serverUrl: string;
staticClientConfig?: McpOauthStaticClientConfig;
requestedAt: string;
completedAt?: string;
errorMessage?: string;
}
+226
View File
@@ -32,6 +32,8 @@ export const reasoningEffortOptions: ReadonlyArray<{ value: ReasoningEffort; lab
{ value: 'xhigh', label: 'Maximum' },
];
import type { PatternAgentCopilotConfig } from '@shared/contracts/sidecar';
export interface PatternAgentDefinition {
id: string;
name: string;
@@ -39,6 +41,7 @@ export interface PatternAgentDefinition {
instructions: string;
model: string;
reasoningEffort?: ReasoningEffort;
copilot?: PatternAgentCopilotConfig;
}
export interface PatternGraphPosition {
@@ -311,6 +314,229 @@ export function createDefaultPatternGraph(
}
}
function sortAgentNodesByOrder(nodes: ReadonlyArray<PatternGraphNode>): PatternGraphNode[] {
return nodes
.filter((node) => node.kind === 'agent')
.slice()
.sort((left, right) =>
(left.order ?? Number.MAX_SAFE_INTEGER) - (right.order ?? Number.MAX_SAFE_INTEGER)
|| left.id.localeCompare(right.id));
}
function renumberAgentOrders(nodes: ReadonlyArray<PatternGraphNode>): PatternGraphNode[] {
const orders = new Map(sortAgentNodesByOrder(nodes).map((node, index) => [node.id, index]));
return nodes.map((node) =>
node.kind === 'agent'
? { ...node, order: orders.get(node.id) ?? node.order ?? 0 }
: node);
}
function getNextAgentNodePosition(graph: PatternGraph): PatternGraphPosition {
const existingAgentNodes = getAgentNodes(graph);
const maxY = existingAgentNodes.reduce((max, node) => Math.max(max, node.position.y), 0);
const avgX = existingAgentNodes.length > 0
? Math.round(existingAgentNodes.reduce((sum, node) => sum + node.position.x, 0) / existingAgentNodes.length)
: 400;
return {
x: avgX,
y: maxY + 120,
};
}
function addUniqueEdge(
edges: ReadonlyArray<PatternGraphEdge>,
source: string | undefined,
target: string | undefined,
): PatternGraphEdge[] {
if (!source || !target || edges.some((edge) => edge.source === source && edge.target === target)) {
return [...edges];
}
return [...edges, createEdge(source, target)];
}
function removeEdgesConnectedToNode(
edges: ReadonlyArray<PatternGraphEdge>,
nodeId: string,
): PatternGraphEdge[] {
return edges.filter((edge) => edge.source !== nodeId && edge.target !== nodeId);
}
function findAgentNode(graph: PatternGraph, agentId: string): PatternGraphNode | undefined {
return graph.nodes.find((node) => node.kind === 'agent' && node.agentId === agentId);
}
function resolveEntryAgentNodeId(graph: PatternGraph): string | undefined {
const { outgoing } = buildAdjacency(graph);
const agentNodeIds = new Set(getAgentNodes(graph).map((node) => node.id));
const directEntry = (outgoing.get(SYSTEM_NODE_IDS.userInput) ?? [])
.map((edge) => edge.target)
.find((nodeId) => agentNodeIds.has(nodeId));
return directEntry ?? sortAgentNodesByOrder(graph.nodes)[0]?.id;
}
function hasAgentToAgentRoute(graph: PatternGraph): boolean {
const agentNodeIds = new Set(getAgentNodes(graph).map((node) => node.id));
return graph.edges.some((edge) =>
agentNodeIds.has(edge.source)
&& agentNodeIds.has(edge.target)
&& edge.source !== edge.target);
}
export function addAgentToGraph(
graph: PatternGraph,
mode: OrchestrationMode,
agent: PatternAgentDefinition,
): PatternGraph {
if (mode === 'single') {
throw new Error('Single-agent chat requires exactly one agent.');
}
if (findAgentNode(graph, agent.id)) {
return graph;
}
const existingAgentNodes = sortAgentNodesByOrder(graph.nodes);
const newNode = createAgentNode(
agent,
existingAgentNodes.length,
getNextAgentNodePosition(graph),
);
let nextEdges = [...graph.edges];
switch (mode) {
case 'sequential':
case 'magentic': {
const outputNode = getNodeByKind(graph, 'user-output');
const inputNode = getNodeByKind(graph, 'user-input');
const { incoming } = buildAdjacency(graph);
const previousNodeId = (outputNode ? incoming.get(outputNode.id)?.[0]?.source : undefined)
?? existingAgentNodes[existingAgentNodes.length - 1]?.id
?? inputNode?.id;
if (outputNode && previousNodeId) {
nextEdges = nextEdges.filter((edge) => !(edge.source === previousNodeId && edge.target === outputNode.id));
nextEdges = addUniqueEdge(nextEdges, previousNodeId, newNode.id);
nextEdges = addUniqueEdge(nextEdges, newNode.id, outputNode.id);
}
break;
}
case 'concurrent': {
const distributorNode = getNodeByKind(graph, 'distributor');
const collectorNode = getNodeByKind(graph, 'collector');
nextEdges = addUniqueEdge(nextEdges, distributorNode?.id, newNode.id);
nextEdges = addUniqueEdge(nextEdges, newNode.id, collectorNode?.id);
break;
}
case 'handoff': {
const inputNode = getNodeByKind(graph, 'user-input');
const outputNode = getNodeByKind(graph, 'user-output');
const entryNodeId = resolveEntryAgentNodeId(graph);
if (entryNodeId) {
nextEdges = addUniqueEdge(nextEdges, entryNodeId, newNode.id);
nextEdges = addUniqueEdge(nextEdges, newNode.id, entryNodeId);
} else {
nextEdges = addUniqueEdge(nextEdges, inputNode?.id, newNode.id);
}
nextEdges = addUniqueEdge(nextEdges, newNode.id, outputNode?.id);
break;
}
case 'group-chat': {
const orchestratorNode = getNodeByKind(graph, 'orchestrator');
nextEdges = addUniqueEdge(nextEdges, orchestratorNode?.id, newNode.id);
nextEdges = addUniqueEdge(nextEdges, newNode.id, orchestratorNode?.id);
break;
}
default:
break;
}
return {
nodes: renumberAgentOrders([...graph.nodes, newNode]),
edges: nextEdges,
};
}
export function removeAgentFromGraph(
graph: PatternGraph,
mode: OrchestrationMode,
agentId: string,
): PatternGraph {
const nodeToRemove = findAgentNode(graph, agentId);
if (!nodeToRemove) {
return graph;
}
const originalAgentNodes = sortAgentNodesByOrder(graph.nodes);
if (mode === 'single' && originalAgentNodes.length <= 1) {
throw new Error('Single-agent chat requires exactly one agent.');
}
const { incoming, outgoing } = buildAdjacency(graph);
const removedWasEntry = (outgoing.get(SYSTEM_NODE_IDS.userInput) ?? []).some(
(edge) => edge.target === nodeToRemove.id,
);
const remainingNodes = graph.nodes.filter((node) => node.id !== nodeToRemove.id);
let nextEdges = removeEdgesConnectedToNode(graph.edges, nodeToRemove.id);
switch (mode) {
case 'sequential':
case 'magentic': {
const predecessorId = incoming.get(nodeToRemove.id)?.[0]?.source;
const successorId = outgoing.get(nodeToRemove.id)?.[0]?.target;
nextEdges = addUniqueEdge(
nextEdges,
predecessorId && predecessorId !== nodeToRemove.id ? predecessorId : undefined,
successorId && successorId !== nodeToRemove.id ? successorId : undefined,
);
break;
}
case 'handoff': {
const remainingGraph: PatternGraph = { nodes: remainingNodes, edges: nextEdges };
const remainingAgentNodes = sortAgentNodesByOrder(remainingNodes);
const outputNode = getNodeByKind(remainingGraph, 'user-output');
const entryNodeId = resolveEntryAgentNodeId(remainingGraph) ?? remainingAgentNodes[0]?.id;
if (entryNodeId) {
const { outgoing: remainingOutgoing, incoming: remainingIncoming } = buildAdjacency(remainingGraph);
if ((remainingOutgoing.get(SYSTEM_NODE_IDS.userInput)?.length ?? 0) === 0) {
nextEdges = addUniqueEdge(nextEdges, SYSTEM_NODE_IDS.userInput, entryNodeId);
}
if (removedWasEntry || (remainingIncoming.get(outputNode?.id ?? '')?.length ?? 0) === 0) {
nextEdges = addUniqueEdge(nextEdges, entryNodeId, outputNode?.id);
}
if (remainingAgentNodes.length > 1 && (removedWasEntry || !hasAgentToAgentRoute(remainingGraph))) {
for (const specialistNode of remainingAgentNodes) {
if (specialistNode.id === entryNodeId) {
continue;
}
nextEdges = addUniqueEdge(nextEdges, entryNodeId, specialistNode.id);
nextEdges = addUniqueEdge(nextEdges, specialistNode.id, entryNodeId);
nextEdges = addUniqueEdge(nextEdges, specialistNode.id, outputNode?.id);
}
}
}
break;
}
case 'concurrent':
case 'group-chat':
default:
break;
}
return {
nodes: renumberAgentOrders(remainingNodes),
edges: nextEdges,
};
}
export function resolvePatternGraph(pattern: PatternDefinition): PatternGraph {
return pattern.graph ?? createDefaultPatternGraph(pattern);
}
+14
View File
@@ -0,0 +1,14 @@
export type PlanReviewStatus = 'pending' | 'acted';
export interface PendingPlanReviewRecord {
id: string;
status: PlanReviewStatus;
agentId?: string;
agentName?: string;
summary: string;
planContent: string;
actions?: string[];
recommendedAction?: string;
requestedAt: string;
actedAt?: string;
}
+2
View File
@@ -1,5 +1,6 @@
import { nowIso } from '@shared/utils/ids';
import type { ProjectDiscoveredTooling } from '@shared/domain/discoveredTooling';
import type { ProjectCustomizationState } from '@shared/domain/projectCustomization';
export type ProjectGitContextStatus = 'ready' | 'not-repository' | 'git-missing' | 'error';
@@ -39,6 +40,7 @@ export interface ProjectRecord {
addedAt: string;
git?: ProjectGitContext;
discoveredTooling?: ProjectDiscoveredTooling;
customization?: ProjectCustomizationState;
}
export const SCRATCHPAD_PROJECT_ID = 'project-scratchpad';
+276
View File
@@ -0,0 +1,276 @@
export interface ProjectInstructionFile {
id: string;
sourcePath: string;
content: string;
}
export interface ProjectAgentProfileMcpServerConfig {
[key: string]: unknown;
}
export interface ProjectAgentProfile {
id: string;
name: string;
displayName?: string;
description?: string;
tools?: string[];
prompt: string;
mcpServers?: Record<string, ProjectAgentProfileMcpServerConfig>;
infer?: boolean;
sourcePath: string;
enabled: boolean;
}
export interface ProjectPromptVariable {
name: string;
placeholder: string;
}
export interface ProjectPromptFile {
id: string;
name: string;
description?: string;
agent?: string;
template: string;
variables: ProjectPromptVariable[];
sourcePath: string;
}
export interface ProjectCustomizationState {
instructions: ProjectInstructionFile[];
agentProfiles: ProjectAgentProfile[];
promptFiles: ProjectPromptFile[];
lastScannedAt?: string;
}
export function createProjectCustomizationState(): ProjectCustomizationState {
return {
instructions: [],
agentProfiles: [],
promptFiles: [],
};
}
export function normalizeProjectCustomizationState(
value?: Partial<ProjectCustomizationState>,
): ProjectCustomizationState {
return {
instructions: (value?.instructions ?? [])
.map(normalizeProjectInstructionFile)
.filter((instruction) => instruction.content.length > 0)
.sort(compareProjectFiles),
agentProfiles: (value?.agentProfiles ?? [])
.map(normalizeProjectAgentProfile)
.filter((profile) => profile.name.length > 0 && profile.prompt.length > 0)
.sort(compareProjectFiles),
promptFiles: (value?.promptFiles ?? [])
.map(normalizeProjectPromptFile)
.filter((promptFile) => promptFile.name.length > 0 && promptFile.template.length > 0)
.sort(compareProjectFiles),
lastScannedAt: normalizeOptionalString(value?.lastScannedAt),
};
}
export function mergeProjectCustomizationState(
current: ProjectCustomizationState | undefined,
scanned: Omit<ProjectCustomizationState, 'lastScannedAt'>,
lastScannedAt: string,
): ProjectCustomizationState {
const normalizedCurrent = normalizeProjectCustomizationState(current);
const currentProfilesById = new Map(
normalizedCurrent.agentProfiles.map((profile) => [profile.id, profile]),
);
return {
instructions: scanned.instructions
.map(normalizeProjectInstructionFile)
.filter((instruction) => instruction.content.length > 0)
.sort(compareProjectFiles),
agentProfiles: scanned.agentProfiles
.map(normalizeProjectAgentProfile)
.filter((profile) => profile.name.length > 0 && profile.prompt.length > 0)
.map((profile) => ({
...profile,
enabled: currentProfilesById.get(profile.id)?.enabled ?? profile.enabled,
}))
.sort(compareProjectFiles),
promptFiles: scanned.promptFiles
.map(normalizeProjectPromptFile)
.filter((promptFile) => promptFile.name.length > 0 && promptFile.template.length > 0)
.sort(compareProjectFiles),
lastScannedAt,
};
}
export function listEnabledProjectAgentProfiles(
state?: Partial<ProjectCustomizationState>,
): ProjectAgentProfile[] {
return normalizeProjectCustomizationState(state).agentProfiles.filter((profile) => profile.enabled);
}
export function resolveProjectInstructionsContent(
state?: Partial<ProjectCustomizationState>,
): string | undefined {
const content = normalizeProjectCustomizationState(state).instructions
.map((instruction) => instruction.content)
.filter((value) => value.length > 0)
.join('\n\n')
.trim();
return content.length > 0 ? content : undefined;
}
export function setProjectAgentProfileEnabled(
state: ProjectCustomizationState | undefined,
agentProfileId: string,
enabled: boolean,
): ProjectCustomizationState {
const normalizedState = normalizeProjectCustomizationState(state);
return {
...normalizedState,
agentProfiles: normalizedState.agentProfiles.map((profile) =>
profile.id === agentProfileId
? {
...profile,
enabled,
}
: profile),
};
}
function normalizeProjectInstructionFile(file: ProjectInstructionFile): ProjectInstructionFile {
return {
id: file.id.trim(),
sourcePath: normalizePathLikeString(file.sourcePath),
content: file.content.trim(),
};
}
function normalizeProjectAgentProfile(profile: ProjectAgentProfile): ProjectAgentProfile {
const tools = normalizeOptionalStringArray(profile.tools);
const normalizedProfile: ProjectAgentProfile = {
id: profile.id.trim(),
name: profile.name.trim(),
prompt: profile.prompt.trim(),
sourcePath: normalizePathLikeString(profile.sourcePath),
enabled: profile.enabled !== false,
};
const displayName = normalizeOptionalString(profile.displayName);
if (displayName) {
normalizedProfile.displayName = displayName;
}
const description = normalizeOptionalString(profile.description);
if (description) {
normalizedProfile.description = description;
}
if (tools) {
normalizedProfile.tools = tools;
}
const mcpServers = normalizeOptionalMcpServers(profile.mcpServers);
if (mcpServers) {
normalizedProfile.mcpServers = mcpServers;
}
if (typeof profile.infer === 'boolean') {
normalizedProfile.infer = profile.infer;
}
return normalizedProfile;
}
function normalizeProjectPromptFile(promptFile: ProjectPromptFile): ProjectPromptFile {
const normalizedPromptFile: ProjectPromptFile = {
id: promptFile.id.trim(),
name: promptFile.name.trim(),
template: promptFile.template.trim(),
variables: promptFile.variables
.map((variable) => ({
name: variable.name.trim(),
placeholder: variable.placeholder.trim(),
}))
.filter((variable) => variable.name.length > 0),
sourcePath: normalizePathLikeString(promptFile.sourcePath),
};
const description = normalizeOptionalString(promptFile.description);
if (description) {
normalizedPromptFile.description = description;
}
const agent = normalizeOptionalString(promptFile.agent);
if (agent) {
normalizedPromptFile.agent = agent;
}
return normalizedPromptFile;
}
function compareProjectFiles(
left: Pick<ProjectInstructionFile | ProjectAgentProfile | ProjectPromptFile, 'sourcePath' | 'id'>,
right: Pick<ProjectInstructionFile | ProjectAgentProfile | ProjectPromptFile, 'sourcePath' | 'id'>,
): number {
return left.sourcePath.localeCompare(right.sourcePath) || left.id.localeCompare(right.id);
}
function normalizeOptionalMcpServers(
value?: Record<string, ProjectAgentProfileMcpServerConfig>,
): Record<string, ProjectAgentProfileMcpServerConfig> | undefined {
if (!value) {
return undefined;
}
const normalizedEntries = Object.entries(value)
.map(([name, config]) => [name.trim(), normalizeYamlValue(config)] as const)
.filter(([name, config]) => name.length > 0 && isPlainObject(config))
.sort(([leftName], [rightName]) => leftName.localeCompare(rightName));
if (normalizedEntries.length === 0) {
return undefined;
}
return Object.fromEntries(
normalizedEntries.map(([name, config]) => [name, config as ProjectAgentProfileMcpServerConfig]),
);
}
function normalizeOptionalString(value?: string): string | undefined {
const trimmed = value?.trim();
return trimmed ? trimmed : undefined;
}
function normalizeOptionalStringArray(values?: ReadonlyArray<string>): string[] | undefined {
if (!values) {
return undefined;
}
return [...new Set(values.map((value) => value.trim()).filter((value) => value.length > 0))];
}
function normalizePathLikeString(value: string): string {
return value.trim().replaceAll('/', '\\');
}
function normalizeYamlValue(value: unknown): unknown {
if (Array.isArray(value)) {
return value.map(normalizeYamlValue);
}
if (!isPlainObject(value)) {
return typeof value === 'string' ? value.trim() : value;
}
return Object.fromEntries(
Object.entries(value)
.map(([key, nestedValue]) => [key.trim(), normalizeYamlValue(nestedValue)] as const)
.filter(([key]) => key.length > 0)
.sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)),
);
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value);
}
+11
View File
@@ -11,6 +11,11 @@ import {
type SessionApprovalSettings,
} from '@shared/domain/approval';
import type { SessionRunRecord } from '@shared/domain/runTimeline';
import type { PendingUserInputRecord } from '@shared/domain/userInput';
import type { PendingPlanReviewRecord } from '@shared/domain/planReview';
import type { PendingMcpAuthRecord } from '@shared/domain/mcpAuth';
import type { ChatMessageAttachment } from '@shared/domain/attachment';
import type { InteractionMode } from '@shared/contracts/sidecar';
export type ChatRole = 'system' | 'user' | 'assistant';
export type SessionStatus = 'idle' | 'running' | 'error';
@@ -28,6 +33,7 @@ export interface ChatMessageRecord {
content: string;
createdAt: string;
pending?: boolean;
attachments?: ChatMessageAttachment[];
}
export interface SessionRecord {
@@ -41,6 +47,8 @@ export interface SessionRecord {
status: SessionStatus;
isPinned?: boolean;
isArchived?: boolean;
interactionMode?: InteractionMode;
cwd?: string;
messages: ChatMessageRecord[];
lastError?: string;
sessionModelConfig?: SessionModelConfig;
@@ -48,6 +56,9 @@ export interface SessionRecord {
approvalSettings?: SessionApprovalSettings;
pendingApproval?: PendingApprovalRecord;
pendingApprovalQueue?: PendingApprovalRecord[];
pendingUserInput?: PendingUserInputRecord;
pendingPlanReview?: PendingPlanReviewRecord;
pendingMcpAuth?: PendingMcpAuthRecord;
runs: SessionRunRecord[];
}
+12
View File
@@ -0,0 +1,12 @@
export interface TerminalSnapshot {
cwd: string;
shell: string;
pid: number;
cols: number;
rows: number;
}
export interface TerminalExitInfo {
exitCode: number;
signal?: number;
}
+198 -16
View File
@@ -9,11 +9,17 @@ import { nowIso } from '@shared/utils/ids';
export type McpServerTransport = 'local' | 'http' | 'sse';
export interface McpProbedTool {
name: string;
description?: string;
}
export interface BaseMcpServerDefinition {
id: string;
name: string;
transport: McpServerTransport;
tools: string[];
probedTools?: McpProbedTool[];
timeoutMs?: number;
createdAt: string;
updatedAt: string;
@@ -57,6 +63,7 @@ export interface WorkspaceSettings {
theme: AppearanceTheme;
tooling: WorkspaceToolingSettings;
discoveredUserTooling: DiscoveredToolingState;
terminalHeight?: number;
}
export interface SessionToolingSelection {
@@ -89,17 +96,72 @@ const lspApprovalOperations = [
{ suffix: 'references', label: 'References' },
] as const;
// Fallback runtime tools used before sidecar capabilities are loaded or when the
// CLI cannot report its built-in tool catalog dynamically.
// Human-readable labels for built-in runtime tools.
// Both bash and powershell variants are included for forward compatibility.
const builtinToolLabels: ReadonlyMap<string, string> = new Map([
// Permission-kind approval categories (used by sidecar for runtime tool session approval)
['shell', 'Shell commands'],
['read', 'Read files'],
['write', 'Write files'],
// Shell tools
['bash', 'Execute shell commands'],
['powershell', 'Execute shell commands'],
['read_bash', 'Read shell output'],
['read_powershell', 'Read shell output'],
['write_bash', 'Write shell input'],
['write_powershell', 'Write shell input'],
['stop_bash', 'Stop shell session'],
['stop_powershell', 'Stop shell session'],
['list_bash', 'List shell sessions'],
['list_powershell', 'List shell sessions'],
// File tools
['view', 'View files'],
['create', 'Create files'],
['edit', 'Edit files'],
['apply_patch', 'Apply patch'],
// Search tools
['grep', 'Search file contents'],
['rg', 'Search file contents'],
['glob', 'Find files by pattern'],
// Agent tools
['task', 'Run sub-agent'],
['read_agent', 'Read agent results'],
['list_agents', 'List agents'],
// Web tools
['web_fetch', 'Fetch web content'],
['web_search', 'Search the web'],
// Other tools
['skill', 'Invoke skill'],
['show_file', 'Show file'],
['fetch_copilot_cli_documentation', 'Fetch CLI docs'],
['update_todo', 'Update checklist'],
['store_memory', 'Store memory'],
['sql', 'Query session data'],
['lsp', 'Language server'],
]);
export function resolveToolLabel(toolId: string): string {
return builtinToolLabels.get(toolId) ?? toolId;
}
// Fallback approval tool categories for runtime tools. The approval UI groups
// built-in tools by permission category (read, write, shell, web, memory) rather
// than listing 20+ individual tools, matching other coding agents (Copilot CLI,
// Cline, Roo Code, etc.).
const fallbackRuntimeApprovalTools: ReadonlyArray<RuntimeToolDefinition> = [
{ id: 'glob', label: 'glob', description: 'Match files by glob pattern.' },
{ id: 'lsp', label: 'lsp', description: 'Query configured language servers.' },
{ id: 'rg', label: 'rg', description: 'Search file contents with ripgrep.' },
{ id: 'view', label: 'view', description: 'Read files and list directories.' },
{ id: 'web_fetch', label: 'web_fetch', description: 'Fetch content from a URL.' },
{ id: 'web_search', label: 'web_search', description: 'Search the web for current information.' },
{ id: 'read', label: 'Read files' },
{ id: 'write', label: 'Write files' },
{ id: 'shell', label: 'Shell commands' },
{ id: 'web_fetch', label: 'Web access' },
{ id: 'store_memory', label: 'Store memory' },
];
const MCP_SERVER_APPROVAL_PREFIX = 'mcp_server:';
export function buildMcpServerApprovalKey(serverName: string): string {
return `${MCP_SERVER_APPROVAL_PREFIX}${serverName}`;
}
export function createWorkspaceSettings(): WorkspaceSettings {
return {
theme: 'dark',
@@ -124,7 +186,17 @@ export function normalizeTheme(value?: string): AppearanceTheme {
return validThemes.has(value ?? '') ? (value as AppearanceTheme) : 'dark';
}
export function normalizeTerminalHeight(value?: number): number | undefined {
if (typeof value !== 'number' || !Number.isFinite(value)) {
return undefined;
}
const normalized = Math.round(value);
return normalized >= 120 ? normalized : undefined;
}
export function normalizeWorkspaceSettings(settings?: Partial<WorkspaceSettings>): WorkspaceSettings {
const terminalHeight = normalizeTerminalHeight(settings?.terminalHeight);
return {
theme: normalizeTheme(settings?.theme),
tooling: {
@@ -132,6 +204,7 @@ export function normalizeWorkspaceSettings(settings?: Partial<WorkspaceSettings>
lspProfiles: (settings?.tooling?.lspProfiles ?? []).map(normalizeLspProfileDefinition),
},
discoveredUserTooling: normalizeDiscoveredToolingState(settings?.discoveredUserTooling),
...(terminalHeight !== undefined ? { terminalHeight } : {}),
};
}
@@ -163,15 +236,16 @@ export function normalizeSessionToolingSelection(
export function listApprovalToolDefinitions(
tooling: WorkspaceToolingSettings,
runtimeTools: ReadonlyArray<RuntimeToolDefinition> = fallbackRuntimeApprovalTools,
_runtimeTools: ReadonlyArray<RuntimeToolDefinition> = fallbackRuntimeApprovalTools,
): ApprovalToolDefinition[] {
const toolsById = new Map<string, ApprovalToolDefinition>();
const runtimeApprovalTools = runtimeTools.length > 0 ? runtimeTools : fallbackRuntimeApprovalTools;
for (const tool of runtimeApprovalTools) {
// Always use category-level approval for built-in runtime tools regardless of
// what the sidecar reports as individual tools.
for (const tool of fallbackRuntimeApprovalTools) {
registerApprovalTool(toolsById, {
id: tool.id,
label: tool.label,
label: resolveToolLabel(tool.id),
description: tool.description,
kind: 'builtin',
providerId: `builtin:${tool.id}`,
@@ -180,10 +254,16 @@ export function listApprovalToolDefinitions(
}
for (const server of tooling.mcpServers) {
for (const toolName of normalizeStringArray(server.tools)) {
const declaredTools = normalizeStringArray(server.tools);
const toolEntries = declaredTools.length > 0
? declaredTools.map((name) => ({ name, description: undefined }))
: (server.probedTools ?? []).filter((t) => t.name.trim().length > 0);
for (const tool of toolEntries) {
registerApprovalTool(toolsById, {
id: toolName,
label: toolName,
id: tool.name,
label: tool.name,
description: tool.description,
kind: 'mcp',
providerId: server.id,
providerName: server.name,
@@ -212,7 +292,103 @@ export function listApprovalToolNames(
tooling: WorkspaceToolingSettings,
runtimeTools?: ReadonlyArray<RuntimeToolDefinition>,
): string[] {
return listApprovalToolDefinitions(tooling, runtimeTools).map((tool) => tool.id);
const toolNames = listApprovalToolDefinitions(tooling, runtimeTools).map((tool) => tool.id);
for (const server of tooling.mcpServers) {
toolNames.push(buildMcpServerApprovalKey(server.name));
}
return [...new Set(toolNames)];
}
export interface ApprovalToolGroup {
id: string;
label: string;
kind: ApprovalToolKind;
tools: ApprovalToolDefinition[];
serverApprovalKey?: string;
}
const approvalToolGroupKindOrder: ApprovalToolKind[] = ['builtin', 'mcp', 'lsp', 'mixed'];
export function groupApprovalToolsByProvider(
tools: ReadonlyArray<ApprovalToolDefinition>,
tooling: WorkspaceToolingSettings,
): ApprovalToolGroup[] {
const serverNames = new Map(tooling.mcpServers.map((s) => [s.id, s.name]));
const profileNames = new Map(tooling.lspProfiles.map((p) => [p.id, p.name]));
const groups = new Map<string, ApprovalToolGroup>();
for (const tool of tools) {
// Place MCP tools in every provider group they belong to, so each server
// shows its own tools even when multiple servers share the same tool names.
if (tool.kind === 'mcp' && tool.providerIds.length > 1) {
for (const providerId of tool.providerIds) {
const groupId = `mcp:${providerId}`;
let group = groups.get(groupId);
if (!group) {
const label = serverNames.get(providerId) ?? providerId;
group = { id: groupId, label, kind: 'mcp', tools: [] };
groups.set(groupId, group);
}
group.tools.push(tool);
}
continue;
}
const groupKey = resolveApprovalToolGroupKey(tool, serverNames, profileNames);
let group = groups.get(groupKey.id);
if (!group) {
group = { id: groupKey.id, label: groupKey.label, kind: groupKey.kind, tools: [] };
groups.set(groupKey.id, group);
}
group.tools.push(tool);
}
// Ensure every MCP server has a group (even with no declared tools) and
// attach server-level approval keys.
for (const server of tooling.mcpServers) {
const groupId = `mcp:${server.id}`;
let group = groups.get(groupId);
if (!group) {
group = { id: groupId, label: server.name, kind: 'mcp', tools: [] };
groups.set(groupId, group);
}
group.serverApprovalKey = buildMcpServerApprovalKey(server.name);
}
return [...groups.values()].sort((a, b) => {
const kindDiff = approvalToolGroupKindOrder.indexOf(a.kind) - approvalToolGroupKindOrder.indexOf(b.kind);
if (kindDiff !== 0) return kindDiff;
return a.label.localeCompare(b.label);
});
}
function resolveApprovalToolGroupKey(
tool: ApprovalToolDefinition,
serverNames: ReadonlyMap<string, string>,
profileNames: ReadonlyMap<string, string>,
): { id: string; label: string; kind: ApprovalToolKind } {
if (tool.kind === 'builtin') {
return { id: 'builtin', label: 'Built-in', kind: 'builtin' };
}
const primaryProviderId = tool.providerIds[0];
if (tool.kind === 'mcp' && primaryProviderId) {
return {
id: `mcp:${primaryProviderId}`,
label: serverNames.get(primaryProviderId) ?? tool.providerNames[0] ?? primaryProviderId,
kind: 'mcp',
};
}
if (tool.kind === 'lsp' && primaryProviderId) {
return {
id: `lsp:${primaryProviderId}`,
label: profileNames.get(primaryProviderId) ?? tool.providerNames[0] ?? primaryProviderId,
kind: 'lsp',
};
}
return { id: 'other', label: 'Other', kind: 'mixed' };
}
export function validateMcpServerDefinition(server: McpServerDefinition): string | undefined {
@@ -329,6 +505,10 @@ function toResolvedMcpServerDefinition(
server: ReturnType<typeof listAcceptedDiscoveredMcpServers>[number],
timestamp = nowIso(),
): McpServerDefinition {
const probedTools = server.probedTools && server.probedTools.length > 0
? [...server.probedTools]
: undefined;
if (server.transport === 'local') {
return normalizeMcpServerDefinition({
id: server.id,
@@ -339,6 +519,7 @@ function toResolvedMcpServerDefinition(
cwd: server.cwd,
env: server.env ? { ...server.env } : undefined,
tools: [...server.tools],
probedTools,
timeoutMs: server.timeoutMs,
createdAt: timestamp,
updatedAt: timestamp,
@@ -352,6 +533,7 @@ function toResolvedMcpServerDefinition(
url: server.url,
headers: server.headers ? { ...server.headers } : undefined,
tools: [...server.tools],
probedTools,
timeoutMs: server.timeoutMs,
createdAt: timestamp,
updatedAt: timestamp,
+14
View File
@@ -0,0 +1,14 @@
export type UserInputStatus = 'pending' | 'answered';
export interface PendingUserInputRecord {
id: string;
status: UserInputStatus;
agentId?: string;
agentName?: string;
question: string;
choices?: string[];
allowFreeform: boolean;
requestedAt: string;
answer?: string;
answeredAt?: string;
}

Some files were not shown because too many files have changed in this diff Show More