@sriinnu/fiche 0.0.0-stage → 0.19.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 (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +288 -2
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +122 -4
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,650 @@
1
+ /**
2
+ * `inkling warp -- <agent-command>`
3
+ *
4
+ * Runs the agent behind a CONNECT proxy that decrypts api.anthropic.com and
5
+ * re-points only /v1/messages at the local inkling proxy. The agent never sees a
6
+ * custom ANTHROPIC_BASE_URL, so the client-side "firstParty" checks that hide
7
+ * /remote-control (and disable claude.ai connectors) still pass, while inkling
8
+ * gets the one path it transforms.
9
+ *
10
+ * Compare the manual equivalent, which needs two extra tools and a CA trusted
11
+ * process-wide:
12
+ *
13
+ * mitmdump --map-remote '|^https://api\.anthropic\.com/v1/messages|http://127.0.0.1:47821/v1/messages'
14
+ * HTTPS_PROXY=http://127.0.0.1:8080 NODE_EXTRA_CA_CERTS=~/.mitmproxy/mitmproxy-ca-cert.pem claude
15
+ */
16
+ import { spawn, spawnSync } from 'node:child_process';
17
+ import { randomBytes } from 'node:crypto';
18
+ import { closeSync, constants as fsConstants, existsSync, fchmodSync, fstatSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeSync, } from 'node:fs';
19
+ import { createServer, get as httpGet } from 'node:http';
20
+ import { connect as netConnect } from 'node:net';
21
+ import { homedir } from 'node:os';
22
+ import { basename, join } from 'node:path';
23
+ import { CertificateAuthority } from './ca.js';
24
+ import { buildWarpAppArgs } from './app-launch.js';
25
+ import { createWarpHandlers } from './connect.js';
26
+ import { isRunnable } from './resolve.js';
27
+ import { parseRoute, routeDestination } from './route.js';
28
+ import { readBrandEnv } from '../core/env.js';
29
+ import { buildUpstreamRegistry, DEFAULT_UPSTREAM_REGISTRY, getEnabledProviders, parseUpstreamHosts, } from '../core/upstream-hosts.js';
30
+ const LOOPBACK_NO_PROXY_HOSTS = ['localhost', '127.0.0.1', '::1'];
31
+ const CODEX_NON_SESSION_SUBCOMMANDS = new Set([
32
+ 'app-server',
33
+ 'remote-control',
34
+ 'completion',
35
+ 'update',
36
+ 'help',
37
+ '--help',
38
+ '-h',
39
+ '--version',
40
+ '-V',
41
+ ]);
42
+ /**
43
+ * Augment wrapped child argv when necessary so clients keep HTTP traffic inside
44
+ * warp's session rather than delegating to an unwrapped background daemon.
45
+ * For `codex` (>= 0.172), inject `-c features.daemon_auto_start=false` unless
46
+ * running daemon-management/meta commands, already overridden, or disabled via
47
+ * `FICHE_CODEX_KEEP_DAEMON=1`.
48
+ */
49
+ export function augmentWrappedCommand(command, env = process.env) {
50
+ if (command.length === 0)
51
+ return [];
52
+ const bin = basename(command[0]).toLowerCase();
53
+ if (bin !== 'codex' && bin !== 'codex.exe')
54
+ return [...command];
55
+ if (/^(1|true|yes|on)$/i.test((env.FICHE_CODEX_KEEP_DAEMON ?? '').trim())) {
56
+ return [...command];
57
+ }
58
+ const rest = command.slice(1);
59
+ if (rest.some((arg) => arg.includes('daemon_auto_start')))
60
+ return [...command];
61
+ if (rest.length > 0 && CODEX_NON_SESSION_SUBCOMMANDS.has(rest[0])) {
62
+ return [...command];
63
+ }
64
+ return [command[0], '-c', 'features.daemon_auto_start=false', ...rest];
65
+ }
66
+ const WARP_TOKEN_RE = /^[0-9a-f]{64}$/i;
67
+ /**
68
+ * Load or atomically generate the per-user 0600 loopback warp auth secret
69
+ * (`~/.fiche/warp-token`) used to authenticate warped desktop apps to Fiche.
70
+ */
71
+ export function loadOrCreateWarpToken(dir) {
72
+ const dirExisted = existsSync(dir);
73
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
74
+ if (!dirExisted) {
75
+ try {
76
+ fchmodSync(openSync(dir, fsConstants.O_RDONLY), 0o700);
77
+ }
78
+ catch {
79
+ /* best effort */
80
+ }
81
+ }
82
+ const tokenPath = join(dir, 'warp-token');
83
+ let readFd;
84
+ try {
85
+ readFd = openSync(tokenPath, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
86
+ const st = fstatSync(readFd);
87
+ if (st.isFile() && st.size > 0 && st.size <= 256) {
88
+ const existing = readFileSync(readFd, 'utf8').trim();
89
+ if (WARP_TOKEN_RE.test(existing)) {
90
+ try {
91
+ fchmodSync(readFd, 0o600);
92
+ }
93
+ catch {
94
+ /* ignore */
95
+ }
96
+ return existing.toLowerCase();
97
+ }
98
+ }
99
+ }
100
+ catch {
101
+ // Missing or invalid token — generate a fresh one below.
102
+ }
103
+ finally {
104
+ if (readFd !== undefined) {
105
+ try {
106
+ closeSync(readFd);
107
+ }
108
+ catch { /* ignore */ }
109
+ }
110
+ }
111
+ const token = randomBytes(32).toString('hex');
112
+ const tmpPath = `${tokenPath}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
113
+ let writeFd;
114
+ try {
115
+ writeFd = openSync(tmpPath, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | (fsConstants.O_NOFOLLOW ?? 0), 0o600);
116
+ const buf = Buffer.from(`${token}\n`, 'utf8');
117
+ let offset = 0;
118
+ while (offset < buf.length) {
119
+ const n = writeSync(writeFd, buf, offset, buf.length - offset);
120
+ if (n <= 0)
121
+ throw new Error('short write');
122
+ offset += n;
123
+ }
124
+ fchmodSync(writeFd, 0o600);
125
+ fsyncSync(writeFd);
126
+ closeSync(writeFd);
127
+ writeFd = undefined;
128
+ renameSync(tmpPath, tokenPath);
129
+ return token;
130
+ }
131
+ catch (err) {
132
+ if (writeFd !== undefined) {
133
+ try {
134
+ closeSync(writeFd);
135
+ }
136
+ catch { /* ignore */ }
137
+ }
138
+ try {
139
+ unlinkSync(tmpPath);
140
+ }
141
+ catch { /* ignore */ }
142
+ throw err;
143
+ }
144
+ }
145
+ /**
146
+ * Only strip `ANTHROPIC_BASE_URL` when it points to Fiche's own local loopback
147
+ * proxy (`127.0.0.1:<port>`, `localhost:<port>`, `[::1]:<port>`). Remote 3rd-party
148
+ * base URLs (DeepSeek, Kimi, GLM, MiniMax, Qwen, OpenRouter, custom gateways)
149
+ * are preserved so warp routes them via `followHosts`.
150
+ */
151
+ export function shouldStripAnthropicBaseUrl(rawUrl, fichePort) {
152
+ const trimmed = rawUrl?.trim();
153
+ if (!trimmed)
154
+ return false;
155
+ let parsed;
156
+ try {
157
+ parsed = new URL(trimmed);
158
+ }
159
+ catch {
160
+ return false;
161
+ }
162
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
163
+ return false;
164
+ const host = parsed.hostname.replace(/^\[|\]$/g, '').toLowerCase();
165
+ if (host !== '127.0.0.1' && host !== 'localhost' && host !== '::1')
166
+ return false;
167
+ const effectivePort = parsed.port
168
+ ? Number(parsed.port)
169
+ : parsed.protocol === 'https:'
170
+ ? 443
171
+ : 80;
172
+ return effectivePort === fichePort;
173
+ }
174
+ export function mergeNoProxy(existing, excludeHosts) {
175
+ const excluded = new Set();
176
+ if (excludeHosts) {
177
+ for (const h of excludeHosts) {
178
+ const lower = h.trim().toLowerCase().replace(/^\[|\]$/g, '');
179
+ if (lower)
180
+ excluded.add(lower);
181
+ }
182
+ }
183
+ const isExcluded = (entry) => {
184
+ const bare = entry.trim().toLowerCase().replace(/^\[|\]$/g, '');
185
+ return excluded.has(bare);
186
+ };
187
+ const entries = (existing ?? '')
188
+ .split(',')
189
+ .map((part) => part.trim())
190
+ .filter((part) => Boolean(part) && !isExcluded(part));
191
+ const seen = new Set(entries.map((part) => part.toLowerCase()));
192
+ for (const host of LOOPBACK_NO_PROXY_HOSTS) {
193
+ if (excluded.has(host))
194
+ continue;
195
+ const alreadyCovered = host === '::1' ? seen.has('::1') || seen.has('[::1]') : seen.has(host);
196
+ if (!alreadyCovered) {
197
+ seen.add(host);
198
+ entries.push(host);
199
+ }
200
+ }
201
+ return entries.join(',');
202
+ }
203
+ /**
204
+ * Only the inference path is diverted for enabled providers. Everything else on
205
+ * the host — OAuth, telemetry, the control plane — is re-originated untouched,
206
+ * which is what keeps the agent's client-side gates satisfied.
207
+ */
208
+ export function defaultRoutes(port, enabledProviders = getEnabledProviders()) {
209
+ const enabled = new Set(enabledProviders);
210
+ const out = [];
211
+ if (enabled.has('anthropic')) {
212
+ out.push(parseRoute(`api.anthropic.com/v1/messages*=http://127.0.0.1:${port}`));
213
+ }
214
+ if (enabled.has('openai')) {
215
+ out.push(parseRoute(`api.openai.com/v1/responses*=http://127.0.0.1:${port}`), parseRoute(`api.openai.com/v1/chat/completions*=http://127.0.0.1:${port}`), parseRoute(`chatgpt.com/backend-api/codex/responses*=http://127.0.0.1:${port}`));
216
+ }
217
+ if (enabled.has('google')) {
218
+ out.push(parseRoute(`cloudcode-pa.googleapis.com/v1internal:streamGenerateContent*=http://127.0.0.1:${port}`), parseRoute(`cloudcode-pa.googleapis.com/v1internal:generateContent*=http://127.0.0.1:${port}`), parseRoute(`daily-cloudcode-pa.googleapis.com/v1internal:streamGenerateContent*=http://127.0.0.1:${port}`), parseRoute(`daily-cloudcode-pa.googleapis.com/v1internal:generateContent*=http://127.0.0.1:${port}`), parseRoute(`generativelanguage.googleapis.com/v1beta/models/*:streamGenerateContent*=http://127.0.0.1:${port}`), parseRoute(`generativelanguage.googleapis.com/v1beta/models/*:generateContent*=http://127.0.0.1:${port}`), parseRoute(`generativelanguage.googleapis.com/v1/models/*:streamGenerateContent*=http://127.0.0.1:${port}`), parseRoute(`generativelanguage.googleapis.com/v1/models/*:generateContent*=http://127.0.0.1:${port}`), parseRoute(`generativelanguage.googleapis.com/v1beta/openai/chat/completions*=http://127.0.0.1:${port}`));
219
+ }
220
+ out.push(...compatRoutes(port, enabledProviders));
221
+ return out;
222
+ }
223
+ /** Inference endpoints, relative to a provider's API prefix. */
224
+ const COMPAT_INFERENCE_PATHS = ['/v1/messages', '/messages', '/v1/chat/completions', '/chat/completions', '/v1/responses', '/responses'];
225
+ /**
226
+ * Third-party providers from the same registry fiche follows, so warp diverts
227
+ * only opted-in built-in providers (or all when `enabledProviders` is omitted
228
+ * for direct callers) plus explicit `FICHE_UPSTREAM_HOSTS` custom entries.
229
+ */
230
+ export function compatRoutes(port, enabledProviders) {
231
+ const registry = buildUpstreamRegistry(parseUpstreamHosts(readBrandEnv('UPSTREAM_HOSTS')));
232
+ const enabled = enabledProviders === undefined ? null : new Set(enabledProviders);
233
+ const specs = new Set();
234
+ for (const entry of registry.values()) {
235
+ if (entry.family !== 'compat')
236
+ continue;
237
+ if (enabled !== null && entry.provider !== undefined && !enabled.has(entry.provider))
238
+ continue;
239
+ for (const prefix of entry.prefixes) {
240
+ for (const tail of COMPAT_INFERENCE_PATHS)
241
+ specs.add(`${entry.host}${prefix}${tail}*`);
242
+ }
243
+ }
244
+ return [...specs].map((pattern) => parseRoute(`${pattern}=http://127.0.0.1:${port}`));
245
+ }
246
+ /**
247
+ * Probe whether a local fiche daemon is accepting TCP connections on `127.0.0.1:port`.
248
+ * Used by `fiche warp` so wrapped commands fall back to an unwrapped launch
249
+ * whenever the daemon is intentionally stopped.
250
+ */
251
+ export function isLocalDaemonReachable(port, timeoutMs = 200) {
252
+ return new Promise((resolve) => {
253
+ let settled = false;
254
+ const sock = netConnect({ host: '127.0.0.1', port });
255
+ const finish = (reachable) => {
256
+ if (settled)
257
+ return;
258
+ settled = true;
259
+ sock.destroy();
260
+ resolve(reachable);
261
+ };
262
+ sock.setTimeout(timeoutMs, () => finish(false));
263
+ sock.once('connect', () => finish(true));
264
+ sock.once('error', () => finish(false));
265
+ });
266
+ }
267
+ export function createWarpRuntime(options) {
268
+ const { port } = options;
269
+ const activeProviders = options.providers ?? getEnabledProviders();
270
+ const explicitRoutes = (options.routes ?? []).map((spec) => parseRoute(spec));
271
+ // Explicit rules first: an operator route for a specific host:port must win
272
+ // over anything built in.
273
+ let currentRoutes = [
274
+ ...explicitRoutes,
275
+ ...defaultRoutes(port, activeProviders),
276
+ ];
277
+ const explicitLoopbackHosts = new Set();
278
+ for (const route of explicitRoutes) {
279
+ const hostSpec = route.pattern.split('/', 1)[0].toLowerCase();
280
+ const bare = hostSpec.startsWith('[')
281
+ ? hostSpec.slice(1, hostSpec.indexOf(']') > 0 ? hostSpec.indexOf(']') : undefined)
282
+ : (hostSpec.match(/:/g)?.length ?? 0) > 1
283
+ ? hostSpec
284
+ : hostSpec.split(':', 1)[0];
285
+ if (bare === 'localhost' || bare === '127.0.0.1' || bare === '::1') {
286
+ explicitLoopbackHosts.add(bare);
287
+ }
288
+ }
289
+ /** POSIX single-quote: safe for anything except a single quote itself. */
290
+ const shellQuote = (arg) => `'${arg.replaceAll("'", `'\\''`)}'`;
291
+ /**
292
+ * Does the user's interactive shell consider this word an alias? Both zsh
293
+ * ("cc is an alias for ...") and bash ("cc is aliased to ...") answer through
294
+ * `type`, and only an interactive shell has sourced the rc file that defines
295
+ * one. Costs a single shell start at launch.
296
+ */
297
+ const shellAliasTarget = (name, shell, env) => {
298
+ if (name.includes('/'))
299
+ return null;
300
+ const probe = spawnSync(shell, ['-ic', `type -- ${shellQuote(name)}`], {
301
+ encoding: 'utf8',
302
+ env,
303
+ timeout: 1500,
304
+ });
305
+ const match = /\bis (?:an alias for|aliased to)\s+(.+)$/m.exec(probe.stdout ?? '');
306
+ if (!match)
307
+ return null;
308
+ // bash wraps the expansion in `backtick quote'; zsh leaves it bare.
309
+ return match[1].trim().replace(/^`/, '').replace(/'$/, '');
310
+ };
311
+ /**
312
+ * Run the child, falling back to the user's interactive shell when the
313
+ * command is not an executable on PATH.
314
+ *
315
+ * spawn() is execvp, which only knows files. An alias like `cc` exists solely
316
+ * inside an interactive zsh, and `sh -c` will not find it either: aliases come
317
+ * from ~/.zshrc, which only an *interactive* shell sources. So the fallback is
318
+ * `$SHELL -ic`, which loads the rc file and expands the alias — including any
319
+ * env assignments baked into it, which no PATH lookup could have carried.
320
+ *
321
+ * Direct spawn stays the fast path: the shell is only involved when execvp
322
+ * would have failed outright.
323
+ */
324
+ const spawnResolved = (command, env) => {
325
+ const direct = { stdio: 'inherit', env };
326
+ const shell = env.SHELL || '/bin/sh';
327
+ const cmd0 = command[0];
328
+ // Only plain command words are valid interactive-shell alias names; anything
329
+ // with spaces, paths, or shell metacharacters must never hit unquoted `shell -ic`.
330
+ const safeAliasWord = /^[A-Za-z0-9._+-]+$/.test(cmd0);
331
+ // Native Windows has no /bin/sh, and Git Bash's SHELL=/usr/bin/bash is not
332
+ // a path Node can spawn. Without a usable shell there are no aliases to
333
+ // consult and no fallback to take.
334
+ const shellUsable = isRunnable(shell, env);
335
+ // An alias can shadow a real binary: `cc` is Apple clang on PATH and a
336
+ // Claude Code alias in the user's zsh, so PATH alone would silently run
337
+ // the wrong program. Ask the interactive shell what the word means first.
338
+ const alias = shellUsable && safeAliasWord ? shellAliasTarget(cmd0, shell, env) : null;
339
+ // But a stale alias must not shadow a working binary either. An alias
340
+ // pointing at an uninstalled path (`claude` -> /opt/homebrew/bin/claude
341
+ // after a move to a node-managed install) would otherwise fail the launch
342
+ // outright, with a real claude sitting on PATH. An env-assignment prefix
343
+ // (`FOO=1 claude`) is unverifiable, so it is taken at its word.
344
+ const aliasWord = alias?.split(/\s+/)[0] ?? '';
345
+ const aliasUsable = alias !== null && (aliasWord.includes('=') || isRunnable(aliasWord, env));
346
+ if (alias !== null && !aliasUsable) {
347
+ console.error(`[fiche] warp: ignoring stale alias ${cmd0} → ${aliasWord} (not executable)`);
348
+ }
349
+ if (!aliasUsable && isRunnable(cmd0, env)) {
350
+ return spawn(cmd0, command.slice(1), direct);
351
+ }
352
+ if (!shellUsable || !safeAliasWord) {
353
+ // Let spawn() report the real ENOENT for the command itself rather
354
+ // than a misleading one for a shell that was never there or unsafe word.
355
+ return spawn(cmd0, command.slice(1), direct);
356
+ }
357
+ console.error(`[fiche] warp: resolving ${cmd0} via interactive shell fallback`);
358
+ // The command word is deliberately left unquoted: a shell only expands
359
+ // aliases on unquoted words, so quoting it would defeat the entire point of
360
+ // this fallback. Arguments are still quoted — they are data, never aliases.
361
+ const script = `unset -f ${shellQuote(cmd0)} 2>/dev/null || true; ${[cmd0, ...command.slice(1).map(shellQuote)].join(' ')}`;
362
+ return spawn(shell, ['-ic', script], direct);
363
+ };
364
+ const wireChildLifecycle = (child, binLabel, onExitCleanup, appLaunchedAt) => {
365
+ let childLive = true;
366
+ child.on('exit', () => {
367
+ childLive = false;
368
+ onExitCleanup?.();
369
+ });
370
+ process.on('exit', () => {
371
+ if (childLive)
372
+ child.kill('SIGTERM');
373
+ });
374
+ child.on('error', (err) => {
375
+ onExitCleanup?.();
376
+ console.error(`[fiche] warp: cannot run ${binLabel}: ${err.message}`);
377
+ process.exit(127);
378
+ });
379
+ // SIGHUP and SIGQUIT matter as much as the interactive two: closing the
380
+ // terminal sends SIGHUP, and without forwarding it the agent survives with
381
+ // its proxy pointed at a port that is about to close.
382
+ const forwarded = ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT'];
383
+ child.on('exit', (code, signal) => {
384
+ if (options.app && appLaunchedAt !== undefined && code === 0 && !signal && Date.now() - appLaunchedAt < 2500) {
385
+ console.error(`[fiche] warp: warning: ${options.app.appName} exited immediately (code 0) — an unwrapped instance is likely already running and handed off to it. Quit ${options.app.appName} completely before launching via \`fiche warp --app ${options.app.appName}\`.`);
386
+ }
387
+ // Reproduce the child's own exit status so warp is transparent to callers.
388
+ // Re-raising means routing the signal back through our own handlers, so
389
+ // drop them first: Ctrl-C kills the child with SIGINT, and without this
390
+ // the re-raise just re-enters the forwarder, kills an already-dead child
391
+ // and leaves warp running forever.
392
+ if (signal) {
393
+ for (const s of forwarded)
394
+ process.removeAllListeners(s);
395
+ process.kill(process.pid, signal);
396
+ return;
397
+ }
398
+ process.exit(code ?? 0);
399
+ });
400
+ for (const signal of forwarded) {
401
+ process.on(signal, () => child.kill(signal));
402
+ }
403
+ };
404
+ const startWrappedLaunch = (command) => {
405
+ const caDir = join(homedir(), '.fiche');
406
+ const legacyCaDir = join(homedir(), '.inkling');
407
+ // Reuse legacy ~/.inkling CA dir if ~/.fiche doesn't exist yet so installed trust certs keep working.
408
+ const resolvedCaDir = existsSync(caDir) || !existsSync(legacyCaDir) ? caDir : legacyCaDir;
409
+ const ca = CertificateAuthority.loadOrCreate(resolvedCaDir);
410
+ const warpAuthToken = loadOrCreateWarpToken(resolvedCaDir);
411
+ let lastProvidersKey = activeProviders.join(',');
412
+ let providersPollTimer;
413
+ if (options.providers === undefined) {
414
+ providersPollTimer = setInterval(() => {
415
+ const req = httpGet({ host: '127.0.0.1', port, path: '/api/providers', agent: false, timeout: 500 }, (res) => {
416
+ if (res.statusCode !== 200) {
417
+ res.resume();
418
+ return;
419
+ }
420
+ const chunks = [];
421
+ res.on('data', (c) => chunks.push(c));
422
+ res.on('end', () => {
423
+ try {
424
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
425
+ if (!Array.isArray(parsed.enabled))
426
+ return;
427
+ const next = parsed.enabled.filter((p) => typeof p === 'string');
428
+ const key = next.join(',');
429
+ if (key !== lastProvidersKey) {
430
+ lastProvidersKey = key;
431
+ currentRoutes = [...explicitRoutes, ...defaultRoutes(port, next)];
432
+ }
433
+ }
434
+ catch {
435
+ // Ignore transient poll errors
436
+ }
437
+ });
438
+ });
439
+ req.on('error', () => { });
440
+ req.on('timeout', () => req.destroy());
441
+ }, 2000);
442
+ providersPollTimer.unref();
443
+ }
444
+ let proxy;
445
+ const handlers = createWarpHandlers({
446
+ routes: () => currentRoutes,
447
+ ca,
448
+ failOpenOnDivertRefused: true,
449
+ warpAuthToken,
450
+ selfPort: () => {
451
+ const addr = proxy?.address();
452
+ return typeof addr === 'object' && addr ? addr.port : undefined;
453
+ },
454
+ // The child inherits this terminal and Claude Code draws a full-screen TUI
455
+ // over it, so anything written after the child starts corrupts the display.
456
+ // Keep the line when stdout is redirected (piping, CI, debugging); stay
457
+ // silent when a human is looking at the agent. events.jsonl records the
458
+ // request either way.
459
+ onDivert: (host, path, target) => {
460
+ if (!process.stdout.isTTY)
461
+ console.error(`[fiche] warp: ${host}${path} → ${target}`);
462
+ },
463
+ });
464
+ // warp's own listener, and the only reason a port is involved at all: the
465
+ // child is configured through HTTPS_PROXY, which can only name a host:port.
466
+ // The kernel picks it, nothing else needs to know it, so there is nothing to
467
+ // collide with a inkling already running.
468
+ proxy = createServer(handlers.handleAbsoluteForm);
469
+ proxy.on('connection', (socket) => socket.setNoDelay(true));
470
+ proxy.on('connect', handlers.handleConnect);
471
+ const spawnChild = (cmd, proxyUrl) => {
472
+ const env = { ...process.env };
473
+ // Only strip ANTHROPIC_BASE_URL when it targets Fiche's own loopback port;
474
+ // preserve remote 3rd-party base URLs (DeepSeek, Kimi, GLM, OpenRouter, etc.).
475
+ if (shouldStripAnthropicBaseUrl(env.ANTHROPIC_BASE_URL, port)) {
476
+ delete env.ANTHROPIC_BASE_URL;
477
+ delete env.ANTHROPIC_UNIX_SOCKET;
478
+ }
479
+ else if (!env.ANTHROPIC_BASE_URL?.trim()) {
480
+ delete env.ANTHROPIC_UNIX_SOCKET;
481
+ }
482
+ env.HTTP_PROXY = proxyUrl;
483
+ env.http_proxy = proxyUrl;
484
+ env.HTTPS_PROXY = proxyUrl;
485
+ env.https_proxy = proxyUrl;
486
+ const rawNoProxy = [env.NO_PROXY, env.no_proxy].filter(Boolean).join(',');
487
+ const mergedNoProxy = mergeNoProxy(rawNoProxy || undefined, explicitLoopbackHosts);
488
+ env.NO_PROXY = mergedNoProxy;
489
+ env.no_proxy = mergedNoProxy;
490
+ // Trust is scoped to this child; nothing is added to the system keychain.
491
+ // Which variable actually works depends on the agent's runtime, and the
492
+ // answer is not stable: the macOS `claude` is a native Mach-O binary, not a
493
+ // Node script, so the Node-only variable alone would silently fail to make
494
+ // it trust us. Set every convention — they are inert for runtimes that
495
+ // ignore them, and one of them is the one that counts.
496
+ // NODE_EXTRA_CA_CERTS appends to Node's built-in roots, so the CA-only
497
+ // file is right there. The other three REPLACE the trust store: handing
498
+ // them a 1-cert file strips the public roots from every other HTTPS client
499
+ // in the session (gcloud, gws, pip all fail verification — #245). They get
500
+ // the bundle: our CA followed by the system roots.
501
+ env.NODE_EXTRA_CA_CERTS = ca.bundlePath; // Node, and Bun-compiled binaries
502
+ env.SSL_CERT_FILE = ca.bundlePath; // OpenSSL: curl, Rust, Go with cgo
503
+ env.CURL_CA_BUNDLE = ca.bundlePath; // libcurl
504
+ env.REQUESTS_CA_BUNDLE = ca.bundlePath; // Python requests / httpx
505
+ // Signal active warp session without setting FICHE_BYPASS=1, so integrated
506
+ // terminals inside warped desktop IDEs stay active and codex still disables daemon_auto_start.
507
+ env.FICHE_WARP_ACTIVE = '1';
508
+ const bypassList = ['localhost', '127.0.0.1', '[::1]']
509
+ .filter((h) => !explicitLoopbackHosts.has(h === '[::1]' ? '::1' : h))
510
+ .join(';');
511
+ const execArgv = options.app
512
+ ? buildWarpAppArgs(options.app, proxyUrl, cmd, {
513
+ spkiPins: ca.spkiPins,
514
+ ...(bypassList ? { proxyBypassList: bypassList } : {}),
515
+ })
516
+ : augmentWrappedCommand(cmd, env);
517
+ const launchedAt = options.app ? Date.now() : undefined;
518
+ const child = spawnResolved(execArgv, env);
519
+ wireChildLifecycle(child, execArgv[0], () => {
520
+ if (providersPollTimer) {
521
+ clearInterval(providersPollTimer);
522
+ providersPollTimer = undefined;
523
+ }
524
+ }, launchedAt);
525
+ // A connection dying is not a warp failure. The upstream resets, the proxy
526
+ // gets restarted, a keep-alive socket goes away between requests — all of
527
+ // that arrives here as an errno on a socket nobody was listening to at that
528
+ // instant. Exiting on it would take the agent down with us (see the exit
529
+ // handler above) and lose a whole run to one dropped TCP connection. Log
530
+ // and keep serving; the request that owned the socket fails on its own and
531
+ // the agent retries. Anything without an errno is a real bug in our code,
532
+ // and staying up for that would leave the agent talking to a proxy in an
533
+ // unknown state, so those still exit.
534
+ const NET_ERRNO = new Set([
535
+ 'ECONNRESET',
536
+ 'ECONNREFUSED',
537
+ 'ECONNABORTED',
538
+ 'EPIPE',
539
+ 'ETIMEDOUT',
540
+ 'EHOSTUNREACH',
541
+ 'ENETUNREACH',
542
+ 'ENETDOWN',
543
+ 'ENOTCONN',
544
+ 'EAI_AGAIN',
545
+ 'ERR_STREAM_DESTROYED',
546
+ 'ERR_STREAM_WRITE_AFTER_END',
547
+ 'ERR_SOCKET_CONNECTION_TIMEOUT',
548
+ ]);
549
+ const isBenignNetError = (err) => {
550
+ if (err instanceof AggregateError) {
551
+ return err.errors.length > 0 && err.errors.every((inner) => isBenignNetError(inner));
552
+ }
553
+ const code = err?.code;
554
+ return typeof code === 'string' && NET_ERRNO.has(code);
555
+ };
556
+ const die = (err) => {
557
+ if (isBenignNetError(err)) {
558
+ const code = err instanceof AggregateError
559
+ ? err.errors.map((e) => e?.code ?? 'ERR').join(',')
560
+ : err.code;
561
+ console.error(`[fiche] warp: connection error ${code} (continuing)`);
562
+ return;
563
+ }
564
+ console.error(`[fiche] warp: ${err instanceof Error ? err.stack : String(err)}`);
565
+ process.exit(1);
566
+ };
567
+ process.on('uncaughtException', die);
568
+ process.on('unhandledRejection', die);
569
+ };
570
+ // Startup banner goes to stderr: stdout belongs to the child, so a caller
571
+ // piping the agent's output gets the agent's bytes and nothing of ours.
572
+ const verboseBanner = Boolean(options.verbose)
573
+ || /^(?:1|true|yes|on)$/i.test((readBrandEnv('WARP_VERBOSE') ?? '').trim());
574
+ if (verboseBanner) {
575
+ for (const route of currentRoutes) {
576
+ console.error(`[fiche] warp route → ${route.pattern} → ${routeDestination(route)}`);
577
+ }
578
+ }
579
+ else {
580
+ const counts = new Map();
581
+ let customCount = explicitRoutes.length;
582
+ for (const route of currentRoutes.slice(explicitRoutes.length)) {
583
+ const routeHost = route.pattern.split('/', 1)[0].split(':', 1)[0].toLowerCase();
584
+ const provider = DEFAULT_UPSTREAM_REGISTRY.get(routeHost)?.provider;
585
+ if (provider)
586
+ counts.set(provider, (counts.get(provider) ?? 0) + 1);
587
+ else
588
+ customCount += 1;
589
+ }
590
+ const parts = activeProviders
591
+ .filter((id) => (counts.get(id) ?? 0) > 0)
592
+ .map((id) => `${id} (${counts.get(id)})`);
593
+ if (customCount > 0)
594
+ parts.push(`custom (${customCount})`);
595
+ const summary = parts.length > 0 ? parts.join(', ') : 'none (direct passthrough)';
596
+ console.error(`[fiche] warp providers → ${summary} → http://127.0.0.1:${port}`);
597
+ }
598
+ console.error(`[fiche] warp CA → ${ca.certPath}`);
599
+ if (ca.systemRootsPath) {
600
+ console.error(`[fiche] warp CA bundle → ${ca.bundlePath} (+ system roots from ${ca.systemRootsPath})`);
601
+ }
602
+ else {
603
+ console.error(`[fiche] warp CA bundle → ${ca.bundlePath} (no system root bundle found; ` +
604
+ `non-fiche HTTPS in the child may fail verification — set SSL_CERT_FILE to your OS bundle before warp)`);
605
+ }
606
+ if (options.app) {
607
+ const modeLabel = options.app.isElectron
608
+ ? 'Electron (--proxy-server + CA env)'
609
+ : 'native bundle (CA/proxy env — custom base URL still recommended if TLS-pinned)';
610
+ console.error(`[fiche] warp app → ${options.app.appName} [${modeLabel}] → ${options.app.appPath}`);
611
+ }
612
+ else {
613
+ console.error(`[fiche] warp exec → ${augmentWrappedCommand(command).join(' ')}`);
614
+ }
615
+ proxy.on('error', (err) => {
616
+ console.error(`[fiche] warp: proxy listener failed: ${err.message}`);
617
+ process.exit(1);
618
+ });
619
+ proxy.listen(0, '127.0.0.1', () => {
620
+ const address = proxy.address();
621
+ const proxyUrl = `http://127.0.0.1:${typeof address === 'object' && address ? address.port : 0}`;
622
+ console.error(`[fiche] warp proxy → ${proxyUrl} (child only)`);
623
+ spawnChild(command, proxyUrl);
624
+ });
625
+ };
626
+ const launch = (command) => {
627
+ if (!options.app && command.length === 0) {
628
+ console.error('[fiche] warp: nothing to run — usage: fiche warp -- <command> [args...]');
629
+ process.exit(2);
630
+ }
631
+ void (async () => {
632
+ if (explicitRoutes.length === 0 && !(await isLocalDaemonReachable(port))) {
633
+ const targetLabel = options.app ? options.app.appName : command.join(' ');
634
+ console.error(`[fiche] daemon on 127.0.0.1:${port} is not running — launching ${targetLabel} directly (unwrapped)`);
635
+ const directEnv = { ...process.env };
636
+ const directCmd = options.app ? [options.app.executablePath, ...command] : command;
637
+ const launchedAt = options.app ? Date.now() : undefined;
638
+ const child = spawnResolved(directCmd, directEnv);
639
+ wireChildLifecycle(child, directCmd[0], undefined, launchedAt);
640
+ return;
641
+ }
642
+ startWrappedLaunch(command);
643
+ })().catch((err) => {
644
+ console.error(`[fiche] warp: ${err instanceof Error ? err.stack : String(err)}`);
645
+ process.exit(1);
646
+ });
647
+ };
648
+ return { launch };
649
+ }
650
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
1
+ /** Does this word name a file path rather than a bare command? */
2
+ export declare const isPathLike: (word: string, platform?: NodeJS.Platform) => boolean;
3
+ /**
4
+ * Minimal `which`: is this bare name an executable on PATH?
5
+ *
6
+ * Windows splits PATH on `;` (a drive letter already contains `:`), and a bare
7
+ * `claude` only exists on disk as `claude.exe`, so PATHEXT has to be tried too.
8
+ */
9
+ export declare const whichSync: (name: string, env: NodeJS.ProcessEnv, platform?: NodeJS.Platform) => boolean;
10
+ /** Can this word actually be executed: a path that exists, or a name on PATH. */
11
+ export declare const isRunnable: (word: string, env: NodeJS.ProcessEnv, platform?: NodeJS.Platform) => boolean;
12
+ //# sourceMappingURL=resolve.d.ts.map