@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,1353 @@
1
+ /**
2
+ * User-pinned instructions.
3
+ *
4
+ * The problem: CLAUDE.md arrives in message 0, and by the time a long tool loop
5
+ * has run, position 0 reads as background rather than instruction. The harness
6
+ * itself works around this for its own rules by re-emitting `<system-reminder>`
7
+ * at the TAIL, where the model reads it last, immediately before generating.
8
+ * A pin buys that slot for the user's rules.
9
+ *
10
+ * Syntax is one line, one pin, wherever the user can type:
11
+ *
12
+ * @inkling pin be concise, no walls of text
13
+ * @inkling unpin
14
+ *
15
+ * The line is identical in a rules file (durable) and in a chat turn (session-only),
16
+ * so a session pin that works is made permanent by pasting it into the file. What
17
+ * differs is only WHERE it was found, which is enough to classify it:
18
+ *
19
+ * - inside the leading `<system-reminder>` run of message 0 → 'file'
20
+ * - anywhere in the system prompt → 'file'
21
+ * - in a user's typed text → 'session'
22
+ * - in any later `<system-reminder>` (inlined `@`-mention) → 'session'
23
+ *
24
+ * Two file locations because harnesses disagree on where a rules file goes.
25
+ * Claude Code inlines CLAUDE.md into message 0 behind a `<system-reminder>`
26
+ * envelope; OpenCode puts AGENTS.md in the system prompt with no wrapper and no
27
+ * label. Scanning only the first shape is what made #155 a no-op under OpenCode.
28
+ * Both are a file the user can edit, so both earn the durable tier.
29
+ *
30
+ * State is re-derived from the transcript on every request — no store, no session
31
+ * id (the Messages API has none), and rewinding the conversation rewinds the pins.
32
+ * This works even though we strip the commands from the outbound copy: inkling only
33
+ * rewrites the request going upstream, so the client's own transcript keeps
34
+ * re-sending them verbatim every turn.
35
+ */
36
+ /** One pin line. Longer than this is a document, not an instruction. */
37
+ const PIN_MAX_CHARS = 300;
38
+ /** Total pinned text emitted at the tail. A pin that dilutes itself is not a pin. */
39
+ const PIN_TOTAL_MAX_CHARS = 2000;
40
+ // `@fiche pin <text>` / `@fiche unpin` (or legacy `inkling`), `>fiche pin`,
41
+ // anchored to a whole line so removal is a whole-line delete - deterministic,
42
+ // with no leftover blank-line ambiguity.
43
+ // Session/chat messages require an explicit `@` or markdown-quote `>` prefix so
44
+ // ordinary prose like "fiche pin is broken" never gets hijacked locally.
45
+ // File sources (CLAUDE.md / AGENTS.md) keep accepting bare `fiche pin ...` too.
46
+ const FILE_PIN_CMD_RE = /^(?:>[ \t]*)?@?(?:fiche|inkling)[ \t]+(pin|unpin)\b(.*)$/;
47
+ const SESSION_PIN_CMD_RE = /^(?:>[ \t]*@?|@)(?:fiche|inkling)[ \t]+(pin|unpin)\b(.*)$/;
48
+ /** Track CommonMark ``` / ~~~ fence state across lines; invokes callback with fence state. */
49
+ function walkLinesWithFences(text, onLine) {
50
+ const lines = text.split('\n');
51
+ let openChar = '';
52
+ let openLen = 0;
53
+ for (let i = 0; i < lines.length; i++) {
54
+ const line = lines[i];
55
+ const trimmedStart = line.replace(/^[ \t]{0,3}/, '');
56
+ const ch = trimmedStart[0];
57
+ let run = 0;
58
+ if (ch === '`' || ch === '~') {
59
+ while (trimmedStart[run] === ch)
60
+ run++;
61
+ }
62
+ if (!openChar && run >= 3 && !(ch === '`' && trimmedStart.indexOf('`', run) >= 0)) {
63
+ openChar = ch;
64
+ openLen = run;
65
+ if (onLine(line, true) === false)
66
+ return;
67
+ continue;
68
+ }
69
+ if (openChar && ch === openChar && run >= openLen && trimmedStart.slice(run).trim() === '') {
70
+ if (onLine(line, true) === false)
71
+ return;
72
+ openChar = '';
73
+ openLen = 0;
74
+ continue;
75
+ }
76
+ if (onLine(line, Boolean(openChar)) === false)
77
+ return;
78
+ }
79
+ }
80
+ function matchPinCmd(line, source = 'session') {
81
+ const re = source === 'file' ? FILE_PIN_CMD_RE : SESSION_PIN_CMD_RE;
82
+ const m = re.exec(line.trim());
83
+ return m ? { verb: m[1], rest: m[2].trim() } : null;
84
+ }
85
+ /** Leading `<system-reminder>` run — the harness's CLAUDE.md envelope. */
86
+ const LEADING_REMINDER_RE = /^\s*<system-reminder>[\s\S]*?<\/system-reminder>/;
87
+ const REMINDER_OPEN = '<system-reminder>';
88
+ const REMINDER_CLOSE = '</system-reminder>';
89
+ /**
90
+ * Drop every reminder, anywhere in a block. The harness appends its own notices
91
+ * (e.g. "task tools haven't been used recently") to a turn the user typed, so a
92
+ * turn is command-only by what the *user* wrote, not by what the harness added.
93
+ *
94
+ * Scanned rather than matched with `/<system-reminder>[\s\S]*?<\/…>/g`: under a
95
+ * lazy body every unterminated open rescans to the end of the string, so a
96
+ * message carrying many of them costs O(n²). An unterminated open ends the
97
+ * scan; the rest of the block is text the user can see, so it stays.
98
+ */
99
+ function stripReminders(text) {
100
+ let out = '';
101
+ let at = 0;
102
+ for (;;) {
103
+ const open = text.indexOf(REMINDER_OPEN, at);
104
+ if (open < 0)
105
+ break;
106
+ const close = text.indexOf(REMINDER_CLOSE, open + REMINDER_OPEN.length);
107
+ if (close < 0)
108
+ break;
109
+ out += text.slice(at, open);
110
+ at = close + REMINDER_CLOSE.length;
111
+ }
112
+ return out + text.slice(at);
113
+ }
114
+ /** Opening marker of a synthesized pin confirmation. We generate these, so the
115
+ * match is on bytes we control, not a heuristic that could eat a real reply. */
116
+ /** Prefix on every synthesized reply, and the whole test for recognizing one on
117
+ * the way back in. Shares the `@inkling` namespace with the commands so there is
118
+ * one token to learn and one to match, and unlike `·` it survives any encoding
119
+ * or copy/paste the transcript is put through. */
120
+ export const PIN_REPLY_MARK = '@fiche ';
121
+ const LEGACY_PIN_REPLY_MARK = '@inkling ';
122
+ /**
123
+ * Fold every pin command in the transcript, oldest to newest.
124
+ *
125
+ * @inkling unpin 2 remove the pin listed as 2
126
+ * @inkling unpin use tabs remove by text (exact, else prefix)
127
+ * @inkling unpin all clear every session pin
128
+ * @inkling unpin NOT destructive — prints the list
129
+ *
130
+ * Bare `unpin` used to clear everything and then print what survived, which read
131
+ * as a menu and destroyed the thing the user was still deciding about. Removal now
132
+ * requires naming a target; the bare form is a query.
133
+ *
134
+ * Every form clears SESSION pins only. Clearing CLAUDE.md pins too would mean an
135
+ * `unpin` typed forty turns ago silently disables the project's rules for the
136
+ * rest of the session with nothing on screen to explain why; to drop a durable
137
+ * pin you delete its line from the file, where the change is visible.
138
+ */
139
+ export function foldPins(messages, system) {
140
+ const pins = [];
141
+ // System first: it is serialized ahead of the messages, so folding in wire
142
+ // order is what makes the emitted block read in the order the user wrote it.
143
+ for (const entry of systemPinLines(system))
144
+ applyPinLine(pins, entry);
145
+ messages.forEach((m, idx) => {
146
+ if (m.role !== 'user')
147
+ return;
148
+ for (const entry of pinLines(m, idx))
149
+ applyPinLine(pins, entry);
150
+ });
151
+ return pins;
152
+ }
153
+ /** Fold one candidate line into the accumulated pin list. */
154
+ function applyPinLine(pins, { line, source, path }) {
155
+ const cmd = matchPinCmd(line, source);
156
+ if (!cmd)
157
+ return;
158
+ if (cmd.verb === 'unpin') {
159
+ applyUnpin(pins, cmd.rest);
160
+ return;
161
+ }
162
+ const raw = cmd.rest;
163
+ // Mark the cut. The source line is stripped from the outbound copy, so a
164
+ // severed rule reads to the model as a whole one — "do X unless Y" becomes
165
+ // "do X" — while the user's own transcript still shows the full text.
166
+ const text = raw.length > PIN_MAX_CHARS
167
+ ? `${raw.slice(0, PIN_MAX_CHARS)}… [fiche: pin truncated]`
168
+ : raw;
169
+ if (source === 'file') {
170
+ // A file is a document, not a list of instructions. Its blank lines and
171
+ // its repeated lines ARE the format: a fence closes with the same ```
172
+ // that opened it, a table rule repeats, and an example that shows
173
+ // `Before: <code sample>` shows the same `<code sample>` again under
174
+ // `After:`. Deduping or dropping those leaves the user's own rules
175
+ // rendered as something they did not write — an empty `After:`, a fence
176
+ // that never closes. Only message 0's leading reminder and the system
177
+ // prompt reach here (see pinLines / systemPinLines), and both are sent
178
+ // once per request, so the document cannot accumulate across turns
179
+ // without the dedup guard.
180
+ const prev = pins[pins.length - 1];
181
+ // Blank runs collapse to one, and a leading blank is dropped: they cost
182
+ // budget that later lines need, and neither changes how the text reads.
183
+ if (!text && (!prev || !prev.text))
184
+ return;
185
+ pins.push({ text, source, path });
186
+ return;
187
+ }
188
+ if (!text)
189
+ return;
190
+ if (pins.some((p) => p.text === text))
191
+ return;
192
+ pins.push({ text, source });
193
+ }
194
+ /**
195
+ * Resolve one `unpin` argument against the pins in effect at that point.
196
+ *
197
+ * Numbers address the SESSION list only — the same list pinReplyText numbers.
198
+ * This is not cosmetic: an `@inkling unpin 2` stays in the transcript and is
199
+ * re-folded on every later request, so if numbering also covered CLAUDE.md pins,
200
+ * adding one line to that file would renumber the list underneath a command
201
+ * already given, and it would silently start deleting a different pin.
202
+ * Numbering only the removable entries makes the indices immune to file edits.
203
+ */
204
+ function applyUnpin(pins, arg) {
205
+ if (!arg)
206
+ return; // bare `unpin` is a query; pinReplyText answers it
207
+ if (arg === 'all') {
208
+ for (let i = pins.length - 1; i >= 0; i--) {
209
+ if (pins[i].source === 'session')
210
+ pins.splice(i, 1);
211
+ }
212
+ return;
213
+ }
214
+ const session = pins.filter((p) => p.source === 'session');
215
+ let target;
216
+ if (/^\d+$/.test(arg)) {
217
+ target = session[Number(arg) - 1];
218
+ }
219
+ else {
220
+ // Text form: the user already knows the words, so accept a prefix rather
221
+ // than demand the pin be retyped exactly.
222
+ const lower = arg.toLowerCase();
223
+ target = session.find((p) => p.text === arg)
224
+ ?? session.find((p) => p.text.toLowerCase().startsWith(lower));
225
+ }
226
+ if (target)
227
+ pins.splice(pins.indexOf(target), 1);
228
+ }
229
+ /**
230
+ * Every line of a user message that may carry a command, tagged with where it
231
+ * came from.
232
+ *
233
+ * Message 0's LEADING reminder run is the harness's file envelope, whatever it
234
+ * chose to inline there: global CLAUDE.md, project CLAUDE.md, AGENTS.md. A file
235
+ * backs those pins, so they are durable and `unpin` cannot reach them.
236
+ *
237
+ * A reminder block anywhere else is inlined `@`-mention content (the harness reads
238
+ * the file and pastes it in) or a per-turn notice. No file tier backs those, so
239
+ * they pin as `session` and `unpin` can drop them. That is deliberate: an inlined
240
+ * document containing `@inkling pin ...` can pin itself, and the removable tier
241
+ * plus the pin report is what makes that visible and reversible.
242
+ */
243
+ function* pinLines(m, idx) {
244
+ const blocks = typeof m.content === 'string'
245
+ ? [{ type: 'text', text: m.content }]
246
+ : Array.isArray(m.content) ? m.content : [];
247
+ let leadingRun = idx === 0;
248
+ for (const blk of blocks) {
249
+ if (!blk || typeof blk !== 'object' || blk.type !== 'text') {
250
+ continue;
251
+ }
252
+ const text = blk.text;
253
+ if (typeof text !== 'string')
254
+ continue;
255
+ if (LEADING_REMINDER_RE.test(text)) {
256
+ // A file backs the leading run, so it owns the durable tier. Everything
257
+ // later is inlined mention content or a per-turn notice: pin it, but keep
258
+ // it in the tier `unpin` can reach.
259
+ const source = leadingRun ? 'file' : 'session';
260
+ // Per block, not per message: one leading run can inline several files,
261
+ // and each pin has to remember which one to send the user back to.
262
+ let consumed = 0;
263
+ for (const block of reminderBlocks(text)) {
264
+ consumed += block.length;
265
+ const path = source === 'file' ? filePathOf(block) : undefined;
266
+ const unfenced = [];
267
+ walkLinesWithFences(block, (line, inFence) => {
268
+ if (!inFence)
269
+ unfenced.push(line);
270
+ });
271
+ for (const line of unfenced)
272
+ yield { line, source, path };
273
+ }
274
+ // The harness packs the envelope and the user's own typed prompt into the
275
+ // SAME block. Stopping at the run would strip a pin typed in the first
276
+ // turn (stripLines is unconditional) without ever folding it.
277
+ const rest = text.slice(consumed);
278
+ if (rest.trim()) {
279
+ leadingRun = false;
280
+ const unfenced = [];
281
+ walkLinesWithFences(rest, (line, inFence) => {
282
+ if (!inFence)
283
+ unfenced.push(line);
284
+ });
285
+ for (const line of unfenced)
286
+ yield { line, source: 'session' };
287
+ }
288
+ continue;
289
+ }
290
+ leadingRun = false;
291
+ const unfenced = [];
292
+ walkLinesWithFences(text, (line, inFence) => {
293
+ if (!inFence)
294
+ unfenced.push(line);
295
+ });
296
+ for (const line of unfenced)
297
+ yield { line, source: 'session' };
298
+ }
299
+ }
300
+ function* systemPinLines(sys) {
301
+ if (sys == null)
302
+ return;
303
+ const blocks = typeof sys === 'string'
304
+ ? [{ type: 'text', text: sys }]
305
+ : Array.isArray(sys) ? sys : [];
306
+ for (const blk of blocks) {
307
+ if (!blk || typeof blk !== 'object' || blk.type !== 'text')
308
+ continue;
309
+ const text = blk.text;
310
+ if (typeof text !== 'string')
311
+ continue;
312
+ // Codex labels its AGENTS.md block, OpenCode does not. Ask anyway: a label
313
+ // costs one regex and buys the user the path to edit.
314
+ const path = filePathOf(text);
315
+ const unfenced = [];
316
+ walkLinesWithFences(text, (line, inFence) => {
317
+ if (!inFence)
318
+ unfenced.push(line);
319
+ });
320
+ for (const line of unfenced)
321
+ yield { line, source: 'file', path };
322
+ }
323
+ }
324
+ /** The leading `<system-reminder>` run of a block, one entry per reminder. */
325
+ function reminderBlocks(text) {
326
+ const out = [];
327
+ let rest = text;
328
+ for (;;) {
329
+ const m = LEADING_REMINDER_RE.exec(rest);
330
+ if (!m)
331
+ break;
332
+ out.push(m[0]);
333
+ rest = rest.slice(m[0].length);
334
+ }
335
+ return out;
336
+ }
337
+ /**
338
+ * The file a reminder block was read from, when it says so.
339
+ *
340
+ * Every harness that inlines a rules file labels it, because the model has to
341
+ * know which file it is reading: Claude Code writes `Contents of <path> (...)`,
342
+ * and Codex the same for AGENTS.md. Matching the label rather than a filename
343
+ * list is what makes this work for a file we have never heard of; an unlabelled
344
+ * block just falls back to the generic header.
345
+ */
346
+ function filePathOf(block) {
347
+ return /^Contents of (.+?)(?: \(|:\s*$)/m.exec(block)?.[1]?.trim();
348
+ }
349
+ /** True when this message's only typed content is pin commands. */
350
+ function isCommandOnlyTurn(m, live = false) {
351
+ if (m.role !== 'user')
352
+ return false;
353
+ const blocks = typeof m.content === 'string'
354
+ ? [{ type: 'text', text: m.content }]
355
+ : Array.isArray(m.content) ? m.content : [];
356
+ let sawCommand = false;
357
+ for (const blk of blocks) {
358
+ if (!blk || typeof blk !== 'object')
359
+ return false;
360
+ if (blk.type !== 'text')
361
+ return false; // tool_result/image: real work
362
+ const raw = blk.text;
363
+ if (typeof raw !== 'string')
364
+ return false;
365
+ // The CLAUDE.md envelope rides in the same block as the user's first typed
366
+ // line, so `pin` as the opening line of a Claude Code session arrives behind
367
+ // it. Answering that turn locally is safe: nothing is forwarded, and the
368
+ // client resends message 0 intact on the next request. Rewriting it is not —
369
+ // the outbound path would drop the whole block and take the project's
370
+ // instructions with it, so only the live test tolerates the envelope.
371
+ if (!live && LEADING_REMINDER_RE.test(raw))
372
+ return false;
373
+ const text = stripReminders(raw);
374
+ let hasNonCmd = false;
375
+ walkLinesWithFences(text, (line, inFence) => {
376
+ if (inFence) {
377
+ hasNonCmd = true;
378
+ return false;
379
+ }
380
+ if (!line.trim())
381
+ return;
382
+ if (!matchPinCmd(line, 'session')) {
383
+ hasNonCmd = true;
384
+ return false;
385
+ }
386
+ sawCommand = true;
387
+ });
388
+ if (hasNonCmd)
389
+ return false;
390
+ }
391
+ return sawCommand;
392
+ }
393
+ function isTextOnlyAssistantMsg(m) {
394
+ if (!m || m.role !== 'assistant')
395
+ return false;
396
+ if (typeof m.content === 'string')
397
+ return true;
398
+ if (!Array.isArray(m.content) || m.content.length === 0)
399
+ return false;
400
+ return m.content.every((b) => !!b && typeof b === 'object' && b.type === 'text');
401
+ }
402
+ /** True when a message is a pin confirmation this proxy synthesized. */
403
+ function isPinReply(m) {
404
+ if (!m || m.role !== 'assistant')
405
+ return false;
406
+ const blocks = Array.isArray(m.content) ? m.content : [];
407
+ const hasMark = (s) => s.startsWith(PIN_REPLY_MARK) || s.startsWith(LEGACY_PIN_REPLY_MARK);
408
+ if (typeof m.content === 'string')
409
+ return hasMark(m.content);
410
+ if (blocks.length !== 1)
411
+ return false;
412
+ const blk = blocks[0];
413
+ return !!blk && typeof blk === 'object'
414
+ && blk.type === 'text'
415
+ && typeof blk.text === 'string'
416
+ && hasMark(blk.text);
417
+ }
418
+ /**
419
+ * Remove pin commands and their synthesized confirmations from the OUTBOUND copy.
420
+ * The client keeps its own transcript, so nothing is lost: the next request still
421
+ * arrives with every command intact and foldPins re-derives the same state.
422
+ *
423
+ * A command-only turn is dropped together with the confirmation that answered it —
424
+ * never one alone, or the user/assistant roles stop alternating. A mixed turn keeps
425
+ * its prose and loses only the command lines, so the model is not distracted by
426
+ * configuration in the middle of a request it has to act on.
427
+ */
428
+ export function stripPinCommands(messages) {
429
+ const out = [];
430
+ for (let i = 0; i < messages.length; i++) {
431
+ const m = messages[i];
432
+ if (isCommandOnlyTurn(m) && isPinReply(messages[i + 1])) {
433
+ i++; // drop the pair
434
+ continue;
435
+ }
436
+ if (m.role !== 'user') {
437
+ out.push(m);
438
+ continue;
439
+ }
440
+ const stripped = stripFromMessage(m, i);
441
+ if (stripped === null) {
442
+ // Only drop an unpaired command turn together with an assistant reply when
443
+ // that assistant turn is purely text (never drop tool_use blocks and orphan
444
+ // downstream tool_result blocks -> HTTP 400).
445
+ if (isTextOnlyAssistantMsg(messages[i + 1])) {
446
+ i++;
447
+ continue;
448
+ }
449
+ out.push(m);
450
+ continue;
451
+ }
452
+ out.push(stripped ?? m);
453
+ }
454
+ return out;
455
+ }
456
+ function continuesLeadingRun(text) {
457
+ if (!LEADING_REMINDER_RE.test(text))
458
+ return false;
459
+ let consumed = 0;
460
+ for (const block of reminderBlocks(text))
461
+ consumed += block.length;
462
+ return !text.slice(consumed).trim();
463
+ }
464
+ function stripUserTextBlock(text, isMsg0) {
465
+ if (isMsg0 && LEADING_REMINDER_RE.test(text)) {
466
+ let consumed = 0;
467
+ let rebuilt = '';
468
+ for (const block of reminderBlocks(text)) {
469
+ consumed += block.length;
470
+ rebuilt += stripLines(block, 'file');
471
+ }
472
+ const rest = text.slice(consumed);
473
+ return rest ? rebuilt + stripLines(rest, 'session') : rebuilt;
474
+ }
475
+ return stripLines(text, 'session');
476
+ }
477
+ /** Strip command lines from a user message, or undefined if nothing changed.
478
+ * Returns the original when stripping would leave the message with no content —
479
+ * an empty `content` is rejected by the API, and dropping a lone message would
480
+ * break role alternation. */
481
+ function stripFromMessage(m, idx = 1) {
482
+ if (typeof m.content === 'string') {
483
+ const text = stripUserTextBlock(m.content, idx === 0);
484
+ if (text === m.content)
485
+ return undefined;
486
+ return text.trim() ? { ...m, content: text } : null;
487
+ }
488
+ if (!Array.isArray(m.content))
489
+ return undefined;
490
+ let changed = false;
491
+ let leadingRun = idx === 0;
492
+ const blocks = [];
493
+ for (const blk of m.content) {
494
+ if (blk && typeof blk === 'object' && blk.type === 'text') {
495
+ const tb = blk;
496
+ if (typeof tb.text === 'string') {
497
+ const text = stripUserTextBlock(tb.text, leadingRun);
498
+ leadingRun = leadingRun ? continuesLeadingRun(tb.text) : false;
499
+ if (text !== tb.text) {
500
+ changed = true;
501
+ if (!text.trim()) {
502
+ const prev = blocks[blocks.length - 1];
503
+ if (tb.cache_control !== undefined && prev) {
504
+ blocks[blocks.length - 1] = { ...prev, cache_control: tb.cache_control };
505
+ }
506
+ else if (tb.cache_control !== undefined) {
507
+ blocks.push(blk);
508
+ }
509
+ continue;
510
+ }
511
+ blocks.push({ ...tb, text });
512
+ continue;
513
+ }
514
+ blocks.push(blk);
515
+ continue;
516
+ }
517
+ }
518
+ leadingRun = false;
519
+ blocks.push(blk);
520
+ }
521
+ if (!changed)
522
+ return undefined;
523
+ if (blocks.length === 0)
524
+ return null;
525
+ return { ...m, content: blocks };
526
+ }
527
+ /**
528
+ * Remove pin commands from the system prompt. Returns `undefined` when nothing
529
+ * changed, so the caller can leave the original object identity alone.
530
+ *
531
+ * Same move as stripFromMessage, including the `cache_control` handoff: system
532
+ * blocks carry the breakpoint that ends the cacheable prefix (extractSystemText
533
+ * keys on it), so a block emptied by stripping must pass its marker forward
534
+ * rather than take the boundary with it.
535
+ *
536
+ * Stripping here does rewrite bytes inside the cached prefix. That is the cost
537
+ * the message path already pays for CLAUDE.md: one cache create on the turn the
538
+ * strip first applies, then a stable prefix, because the rewrite is a pure
539
+ * function of the input and the client keeps re-sending the same source lines.
540
+ */
541
+ export function stripPinCommandsFromSystem(sys) {
542
+ if (sys == null)
543
+ return undefined;
544
+ if (typeof sys === 'string') {
545
+ const text = stripLines(sys, 'file');
546
+ return text === sys ? undefined : text;
547
+ }
548
+ if (!Array.isArray(sys))
549
+ return undefined;
550
+ let changed = false;
551
+ const out = [];
552
+ for (const blk of sys) {
553
+ if (blk && typeof blk === 'object' && blk.type === 'text') {
554
+ const tb = blk;
555
+ if (typeof tb.text === 'string') {
556
+ const text = stripLines(tb.text, 'file');
557
+ if (text !== tb.text) {
558
+ changed = true;
559
+ if (!text.trim()) {
560
+ const prev = out[out.length - 1];
561
+ if (tb.cache_control !== undefined && prev && prev.type === 'text') {
562
+ out[out.length - 1] = { ...prev, cache_control: tb.cache_control };
563
+ }
564
+ else if (tb.cache_control !== undefined) {
565
+ out.push(blk); // nothing in front to hold it: leave as sent
566
+ }
567
+ continue;
568
+ }
569
+ out.push({ ...tb, text });
570
+ continue;
571
+ }
572
+ }
573
+ }
574
+ out.push(blk);
575
+ }
576
+ return changed ? out : undefined;
577
+ }
578
+ function stripLines(text, source = 'session') {
579
+ const kept = [];
580
+ walkLinesWithFences(text, (line, inFence) => {
581
+ if (inFence || !matchPinCmd(line, source))
582
+ kept.push(line);
583
+ });
584
+ return kept.join('\n');
585
+ }
586
+ /**
587
+ * The block appended at the tail. Sits after every existing `cache_control`
588
+ * breakpoint, so its bytes are re-read each turn by construction and it can never
589
+ * cost a cache miss — which is also why formatting drift in the user's source
590
+ * lines is free here, and why we normalize purely for tidy counters.
591
+ */
592
+ /** Neutralize closing `</system-reminder>` tags inside user/file pin text so
593
+ * relocated pins cannot break out of the outer `<system-reminder>` envelope. */
594
+ function escapeReminderClose(text) {
595
+ return text.replace(/<\/(system-reminder)\b/gi, '<\\/$1');
596
+ }
597
+ export function pinBlockText(pins) {
598
+ if (pins.length === 0)
599
+ return '';
600
+ let budget = PIN_TOTAL_MAX_CHARS;
601
+ const lines = [];
602
+ for (const p of pins) {
603
+ const safeText = escapeReminderClose(p.text);
604
+ // Skip, don't stop: one long file excerpt early in a big CLAUDE.md would
605
+ // otherwise swallow every session pin the user typed this turn.
606
+ if (budget - safeText.length < 0)
607
+ continue;
608
+ budget -= safeText.length;
609
+ // Session pins are a list the user dictated one line at a time, so a bullet
610
+ // is what they meant. A file excerpt is markdown the user already formatted;
611
+ // bulleting it turns their `##` headings, table rows and fenced blocks into
612
+ // list items, i.e. we would be reformatting the very text we claim is "the
613
+ // user's own words".
614
+ lines.push(p.source === 'file' ? safeText : `- ${safeText}`);
615
+ }
616
+ if (lines.length === 0)
617
+ return '';
618
+ return [
619
+ '<system-reminder>',
620
+ '[fiche pin] The user pinned these instructions and fiche relocated them here,',
621
+ 'last in the request, because rules stated far above get read as background. They',
622
+ "are the user's own words and they govern this reply; on conflict they win.",
623
+ ...lines,
624
+ '</system-reminder>',
625
+ ].join('\n');
626
+ }
627
+ /**
628
+ * True when appendPinBlock has somewhere to land.
629
+ *
630
+ * Pins are MOVED, not copied, so the strip and the append are one operation: an
631
+ * assistant prefill as the final message (nothing may follow it) or a final user
632
+ * turn with content we cannot push onto means the block has no home, and
633
+ * stripping anyway would delete the user's rules from the request entirely.
634
+ */
635
+ export function canAppendPinBlock(messages) {
636
+ const last = messages[messages.length - 1];
637
+ if (!last || last.role !== 'user')
638
+ return false;
639
+ return typeof last.content === 'string' || Array.isArray(last.content);
640
+ }
641
+ /** Append the pin block to the final user message. Returns chars added. */
642
+ export function appendPinBlock(messages, pins) {
643
+ const text = pinBlockText(pins);
644
+ if (!text)
645
+ return 0;
646
+ const last = messages[messages.length - 1];
647
+ // An assistant prefill must remain the final message, and nothing may follow it.
648
+ if (!last || last.role !== 'user')
649
+ return 0;
650
+ if (typeof last.content === 'string') {
651
+ last.content = [{ type: 'text', text: last.content }];
652
+ }
653
+ if (!Array.isArray(last.content))
654
+ return 0;
655
+ last.content.push({ type: 'text', text });
656
+ return text.length;
657
+ }
658
+ /**
659
+ * The confirmation shown when a bare pin command is answered locally.
660
+ *
661
+ * Always the COMPLETE list, never a delta: the question a user has after typing a
662
+ * pin is "what is in effect now", and a delta makes them replay the session in
663
+ * their head to find out. The source header is the part that matters: it says
664
+ * which lines survive a restart and which `unpin` will clear.
665
+ */
666
+ /**
667
+ * File pins grouped under the file they came from, in first-seen order.
668
+ *
669
+ * Grouped rather than tagged per line: against a real rules file the tag repeats
670
+ * down the whole list and buries the text it means to annotate. A block the
671
+ * harness did not label still gets a header, because the alternative is a run of
672
+ * lines with no answer to "where do I edit this".
673
+ */
674
+ function fileHeaders(pins) {
675
+ const out = [];
676
+ for (const p of pins) {
677
+ if (p.source !== 'file')
678
+ continue;
679
+ const path = p.path ?? 'system instructions';
680
+ const last = out[out.length - 1];
681
+ if (last && last.path === path)
682
+ last.pins.push(p);
683
+ else
684
+ out.push({ path, pins: [p] });
685
+ }
686
+ return out;
687
+ }
688
+ export function pinReplyText(pins, verb = 'pin') {
689
+ if (verb === 'unpin') {
690
+ // `unpin` is a removal prompt, so it lists removal targets. Showing the file
691
+ // lines here offers the user things this command cannot act on, and with a
692
+ // file of any size the few numbered entries are buried under dozens of
693
+ // unactionable ones. `pin` still lists everything in effect.
694
+ const session = pins.filter((p) => p.source === 'session');
695
+ if (session.length === 0) {
696
+ const where = fileHeaders(pins);
697
+ const fromFile = pins.length > 0
698
+ ? `\n ${pins.length} pinned ${pins.length === 1 ? 'line' : 'lines'} come from ${where.length === 1 ? where[0].path : `${where.length} files`} (edit the file to change these)`
699
+ : '';
700
+ return `${PIN_REPLY_MARK}nothing to unpin${fromFile}`;
701
+ }
702
+ const lines = [`session (@fiche unpin <n>, or unpin all)`, ''];
703
+ session.forEach((p, i) => lines.push(`${i + 1}. ${p.text}`));
704
+ return `${PIN_REPLY_MARK}${session.length} removable\n${lines.join('\n')}`;
705
+ }
706
+ if (pins.length === 0) {
707
+ return `${PIN_REPLY_MARK}nothing pinned\n @fiche pin <instruction>`;
708
+ }
709
+ // Grouped under a source header rather than tagging each line: against a real
710
+ // CLAUDE.md the tag repeats down the whole list and buries the text it means to
711
+ // annotate. Only session pins are numbered, because only they can be removed by
712
+ // one, so the numbering doubles as the marker for what `unpin N` will act on.
713
+ const out = [];
714
+ const session = pins.filter((p) => p.source === 'session');
715
+ for (const group of fileHeaders(pins)) {
716
+ out.push('', `${group.path} (edit the file to change these)`, '');
717
+ // Column 0, never indented: the pinned text is the user's markdown, and a
718
+ // four-space indent turns the whole block into one code span, which is how
719
+ // a rules file full of headings, tables and fences stops rendering at all.
720
+ for (const p of group.pins)
721
+ out.push(p.text);
722
+ }
723
+ if (session.length > 0) {
724
+ out.push('', `session (@fiche unpin <n>, or unpin all)`, '');
725
+ session.forEach((p, i) => out.push(`${i + 1}. ${p.text}`));
726
+ }
727
+ return `${PIN_REPLY_MARK}${pins.length} pinned\n${out.slice(1).join('\n')}`;
728
+ }
729
+ /**
730
+ * True when the live turn is nothing but pin commands, so the proxy can answer it
731
+ * without spending an upstream call. Deliberately narrow: a turn carrying any real
732
+ * prose, or a tool_result (a tool loop that must not be hijacked mid-flight), is
733
+ * forwarded normally with the command lines merely stripped.
734
+ */
735
+ export function isPinOnlyRequest(messages) {
736
+ const live = liveTurn(messages);
737
+ return !!live && isCommandOnlyTurn(live, true);
738
+ }
739
+ /**
740
+ * The turn the request is actually asking about. Claude Code appends a
741
+ * system-role message (its agent-type catalogue) *after* the user's turn, so
742
+ * the literal last element is client metadata, not work — every cc pin command
743
+ * went upstream unanswered because of it. Only `system` is skipped: a trailing
744
+ * tool_result or assistant prefill is real work and must stay on the normal
745
+ * path, which is what keeps a mid-tool-loop turn from being hijacked.
746
+ */
747
+ function liveTurn(messages) {
748
+ const list = messages ?? [];
749
+ for (let i = list.length - 1; i >= 0; i--) {
750
+ const m = list[i];
751
+ if (m && m.role === 'system')
752
+ continue;
753
+ return m;
754
+ }
755
+ return undefined;
756
+ }
757
+ /**
758
+ * The verb the live turn ended with. Last one wins: a turn is answered once, so
759
+ * `pin x` followed by `unpin` is a removal prompt, not a listing.
760
+ */
761
+ function liveVerb(m) {
762
+ let verb = 'pin';
763
+ if (!m)
764
+ return verb;
765
+ const blocks = typeof m.content === 'string'
766
+ ? [{ type: 'text', text: m.content }]
767
+ : Array.isArray(m.content) ? m.content : [];
768
+ for (const blk of blocks) {
769
+ const text = blk?.text;
770
+ if (typeof text !== 'string')
771
+ continue;
772
+ walkLinesWithFences(text, (line, inFence) => {
773
+ if (inFence)
774
+ return;
775
+ const cmd = matchPinCmd(line, 'session');
776
+ if (cmd)
777
+ verb = cmd.verb;
778
+ });
779
+ }
780
+ return verb;
781
+ }
782
+ /**
783
+ * Answer a bare pin turn locally, or undefined to forward normally.
784
+ *
785
+ * Fails open on anything unexpected — a malformed body is the upstream's problem
786
+ * to report, not ours to swallow, and a parse quirk must never cost the user a
787
+ * turn that had real work in it.
788
+ */
789
+ export function pinCommandResponse(bodyIn) {
790
+ let req;
791
+ try {
792
+ req = JSON.parse(new TextDecoder().decode(bodyIn));
793
+ }
794
+ catch {
795
+ return undefined;
796
+ }
797
+ if (!Array.isArray(req.messages) || !isPinOnlyRequest(req.messages))
798
+ return undefined;
799
+ return synthesizeReply(
800
+ // `system` is where OpenCode puts AGENTS.md, so a listing that skips it
801
+ // answers "nothing pinned" to a user staring at four pinned lines. The
802
+ // OpenAI twin below has always passed its own system field.
803
+ pinReplyText(foldPins(req.messages, req.system), liveVerb(liveTurn(req.messages))), typeof req.model === 'string' ? req.model : 'fiche', req.stream === true);
804
+ }
805
+ /** A local `/v1/messages` response carrying `text`, matching the client's
806
+ * streaming preference. Zero usage: nothing was billed, and reporting otherwise
807
+ * would corrupt the dashboard's token accounting. */
808
+ export function synthesizeReply(text, model, stream) {
809
+ const id = `msg_fiche_pin_${Date.now().toString(36)}`;
810
+ const usage = { input_tokens: 0, output_tokens: 0 };
811
+ if (!stream) {
812
+ return {
813
+ contentType: 'application/json',
814
+ body: JSON.stringify({
815
+ id,
816
+ type: 'message',
817
+ role: 'assistant',
818
+ model,
819
+ content: [{ type: 'text', text }],
820
+ stop_reason: 'end_turn',
821
+ stop_sequence: null,
822
+ usage,
823
+ }),
824
+ };
825
+ }
826
+ const ev = (event, data) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
827
+ return {
828
+ contentType: 'text/event-stream',
829
+ body: ev('message_start', {
830
+ type: 'message_start',
831
+ message: {
832
+ id,
833
+ type: 'message',
834
+ role: 'assistant',
835
+ model,
836
+ content: [],
837
+ stop_reason: null,
838
+ stop_sequence: null,
839
+ usage,
840
+ },
841
+ }) +
842
+ ev('content_block_start', {
843
+ type: 'content_block_start',
844
+ index: 0,
845
+ content_block: { type: 'text', text: '' },
846
+ }) +
847
+ ev('content_block_delta', {
848
+ type: 'content_block_delta',
849
+ index: 0,
850
+ delta: { type: 'text_delta', text },
851
+ }) +
852
+ ev('content_block_stop', { type: 'content_block_stop', index: 0 }) +
853
+ ev('message_delta', {
854
+ type: 'message_delta',
855
+ delta: { stop_reason: 'end_turn', stop_sequence: null },
856
+ usage: { output_tokens: 0 },
857
+ }) +
858
+ ev('message_stop', { type: 'message_stop' }),
859
+ };
860
+ }
861
+ /** Parts of one OpenAI message. `input_text`/`output_text` are the Responses
862
+ * spellings of Chat Completions' `text`; non-text items (`image_url`,
863
+ * `input_image`, `input_file`, etc.) are preserved as non-text placeholders so
864
+ * multimodal turns carrying `@fiche pin` are never misclassified as
865
+ * command-only and swallowed locally. */
866
+ function openAIContentBlocks(content) {
867
+ if (typeof content === 'string')
868
+ return [{ type: 'text', text: content }];
869
+ if (!Array.isArray(content))
870
+ return [];
871
+ const out = [];
872
+ for (const raw of content) {
873
+ if (!raw || typeof raw !== 'object') {
874
+ out.push({ type: 'non_text' });
875
+ continue;
876
+ }
877
+ const part = raw;
878
+ const isTextType = part.type === undefined ||
879
+ part.type === 'text' ||
880
+ part.type === 'input_text' ||
881
+ part.type === 'output_text';
882
+ if (isTextType && typeof part.text === 'string') {
883
+ out.push({ type: 'text', text: part.text });
884
+ }
885
+ else {
886
+ const placeholderType = typeof part.type === 'string' && part.type !== 'text' ? part.type : 'non_text';
887
+ out.push({ type: placeholderType });
888
+ }
889
+ }
890
+ return out;
891
+ }
892
+ /**
893
+ * Rewrite an OpenAI request into the Messages shape the pin folder understands.
894
+ * `instructions` and system/developer turns become the system field, which is
895
+ * where file-sourced pins live on this wire.
896
+ */
897
+ function normalizeOpenAIRequest(req) {
898
+ const items = Array.isArray(req.input) ? req.input
899
+ : Array.isArray(req.messages) ? req.messages
900
+ : typeof req.input === 'string' ? [{ role: 'user', content: req.input }]
901
+ : undefined;
902
+ if (!items)
903
+ return undefined;
904
+ const system = [];
905
+ if (typeof req.instructions === 'string' && req.instructions) {
906
+ system.push({ type: 'text', text: req.instructions });
907
+ }
908
+ const messages = [];
909
+ for (const raw of items) {
910
+ if (!raw || typeof raw !== 'object')
911
+ return undefined;
912
+ const item = raw;
913
+ // reasoning / function_call / function_call_output are not messages. They
914
+ // still occupy a slot: a tool result in the last position must not let an
915
+ // older pin command look like the live turn and replay its answer.
916
+ if (item.type !== undefined && item.type !== 'message') {
917
+ messages.push({ role: 'assistant', content: [] });
918
+ continue;
919
+ }
920
+ const blocks = openAIContentBlocks(item.content);
921
+ if (item.role === 'system' || item.role === 'developer') {
922
+ for (const blk of blocks) {
923
+ if (blk.type === 'text')
924
+ system.push(blk);
925
+ }
926
+ continue;
927
+ }
928
+ messages.push({ role: item.role === 'user' ? 'user' : 'assistant', content: blocks });
929
+ }
930
+ return { messages, system: system.length > 0 ? system : undefined };
931
+ }
932
+ function openAIItemToMessage(item) {
933
+ if (item.type !== undefined && item.type !== 'message')
934
+ return undefined;
935
+ if (item.role !== 'user' && item.role !== 'assistant')
936
+ return undefined;
937
+ const blocks = openAIContentBlocks(item.content);
938
+ const toolCalls = item.tool_calls;
939
+ const hasFnCall = Boolean(item.function_call);
940
+ if (item.role === 'assistant' && ((Array.isArray(toolCalls) && toolCalls.length > 0) || hasFnCall)) {
941
+ blocks.push({ type: 'tool_use', id: '', name: '', input: {} });
942
+ }
943
+ return { role: item.role, content: blocks };
944
+ }
945
+ function stripOpenAIContent(content, source, isFirstUser = false) {
946
+ if (typeof content === 'string') {
947
+ const next = source === 'session'
948
+ ? stripUserTextBlock(content, isFirstUser)
949
+ : stripLines(content, 'file');
950
+ return { content: next, empty: !next.trim(), changed: next !== content };
951
+ }
952
+ if (!Array.isArray(content))
953
+ return { content, empty: false, changed: false };
954
+ let changed = false;
955
+ let leadingRun = isFirstUser;
956
+ const out = [];
957
+ for (const raw of content) {
958
+ const part = raw;
959
+ const isTextType = part &&
960
+ typeof part === 'object' &&
961
+ (part.type === undefined ||
962
+ part.type === 'text' ||
963
+ part.type === 'input_text' ||
964
+ part.type === 'output_text') &&
965
+ typeof part.text === 'string';
966
+ if (isTextType) {
967
+ const next = source === 'session'
968
+ ? stripUserTextBlock(part.text, leadingRun)
969
+ : stripLines(part.text, 'file');
970
+ leadingRun = leadingRun ? continuesLeadingRun(part.text) : false;
971
+ if (next !== part.text) {
972
+ changed = true;
973
+ if (!next.trim())
974
+ continue;
975
+ out.push({ ...part, text: next });
976
+ continue;
977
+ }
978
+ out.push(raw);
979
+ continue;
980
+ }
981
+ else {
982
+ leadingRun = false;
983
+ }
984
+ out.push(raw);
985
+ }
986
+ return { content: out, empty: out.length === 0, changed };
987
+ }
988
+ /** Move OpenAI-wire pin commands to the latest user input, using the same
989
+ * trailing system-reminder block as the Messages transformer. */
990
+ export function relocateOpenAIPins(req) {
991
+ const norm = normalizeOpenAIRequest(req);
992
+ if (!norm)
993
+ return 0;
994
+ const pins = foldPins(norm.messages, norm.system);
995
+ if (pins.length === 0)
996
+ return 0;
997
+ const pinText = pinBlockText(pins);
998
+ if (!pinText)
999
+ return 0;
1000
+ const isResponses = Array.isArray(req.input);
1001
+ const items = isResponses
1002
+ ? req.input
1003
+ : Array.isArray(req.messages)
1004
+ ? req.messages
1005
+ : undefined;
1006
+ const stringInput = typeof req.input === 'string';
1007
+ // Validate delivery target BEFORE stripping source pins so pins are never lost.
1008
+ let target;
1009
+ let appendTrailing = false;
1010
+ if (!stringInput && items) {
1011
+ const last = items[items.length - 1];
1012
+ if (last?.role === 'user' &&
1013
+ (last.type === undefined || last.type === 'message') &&
1014
+ (typeof last.content === 'string' || Array.isArray(last.content))) {
1015
+ target = last;
1016
+ }
1017
+ else if (items.some((raw) => raw?.role === 'user')) {
1018
+ // Mid-tool-loop (last item is tool / function_call_output / assistant):
1019
+ // never mutate a buried earlier turn (which busts automatic prefix cache);
1020
+ // append at the tail instead.
1021
+ appendTrailing = true;
1022
+ }
1023
+ }
1024
+ if (!stringInput && !target && !appendTrailing)
1025
+ return 0;
1026
+ if (typeof req.instructions === 'string') {
1027
+ const cleanedInst = stripLines(req.instructions, 'file');
1028
+ if (cleanedInst !== req.instructions) {
1029
+ if (!cleanedInst.trim()) {
1030
+ delete req.instructions;
1031
+ }
1032
+ else {
1033
+ req.instructions = cleanedInst;
1034
+ }
1035
+ }
1036
+ }
1037
+ if (items) {
1038
+ const keptItems = [];
1039
+ let nonSystemIdx = 0;
1040
+ for (let i = 0; i < items.length; i++) {
1041
+ const raw = items[i];
1042
+ const item = raw;
1043
+ if (item.role === 'system' || item.role === 'developer') {
1044
+ const res = stripOpenAIContent(item.content, 'file', false);
1045
+ if (res.changed && res.empty)
1046
+ continue;
1047
+ if (res.changed)
1048
+ item.content = res.content;
1049
+ keptItems.push(item);
1050
+ continue;
1051
+ }
1052
+ const curMsgIdx = nonSystemIdx++;
1053
+ const isMessageItem = item.type === undefined || item.type === 'message';
1054
+ if (!isMessageItem || (item.role !== 'user' && item.role !== 'assistant')) {
1055
+ keptItems.push(raw);
1056
+ continue;
1057
+ }
1058
+ const isTarget = item === target;
1059
+ if (!isTarget && item.role === 'user') {
1060
+ const msg = openAIItemToMessage(item);
1061
+ const nextRaw = items[i + 1];
1062
+ const nextMsg = nextRaw && !isResponses ? openAIItemToMessage(nextRaw)
1063
+ : nextRaw && isResponses && nextRaw !== target ? openAIItemToMessage(nextRaw)
1064
+ : undefined;
1065
+ if (msg && isCommandOnlyTurn(msg) && isPinReply(nextMsg)) {
1066
+ i++; // splice command-only turn + synthesized reply pair
1067
+ continue;
1068
+ }
1069
+ const res = stripOpenAIContent(item.content, 'session', curMsgIdx === 0);
1070
+ if (res.changed && res.empty) {
1071
+ if (isTextOnlyAssistantMsg(nextMsg)) {
1072
+ i++;
1073
+ continue;
1074
+ }
1075
+ // Preserve unmodified so we never emit an empty user message.
1076
+ keptItems.push(item);
1077
+ continue;
1078
+ }
1079
+ if (res.changed)
1080
+ item.content = res.content;
1081
+ keptItems.push(item);
1082
+ continue;
1083
+ }
1084
+ if (isTarget) {
1085
+ const res = stripOpenAIContent(item.content, 'session', curMsgIdx === 0);
1086
+ if (res.changed)
1087
+ item.content = res.content;
1088
+ keptItems.push(item);
1089
+ continue;
1090
+ }
1091
+ keptItems.push(item);
1092
+ }
1093
+ items.splice(0, items.length, ...keptItems);
1094
+ }
1095
+ if (stringInput) {
1096
+ const cleaned = stripUserTextBlock(req.input, true).trimEnd();
1097
+ req.input = cleaned ? `${cleaned}\n\n${pinText}` : pinText;
1098
+ }
1099
+ else if (target) {
1100
+ if (typeof target.content === 'string') {
1101
+ target.content = target.content.trim() ? `${target.content}\n\n${pinText}` : pinText;
1102
+ }
1103
+ else if (Array.isArray(target.content)) {
1104
+ const type = isResponses ? 'input_text' : 'text';
1105
+ target.content.push({ type, text: pinText });
1106
+ }
1107
+ }
1108
+ else if (appendTrailing && items) {
1109
+ if (isResponses) {
1110
+ items.push({ type: 'message', role: 'user', content: [{ type: 'input_text', text: pinText }] });
1111
+ }
1112
+ else {
1113
+ items.push({ role: 'user', content: pinText });
1114
+ }
1115
+ }
1116
+ return pinText.length;
1117
+ }
1118
+ function googleContentToMessage(content) {
1119
+ const blocks = [];
1120
+ if (Array.isArray(content.parts)) {
1121
+ for (const part of content.parts) {
1122
+ if (part && typeof part.text === 'string' && part.thought !== true) {
1123
+ blocks.push({ type: 'text', text: part.text });
1124
+ }
1125
+ else {
1126
+ blocks.push({ type: 'non_text' });
1127
+ }
1128
+ }
1129
+ }
1130
+ return { role: content.role === 'user' ? 'user' : 'assistant', content: blocks };
1131
+ }
1132
+ function stripGoogleParts(parts, source, isFirstUser = false) {
1133
+ let changed = false;
1134
+ let leadingRun = isFirstUser;
1135
+ const out = [];
1136
+ for (const part of parts) {
1137
+ if (part && typeof part.text === 'string' && part.thought !== true) {
1138
+ const next = source === 'session'
1139
+ ? stripUserTextBlock(part.text, leadingRun)
1140
+ : stripLines(part.text, 'file');
1141
+ leadingRun = leadingRun ? continuesLeadingRun(part.text) : false;
1142
+ if (next !== part.text) {
1143
+ changed = true;
1144
+ if (!next.trim())
1145
+ continue;
1146
+ out.push({ ...part, text: next });
1147
+ continue;
1148
+ }
1149
+ out.push(part);
1150
+ continue;
1151
+ }
1152
+ else {
1153
+ leadingRun = false;
1154
+ }
1155
+ out.push(part);
1156
+ }
1157
+ return { parts: out, empty: out.length === 0, changed };
1158
+ }
1159
+ /** Gemini-wire equivalent of relocateOpenAIPins. */
1160
+ export function relocateGooglePins(req) {
1161
+ if (!Array.isArray(req.contents))
1162
+ return 0;
1163
+ const systemText = Array.isArray(req.systemInstruction?.parts)
1164
+ ? req.systemInstruction.parts
1165
+ .map((part) => typeof part?.text === 'string' ? part.text : '')
1166
+ .filter(Boolean)
1167
+ .join('\n')
1168
+ : '';
1169
+ const messages = req.contents.map(googleContentToMessage);
1170
+ const pins = foldPins(messages, systemText || undefined);
1171
+ if (pins.length === 0)
1172
+ return 0;
1173
+ const pinText = pinBlockText(pins);
1174
+ if (!pinText)
1175
+ return 0;
1176
+ const last = req.contents[req.contents.length - 1];
1177
+ const canAppendToLast = last?.role === 'user' && Array.isArray(last.parts);
1178
+ const hasAnyUser = req.contents.some((c) => c?.role === 'user');
1179
+ if (!canAppendToLast && !hasAnyUser)
1180
+ return 0;
1181
+ if (Array.isArray(req.systemInstruction?.parts)) {
1182
+ const sysRes = stripGoogleParts(req.systemInstruction.parts, 'file', false);
1183
+ if (sysRes.changed && sysRes.empty) {
1184
+ delete req.systemInstruction;
1185
+ }
1186
+ else if (sysRes.changed) {
1187
+ req.systemInstruction.parts = sysRes.parts;
1188
+ }
1189
+ }
1190
+ const target = canAppendToLast ? last : undefined;
1191
+ const keptContents = [];
1192
+ for (let i = 0; i < req.contents.length; i++) {
1193
+ const content = req.contents[i];
1194
+ const isTarget = content === target;
1195
+ if (!isTarget && content.role === 'user' && Array.isArray(content.parts)) {
1196
+ const msg = messages[i];
1197
+ const nextMsg = messages[i + 1];
1198
+ if (isCommandOnlyTurn(msg) && isPinReply(nextMsg)) {
1199
+ i++; // splice command-only turn + synthesized reply pair
1200
+ continue;
1201
+ }
1202
+ const res = stripGoogleParts(content.parts, 'session', i === 0);
1203
+ if (res.changed && res.empty) {
1204
+ if (isTextOnlyAssistantMsg(nextMsg)) {
1205
+ i++;
1206
+ continue;
1207
+ }
1208
+ // Keep unmodified if dropping alone would leave an empty user turn.
1209
+ keptContents.push(content);
1210
+ continue;
1211
+ }
1212
+ if (res.changed)
1213
+ content.parts = res.parts;
1214
+ keptContents.push(content);
1215
+ continue;
1216
+ }
1217
+ if (isTarget && Array.isArray(content.parts)) {
1218
+ const res = stripGoogleParts(content.parts, 'session', i === 0);
1219
+ if (res.changed)
1220
+ content.parts = res.parts;
1221
+ keptContents.push(content);
1222
+ continue;
1223
+ }
1224
+ keptContents.push(content);
1225
+ }
1226
+ req.contents.splice(0, req.contents.length, ...keptContents);
1227
+ if (target && Array.isArray(target.parts)) {
1228
+ target.parts.push({ text: pinText });
1229
+ }
1230
+ else {
1231
+ req.contents.push({ role: 'user', parts: [{ text: pinText }] });
1232
+ }
1233
+ return pinText.length;
1234
+ }
1235
+ /** `pinCommandResponse` for the OpenAI routes. Codex talks Responses and other
1236
+ * clients talk Chat Completions, so the same command has to be answered in
1237
+ * whichever schema the caller used. */
1238
+ export function pinCommandResponseOpenAI(bodyIn, wire) {
1239
+ let req;
1240
+ try {
1241
+ req = JSON.parse(new TextDecoder().decode(bodyIn));
1242
+ }
1243
+ catch {
1244
+ return undefined;
1245
+ }
1246
+ const norm = normalizeOpenAIRequest(req);
1247
+ if (!norm || !isPinOnlyRequest(norm.messages))
1248
+ return undefined;
1249
+ const text = pinReplyText(foldPins(norm.messages, norm.system), liveVerb(norm.messages[norm.messages.length - 1]));
1250
+ const model = typeof req.model === 'string' ? req.model : 'fiche';
1251
+ return wire === 'responses'
1252
+ ? synthesizeResponsesReply(text, model, req.stream === true)
1253
+ : synthesizeChatReply(text, model, req.stream === true);
1254
+ }
1255
+ /** Local `/v1/chat/completions` reply carrying `text`. Zero usage: nothing was
1256
+ * billed, and reporting otherwise would corrupt the dashboard's accounting. */
1257
+ export function synthesizeChatReply(text, model, stream) {
1258
+ const id = `chatcmpl_fiche_pin_${Date.now().toString(36)}`;
1259
+ const created = Math.floor(Date.now() / 1000);
1260
+ if (!stream) {
1261
+ return {
1262
+ contentType: 'application/json',
1263
+ body: JSON.stringify({
1264
+ id,
1265
+ object: 'chat.completion',
1266
+ created,
1267
+ model,
1268
+ choices: [{
1269
+ index: 0,
1270
+ message: { role: 'assistant', content: text },
1271
+ finish_reason: 'stop',
1272
+ logprobs: null,
1273
+ }],
1274
+ usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
1275
+ }),
1276
+ };
1277
+ }
1278
+ const chunk = (delta, finish) => `data: ${JSON.stringify({
1279
+ id,
1280
+ object: 'chat.completion.chunk',
1281
+ created,
1282
+ model,
1283
+ choices: [{ index: 0, delta, finish_reason: finish }],
1284
+ })}\n\n`;
1285
+ return {
1286
+ contentType: 'text/event-stream',
1287
+ body: chunk({ role: 'assistant', content: '' }, null)
1288
+ + chunk({ content: text }, null)
1289
+ + chunk({}, 'stop')
1290
+ + 'data: [DONE]\n\n',
1291
+ };
1292
+ }
1293
+ /** Local `/v1/responses` reply carrying `text`, in the event order the Responses
1294
+ * API emits: clients read the final item from `response.completed`, but Codex
1295
+ * renders the streamed deltas, so both have to be present. */
1296
+ export function synthesizeResponsesReply(text, model, stream) {
1297
+ const stamp = Date.now().toString(36);
1298
+ const id = `resp_fiche_pin_${stamp}`;
1299
+ const itemId = `msg_fiche_pin_${stamp}`;
1300
+ const created_at = Math.floor(Date.now() / 1000);
1301
+ const usage = { input_tokens: 0, output_tokens: 0, total_tokens: 0 };
1302
+ const item = {
1303
+ id: itemId,
1304
+ type: 'message',
1305
+ status: 'completed',
1306
+ role: 'assistant',
1307
+ content: [{ type: 'output_text', text, annotations: [] }],
1308
+ };
1309
+ const response = (status, output) => ({
1310
+ id,
1311
+ object: 'response',
1312
+ created_at,
1313
+ status,
1314
+ model,
1315
+ output,
1316
+ error: null,
1317
+ incomplete_details: null,
1318
+ usage: status === 'completed' ? usage : null,
1319
+ });
1320
+ if (!stream) {
1321
+ return {
1322
+ contentType: 'application/json',
1323
+ body: JSON.stringify(response('completed', [item])),
1324
+ };
1325
+ }
1326
+ let seq = 0;
1327
+ const ev = (type, data) => `event: ${type}\ndata: ${JSON.stringify({ type, sequence_number: seq++, ...data })}\n\n`;
1328
+ const part = (t) => ({ type: 'output_text', text: t, annotations: [] });
1329
+ return {
1330
+ contentType: 'text/event-stream',
1331
+ body: ev('response.created', { response: response('in_progress', []) })
1332
+ + ev('response.in_progress', { response: response('in_progress', []) })
1333
+ + ev('response.output_item.added', {
1334
+ output_index: 0,
1335
+ item: { id: itemId, type: 'message', status: 'in_progress', role: 'assistant', content: [] },
1336
+ })
1337
+ + ev('response.content_part.added', {
1338
+ item_id: itemId, output_index: 0, content_index: 0, part: part(''),
1339
+ })
1340
+ + ev('response.output_text.delta', {
1341
+ item_id: itemId, output_index: 0, content_index: 0, delta: text,
1342
+ })
1343
+ + ev('response.output_text.done', {
1344
+ item_id: itemId, output_index: 0, content_index: 0, text,
1345
+ })
1346
+ + ev('response.content_part.done', {
1347
+ item_id: itemId, output_index: 0, content_index: 0, part: part(text),
1348
+ })
1349
+ + ev('response.output_item.done', { output_index: 0, item })
1350
+ + ev('response.completed', { response: response('completed', [item]) }),
1351
+ };
1352
+ }
1353
+ //# sourceMappingURL=pin.js.map