claude-token-saver 3.28.1 → 3.28.2

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.
package/README.en.md CHANGED
@@ -461,6 +461,23 @@ Conversion is one-way — editing the cached `.md` changes nothing in the source
461
461
 
462
462
  All four formats were exercised end to end on 2026-09-06: 10 docx run replacements plus three consecutive re-saves, a pptx bar-to-line chart swap with an added data point, xlsx value edits and a new row, and a fig text edit with re-encode and re-parse. In every case the original was byte-identical afterwards and the re-converted copy showed the change. One caveat: removing a chart shape from a pptx leaves the old chart XML part orphaned — PowerPoint ignores it, but delete the part and its rels for a clean file. Charts and images never appear in a conversion, so visual edits must be confirmed in the application itself.
463
463
 
464
+ ### Locked documents, and Windows
465
+
466
+ **A password-protected document is a state, not an error.** Office encrypts by wrapping the package in an OLE compound file rather than a zip, so opening one as a zip used to report "not a zip file" — which reads as a broken download and sends the user after the wrong problem. It is now identified before conversion:
467
+
468
+ ```
469
+ ✗ encrypted: password-protected Office file (OLE-wrapped)
470
+ ✗ encrypted: password-protected PDF
471
+ ```
472
+
473
+ The model is told to ask for an unlocked copy. This tool never asks for or stores a password, and never blocks the original `Read`, so work continues either way. A PDF that merely restricts printing still opens and still converts — checked against a false positive — and a legacy `.xls`, which is an OLE file by design, is not mistaken for an encrypted one.
474
+
475
+ **Windows is supported.** For teams with Windows machines:
476
+
477
+ - The Python search uses the `py -3` launcher. `python3` is rarely on PATH there, and a bare `python` may be the Store alias stub that opens a web page instead of running anything. Venv interpreters are looked for at `Scripts\python.exe`.
478
+ - The `.fig` parser installs through `npm.cmd` via the shell, and the package spec dropped its caret (`openfig-core@0.4.x`): in cmd.exe `^` is the escape character and never reaches npm.
479
+ - The background install and every child process set `windowsHide`, so no console window appears in the middle of someone's prompt.
480
+
464
481
  `claude-token-saver doc2md --clean` empties the conversion cache; `doc2md off` removes the hook. Removal filters for this tool's own entry, so anything else you registered under `PreToolUse` stays.
465
482
 
466
483
  ## 🌐 Behind a gateway (Bedrock / Vertex)
package/README.md CHANGED
@@ -457,6 +457,23 @@ PDF 는 첨부하면 모델이 내용을 그대로 읽습니다. 대신 페이
457
457
 
458
458
  네 형식 모두 실제로 몇 바퀴 돌려 검증했습니다(2026-09-06): docx 텍스트 치환 10건과 3회 연속 재저장, pptx 막대→꺾은선 차트 교체와 데이터 행 추가, xlsx 값 정정·행 추가, fig 텍스트 수정·재인코드·재파싱. 전 케이스에서 원본은 바이트 그대로였고, 수정본 재변환에 변경 내용이 반영됐습니다. 한 가지 주의: pptx 에서 차트 도형을 제거하면 옛 차트 XML 파트가 고아로 남습니다. PowerPoint 는 무시하지만, 깔끔히 하려면 파트와 rels 도 지우십시오. 차트·이미지 같은 시각 요소는 변환본에 잡히지 않으므로, 시각 편집의 최종 확인은 해당 프로그램에서 해야 합니다.
459
459
 
460
+ ### 암호가 걸린 문서와 Windows
461
+
462
+ **암호 문서는 오류가 아니라 상태로 다룹니다.** 사내에서 받는 문서 중 일부는 암호가 걸려 있습니다. 이전에는 암호 걸린 docx 를 "손상된 zip"이라고 알려서 사용자가 원인을 엉뚱한 곳에서 찾게 만들었습니다. 암호가 걸린 Office 문서는 zip 이 아니라 OLE 복합 문서로 저장되기 때문입니다. 지금은 변환 전에 판별해서 이렇게 알립니다.
463
+
464
+ ```
465
+ ✗ encrypted: password-protected Office file (OLE-wrapped)
466
+ ✗ encrypted: password-protected PDF
467
+ ```
468
+
469
+ 모델에게는 암호를 푼 사본을 사용자에게 요청하라고 안내합니다. 이 도구는 암호를 묻지도 저장하지도 않습니다. 어느 경우에도 원본 `Read` 를 막지 않으므로 작업이 중단되지 않습니다. 열람은 자유롭고 인쇄만 제한된 PDF 는 암호 문서가 아니므로 그대로 변환합니다(오탐 확인 완료). 구형 `.xls` 도 원래 OLE 형식이라 암호로 오인하지 않습니다.
470
+
471
+ **Windows 를 지원합니다.** 사내에 Windows 사용자가 있어 다음을 맞췄습니다.
472
+
473
+ - 파이썬 탐색이 `py -3` 런처를 씁니다. Windows 에서는 `python3` 가 PATH 에 없는 경우가 많고, 맨 `python` 은 실행 대신 마이크로소프트 스토어를 여는 별칭 스텁일 수 있습니다. venv 기반 인터프리터도 `Scripts\python.exe` 경로로 찾습니다.
474
+ - `.fig` 파서 설치가 `npm.cmd` 를 셸로 호출합니다. 그리고 패키지 지정자에서 캐럿을 뺐습니다(`openfig-core@0.4.x`). cmd.exe 에서 `^` 는 이스케이프 문자라 npm 에 닿기 전에 먹힙니다.
475
+ - 백그라운드 자동 설치와 모든 하위 프로세스에 `windowsHide` 를 걸어, 프롬프트 도중에 콘솔 창이 튀어나오지 않게 했습니다.
476
+
460
477
  `claude-token-saver doc2md --clean` 으로 변환 캐시를 비우고, `doc2md off` 로 훅을 제거합니다. 훅 해제는 자기 항목만 골라 지우므로 `PreToolUse` 에 등록해 둔 다른 훅은 그대로 남습니다.
461
478
 
462
479
  ## 🌐 Bedrock·Vertex 경유 환경
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-token-saver",
3
- "version": "3.28.1",
3
+ "version": "3.28.2",
4
4
  "description": "Route the easy work your expensive Claude model keeps repeating down to haiku/sonnet — post-hoc session analysis, no realtime router, no extra LLM calls.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -43,6 +43,55 @@ def fail(reason, detail=""):
43
43
  sys.exit(0)
44
44
 
45
45
 
46
+ # A password-protected OOXML file is not a zip at all: Office wraps the whole
47
+ # package in an OLE compound file whose streams hold the ciphertext. Opening it
48
+ # as a zip therefore reports "not a zip file", which reads as a broken download
49
+ # and sends the user looking for the wrong problem.
50
+ OLE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
51
+
52
+
53
+ def encryption_problem(path, ext):
54
+ """('encrypted', detail) when the file is password-protected, else None."""
55
+ try:
56
+ with open(path, "rb") as fh:
57
+ head = fh.read(8)
58
+ except OSError:
59
+ return None
60
+
61
+ # Legacy .xls is an OLE file by design, so the magic alone proves nothing
62
+ # there. For the modern formats it can only mean encryption.
63
+ if ext in ZIP_EXTS and head == OLE_MAGIC:
64
+ return ("encrypted", "password-protected Office file (OLE-wrapped)")
65
+
66
+ # Some producers keep the zip container and put the ciphertext inside it.
67
+ if ext in ZIP_EXTS:
68
+ try:
69
+ import zipfile
70
+ with zipfile.ZipFile(path) as z:
71
+ names = z.namelist()
72
+ if any(n.startswith("EncryptedPackage") for n in names):
73
+ return ("encrypted", "password-protected Office file")
74
+ except Exception:
75
+ return None
76
+
77
+ if ext == ".pdf":
78
+ try:
79
+ from pdfminer.pdfparser import PDFParser
80
+ from pdfminer.pdfdocument import PDFDocument
81
+ with open(path, "rb") as fh:
82
+ doc = PDFDocument(PDFParser(fh))
83
+ # An empty owner password is the ordinary "printing restricted"
84
+ # case, which extracts fine. Only a document that refuses to open
85
+ # counts as encrypted here.
86
+ if doc.encryption is not None and not doc.is_extractable:
87
+ return ("encrypted", "password-protected PDF")
88
+ except Exception as e:
89
+ if "password" in str(type(e).__name__).lower() or "password" in str(e).lower():
90
+ return ("encrypted", "password-protected PDF")
91
+ return None
92
+ return None
93
+
94
+
46
95
  def check_zip(path):
47
96
  """Classify an archive before opening it as a document.
48
97
 
@@ -189,6 +238,13 @@ def main():
189
238
  fail("missing", path)
190
239
 
191
240
  ext = os.path.splitext(path)[1].lower()
241
+
242
+ # Checked before anything else opens the file: an encrypted document is a
243
+ # normal thing to receive, not a failure to report as corruption.
244
+ locked = encryption_problem(path, ext)
245
+ if locked:
246
+ fail(locked[0], locked[1])
247
+
192
248
  if ext in ZIP_EXTS:
193
249
  problem = check_zip(path)
194
250
  if problem:
@@ -224,6 +280,11 @@ def main():
224
280
  result = MarkItDown().convert(path)
225
281
  text = (result.text_content or "").strip()
226
282
  except Exception as e:
283
+ # markitdown surfaces the password failure from whichever backend hit
284
+ # it, so the type name is the reliable part.
285
+ blob = (type(e).__name__ + " " + str(e)).lower()
286
+ if "password" in blob or "encrypted" in blob:
287
+ fail("encrypted", "the file is password-protected")
227
288
  fail("convert-failed", e)
228
289
 
229
290
  if not text:
package/src/doc2md.cjs CHANGED
@@ -233,28 +233,55 @@ function writeCache(filePath, markdown, extra) {
233
233
  // during the first-use auto-install, where the window is about a second wide.
234
234
  const PROBE = 'from markitdown import MarkItDown';
235
235
 
236
+ const IS_WINDOWS = process.platform === 'win32';
237
+
238
+ /**
239
+ * Interpreters to try, as `{ bin, args }` so the Windows launcher can carry
240
+ * its version flag. `py -3` is how a Windows box usually reaches Python at
241
+ * all: `python3` is rarely on PATH there, and a bare `python` may be the App
242
+ * Execution Alias stub that opens the Microsoft Store instead of running
243
+ * anything.
244
+ */
245
+ function interpreterCandidates() {
246
+ const out = [];
247
+ if (process.env.CTS_DOC2MD_PYTHON) out.push({ bin: process.env.CTS_DOC2MD_PYTHON, args: [] });
248
+ // The tool's own venv, created by `doc2md install-converter`. First because
249
+ // it is the only one this tool controls: telling people to `pip install`
250
+ // into the system interpreter is how a token-saving CLI ends up owning a
251
+ // break in someone else's project.
252
+ out.push({ bin: managedPython(), args: [] });
253
+ if (IS_WINDOWS) {
254
+ out.push(
255
+ { bin: path.join(os.homedir(), '.local', 'share', 'uv', 'tools', 'markitdown', 'Scripts', 'python.exe'), args: [] },
256
+ { bin: 'py', args: ['-3'] },
257
+ { bin: 'python', args: [] },
258
+ );
259
+ } else {
260
+ out.push(
261
+ { bin: path.join(os.homedir(), '.local', 'share', 'uv', 'tools', 'markitdown', 'bin', 'python'), args: [] },
262
+ { bin: path.join(os.homedir(), '.local', 'bin', 'markitdown-python'), args: [] },
263
+ { bin: 'python3', args: [] },
264
+ { bin: 'python', args: [] },
265
+ );
266
+ }
267
+ return out;
268
+ }
269
+
236
270
  let interpreterCache;
237
271
  function findInterpreter() {
238
272
  if (interpreterCache !== undefined) return interpreterCache;
239
- const candidates = [];
240
- if (process.env.CTS_DOC2MD_PYTHON) candidates.push(process.env.CTS_DOC2MD_PYTHON);
241
- candidates.push(
242
- // The tool's own venv, created by `doc2md install-converter`. First
243
- // because it is the only one this tool controls: telling people to
244
- // `pip install` into the system interpreter is how a token-saving CLI
245
- // ends up owning a break in someone else's project.
246
- managedPython(),
247
- path.join(os.homedir(), '.local', 'share', 'uv', 'tools', 'markitdown', 'bin', 'python'),
248
- path.join(os.homedir(), '.local', 'bin', 'markitdown-python'),
249
- 'python3',
250
- 'python',
251
- );
252
- for (const bin of candidates) {
273
+ for (const { bin, args } of interpreterCandidates()) {
253
274
  try {
254
- const probe = spawnSync(bin, ['-c', PROBE], { timeout: 20_000, stdio: 'ignore' });
275
+ const probe = spawnSync(bin, [...args, '-c', PROBE], {
276
+ timeout: 20_000,
277
+ stdio: 'ignore',
278
+ windowsHide: true,
279
+ });
255
280
  if (probe.status === 0) {
256
- interpreterCache = bin;
257
- return bin;
281
+ // Only a bare interpreter is cached as a string; the launcher form
282
+ // keeps its flag, since dropping it would run the wrong Python.
283
+ interpreterCache = args.length ? { bin, args } : bin;
284
+ return interpreterCache;
258
285
  }
259
286
  } catch { /* candidate unusable, try the next */ }
260
287
  }
@@ -262,6 +289,11 @@ function findInterpreter() {
262
289
  return null;
263
290
  }
264
291
 
292
+ /** Split a `findInterpreter()` result into the pair spawnSync wants. */
293
+ function interpreterParts(found) {
294
+ return typeof found === 'string' ? { bin: found, args: [] } : found;
295
+ }
296
+
265
297
  const CONVERTER = path.join(__dirname, '..', 'presets', 'doc2md', 'convert.py');
266
298
 
267
299
  /** Path to the interpreter inside the venv this tool manages. */
@@ -295,18 +327,33 @@ const EDIT_LIBS = ['python-pptx', 'python-docx', 'openpyxl'];
295
327
  * Homebrew interpreter wins over the system one regardless of PATH order.
296
328
  */
297
329
  function findVenvBase() {
298
- const candidates = [
299
- 'python3.14', 'python3.13', 'python3.12', 'python3.11', 'python3.10',
300
- 'python3', 'python',
301
- ];
302
- for (const bin of candidates) {
303
- const r = spawnSync(bin, ['-c', 'import sys; print("%d.%d" % sys.version_info[:2])'], {
330
+ const candidates = IS_WINDOWS
331
+ ? [
332
+ // The launcher first, asked for each version in turn: it knows about
333
+ // installs that never touched PATH, which is the normal case on
334
+ // Windows.
335
+ { bin: 'py', args: ['-3.14'] }, { bin: 'py', args: ['-3.13'] },
336
+ { bin: 'py', args: ['-3.12'] }, { bin: 'py', args: ['-3.11'] },
337
+ { bin: 'py', args: ['-3.10'] }, { bin: 'py', args: ['-3'] },
338
+ { bin: 'python', args: [] },
339
+ ]
340
+ : [
341
+ { bin: 'python3.14', args: [] }, { bin: 'python3.13', args: [] },
342
+ { bin: 'python3.12', args: [] }, { bin: 'python3.11', args: [] },
343
+ { bin: 'python3.10', args: [] },
344
+ { bin: 'python3', args: [] }, { bin: 'python', args: [] },
345
+ ];
346
+ for (const { bin, args } of candidates) {
347
+ const r = spawnSync(bin, [...args, '-c', 'import sys; print("%d.%d" % sys.version_info[:2])'], {
304
348
  encoding: 'utf8',
305
349
  timeout: 20_000,
350
+ windowsHide: true,
306
351
  });
307
352
  if (r.status !== 0) continue;
308
353
  const [major, minor] = String(r.stdout).trim().split('.').map(Number);
309
- if (major > 3 || (major === 3 && minor >= 10)) return { bin, version: `python ${major}.${minor}` };
354
+ if (major > 3 || (major === 3 && minor >= 10)) {
355
+ return { bin, args, version: `python ${major}.${minor}` };
356
+ }
310
357
  }
311
358
  return null;
312
359
  }
@@ -332,7 +379,11 @@ function installConverter({ onProgress = () => {} } = {}) {
332
379
  };
333
380
  }
334
381
  onProgress(`creating ${venv} (${base.version})`);
335
- const r = spawnSync(base.bin, ['-m', 'venv', venv], { encoding: 'utf8', timeout: 180_000 });
382
+ const r = spawnSync(base.bin, [...(base.args || []), '-m', 'venv', venv], {
383
+ encoding: 'utf8',
384
+ timeout: 180_000,
385
+ windowsHide: true,
386
+ });
336
387
  if (r.status !== 0) {
337
388
  return { ok: false, reason: 'no-python', detail: (r.stderr || 'venv creation failed').slice(0, 300) };
338
389
  }
@@ -342,6 +393,7 @@ function installConverter({ onProgress = () => {} } = {}) {
342
393
  const install = spawnSync(target, ['-m', 'pip', 'install', '--quiet', MARKITDOWN_SPEC, ...EDIT_LIBS], {
343
394
  encoding: 'utf8',
344
395
  timeout: 900_000,
396
+ windowsHide: true,
345
397
  });
346
398
  if (install.status !== 0) {
347
399
  return { ok: false, reason: 'pip-failed', detail: (install.stderr || '').slice(0, 400) };
@@ -349,7 +401,7 @@ function installConverter({ onProgress = () => {} } = {}) {
349
401
 
350
402
  // The probe is the actual acceptance test: pip can exit 0 and still leave an
351
403
  // interpreter that cannot import what was asked for.
352
- const probe = spawnSync(target, ['-c', PROBE], { timeout: 60_000, stdio: 'ignore' });
404
+ const probe = spawnSync(target, ['-c', PROBE], { timeout: 60_000, stdio: 'ignore', windowsHide: true });
353
405
  if (probe.status !== 0) {
354
406
  return { ok: false, reason: 'import-failed', detail: 'installed, but markitdown does not import' };
355
407
  }
@@ -361,8 +413,8 @@ function installConverter({ onProgress = () => {} } = {}) {
361
413
  /**
362
414
  * Convert one file. Returns `{ ok: true, cacheFile, meta }`, or
363
415
  * `{ ok: false, reason, detail }` where reason is one of:
364
- * no-markitdown | python-too-old | no-figparser | too-large | sensitive |
365
- * unsafe-archive | no-text | convert-failed | timeout
416
+ * no-markitdown | python-too-old | no-figparser | encrypted | too-large |
417
+ * sensitive | unsafe-archive | no-text | convert-failed | timeout
366
418
  *
367
419
  * Every failure is a reason to leave the original Read alone, never to break
368
420
  * it. That is the whole contract with the hook.
@@ -446,10 +498,12 @@ function convert(filePath, { converter = CONVERTER, python: pythonOverride = nul
446
498
  }
447
499
  if (!python) return { ok: false, reason: 'no-markitdown' };
448
500
 
449
- const run = spawnSync(python, [converter, filePath], {
501
+ const py = interpreterParts(python);
502
+ const run = spawnSync(py.bin, [...py.args, converter, filePath], {
450
503
  encoding: 'utf8',
451
504
  timeout: CONVERT_TIMEOUT_MS,
452
505
  maxBuffer: MAX_MARKDOWN_BYTES * 4,
506
+ windowsHide: true,
453
507
  });
454
508
  if (run.error && run.error.code === 'ETIMEDOUT') return { ok: false, reason: 'timeout' };
455
509
  if (run.status !== 0) {
@@ -522,6 +576,9 @@ function ensureConverterInstalled({ waitMs = 15_000 } = {}) {
522
576
  const child = spawn(process.execPath, [cli, 'doc2md', 'install-converter'], {
523
577
  detached: true,
524
578
  stdio: 'ignore',
579
+ // Without this Windows pops a console window for the install, in the
580
+ // middle of someone's prompt.
581
+ windowsHide: true,
525
582
  });
526
583
  child.unref();
527
584
  } catch {
@@ -623,6 +680,13 @@ function decideForRead(context, opts = {}) {
623
680
  + ` 진행 상황: ${INSTALL_HINT} 를 직접 실행하면 설치 로그를 볼 수 있습니다.`,
624
681
  };
625
682
  }
683
+ if (result.reason === 'encrypted') {
684
+ return {
685
+ deny: false,
686
+ reason: `[doc2md] ${name} 는 암호가 걸린 문서라 변환하지 못했습니다. `
687
+ + '사용자에게 암호를 푼 사본을 요청하십시오. 이 도구는 암호를 묻거나 저장하지 않습니다.',
688
+ };
689
+ }
626
690
  if (result.reason === 'python-too-old') {
627
691
  if (noticeAlreadyShown()) return null;
628
692
  markNoticeShown();
@@ -753,6 +817,10 @@ function contextForPrompt(payload, opts = {}) {
753
817
  lines.push(lang === 'ko'
754
818
  ? ` ${name}: 변환기를 설치하는 중입니다(첫 실행에만 걸립니다). 설치가 끝나면 다음 요청부터 자동 변환됩니다.`
755
819
  : ` ${name}: the converter is installing now (first run only). It will convert automatically from the next request.`);
820
+ } else if (result.reason === 'encrypted') {
821
+ lines.push(lang === 'ko'
822
+ ? ` ${name}: 암호가 걸린 문서입니다. 암호를 푼 사본을 달라고 사용자에게 요청하십시오.`
823
+ : ` ${name}: the document is password-protected. Ask the user for an unlocked copy.`);
756
824
  } else if (result.reason === 'python-too-old') {
757
825
  lines.push(lang === 'ko'
758
826
  ? ` ${name}: 변환기가 Python 3.10 이상을 요구하는데 PATH 에 없습니다(macOS 기본은 3.9). \`brew install python\` 후 다시 시도하도록 사용자에게 안내하십시오.`
@@ -888,6 +956,8 @@ module.exports = {
888
956
  installConverter,
889
957
  ensureConverterInstalled,
890
958
  findVenvBase,
959
+ interpreterCandidates,
960
+ interpreterParts,
891
961
  clearNotice,
892
962
  cacheDir,
893
963
  cachePathFor,
package/src/fig2md.cjs CHANGED
@@ -28,7 +28,10 @@ const fs = require('node:fs');
28
28
  const path = require('node:path');
29
29
  const { spawnSync } = require('node:child_process');
30
30
 
31
- const FIG_PARSER_SPEC = 'openfig-core@^0.4.1';
31
+ // `0.4.x` rather than `^0.4.1` on purpose: the Windows install goes through
32
+ // cmd.exe, where `^` is the escape character and would be eaten before npm
33
+ // ever saw it. The range is the same one caret means for a 0.x package.
34
+ const FIG_PARSER_SPEC = 'openfig-core@0.4.x';
32
35
 
33
36
  /** Where the on-demand parser install lives, under the tool's state dir. */
34
37
  function managedFigDir(userDataDir) {
@@ -56,10 +59,16 @@ function installFigParser(userDataDir, { onProgress = () => {} } = {}) {
56
59
  fs.writeFileSync(pkgJson, JSON.stringify({ name: 'doc2md-fig', private: true }) + '\n');
57
60
  }
58
61
  onProgress(`installing ${FIG_PARSER_SPEC}`);
59
- const r = spawnSync('npm', ['install', '--no-audit', '--no-fund', '--silent', FIG_PARSER_SPEC], {
62
+ // npm on Windows is npm.cmd, which spawnSync cannot execute directly — it
63
+ // needs the shell. Elsewhere the shell is avoided, since the package spec
64
+ // would then go through shell quoting for no benefit.
65
+ const isWindows = process.platform === 'win32';
66
+ const r = spawnSync(isWindows ? 'npm.cmd' : 'npm', ['install', '--no-audit', '--no-fund', '--silent', FIG_PARSER_SPEC], {
60
67
  cwd: dir,
61
68
  encoding: 'utf8',
62
69
  timeout: 300_000,
70
+ windowsHide: true,
71
+ shell: isWindows,
63
72
  });
64
73
  if (r.status !== 0) {
65
74
  return { ok: false, reason: 'npm-failed', detail: (r.stderr || '').slice(0, 400) };