@junghanacs/entwurf 0.14.2 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/AGENTS.md +8 -5
  2. package/CHANGELOG.md +79 -0
  3. package/DELIVERY.md +72 -59
  4. package/README.md +55 -4
  5. package/VERIFY.md +2 -2
  6. package/demo/README.md +1 -1
  7. package/docs/acp-backend-rail.md +1 -1
  8. package/docs/external-mcp-host.md +26 -4
  9. package/docs/setup-clean-host.md +3 -3
  10. package/mcp/entwurf-bridge/dist/mcp/entwurf-bridge/src/index.js +8 -6
  11. package/mcp/entwurf-bridge/dist/pi-extensions/entwurf-capabilities.json +1 -0
  12. package/mcp/entwurf-bridge/dist/pi-extensions/lib/copilot-fresh-preflight.js +253 -0
  13. package/mcp/entwurf-bridge/dist/pi-extensions/lib/meta-sender-identity.js +10 -2
  14. package/mcp/entwurf-bridge/dist/pi-extensions/lib/meta-session.js +102 -28
  15. package/mcp/entwurf-bridge/dist/pi-extensions/lib/mux-fresh-call.js +77 -11
  16. package/mcp/entwurf-bridge/dist/pi-extensions/meta-bridge-hook-copilot.js +288 -0
  17. package/mcp/entwurf-bridge/src/index.ts +10 -6
  18. package/mcp/entwurf-bridge/tsconfig.build.json +2 -1
  19. package/package.json +22 -11
  20. package/pi/copilot-receive/entwurf-receive/extension.mjs +323 -0
  21. package/pi/entwurf-capabilities.json +1 -0
  22. package/pi/meta-bridge-copilot/.claude-plugin/marketplace.json +11 -0
  23. package/pi/meta-bridge-copilot/entwurf-meta-receive-copilot/.claude-plugin/plugin.json +5 -0
  24. package/pi/meta-bridge-copilot/entwurf-meta-receive-copilot/hooks/hooks.json +7 -0
  25. package/pi/meta-bridge-copilot/entwurf-meta-receive-copilot/scripts/copilot-hook-launch.sh +85 -0
  26. package/pi-extensions/entwurf-control.ts +17 -8
  27. package/pi-extensions/lib/copilot-fresh-preflight.ts +251 -0
  28. package/pi-extensions/lib/meta-sender-identity.ts +10 -2
  29. package/pi-extensions/lib/meta-session.ts +102 -29
  30. package/pi-extensions/lib/mux-fresh-call.ts +82 -11
  31. package/pi-extensions/meta-bridge-hook-copilot.ts +323 -0
  32. package/run.sh +334 -16
  33. package/scripts/check-copilot-birth-hook.ts +497 -0
  34. package/scripts/check-copilot-launch.ts +395 -0
  35. package/scripts/check-copilot-receive-arm.ts +734 -0
  36. package/scripts/check-copilot-statusline.ts +122 -0
  37. package/scripts/check-entwurf-capabilities.ts +25 -6
  38. package/scripts/check-fresh-cut-gate.sh +92 -23
  39. package/scripts/check-gate-qualification.ts +7 -1
  40. package/scripts/check-install-container.sh +2 -2
  41. package/scripts/check-install-surface.ts +1 -1
  42. package/scripts/check-meta-capability-source.ts +89 -5
  43. package/scripts/check-meta-doctor-oracle.sh +26 -0
  44. package/scripts/check-meta-manifest-schema.py +38 -0
  45. package/scripts/check-meta-receiver-marker.ts +25 -2
  46. package/scripts/check-meta-session.ts +32 -0
  47. package/scripts/copilot-bridge-doctor.sh +209 -0
  48. package/scripts/copilot-bridge-install.sh +224 -0
  49. package/scripts/copilot-launch.sh +236 -0
  50. package/scripts/copilot-mcp-bridge.sh +177 -0
  51. package/scripts/copilot-mcp-config.py +221 -0
  52. package/scripts/copilot-receive-bridge.sh +483 -0
  53. package/scripts/copilot-statusline-bridge.sh +149 -0
  54. package/scripts/copilot-statusline-config.py +201 -0
  55. package/scripts/copilot-statusline.sh +68 -0
  56. package/scripts/dev-bin.sh +4 -1
  57. package/scripts/meta-bridge-hook-log.sh +17 -5
  58. package/scripts/mutants/capability-cache.json +64 -0
  59. package/scripts/mutants/copilot-birth.json +155 -0
  60. package/scripts/mutants/copilot-launch.json +187 -0
  61. package/scripts/mutants/copilot-receive.json +263 -0
  62. package/scripts/mutants/fresh-cut.json +17 -0
  63. package/scripts/mutants/mux-fresh-call.json +216 -2
  64. package/scripts/mutants/pack-install.json +17 -0
  65. package/scripts/raw-async-delivery/README.md +170 -125
  66. package/scripts/raw-async-delivery/copilot-enqueue-addressed.sh +35 -0
  67. package/scripts/raw-async-delivery/copilot-extension-receive/extension.mjs +123 -0
  68. package/scripts/smoke-copilot-mcp-state.sh +153 -0
  69. package/scripts/smoke-copilot-statusline-state.sh +131 -0
  70. package/scripts/smoke-mux-fresh-call-live.ts +2 -0
  71. package/scripts/smoke-mux-lifecycle-live.ts +3 -1
  72. package/scripts/tsconfig.json +1 -0
@@ -0,0 +1,236 @@
1
+ #!/usr/bin/env bash
2
+ # copilot-launch.sh — the managed Copilot launch, `entwurf copilot` (#82 RAIL 7).
3
+ #
4
+ # WHY THIS EXISTS. The receiver installer owns the extension artifact but it cannot
5
+ # arm anything by itself: Copilot scans for extensions only when the CLI is started
6
+ # with `COPILOT_CLI_ENABLED_FEATURE_FLAGS=EXTENSIONS`, and that lives in the
7
+ # environment of the operator's own launch. Without it the scan is skipped SILENTLY —
8
+ # no error, no log line, no receiver — so a perfectly installed unit stays inert and
9
+ # the citizen never becomes deliverable. entwurf does not own the operator's shell,
10
+ # and it will not write their rc files. What it can own is ONE invocation: this leaf
11
+ # sets the flag for the process it is about to become, and nothing outside it.
12
+ #
13
+ # WHAT IT IS NOT. It is not a launcher rail. It does not place a tmux window, it is
14
+ # not fresh-call, and it mints NO citizen: birth authority stays exactly where it was,
15
+ # on the Copilot session's FIRST PROMPT (Hard Rule 2 — the record is the sole garden
16
+ # address authority, and nothing here writes a record). It `exec`s in the caller's own
17
+ # terminal, so cwd, tty, pid and exit status are the vendor's, unchanged.
18
+ #
19
+ # CONSENT. Calling `entwurf copilot` IS the consent to the managed profile: EXTENSIONS
20
+ # on, `--model auto` when no model was given, and `--yolo` when no explicit permission
21
+ # or surface policy was given. An operator who wants the plain vendor behaviour keeps
22
+ # running `copilot` directly — that path is untouched and is not deprecated.
23
+ #
24
+ # FAIL-CLOSED SCAN. The argv scan is element-wise and deliberately naive: it does not
25
+ # model which options consume the next word. Both of its possible mistakes are safe.
26
+ # Reading an option's VALUE as a policy token suppresses an injected default; reading
27
+ # it as a model suppresses `--model auto`. Every error direction is "inject less",
28
+ # never "widen the operator's permissions behind their back".
29
+ #
30
+ # PRECONDITION SCOPE, deliberately unchanged by #82 RAIL 9. This launcher guards the
31
+ # RECEIVER and nothing else, because that is the promise the EXTENSIONS flag makes. The
32
+ # fresh-call lane needs more than that (birth, MCP hand, receiver AND visible footer), but
33
+ # those belong to `pi-extensions/lib/copilot-fresh-preflight.ts`, which decides them BEFORE
34
+ # tmux opens a window. A refusal here necessarily happens inside a window that already
35
+ # exists, so widening this list would only turn a clean pre-mutation refusal into a dead
36
+ # window plus a launch receipt for a sibling that never was. The manual `entwurf copilot`
37
+ # contract stays receive-only.
38
+ set -euo pipefail
39
+
40
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
41
+ REPO_DIR="$(cd "$HERE/.." && pwd)"
42
+
43
+ UNIT="entwurf-receive"
44
+ EXT_ROOT="${COPILOT_EXTENSIONS_DIR:-$HOME/.copilot/extensions}"
45
+ DEST="$EXT_ROOT/$UNIT"
46
+ STATE_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/entwurf/copilot-receive"
47
+ STATE_FILE="$STATE_DIR/install-state.json"
48
+ FLAG_ENV="COPILOT_CLI_ENABLED_FEATURE_FLAGS"
49
+ FLAG_VALUE="EXTENSIONS"
50
+ REPAIR="entwurf install-copilot-receive"
51
+
52
+ # The vendor command this leaf manages. A CONSTANT, and deliberately not overridable:
53
+ # an env seam here would be a production switch for "which binary is the Copilot CLI",
54
+ # and anything that can redirect an exec is an authority, not a test convenience. The
55
+ # gate proves the real contract instead — it puts its fake vendor on a sandbox PATH under
56
+ # this exact name and drives the public address.
57
+ VENDOR_CMD="copilot"
58
+
59
+ fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
60
+
61
+ # --- recursion fence -------------------------------------------------------
62
+ # A `copilot` earlier on PATH that itself calls `entwurf copilot` would spin forever,
63
+ # and the symptom would be a hung terminal rather than an error. One sentinel closes
64
+ # it: the flag is invocation-local, so seeing it already set means we are inside our
65
+ # own exec chain.
66
+ if [ -n "${ENTWURF_COPILOT_LAUNCH_ACTIVE:-}" ]; then
67
+ fail "recursive managed launch detected (ENTWURF_COPILOT_LAUNCH_ACTIVE is already set).
68
+ Something on PATH named '$VENDOR_CMD' resolves back to this launcher. Fix PATH so
69
+ '$VENDOR_CMD' is the GitHub Copilot CLI, or run the vendor binary by its full path."
70
+ fi
71
+
72
+ # --- precondition: the receiver this launch promises to arm -----------------
73
+ # The flag is a PROMISE of a doorbell. Setting it while no receiver unit is installed
74
+ # would produce a session that looks managed and can never be delivered to, which is
75
+ # the exact false-success this repo refuses. Every failure below names the one command
76
+ # that repairs it.
77
+ [ -f "$STATE_FILE" ] \
78
+ || fail "no receiver install-state at $STATE_FILE.
79
+ '$VENDOR_CMD' launched with $FLAG_ENV=$FLAG_VALUE would scan for an extension that is
80
+ not there, and the session would never become deliverable. Run: $REPAIR"
81
+
82
+ claimed_path=""
83
+ claimed_unit=""
84
+ if ! claimed_path="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("path",""))' "$STATE_FILE" 2>/dev/null)"; then
85
+ fail "receiver install-state at $STATE_FILE is not readable JSON — refusing to launch on a
86
+ state file we cannot verify. Run: $REPAIR"
87
+ fi
88
+ claimed_unit="$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1])).get("unit",""))' "$STATE_FILE" 2>/dev/null || true)"
89
+
90
+ [ -n "$claimed_path" ] \
91
+ || fail "receiver install-state at $STATE_FILE names no path. Run: $REPAIR"
92
+ [ "$claimed_unit" = "$UNIT" ] \
93
+ || fail "receiver install-state at $STATE_FILE claims unit '${claimed_unit:-<empty>}', expected '$UNIT'. Run: $REPAIR"
94
+ # Path mismatch is its own failure, not a missing file: it means the state file and the
95
+ # directory this launch would arm from disagree, and the extensions root the CLI will
96
+ # actually scan is $EXT_ROOT.
97
+ [ "$claimed_path" = "$DEST" ] \
98
+ || fail "receiver install-state points at '$claimed_path' but this environment scans '$DEST'.
99
+ The CLI would read a different extensions root than the one that was installed
100
+ (COPILOT_EXTENSIONS_DIR / HOME differ from install time). Run: $REPAIR"
101
+ [ -d "$claimed_path" ] \
102
+ || fail "receiver unit directory '$claimed_path' is missing. Run: $REPAIR"
103
+ [ -f "$claimed_path/extension.mjs" ] \
104
+ || fail "receiver unit at '$claimed_path' holds no extension.mjs — it is not our unit any more. Run: $REPAIR"
105
+
106
+ # --- resolve the vendor executable -----------------------------------------
107
+ # `type -P` returns the PATH hit only — never a shell function, alias or builtin — so
108
+ # what is exec'd is a real external file. `exec command copilot` is deliberately NOT
109
+ # used: it would re-enter shell lookup at exec time and could pick up something other
110
+ # than the file that was validated here.
111
+ copilot_bin="$(type -P "$VENDOR_CMD" 2>/dev/null || true)"
112
+ [ -n "$copilot_bin" ] \
113
+ || fail "no '$VENDOR_CMD' executable found on PATH.
114
+ The managed launch runs the GitHub Copilot CLI; install it, or put it on PATH."
115
+ [ -f "$copilot_bin" ] && [ -x "$copilot_bin" ] \
116
+ || fail "'$copilot_bin' is not an executable regular file — refusing to exec it."
117
+
118
+ # Self-exec fence, the second half of the recursion guard: resolve symlinks and refuse
119
+ # anything that is one of our own entrypoints even if the sentinel was stripped.
120
+ resolved_bin="$(readlink -f "$copilot_bin" 2>/dev/null || printf '%s' "$copilot_bin")"
121
+ for own in "$HERE/copilot-launch.sh" "$REPO_DIR/run.sh"; do
122
+ own_resolved="$(readlink -f "$own" 2>/dev/null || printf '%s' "$own")"
123
+ [ "$resolved_bin" = "$own_resolved" ] \
124
+ && fail "'$VENDOR_CMD' on PATH resolves to entwurf's own '$own_resolved' — that is a launch loop, not the vendor CLI."
125
+ done
126
+
127
+ # --- argv scan: everything BEFORE the first literal `--` --------------------
128
+ # The terminator and everything after it belong to the user/vendor as data. We neither
129
+ # read policy out of it nor inject into it: injected defaults go immediately BEFORE the
130
+ # terminator so they remain options, and every original element crosses byte-identical.
131
+ args=("$@")
132
+ term_index=-1
133
+ for i in "${!args[@]}"; do
134
+ if [ "${args[$i]}" = "--" ]; then
135
+ term_index="$i"
136
+ break
137
+ fi
138
+ done
139
+ scan_end=$(( term_index >= 0 ? term_index : ${#args[@]} ))
140
+
141
+ # The explicit permission / surface policy overrides, measured against GitHub Copilot
142
+ # CLI 1.0.80 `--help`. Two groups, one rule: if the operator named ANY of them before
143
+ # the terminator, they have stated their own policy and we add none.
144
+ # authorization: --yolo, --allow-all{,-tools,-paths,-urls}, --allow-tool, --deny-tool,
145
+ # --allow-url, --deny-url
146
+ # tool surface : --available-tools, --excluded-tools
147
+ # Narrowing flags count too: appending `--yolo` (= all tools + paths + URLs) beside an
148
+ # operator's `--allow-url=https://one.example` would silently widen exactly what they
149
+ # were narrowing.
150
+ # NOT overrides, deliberately: `--allow-all-mcp-server-instructions` is prompt content,
151
+ # not authorization, and `--autopilot` is a mode. Matching is EXACT on the token head,
152
+ # so neither is caught by the `--allow-all` entry that is a prefix of one of them.
153
+ POLICY_OVERRIDES=(
154
+ --yolo
155
+ --allow-all
156
+ --allow-all-tools
157
+ --allow-all-paths
158
+ --allow-all-urls
159
+ --allow-tool
160
+ --deny-tool
161
+ --allow-url
162
+ --deny-url
163
+ --available-tools
164
+ --excluded-tools
165
+ )
166
+
167
+ has_model=0
168
+ has_policy=0
169
+ for (( i = 0; i < scan_end; i++ )); do
170
+ tok="${args[$i]}"
171
+ # `--opt=value` and `--opt value` are the same option; compare the head only.
172
+ head="${tok%%=*}"
173
+ if [ "$head" = "--model" ]; then
174
+ has_model=1
175
+ fi
176
+ for ov in "${POLICY_OVERRIDES[@]}"; do
177
+ if [ "$head" = "$ov" ]; then
178
+ has_policy=1
179
+ break
180
+ fi
181
+ done
182
+ done
183
+
184
+ injected=()
185
+ [ "$has_model" -eq 0 ] && injected+=(--model auto)
186
+ [ "$has_policy" -eq 0 ] && injected+=(--yolo)
187
+
188
+ # Rebuild argv with the defaults before the terminator. Original elements are copied by
189
+ # index, so empty strings, embedded spaces and post-terminator data all survive intact.
190
+ final_args=()
191
+ for (( i = 0; i < scan_end; i++ )); do final_args+=("${args[$i]}"); done
192
+ if [ "${#injected[@]}" -gt 0 ]; then final_args+=("${injected[@]}"); fi
193
+ for (( i = scan_end; i < ${#args[@]}; i++ )); do final_args+=("${args[$i]}"); done
194
+
195
+ # --- the feature flag, invocation-local ------------------------------------
196
+ # Preserve the operator's existing tokens and their order, drop empties, drop
197
+ # duplicates, and guarantee EXTENSIONS is present exactly once. Nothing is written to
198
+ # any config or rc file: this export reaches only the image this process becomes.
199
+ flags_out=""
200
+ seen_extensions=0
201
+ if [ -n "${!FLAG_ENV:-}" ]; then
202
+ IFS=',' read -r -a existing <<< "${!FLAG_ENV}"
203
+ for tok in "${existing[@]}"; do
204
+ # Vendor tokens are comma-separated names; surrounding whitespace is noise, and an
205
+ # empty field (",," or a trailing comma) is not a token.
206
+ tok="${tok#"${tok%%[![:space:]]*}"}"
207
+ tok="${tok%"${tok##*[![:space:]]}"}"
208
+ [ -n "$tok" ] || continue
209
+ case ",$flags_out," in *",$tok,"*) continue ;; esac
210
+ [ "$tok" = "$FLAG_VALUE" ] && seen_extensions=1
211
+ flags_out="${flags_out:+$flags_out,}$tok"
212
+ done
213
+ fi
214
+ [ "$seen_extensions" -eq 1 ] || flags_out="${flags_out:+$flags_out,}$FLAG_VALUE"
215
+
216
+ export "$FLAG_ENV=$flags_out"
217
+ export ENTWURF_COPILOT_LAUNCH_ACTIVE=1
218
+
219
+ # --- foreign identity carriers, removed before exec ------------------------
220
+ # The MCP bridge trusts a COMPLETE `PI_SESSION_ID` + `PI_AGENT_ID` pair ahead of a native
221
+ # sender marker when it resolves who is speaking. Inside the pi process that planted them
222
+ # from record birth that is correct. In another harness they are somebody else's identity:
223
+ # start Copilot from a pi citizen's bash and this session — plus every MCP child and
224
+ # extension child that inherits from it — can speak under the PARENT pi garden id, and the
225
+ # delivery layer will stamp envelopes with an address this session does not hold.
226
+ #
227
+ # Both go, together. Clearing one only changes the wording of the failure while leaving a
228
+ # carrier for a future partial reader to pick up, so an incomplete pair is not a repair.
229
+ # Nothing is substituted: identity for this session comes from its OWN trusted birth marker
230
+ # on its first prompt, which is exactly where the record authority already lives.
231
+ #
232
+ # `unset` is unconditional on purpose. Branching on "was it set?" would only add a way to
233
+ # be wrong; unsetting an absent variable is a no-op in every shell this runs on.
234
+ unset PI_SESSION_ID PI_AGENT_ID
235
+
236
+ exec "$copilot_bin" "${final_args[@]}"
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env bash
2
+ # Copilot MCP install adapter. Birth plugin and personal MCP stay separate.
3
+ # Owns ONE mcpServers.entwurf-bridge key; file wrapper is always mcpServers.
4
+ # Entry type is "local" (Copilot CLI writer), never "stdio".
5
+ set -euo pipefail
6
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
7
+ REPO_DIR="$(cd "$HERE/.." && pwd)"
8
+ CONFIG_PY="$HERE/copilot-mcp-config.py"
9
+ CONFIG="${COPILOT_MCP_CONFIG:-$HOME/.copilot/mcp-config.json}"
10
+ COMMAND="${COPILOT_MCP_COMMAND:-entwurf-bridge}"
11
+ STATE_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/entwurf/copilot-mcp"
12
+ STATE_FILE="$STATE_DIR/install-state.json"
13
+ log() { printf '%s\n' "$*"; }
14
+ fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
15
+ command_resolvable() {
16
+ case "$1" in
17
+ */*) [ -x "$1" ] ;;
18
+ *) command -v "$1" >/dev/null 2>&1 ;;
19
+ esac
20
+ }
21
+ run_config() {
22
+ local out rc
23
+ set +e
24
+ out="$(python3 "$CONFIG_PY" "$@" 2>&1)"
25
+ rc=$?
26
+ set -e
27
+ printf '%s\n' "$out"
28
+ return "$rc"
29
+ }
30
+ BOOT_PROBED_INVOCATION=""
31
+ BOOT_PROBED_RC=1
32
+ BOOT_PROBED_OUT=""
33
+ BOOT_DETAIL=""
34
+ command_boots() {
35
+ local invocation="$1" out rc
36
+ if [ "$invocation" = "$BOOT_PROBED_INVOCATION" ]; then
37
+ BOOT_DETAIL="$BOOT_PROBED_OUT"
38
+ return "$BOOT_PROBED_RC"
39
+ fi
40
+ set +e
41
+ out="$("$REPO_DIR/run.sh" probe-bridge-command --invocation-json "$invocation" 2>&1)"
42
+ rc=$?
43
+ set -e
44
+ BOOT_PROBED_INVOCATION="$invocation"; BOOT_PROBED_RC="$rc"; BOOT_PROBED_OUT="$out"; BOOT_DETAIL="$out"
45
+ return "$rc"
46
+ }
47
+ do_install() {
48
+ log "[copilot-mcp install]"
49
+ log " target: $CONFIG"
50
+ log " command: $COMMAND"
51
+ log " state: $STATE_FILE"
52
+ if ! command_resolvable "$COMMAND"; then
53
+ log " note: '$COMMAND' is not currently resolvable; install records it and doctor stays red until it is on PATH"
54
+ fi
55
+ local out rc
56
+ set +e
57
+ out="$(run_config install "$CONFIG" "$COMMAND" "$STATE_FILE")"
58
+ rc=$?
59
+ set -e
60
+ case "$rc" in
61
+ 0) log " ok: $out" ;;
62
+ 3) fail "refused (symlink) — $out" ;;
63
+ 4) fail "invalid config/state — $out" ;;
64
+ *) fail "install error (rc=$rc) — $out" ;;
65
+ esac
66
+ log " installed. Verify with: ./run.sh doctor-copilot-mcp"
67
+ }
68
+ do_uninstall() {
69
+ log "[copilot-mcp uninstall]"
70
+ local out rc
71
+ set +e
72
+ out="$(run_config uninstall "$STATE_FILE")"
73
+ rc=$?
74
+ set -e
75
+ case "$rc" in
76
+ 0) log " ok: $out" ;;
77
+ 2) log " note: $out" ;;
78
+ 3) fail "refused (symlink) — $out" ;;
79
+ *) fail "uninstall error (rc=$rc) — $out" ;;
80
+ esac
81
+ }
82
+ state_target() {
83
+ python3 - "$STATE_FILE" <<'PY'
84
+ import json, os, sys
85
+ try:
86
+ state = json.load(open(sys.argv[1]))
87
+ required = ("serverKey", "command", "detectMode", "configExistedBefore", "preimage")
88
+ if state.get("schemaVersion") != 1 or any(key not in state for key in required): raise ValueError()
89
+ if state.get("serverKey") != "entwurf-bridge": raise ValueError()
90
+ value = state.get("managedConfigPath")
91
+ if not isinstance(value, str) or not os.path.isabs(value): raise ValueError()
92
+ print(os.path.abspath(value))
93
+ except Exception:
94
+ raise SystemExit(1)
95
+ PY
96
+ }
97
+ do_doctor() {
98
+ log "[copilot-mcp doctor]"
99
+ local hard_fail=0 status out rc installed=0
100
+ [ -f "$STATE_FILE" ] && installed=1
101
+ set +e
102
+ out="$(run_config doctor-static "$CONFIG" "$COMMAND")"
103
+ rc=$?
104
+ set -e
105
+ status="${out##*$'\n'}"
106
+ if [ "$rc" -ne 0 ]; then
107
+ log " config: unexpected config reader failure (rc=$rc): $out"
108
+ if [ "$installed" -eq 1 ]; then hard_fail=1; fi
109
+ else
110
+ case "$status" in
111
+ configured\ *)
112
+ local invocation
113
+ if ! invocation="$(python3 "$CONFIG_PY" doctor-invocation "$CONFIG" "$COMMAND")"; then
114
+ log " config: configured → '$COMMAND' but its exact invocation is unreadable"
115
+ [ "$installed" -eq 1 ] && hard_fail=1
116
+ elif command_boots "$invocation"; then
117
+ log " config: configured → '$COMMAND' (the exact configured invocation boots the entwurf MCP surface)"
118
+ else
119
+ log " config: configured → '$COMMAND' does NOT serve MCP with its configured args/env"
120
+ log " $BOOT_DETAIL"
121
+ [ "$installed" -eq 1 ] && hard_fail=1
122
+ fi ;;
123
+ symlink)
124
+ log " config: REFUSED symlink (someone else's SSOT)"
125
+ [ "$installed" -eq 1 ] && hard_fail=1 ;;
126
+ invalid-json|invalid-entry)
127
+ log " config: $status"
128
+ [ "$installed" -eq 1 ] && hard_fail=1 ;;
129
+ file-absent|not-ours)
130
+ if [ "$installed" -eq 1 ]; then
131
+ log " config: $status (owned state present — this is drift)"
132
+ hard_fail=1
133
+ else
134
+ log " config: $status (not ours; run install-copilot-mcp to adopt)"
135
+ fi ;;
136
+ *)
137
+ log " config: unexpected status '$out'"
138
+ [ "$installed" -eq 1 ] && hard_fail=1 ;;
139
+ esac
140
+ fi
141
+ if [ -f "$STATE_FILE" ]; then
142
+ local managed expected managed_status
143
+ expected="$(python3 -c 'import os,sys; print(os.path.abspath(sys.argv[1]))' "$CONFIG")"
144
+ if ! managed="$(state_target)"; then
145
+ log " state: CORRUPT — $STATE_FILE has no absolute managedConfigPath"
146
+ hard_fail=1
147
+ elif [ "$managed" != "$expected" ]; then
148
+ log " state: FOREIGN TARGET — state manages '$managed', Copilot reads '$expected'"
149
+ hard_fail=1
150
+ else
151
+ managed_status="$(run_config doctor-static "$managed" "$COMMAND" | tail -1)"
152
+ case "$managed_status" in
153
+ configured\ *) log " state: install-state present; managed config still configures entwurf-bridge." ;;
154
+ file-absent)
155
+ log " state: ORPHANED — managed config disappeared; removing stale state."
156
+ rm -f "$STATE_FILE" ;;
157
+ *)
158
+ log " state: DRIFT — managed config no longer satisfies the MCP contract ($managed_status)."
159
+ hard_fail=1 ;;
160
+ esac
161
+ fi
162
+ else
163
+ log " state: absent (no MCP ownership recorded)"
164
+ fi
165
+
166
+ if [ "$hard_fail" -ne 0 ]; then
167
+ fail "doctor found a broken Copilot MCP configuration."
168
+ fi
169
+ log "doctor: ok."
170
+ }
171
+
172
+ case "${1:-}" in
173
+ install) do_install ;;
174
+ uninstall) do_uninstall ;;
175
+ doctor) do_doctor ;;
176
+ *) echo "usage: copilot-mcp-bridge.sh <install|uninstall|doctor>" >&2; exit 2 ;;
177
+ esac
@@ -0,0 +1,221 @@
1
+ #!/usr/bin/env python3
2
+ """Stateful Copilot MCP-config adapter; stdlib only.
3
+
4
+ Owns ONE server key (``entwurf-bridge``) inside ``~/.copilot/mcp-config.json``.
5
+ The file wrapper is always ``mcpServers``. The stdio entry follows Copilot CLI's
6
+ writer, not the API wire schema: ``{type:"local", command, args?}``.
7
+ Adopts regular files, refuses symlinks, records first-install preimages.
8
+ """
9
+
10
+ import datetime
11
+ import json
12
+ import os
13
+ import sys
14
+ import tempfile
15
+
16
+ STATE_SCHEMA_VERSION = 1
17
+ SERVER_KEY = "entwurf-bridge"
18
+ ENTRY_TYPE = "local"
19
+
20
+
21
+ def die(code: int, message: str) -> "None":
22
+ sys.stderr.write(message.rstrip("\n") + "\n")
23
+ raise SystemExit(code)
24
+
25
+
26
+ def load_object(path: str, label: str) -> dict:
27
+ try:
28
+ with open(path, "r", encoding="utf-8") as handle:
29
+ raw = handle.read()
30
+ except OSError as error:
31
+ die(4, f"copilot-mcp: cannot read {label} {path}: {error}")
32
+ if not raw.strip():
33
+ return {}
34
+ try:
35
+ value = json.loads(raw)
36
+ except json.JSONDecodeError as error:
37
+ die(4, f"copilot-mcp: {label} {path} is not valid JSON: {error}")
38
+ if not isinstance(value, dict):
39
+ die(4, f"copilot-mcp: {label} {path} top-level must be a JSON object")
40
+ return value
41
+
42
+
43
+ def atomic_write(path: str, value: dict) -> None:
44
+ directory = os.path.dirname(os.path.abspath(path))
45
+ os.makedirs(directory, exist_ok=True)
46
+ fd, temporary = tempfile.mkstemp(dir=directory, prefix=".copilot-mcp-", suffix=".json")
47
+ try:
48
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
49
+ json.dump(value, handle, indent=2)
50
+ handle.write("\n")
51
+ os.replace(temporary, path)
52
+ except BaseException:
53
+ try:
54
+ os.unlink(temporary)
55
+ except FileNotFoundError:
56
+ pass
57
+ raise
58
+
59
+
60
+ def now() -> str:
61
+ return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
62
+
63
+
64
+ def our_entry(command: str) -> dict:
65
+ # CLI `copilot mcp add` writes type:"local" (not "stdio") plus command/args.
66
+ # args is present and empty so the inverse has a stable shape; env/timeout/tools stay omitted.
67
+ return {"type": ENTRY_TYPE, "command": command, "args": []}
68
+
69
+
70
+ def checked_state(state_path: str) -> dict:
71
+ state = load_object(state_path, "install-state")
72
+ required = (
73
+ "managedConfigPath",
74
+ "serverKey",
75
+ "command",
76
+ "detectMode",
77
+ "configExistedBefore",
78
+ "preimage",
79
+ )
80
+ if state.get("schemaVersion") != STATE_SCHEMA_VERSION or any(key not in state for key in required):
81
+ die(4, f"copilot-mcp: install-state {state_path} has an unsupported shape")
82
+ if state.get("serverKey") != SERVER_KEY:
83
+ die(4, f"copilot-mcp: install-state {state_path} serverKey is not {SERVER_KEY}")
84
+ return state
85
+
86
+
87
+ def prior_state(state_path: str, config_path: str) -> dict | None:
88
+ if not os.path.exists(state_path):
89
+ return None
90
+ state = checked_state(state_path)
91
+ return state if state["managedConfigPath"] == os.path.abspath(config_path) else None
92
+
93
+
94
+ def install(config_path: str, command: str, state_path: str) -> None:
95
+ if os.path.islink(config_path):
96
+ die(3, f"copilot-mcp: refusing to adopt {config_path} — symlink to {os.readlink(config_path)} (someone else's SSOT)")
97
+
98
+ existed = os.path.exists(config_path)
99
+ data = load_object(config_path, "config") if existed else {}
100
+ servers = data.get("mcpServers")
101
+ if servers is None:
102
+ servers = {}
103
+ data["mcpServers"] = servers
104
+ if not isinstance(servers, dict):
105
+ die(4, f"copilot-mcp: {config_path} mcpServers must be a JSON object")
106
+
107
+ prior = prior_state(state_path, config_path)
108
+ if prior is None:
109
+ state = {
110
+ "schemaVersion": STATE_SCHEMA_VERSION,
111
+ "managedConfigPath": os.path.abspath(config_path),
112
+ "serverKey": SERVER_KEY,
113
+ "command": command,
114
+ "detectMode": "adopt-regular-file" if existed else "created-new",
115
+ "configExistedBefore": existed,
116
+ "preimage": servers.get(SERVER_KEY),
117
+ "installedAt": now(),
118
+ }
119
+ else:
120
+ state = prior
121
+
122
+ servers[SERVER_KEY] = our_entry(command)
123
+ atomic_write(config_path, data)
124
+ atomic_write(state_path, state)
125
+ sys.stdout.write(f"{state['detectMode']} {os.path.abspath(config_path)}\n")
126
+
127
+
128
+ def uninstall(state_path: str) -> None:
129
+ if not os.path.exists(state_path):
130
+ die(2, f"copilot-mcp: no install-state at {state_path} — nothing to undo")
131
+ state = checked_state(state_path)
132
+ config_path = state.get("managedConfigPath")
133
+ if not isinstance(config_path, str) or not os.path.isabs(config_path):
134
+ die(4, f"copilot-mcp: install-state {state_path} has no absolute managedConfigPath")
135
+ if os.path.islink(config_path):
136
+ die(3, f"copilot-mcp: refusing to uninstall — {config_path} became a symlink (someone else's SSOT)")
137
+
138
+ if os.path.exists(config_path):
139
+ data = load_object(config_path, "config")
140
+ servers = data.get("mcpServers")
141
+ if isinstance(servers, dict):
142
+ preimage = state.get("preimage")
143
+ if preimage is None:
144
+ servers.pop(SERVER_KEY, None)
145
+ else:
146
+ servers[SERVER_KEY] = preimage
147
+ created = state.get("detectMode") == "created-new" and state.get("configExistedBefore") is False
148
+ only_ours = created and len(servers) == 0 and set(data.keys()) == {"mcpServers"}
149
+ if only_ours:
150
+ os.remove(config_path)
151
+ else:
152
+ atomic_write(config_path, data)
153
+
154
+ os.remove(state_path)
155
+ sys.stdout.write(f"uninstalled {config_path}\n")
156
+
157
+
158
+ def _doctor_invocation(config_path: str, command: str):
159
+ if os.path.islink(config_path):
160
+ return "symlink", None
161
+ if not os.path.exists(config_path):
162
+ return "file-absent", None
163
+ try:
164
+ data = load_object(config_path, "config")
165
+ except SystemExit:
166
+ return "invalid-json", None
167
+ servers = data.get("mcpServers")
168
+ if not isinstance(servers, dict) or SERVER_KEY not in servers:
169
+ return "not-ours", None
170
+ server = servers.get(SERVER_KEY)
171
+ if not isinstance(server, dict):
172
+ return "invalid-entry", None
173
+ found = server.get("command")
174
+ args = server.get("args", [])
175
+ env = server.get("env", {})
176
+ if server.get("type") != ENTRY_TYPE:
177
+ return "invalid-entry", None
178
+ if not isinstance(found, str) or not found:
179
+ return "invalid-entry", None
180
+ if found != command:
181
+ return "not-ours", None
182
+ if not isinstance(args, list) or not all(isinstance(arg, str) for arg in args):
183
+ return "invalid-entry", None
184
+ if not isinstance(env, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in env.items()):
185
+ return "invalid-entry", None
186
+ return "configured", {"command": found, "args": args, "env": env}
187
+
188
+
189
+ def doctor_static(config_path: str, command: str) -> None:
190
+ status, invocation = _doctor_invocation(config_path, command)
191
+ if status != "configured":
192
+ sys.stdout.write(f"{status}\n")
193
+ return
194
+ sys.stdout.write(f"configured {invocation['command']}\n")
195
+
196
+
197
+ def doctor_invocation(config_path: str, command: str) -> None:
198
+ status, invocation = _doctor_invocation(config_path, command)
199
+ if status != "configured":
200
+ die(4, f"copilot-mcp: cannot read configured invocation from {config_path}: {status}")
201
+ sys.stdout.write(json.dumps(invocation, separators=(",", ":")) + "\n")
202
+
203
+
204
+ def main(argv: list[str]) -> None:
205
+ if len(argv) < 2:
206
+ die(5, "usage: copilot-mcp-config.py <install|uninstall|doctor-static|doctor-invocation> ...")
207
+ match argv[1]:
208
+ case "install" if len(argv) == 5:
209
+ install(argv[2], argv[3], argv[4])
210
+ case "uninstall" if len(argv) == 3:
211
+ uninstall(argv[2])
212
+ case "doctor-static" if len(argv) == 4:
213
+ doctor_static(argv[2], argv[3])
214
+ case "doctor-invocation" if len(argv) == 4:
215
+ doctor_invocation(argv[2], argv[3])
216
+ case _:
217
+ die(5, "usage: copilot-mcp-config.py <install config command state|uninstall state|doctor-static config command|doctor-invocation config command>")
218
+
219
+
220
+ if __name__ == "__main__":
221
+ main(sys.argv)