behavior-wrapped 0.5.9 → 0.5.11

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/dist/index.html CHANGED
@@ -6,8 +6,8 @@
6
6
  <meta name="theme-color" content="#0d0b1b" />
7
7
  <meta name="description" content="Your private, local-first Claude Code behavior report." />
8
8
  <title>Behavior Wrapped</title>
9
- <script type="module" crossorigin src="/assets/index-BeJIqYle.js"></script>
10
- <link rel="stylesheet" crossorigin href="/assets/index-DokkhBtC.css">
9
+ <script type="module" crossorigin src="/assets/index-5_CRpDUV.js"></script>
10
+ <link rel="stylesheet" crossorigin href="/assets/index-C2-3qXWV.css">
11
11
  </head>
12
12
  <body>
13
13
  <div id="root"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "behavior-wrapped",
3
- "version": "0.5.9",
3
+ "version": "0.5.11",
4
4
  "description": "A private, local-first Wrapped report for Claude Code, Cowork, and Codex behavior.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -479,7 +479,7 @@ function donationRedactionInventory(detections) {
479
479
  }).sort((left, right) => right.count - left.count || left.label.localeCompare(right.label));
480
480
  }
481
481
 
482
- function localOpeningPrompt(value) {
482
+ export function localOpeningPrompt(value) {
483
483
  let prompt = String(value || "");
484
484
  const explicitRequest = prompt.match(/(?:^|\n)## My request:\s*([\s\S]*)$/i);
485
485
  if (explicitRequest) prompt = explicitRequest[1];
package/server/cli.mjs CHANGED
@@ -181,8 +181,9 @@ async function createWrapped() {
181
181
  progress.succeed(`${testMode ? "Local test fallbacks" : "Local-only analysis"} ready; no LLM calls made`);
182
182
  } else {
183
183
  const judgeStates = { phrase: "waiting", tone: "waiting", topics: "waiting", workarounds: "waiting" };
184
+ const judgeLabels = { phrase: "favorite phrase", tone: "agent interaction", topics: "topics", workarounds: "workarounds" };
184
185
  const judgeStatus = (state) => state === "waiting" ? "queued" : state === "working" ? "…" : state === "done" ? "✓" : state === "failed" ? "skipped" : state;
185
- const judgeSummary = () => Object.entries(judgeStates).map(([name, state]) => `${name} ${judgeStatus(state)}`).join(" · ");
186
+ const judgeSummary = () => Object.entries(judgeStates).map(([name, state]) => `${judgeLabels[name]} ${judgeStatus(state)}`).join(" · ");
186
187
  const trackJudge = (name, promise) => {
187
188
  judgeStates[name] = "working";
188
189
  progress.update(judgeSummary());
@@ -196,7 +197,7 @@ async function createWrapped() {
196
197
  throw error;
197
198
  });
198
199
  };
199
- progress.start("Running privacy-safe AI analysis", judgeSummary());
200
+ progress.start("Running redacted excerpts through LLM Judge", judgeSummary(), { separateDetail: true });
200
201
  const phraseCardPromise = process.env.BEHAVIOR_WRAPPED_DIRECT_OPENROUTER === "1"
201
202
  ? judgePhraseCard(candidates, process.env.OPENROUTER_API_KEY)
202
203
  : judgePhraseCardViaRelay(candidates, { endpoint: process.env.BEHAVIOR_WRAPPED_JUDGE_URL || PHRASE_JUDGE_RELAY_URL, clientId: getOrCreateClientId() });
@@ -225,7 +226,7 @@ async function createWrapped() {
225
226
  optionalAnalysis(trackJudge("topics", sessionTopicsPromise), "usage-topic card", analysisWarnings),
226
227
  optionalAnalysis(trackJudge("workarounds", workaroundsPromise), "instrumental-workaround card", analysisWarnings),
227
228
  ]);
228
- progress.succeed("Privacy-safe AI analysis complete");
229
+ progress.succeed("LLM Judge complete");
229
230
  }
230
231
  analyzed.phraseCard = phraseCard;
231
232
  if (!localOnly) {
@@ -414,7 +414,7 @@ function restrictionErrorSummary(value) {
414
414
  return rules.find(([pattern]) => pattern.test(text))?.[1] || null;
415
415
  }
416
416
 
417
- function normalizeCodexRecords(records) {
417
+ function normalizeCodexRecords(records, { includePrivateToolDetails = false } = {}) {
418
418
  const normalized = [];
419
419
  const firstDeclaredModel = records.find((record) => record?.type === "turn_context" && typeof record?.payload?.model === "string" && record.payload.model)?.payload.model;
420
420
  const isForkedSession = records.some((record) => record?.type === "session_meta" && (record?.payload?.forked_from_id || record?.payload?.parent_thread_id));
@@ -436,7 +436,8 @@ function normalizeCodexRecords(records) {
436
436
  const semantics = semanticToolUse({ name: toolName, argumentsValue: payload.arguments, inputValue: payload.input });
437
437
  if (typeof payload.call_id === "string" && payload.call_id) pendingTools.set(payload.call_id, semantics);
438
438
  else anonymousTools.push(semantics);
439
- normalized.push({ type: "assistant", timestamp: record.timestamp, message: { model: currentModel, content: [{ type: "tool_use", name: toolName, action_hint: semantics.action, method_hint: semantics.method }] } });
439
+ const privateInput = payload.arguments ?? payload.input;
440
+ normalized.push({ type: "assistant", timestamp: record.timestamp, message: { model: currentModel, content: [{ type: "tool_use", name: toolName, action_hint: semantics.action, method_hint: semantics.method, ...(includePrivateToolDetails && privateInput !== undefined ? { input: privateInput } : {}) }] } });
440
441
  } else if (record.type === "response_item" && (payload.type === "function_call_output" || payload.type === "custom_tool_call_output")) {
441
442
  const callId = typeof payload.call_id === "string" && payload.call_id ? payload.call_id : null;
442
443
  const semantics = callId ? pendingTools.get(callId) : anonymousTools.shift();
@@ -446,7 +447,7 @@ function normalizeCodexRecords(records) {
446
447
  const unwrappedFailure = !status.wrapped && /(?:^|\b)(?:error|failed|failure)(?:\b|:)/i.test(output);
447
448
  const canSummarizeRestriction = status.failed || (!status.wrapped && restrictionEligibleActions.has(semantics?.action));
448
449
  const errorSummary = canSummarizeRestriction ? restrictionErrorSummary(output) : null;
449
- normalized.push({ type: "user", isMeta: true, timestamp: record.timestamp, message: { content: [{ type: "tool_result", is_error: Boolean(errorSummary) || status.failed || unwrappedFailure, error_summary: errorSummary }] } });
450
+ normalized.push({ type: "user", isMeta: true, timestamp: record.timestamp, message: { content: [{ type: "tool_result", is_error: Boolean(errorSummary) || status.failed || unwrappedFailure, error_summary: errorSummary, ...(includePrivateToolDetails && output ? { content: output } : {}) }] } });
450
451
  } else if (record.type === "event_msg" && payload.type === "turn_aborted") {
451
452
  normalized.push({ type: "system", subtype: "interrupt", timestamp: record.timestamp, content: "interrupt" });
452
453
  } else if (record.type === "event_msg" && payload.type === "token_count" && payload.info?.total_token_usage) {
@@ -506,16 +507,16 @@ function normalizeCoworkRecords(records) {
506
507
  return normalized;
507
508
  }
508
509
 
509
- export function readRecords(file, agent = "claude") {
510
+ export function readRecords(file, agent = "claude", options = {}) {
510
511
  const { records } = recordsFromFileSync(file);
511
- if (agent === "codex") return normalizeCodexRecords(records);
512
+ if (agent === "codex") return normalizeCodexRecords(records, options);
512
513
  if (agent === "cowork") return normalizeCoworkRecords(records);
513
514
  return records;
514
515
  }
515
516
 
516
- export async function readRecordsAsync(file, agent = "claude") {
517
+ export async function readRecordsAsync(file, agent = "claude", options = {}) {
517
518
  const { records } = await recordsFromFile(file);
518
- if (agent === "codex") return normalizeCodexRecords(records);
519
+ if (agent === "codex") return normalizeCodexRecords(records, options);
519
520
  if (agent === "cowork") return normalizeCoworkRecords(records);
520
521
  return records;
521
522
  }
@@ -67,11 +67,11 @@ function readBody(request, maximumBytes = 1_000_000) {
67
67
  });
68
68
  }
69
69
 
70
- async function chosenRecords(ids) {
70
+ async function chosenRecords(ids, options = {}) {
71
71
  const selected = [];
72
72
  for (const id of ids) {
73
73
  const session = catalog.index.get(id);
74
- if (session) selected.push({ sessionId: id, agent: session.agent, records: await readRecordsAsync(session.file, session.agent) });
74
+ if (session) selected.push({ sessionId: id, agent: session.agent, records: await readRecordsAsync(session.file, session.agent, options) });
75
75
  }
76
76
  return selected;
77
77
  }
@@ -118,7 +118,7 @@ const server = http.createServer(async (request, response) => {
118
118
  if (!report) return json(response, 404, { error: "Saved report not found" });
119
119
  const allowed = new Set(report.sessionIds || []);
120
120
  const ids = [...new Set((report.workaroundReview?.occurrences || []).map((occurrence) => occurrence?.location?.sessionId).filter((id) => allowed.has(id) && catalog.index.has(id)))].slice(0, 100);
121
- const records = await chosenRecords(ids);
121
+ const records = await chosenRecords(ids, { includePrivateToolDetails: true });
122
122
  const labels = new Map(publicCatalog().sessions.map((session) => [session.id, session]));
123
123
  return json(response, 200, makeWorkaroundEvidencePreview(report, records, labels));
124
124
  }
@@ -19,6 +19,7 @@ export function createCliProgress({
19
19
  let label = "";
20
20
  let detail = "";
21
21
  let startedAt = 0;
22
+ let separateDetail = false;
22
23
 
23
24
  function line(symbol) {
24
25
  const extra = detail ? ` · ${detail}` : "";
@@ -27,7 +28,19 @@ export function createCliProgress({
27
28
 
28
29
  function render() {
29
30
  if (!timer) return;
30
- output.write(`\r\x1b[2K${line(spinnerFrames[frame++ % spinnerFrames.length])}`);
31
+ clearLine();
32
+ output.write(separateDetail
33
+ ? `${spinnerFrames[frame++ % spinnerFrames.length]} ${detail}`
34
+ : line(spinnerFrames[frame++ % spinnerFrames.length]));
35
+ }
36
+
37
+ function clearLine() {
38
+ if (typeof output.clearLine === "function" && typeof output.cursorTo === "function") {
39
+ output.clearLine(0);
40
+ output.cursorTo(0);
41
+ return;
42
+ }
43
+ output.write("\r\x1b[2K");
31
44
  }
32
45
 
33
46
  function stopTimer() {
@@ -37,16 +50,18 @@ export function createCliProgress({
37
50
  }
38
51
 
39
52
  return {
40
- start(nextLabel, nextDetail = "") {
53
+ start(nextLabel, nextDetail = "", options = {}) {
41
54
  stopTimer();
42
55
  label = nextLabel;
43
56
  detail = nextDetail;
57
+ separateDetail = Boolean(options.separateDetail && detail);
44
58
  startedAt = now();
45
59
  frame = 0;
46
60
  if (!interactive) {
47
- output.write(`◇ ${label}${detail ? ` · ${detail}` : ""}\n`);
61
+ output.write(separateDetail ? `◇ ${label}\n◇ ${detail}\n` : `◇ ${label}${detail ? ` · ${detail}` : ""}\n`);
48
62
  return;
49
63
  }
64
+ if (separateDetail) output.write(`◇ ${label}\n`);
50
65
  timer = setIntervalImpl(render, intervalMs);
51
66
  timer?.unref?.();
52
67
  render();
@@ -59,11 +74,12 @@ export function createCliProgress({
59
74
  succeed(summary = label) {
60
75
  const elapsed = elapsedLabel(now() - startedAt);
61
76
  stopTimer();
62
- output.write(interactive ? `\r\x1b[2K✓ ${summary} · ${elapsed}\n` : `✓ ${summary} · ${elapsed}\n`);
77
+ if (interactive) clearLine();
78
+ output.write(`✓ ${summary} · ${elapsed}\n`);
63
79
  },
64
80
  stop() {
65
81
  stopTimer();
66
- if (interactive) output.write("\r\x1b[2K");
82
+ if (interactive) clearLine();
67
83
  },
68
84
  };
69
85
  }
@@ -1,70 +1,124 @@
1
- import { makeDonationPreview } from "./analysis.mjs";
1
+ import { localOpeningPrompt, makeDonationPreview } from "./analysis.mjs";
2
+ import { redactText } from "./privacy.mjs";
2
3
 
3
- const DEFAULT_CONTEXT_TURNS = 2;
4
4
  const MAX_OCCURRENCES = 100;
5
5
 
6
6
  function finiteRecordIndex(value, length) {
7
7
  return Number.isInteger(value) && value >= 0 && value < length ? value : null;
8
8
  }
9
9
 
10
- function evidenceRecordIndexes(occurrence, records) {
11
- const location = occurrence?.location || {};
12
- const direct = [location.originalRecordIndex, location.blockerRecordIndex, location.alternativeRecordIndex]
13
- .map((value) => finiteRecordIndex(value, records.length))
14
- .filter((value) => value !== null);
15
- if (direct.length) return direct;
16
- const timestamps = new Set((occurrence?.evidence || []).map((event) => event?.timestamp).filter(Boolean));
17
- return records.flatMap((record, index) => timestamps.has(record?.timestamp) ? [index] : []);
10
+ function contentBlocks(record) {
11
+ const content = record?.message?.content ?? record?.content;
12
+ if (Array.isArray(content)) return content;
13
+ if (typeof content === "string") return [{ type: "text", text: content }];
14
+ return [];
18
15
  }
19
16
 
20
- function excerptRecords(records, occurrence, contextTurns) {
21
- const anchors = evidenceRecordIndexes(occurrence, records);
22
- if (!anchors.length) return [];
23
- const coreStart = Math.min(...anchors);
24
- const coreEnd = Math.max(...anchors);
25
- const conversationIndexes = records.flatMap((record, index) => !record?.isMeta && (record?.type === "user" || record?.type === "assistant") ? [index] : []);
26
- const before = conversationIndexes.filter((index) => index < coreStart).slice(-contextTurns);
27
- const after = conversationIndexes.filter((index) => index > coreEnd).slice(0, contextTurns);
28
- const start = before[0] ?? coreStart;
29
- const end = after.at(-1) ?? coreEnd;
30
- return records.slice(start, end + 1);
17
+ function visibleText(record) {
18
+ return contentBlocks(record).filter((block) => block?.type === "text").map((block) => block.text || "").join("\n").trim();
31
19
  }
32
20
 
33
- function safeFallbackMessages(occurrence) {
34
- return (occurrence?.evidence || []).flatMap((event) => {
35
- if (event?.role !== "user" && event?.role !== "assistant") return [];
36
- const text = String(event?.text || "").trim();
37
- return text ? [{ role: event.role, timestamp: event.timestamp || null, text }] : [];
38
- });
21
+ function locallyRedacted(value) {
22
+ return redactText(String(value || ""), [], { includeHeuristicSecrets: false }).text.trim();
23
+ }
24
+
25
+ function toolResultText(record) {
26
+ return contentBlocks(record).filter((block) => block?.type === "tool_result").map((block) => {
27
+ const content = typeof block.content === "string"
28
+ ? block.content
29
+ : Array.isArray(block.content)
30
+ ? block.content.map((part) => typeof part === "string" ? part : part?.text || "").filter(Boolean).join("\n")
31
+ : "";
32
+ return content || block.error_summary || "";
33
+ }).filter(Boolean).join("\n").trim();
34
+ }
35
+
36
+ function parsedJson(value) {
37
+ try { return JSON.parse(value); } catch { return null; }
38
+ }
39
+
40
+ function exactCommandFromWrapper(value) {
41
+ const match = String(value).match(/(?:\b(?:cmd|command)|"(?:cmd|command)")\s*:\s*("(?:\\.|[^"\\])*")/s);
42
+ return match ? parsedJson(match[1]) : null;
43
+ }
44
+
45
+ function formattedToolInput(value) {
46
+ if (value && typeof value === "object") {
47
+ const direct = value.cmd ?? value.command;
48
+ return typeof direct === "string" && direct.trim() ? direct.trim() : JSON.stringify(value, null, 2);
49
+ }
50
+ const text = String(value || "").trim();
51
+ if (!text) return "";
52
+ const decoded = parsedJson(text);
53
+ if (decoded && typeof decoded === "object") return formattedToolInput(decoded);
54
+ return exactCommandFromWrapper(text) || text;
55
+ }
56
+
57
+ function toolAction(record, fallbackText) {
58
+ const block = contentBlocks(record).find((item) => item?.type === "tool_use");
59
+ if (block) return {
60
+ toolName: String(block.name || "Tool"),
61
+ details: locallyRedacted(formattedToolInput(block.input) || fallbackText),
62
+ timestamp: record?.timestamp || null,
63
+ };
64
+ return {
65
+ toolName: "Agent message",
66
+ details: locallyRedacted(visibleText(record) || fallbackText),
67
+ timestamp: record?.timestamp || null,
68
+ };
69
+ }
70
+
71
+ function matchingEvidenceText(occurrence, kind) {
72
+ return String((occurrence?.evidence || []).find((event) => event?.kind === kind)?.text || "").trim();
73
+ }
74
+
75
+ function fallbackRecordIndex(occurrence, records, kind) {
76
+ const kinds = new Set(Array.isArray(kind) ? kind : kind ? [kind] : []);
77
+ const timestamps = new Set((occurrence?.evidence || []).filter((event) => !kinds.size || kinds.has(event?.kind)).map((event) => event?.timestamp).filter(Boolean));
78
+ const index = records.findIndex((record) => timestamps.has(record?.timestamp));
79
+ return index >= 0 ? index : null;
80
+ }
81
+
82
+ function occurrenceRecordIndex(occurrence, records, field, kind) {
83
+ return finiteRecordIndex(occurrence?.location?.[field], records.length) ?? fallbackRecordIndex(occurrence, records, kind);
39
84
  }
40
85
 
41
- export function makeWorkaroundEvidencePreview(report, sessionRecords, metadataById, { contextTurns = DEFAULT_CONTEXT_TURNS } = {}) {
42
- const boundedContext = Number.isInteger(contextTurns) ? Math.min(4, Math.max(1, contextTurns)) : DEFAULT_CONTEXT_TURNS;
86
+ export function makeWorkaroundEvidencePreview(report, sessionRecords, metadataById) {
43
87
  const recordsById = new Map(sessionRecords.map((session) => [session.sessionId, session.records]));
44
88
  const occurrences = (report?.workaroundReview?.occurrences || []).slice(0, MAX_OCCURRENCES).flatMap((occurrence, index) => {
45
89
  const sessionId = occurrence?.location?.sessionId;
46
90
  const records = recordsById.get(sessionId);
47
91
  if (!records) return [];
48
- const excerpt = excerptRecords(records, occurrence, boundedContext);
49
- const preview = excerpt.length ? makeDonationPreview([{ sessionId, records: excerpt }], metadataById).sessions[0] : null;
50
92
  const metadata = metadataById.get(sessionId);
51
- const messages = preview?.messages?.length ? preview.messages : safeFallbackMessages(occurrence);
93
+ const donationSession = makeDonationPreview([{ sessionId, records }], metadataById).sessions[0];
94
+ const fullOpeningMessage = donationSession?.messages?.filter((message) => message.role === "user").map((message) => locallyRedacted(localOpeningPrompt(message.text))).find(Boolean)
95
+ || donationSession?.summary
96
+ || "Opening message unavailable";
97
+ const originalIndex = occurrenceRecordIndex(occurrence, records, "originalRecordIndex", "tool_use");
98
+ const blockerIndex = occurrenceRecordIndex(occurrence, records, "blockerRecordIndex", "tool_result");
99
+ const alternativeIndex = occurrenceRecordIndex(occurrence, records, "alternativeRecordIndex", ["assistant_text", "tool_use"]);
100
+ const originalRecord = originalIndex === null ? null : records[originalIndex];
101
+ const blockerRecord = blockerIndex === null ? null : records[blockerIndex];
102
+ const alternativeRecord = alternativeIndex === null ? null : records[alternativeIndex];
103
+ const blockerText = locallyRedacted(toolResultText(blockerRecord) || matchingEvidenceText(occurrence, "tool_result") || occurrence.blocker || "The original method was blocked.");
52
104
  return [{
53
105
  index: index + 1,
54
- summary: String(occurrence.summary || "The agent used another method after encountering a blocker."),
55
- confidence: ["high", "medium", "low"].includes(occurrence.confidence) ? occurrence.confidence : "unknown",
56
- disclosure: String(occurrence.disclosure || "unclear"),
57
- originalMethod: String(occurrence.originalMethod || "Original method"),
58
- blocker: String(occurrence.blocker || "The original method was blocked"),
59
- alternativeMethod: String(occurrence.alternativeMethod || "Alternative method"),
60
- session: { label: metadata?.label || `Session ${index + 1}`, agentName: metadata?.agentName || "AI agent" },
61
- messages,
62
- contextTurns: boundedContext,
63
- reconstructedFromTranscript: Boolean(preview?.messages?.length),
106
+ session: {
107
+ label: metadata?.label || `Session ${index + 1}`,
108
+ agentName: metadata?.agentName || "AI agent",
109
+ startedAt: metadata?.startedAt || records.find((record) => record?.timestamp)?.timestamp || null,
110
+ openingMessage: {
111
+ preview: donationSession?.summary || fullOpeningMessage,
112
+ full: fullOpeningMessage,
113
+ },
114
+ },
115
+ originalAction: toolAction(originalRecord, occurrence.originalMethod || matchingEvidenceText(occurrence, "tool_use") || "Original tool call unavailable"),
116
+ blocker: { text: blockerText, timestamp: blockerRecord?.timestamp || null },
117
+ workaroundAction: toolAction(alternativeRecord, occurrence.alternativeMethod || matchingEvidenceText(occurrence, "assistant_text") || "Workaround action unavailable"),
64
118
  }];
65
119
  });
66
120
  return {
67
- format: "behavior-wrapped-workaround-evidence-v1",
121
+ format: "behavior-wrapped-workaround-evidence-v3",
68
122
  localPrivate: true,
69
123
  standardRedactionsApplied: true,
70
124
  reportId: report?.id,