Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(hooks): deliver the SessionStart handoff to Copilot CLI
AkitaOnRails43fa811e736b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f646471c..8fda8773 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,9 +15,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0payload. Ten events — Claude Code's nine plus `PostToolUseFailure` — withnative commands enforcing capture exclusions; tool output is read from`tool_result.text_result_for_llm` and the outcome from- `tool_result.result_type`. Copilot reads a top-level `additionalContext` on- `SessionStart` rather than Claude Code's envelope, so handoffs are not- injected yet: recover them with `memory_handoff_accept`. The bare+ `tool_result.result_type`. The `SessionStart` hook delivers the prior+ session's handoff through Copilot's top-level `additionalContext` (ported+ from #1069). There is deliberately no `--scope project`. The bare`install-mcp --client copilot` alias keeps meaning VS Code Copilot;`install-mcp --client copilot-cli` and `ai-memory run copilot` followseparately. (#1040)diff --git a/crates/ai-memory-cli/src/commands/hook.rs b/crates/ai-memory-cli/src/commands/hook.rsindex 6d74a5bf..adaef576 100644--- a/crates/ai-memory-cli/src/commands/hook.rs+++ b/crates/ai-memory-cli/src/commands/hook.rs@@ -523,6 +523,12 @@ fn session_start_handoff_envelope(agent: AgentKind, handoff: String) -> serde_js"ephemeralMessage": handoff,}]})+ } else if agent == AgentKind::CopilotCli {+ // Copilot CLI requires the SessionStart output envelope itself, rather+ // than Claude Code's nested hookSpecificOutput shape.+ serde_json::json!({+ "additionalContext": handoff,+ })} else {serde_json::json!({"hookSpecificOutput": {@@ -3204,6 +3210,19 @@ mod tests {}}+ fn copilot_cli_hook_args(event: &str, server_url: &str) -> HookArgs {+ HookArgs {+ event: event.into(),+ agent: "copilot-cli".into(),+ server_url: server_url.into(),+ auth_token: None,+ project_strategy: None,+ check_capture: false,+ capture_assistant: false,+ capture_mode: None,+ }+ }+fn antigravity_hook_args(event: &str, server_url: &str) -> HookArgs {HookArgs {event: event.into(),@@ -3365,6 +3384,48 @@ mod tests {);}+ #[tokio::test]+ async fn copilot_cli_session_start_prints_top_level_handoff_envelope() {+ let tmp = tempfile::tempdir().unwrap();+ let (base, mut requests) = serve_requests("200 OK", "COPILOT-HANDOFF").await;+ let mut stdout = Vec::new();+ run_with_payload(+ Some(tmp.path().join("data")),+ copilot_cli_hook_args("session-start", &base),+ serde_json::json!({+ "session_id": "copilot-session",+ "cwd": tmp.path()+ })+ .to_string(),+ &mut stdout,+ |_, _| Ok(()),+ )+ .await+ .unwrap();++ let envelope: serde_json::Value = serde_json::from_slice(stdout.trim_ascii()).unwrap();+ assert_eq!(+ envelope,+ serde_json::json!({"additionalContext": "COPILOT-HANDOFF"})+ );+ assert!(+ envelope.get("hookSpecificOutput").is_none(),+ "Copilot reads the top-level SessionStart envelope"+ );+ let mut recorded = Vec::new();+ while let Some(request) = first_request(&mut requests).await {+ recorded.push(request);+ }+ assert!(+ recorded.iter().any(|request| {+ request.starts_with("GET /handoff?")+ && request.contains("agent=copilot-cli")+ && request.contains("session_id=copilot-session")+ }),+ "{recorded:?}"+ );+ }+// ── #992: per-repository server profiles ─────────────────────────────/// Register `name` in `data_dir` with a token and the given roots.diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rsindex fca2a3e3..0f081fa1 100644--- a/crates/ai-memory-core/src/ids.rs+++ b/crates/ai-memory-core/src/ids.rs@@ -419,14 +419,10 @@ impl AgentKind {/// model (verified live against the embedded engine v0.16.5, capture logs/// 2026-08-28), so its native hook fetches the handoff like Claude Code's.///- /// GitHub Copilot CLI documents `SessionStart` context injection, but- /// through a top-level `additionalContext` key — not Claude Code's- /// `hookSpecificOutput` envelope, which is what the native hook emits —- /// even in its PascalCase/VS-Code-compatible payload mode, and no live- /// capture proves the model sees it. Fails safe like Pool/Hermes until a- /// Copilot-specific envelope is wired and verified: the handoff stays- /// available on demand via `memory_handoff_accept` rather than risking a- /// destructive fetch-and-discard.+ /// GitHub Copilot CLI injects `SessionStart` context from a top-level+ /// `additionalContext` key (GitHub's hooks reference), not Claude Code's+ /// `hookSpecificOutput` envelope, even in its PascalCase payload mode; the+ /// native hook prints that top-level envelope for it.#[must_use]pub fn session_start_injects_handoff(self) -> bool {!matches!(@@ -437,7 +433,6 @@ impl AgentKind {| Self::KimiCode| Self::Hermes| Self::Pool- | Self::CopilotCli| Self::Other)}@@ -659,11 +654,9 @@ mod tests {assert_eq!(AgentKind::from_wire("copilot"), AgentKind::Other);// Unknown tags still degrade to Other.assert_eq!(AgentKind::from_wire("copilot-cli-2"), AgentKind::Other);- // Copilot CLI reads a top-level `additionalContext`, not the- // `hookSpecificOutput` envelope the native hook prints, so the- // destructive handoff fetch must not happen from its native hook yet- // (see the doc comment on `session_start_injects_handoff`).- assert!(!AgentKind::CopilotCli.session_start_injects_handoff());+ // Copilot CLI reads a top-level `additionalContext` at SessionStart,+ // which the native hook prints for it.+ assert!(AgentKind::CopilotCli.session_start_injects_handoff());assert!(!AgentKind::CopilotCli.user_prompt_injects_handoff());}diff --git a/hooks/copilot-cli/session-start.ps1 b/hooks/copilot-cli/session-start.ps1index ada159f5..ceb57e54 100644--- a/hooks/copilot-cli/session-start.ps1+++ b/hooks/copilot-cli/session-start.ps1@@ -1,8 +1,3 @@-# GitHub Copilot CLI session-start hook.-# Capture only — Copilot CLI's SessionStart stdout injection is not-# demonstrated live, so no -FetchHandoff: accepting a handoff is destructive-# and the context could be silently lost. Recover handoffs via MCP-# `memory_handoff_accept`.. "$PSScriptRoot\..\lib\ai-memory-hook.ps1"-Invoke-AiMemoryHook -Event "session-start" -Agent "copilot-cli"+Invoke-AiMemoryHook -Event "session-start" -Agent "copilot-cli" -FetchHandoff -CopilotCliSessionStartOutputexit 0diff --git a/hooks/copilot-cli/session-start.sh b/hooks/copilot-cli/session-start.shindex 515a6daa..986f8a3e 100755--- a/hooks/copilot-cli/session-start.sh+++ b/hooks/copilot-cli/session-start.sh@@ -1,11 +1,15 @@#!/bin/sh# GitHub Copilot CLI SessionStart hook.-# Copilot CLI reads a top-level `additionalContext` from SessionStart stdout-# (not Claude Code's `hookSpecificOutput` envelope), and that injection is not-# demonstrated live, so this hook captures the event only. Do NOT fetch-# /handoff here: accepting a handoff is destructive and an undelivered handoff-# would be silently lost. Recover a prior session's handoff via the MCP-# `memory_handoff_accept` tool instead.+# 1. Forwards the event JSON to the ai-memory server (fire-and-forget).+# 2. Synchronously fetches the pending cross-agent handoff and prints it as+# Copilot's top-level `additionalContext`, which Copilot adds to the new+# session's context, so the resuming agent sees prior context with no+# human in the loop.+#+# Walks up from the payload's cwd for a .ai-memory.toml marker file+# and appends cwd plus marker query params to both URLs — so a session+# resuming under basename or marker-declared routing doesn't query the+# wrong bucket and miss its own handoff.# At runtime (after `install-hooks --apply`) `_lib.sh` is staged# alongside this script. From the source tree it lives one dir up._lib_dir="$(dirname "$0")"@@ -16,8 +20,23 @@ SERVER="${AI_MEMORY_HOOK_URL:-http://127.0.0.1:49374}"PAYLOAD=$(cat)CWD=$(ai_memory_extract_cwd "$PAYLOAD")QS=$(ai_memory_marker_qs "$CWD")+# The `[briefing]` opt-in rides the handoff GET, as in the native hook.+BRIEF_QS=$(ai_memory_briefing_qs "$CWD")+SESSION_ID=$(ai_memory_extract_session_id "$PAYLOAD")+SESSION_QS=""+[ -n "$SESSION_ID" ] && SESSION_QS="&session_id=$(ai_memory_url_encode "$SESSION_ID")"printf '%s' "$PAYLOAD" \| ai_memory_post_hook "$SERVER/hook?event=session-start&agent=copilot-cli${QS}" >/dev/null 2>&1 || true-printf '{}\n'++# Copilot CLI accepts SessionStart context only in its top-level+# additionalContext envelope. The hook protocol maps the PascalCase event+# name to snake_case fields before this script receives it; no handoff -> {}.+HANDOFF=$(ai_memory_get_handoff "$SERVER/handoff?agent=copilot-cli${QS}${SESSION_QS}${BRIEF_QS}" 2>/dev/null || true)+if [ -n "$HANDOFF" ]; then+ printf '{"additionalContext":%s}\n' \+ "$(printf '%s' "$HANDOFF" | ai_memory_json_string)"+else+ printf '{}\n'+fiexit 0diff --git a/hooks/lib/ai-memory-hook.ps1 b/hooks/lib/ai-memory-hook.ps1index e81c16c4..caf51993 100644--- a/hooks/lib/ai-memory-hook.ps1+++ b/hooks/lib/ai-memory-hook.ps1@@ -462,6 +462,10 @@ function Invoke-AiMemoryHook {[Parameter(Mandatory = $true)] [string] $Event,[Parameter(Mandatory = $true)] [string] $Agent,[switch] $FetchHandoff,+ # Copilot CLI requires SessionStart output as a top-level+ # `{ "additionalContext": ... }` envelope rather than Claude Code's+ # nested hookSpecificOutput shape.+ [switch] $CopilotCliSessionStartOutput,[switch] $AntigravityPreInvocationOutput,# Deliver the `[briefing]` compiled project brief on the FIRST# handoff fetch of a session only (kimi-code's user-prompt path:@@ -614,6 +618,9 @@ function Invoke-AiMemoryHook {}}[Console]::Out.Write(($Wrapped | ConvertTo-Json -Depth 5 -Compress))+ } elseif ($CopilotCliSessionStartOutput) {+ $Payload = @{ additionalContext = $Response.Content }+ [Console]::Out.Write(($Payload | ConvertTo-Json -Depth 5 -Compress))} elseif ($AntigravityPreInvocationOutput) {$Payload = @{injectSteps = @(@{ ephemeralMessage = $Response.Content })@@ -622,11 +629,11 @@ function Invoke-AiMemoryHook {} else {[Console]::Out.Write($Response.Content)}- } elseif ($AntigravityPreInvocationOutput -or $GrokPostTool) {+ } elseif ($AntigravityPreInvocationOutput -or $GrokPostTool -or $CopilotCliSessionStartOutput) {[Console]::Out.Write("{}")}} catch {- if ($AntigravityPreInvocationOutput -or $GrokPostTool) {+ if ($AntigravityPreInvocationOutput -or $GrokPostTool -or $CopilotCliSessionStartOutput) {[Console]::Out.Write("{}")}}