@ascenda-one/agent-mcp 0.1.27 → 0.1.33

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/cli.js CHANGED
@@ -411,39 +411,44 @@ var require_metricKeys = __commonJS({
411
411
  exports.METRIC_KEYS = {
412
412
  // ── Read by a backend reader ────────────────────────────────────────────
413
413
  contextWindowPeakPct: {
414
+ family: "context",
414
415
  readBy: ["backend", "handoff"],
415
416
  backendAliases: CONTEXT_WINDOW_CANONICAL_ALIASES,
416
417
  unit: "fraction of the context window (0\u20131; uncapped for >200k contexts)",
417
418
  note: "Claude Code reports a true per-session peak. Cursor reports its composer's last known occupancy under the same key \u2014 the closest its store can answer, and not the same measurement."
418
419
  },
419
420
  contextUsagePercent: {
421
+ family: "context",
420
422
  readBy: ["backend", "handoff"],
421
423
  backendAliases: CONTEXT_WINDOW_CURSOR_PERCENT_ALIASES,
422
424
  unit: "percent (0\u2013100)",
423
425
  note: "Cursor's own column name. Superseded by contextWindowPeakPct on the wire; kept because the handoff reads it and imported rows carry it. Unit-explicit on the backend: always divided by 100, never put through the fraction-or-percent heuristic."
424
426
  },
425
- promptCount: { readBy: ["backend", "handoff"], backendAliases: ["promptCount", "prompt_count"] },
426
- sessionMinutes: { readBy: ["backend"], backendAliases: ["sessionMinutes", "session_minutes"], unit: "minutes" },
427
- durationBucket: { readBy: ["backend", "handoff"], backendAliases: ["durationBucket", "duration_bucket"] },
428
- afterHoursPrompts: { readBy: ["backend", "handoff"], backendAliases: ["afterHoursPrompts", "after_hours_prompts"] },
429
- inputTokens: { readBy: ["backend"], backendAliases: ["inputTokens", "input_tokens"], unit: "tokens" },
430
- outputTokens: { readBy: ["backend"], backendAliases: ["outputTokens", "output_tokens"], unit: "tokens" },
431
- cacheReadTokens: { readBy: ["backend"], backendAliases: ["cacheReadTokens", "cache_read_tokens"], unit: "tokens" },
432
- queuedPrompts: { readBy: ["backend"], backendAliases: ["queuedPrompts", "queued_prompts"] },
433
- linesChangedBucket: { readBy: ["backend"], backendAliases: ["linesChangedBucket", "lines_changed_bucket"] },
427
+ promptCount: { family: "counts", readBy: ["backend", "handoff"], backendAliases: ["promptCount", "prompt_count"] },
428
+ sessionMinutes: { family: "session", readBy: ["backend"], backendAliases: ["sessionMinutes", "session_minutes"], unit: "minutes" },
429
+ durationBucket: { family: "session", readBy: ["backend", "handoff"], backendAliases: ["durationBucket", "duration_bucket"] },
430
+ afterHoursPrompts: { family: "clock", readBy: ["backend", "handoff"], backendAliases: ["afterHoursPrompts", "after_hours_prompts"] },
431
+ inputTokens: { family: "context", readBy: ["backend"], backendAliases: ["inputTokens", "input_tokens"], unit: "tokens" },
432
+ outputTokens: { family: "context", readBy: ["backend"], backendAliases: ["outputTokens", "output_tokens"], unit: "tokens" },
433
+ cacheReadTokens: { family: "context", readBy: ["backend"], backendAliases: ["cacheReadTokens", "cache_read_tokens"], unit: "tokens" },
434
+ queuedPrompts: { family: "counts", readBy: ["backend"], backendAliases: ["queuedPrompts", "queued_prompts"] },
435
+ linesChangedBucket: { family: "edits", readBy: ["backend"], backendAliases: ["linesChangedBucket", "lines_changed_bucket"] },
434
436
  // ── Read by the local handoff only ──────────────────────────────────────
435
- activeMinutes: { readBy: ["handoff"], unit: "minutes" },
437
+ activeMinutes: { family: "session", readBy: ["handoff"], unit: "minutes" },
436
438
  syntheticPromptLines: {
439
+ family: "reading",
437
440
  readBy: ["handoff"],
438
441
  unit: "lines",
439
442
  note: "Main-thread user lines the runtime wrote on the person's behalf (notifications, its own bookkeeping, slash-command wrappers, interrupt markers) and promptCount left out. Claude Code only; the receipt for the handoff's promptBasis. Counted per transcript, so a resumed transcript's copies count again."
440
443
  },
441
444
  dispatchedPromptLines: {
445
+ family: "reading",
442
446
  readBy: ["handoff"],
443
447
  unit: "lines",
444
448
  note: "Main-thread user lines that read as typed but are the prompt of a chip that launched the session, so promptCount left them out. Counted once per line across the store, as prompts are. Claude Code only; written beside promptBasis: typed_once."
445
449
  },
446
450
  interruptedRuns: {
451
+ family: "waiting",
447
452
  readBy: ["handoff"],
448
453
  unit: "runs",
449
454
  note: "Agent turns the person cut short with an interrupt while the turn was still going. A count per session, never a rate. Claude Code only; a handoff that counted them says so with interruptedRunsCounted, and absent means not counted, never zero."
@@ -459,11 +464,13 @@ var require_metricKeys = __commonJS({
459
464
  * they are.
460
465
  */
461
466
  handsOnMinutes: {
467
+ family: "session",
462
468
  readBy: ["handoff"],
463
469
  unit: "minutes",
464
470
  note: "Active time immediately preceding a human prompt \u2014 the only interval a transcript can show a person present for, because the prompt at its end is the evidence."
465
471
  },
466
472
  agentSupervisingMinutes: {
473
+ family: "session",
467
474
  readBy: ["handoff"],
468
475
  unit: "minutes",
469
476
  note: "The remaining active time: the agent was working and the person was not typing. NOT a claim that anyone watched it \u2014 nothing in a transcript could show that. Never render as attention."
@@ -473,127 +480,147 @@ var require_metricKeys = __commonJS({
473
480
  // a complete one, and a reader that ignores them is choosing to, rather than
474
481
  // being unable to.
475
482
  activeSplitInstants: {
483
+ family: "session",
476
484
  readBy: ["diagnostic"],
477
485
  note: "Distinct timestamps the split ran over, after collapsing ties. The denominator: two minutes off four instants and off four hundred are not the same measurement."
478
486
  },
479
487
  activeSplitUndatedLines: {
488
+ family: "session",
480
489
  readBy: ["diagnostic"],
481
490
  note: "Known lines carrying a timestamp that would not parse. Absent from the timeline, so both halves are short by an unknown amount and only this says so."
482
491
  },
483
492
  activeSplitUnposturedInstants: {
493
+ family: "posture",
484
494
  readBy: ["diagnostic"],
485
495
  note: "Instants reached before any permissionMode had been declared. Their supervising time lands in the unknown band, which is a blind spot rather than a posture."
486
496
  },
487
- afterHoursRequests: { readBy: ["handoff"] },
488
- approximateLintErrorsCount: { readBy: ["handoff"] },
489
- canceledCount: { readBy: ["handoff"] },
490
- chatEditCount: { readBy: ["handoff"] },
497
+ afterHoursRequests: { family: "clock", readBy: ["handoff"] },
498
+ approximateLintErrorsCount: { family: "outcome", readBy: ["handoff"] },
499
+ canceledCount: { family: "outcome", readBy: ["handoff"] },
500
+ chatEditCount: { family: "edits", readBy: ["handoff"] },
491
501
  compactionCount: {
502
+ family: "context",
492
503
  readBy: ["handoff"],
493
504
  note: "The backend counts context_compression_* event rows, not this key. Both are emitted; this one is for the handoff."
494
505
  },
495
506
  contextWindowPeakTokens: {
507
+ family: "context",
496
508
  readBy: ["handoff"],
497
509
  unit: "tokens",
498
510
  note: "The measured quantity, with no assumed denominator. Prefer this to the ratio for any within-person baseline."
499
511
  },
500
512
  contextWindowTokens: {
513
+ family: "context",
501
514
  readBy: ["handoff"],
502
515
  unit: "tokens",
503
516
  note: "Codex only: the model_context_window the rollout itself recorded \u2014 the real denominator its contextWindowPeakPct was computed against. Claude Code records no window and its ratio assumes 200k; absent here means the store never said."
504
517
  },
505
- date: { readBy: ["handoff"] },
506
- errorCount: { readBy: ["handoff"] },
507
- filesChangedCount: { readBy: ["handoff"] },
508
- humanChangesCount: { readBy: ["handoff"] },
509
- linesAdded: { readBy: ["handoff"] },
510
- linesRemoved: { readBy: ["handoff"] },
511
- primaryModel: { readBy: ["handoff"] },
512
- requestCount: { readBy: ["handoff"] },
513
- sessionStartedAt: { readBy: ["handoff"] },
514
- subagentComposers: { readBy: ["handoff"] },
518
+ date: { family: "clock", readBy: ["handoff"] },
519
+ errorCount: { family: "outcome", readBy: ["handoff"] },
520
+ filesChangedCount: { family: "edits", readBy: ["handoff"] },
521
+ humanChangesCount: { family: "edits", readBy: ["handoff"] },
522
+ linesAdded: { family: "edits", readBy: ["handoff"] },
523
+ linesRemoved: { family: "edits", readBy: ["handoff"] },
524
+ primaryModel: {
525
+ family: "model",
526
+ readBy: ["backend", "handoff"],
527
+ backendAliases: ["primaryModel", "primary_model"],
528
+ note: "Read twice: the desktop's local handoff folds it, and a server-side reader resolves it to group a bucket's sessions by the model that served them. Declared handoff-only until 23 Sep 2026 \u2014 see toolName for why that direction of mistake has no symptom."
529
+ },
530
+ requestCount: { family: "counts", readBy: ["handoff"] },
531
+ sessionStartedAt: { family: "session", readBy: ["handoff"] },
532
+ subagentComposers: { family: "counts", readBy: ["handoff"] },
515
533
  subagentToolCallCount: {
534
+ family: "tools",
516
535
  readBy: ["handoff"],
517
536
  note: "Claude Code only: calls made inside subagent transcripts, kept out of toolCallCount so the main-loop count matches what the wire events carry."
518
537
  },
519
- subagentTranscripts: { readBy: ["handoff"] },
538
+ subagentTranscripts: { family: "counts", readBy: ["handoff"] },
520
539
  toolCallCount: {
540
+ family: "tools",
521
541
  readBy: ["handoff"],
522
542
  note: "The backend counts ai_tool_call_started event rows, not this key \u2014 same split as compactionCount. Deduplicated on the tool-call id; see each extractor for what one call means in its store."
523
543
  },
524
544
  toolCallsUndated: {
545
+ family: "tools",
525
546
  readBy: ["handoff"],
526
547
  note: "Cursor only: calls whose every record carries an empty createdAt. Counted in toolCallCount, but no event exists for them \u2014 the wire total is smaller than this session count by exactly this number."
527
548
  },
528
- toolFailureCount: { readBy: ["handoff"] },
529
- totalEntryCount: { readBy: ["handoff"] },
549
+ toolFailureCount: { family: "outcome", readBy: ["handoff"] },
550
+ totalEntryCount: { family: "counts", readBy: ["handoff"] },
530
551
  userModifiedEditCount: {
552
+ family: "edits",
531
553
  readBy: ["handoff"],
532
554
  note: "Null, never 0 \u2014 Claude Code never sets userModified true, so 0 would assert 'no AI edit was ever corrected by hand'."
533
555
  },
534
556
  // ── Diagnostic: read by nobody, on purpose ──────────────────────────────
535
- abandonedPromptCount: { readBy: ["diagnostic"] },
557
+ abandonedPromptCount: { family: "counts", readBy: ["diagnostic"] },
536
558
  // Epoch-marker metrics. The marker is local-only and never reaches the wire
537
559
  // (see EXTRACTION_EPOCH_KIND), but it travels as a NormalizedHistoricalEvent
538
560
  // and so is keyed by the same vocabulary.
539
- windowOldest: { readBy: ["handoff"], note: "Oldest event the extraction saw \u2014 the marker's left edge." },
540
- windowNewest: { readBy: ["handoff"], note: "Newest event the extraction saw \u2014 the marker's right edge." },
541
- projectsWithNoReadableTranscript: { readBy: ["diagnostic"] },
542
- unparsedComposerHeaders: { readBy: ["diagnostic"] },
543
- unknownComposerHeaderTypes: { readBy: ["diagnostic"] },
544
- orphanedBubbles: { readBy: ["diagnostic"] },
545
- orphanedSubagentBubbles: { readBy: ["diagnostic"] },
546
- sessionsWithoutTimeline: { readBy: ["diagnostic"] },
561
+ windowOldest: { family: "session", readBy: ["handoff"], note: "Oldest event the extraction saw \u2014 the marker's left edge." },
562
+ windowNewest: { family: "session", readBy: ["handoff"], note: "Newest event the extraction saw \u2014 the marker's right edge." },
563
+ projectsWithNoReadableTranscript: { family: "reading", readBy: ["diagnostic"] },
564
+ unparsedComposerHeaders: { family: "reading", readBy: ["diagnostic"] },
565
+ unknownComposerHeaderTypes: { family: "reading", readBy: ["diagnostic"] },
566
+ orphanedBubbles: { family: "reading", readBy: ["diagnostic"] },
567
+ orphanedSubagentBubbles: { family: "reading", readBy: ["diagnostic"] },
568
+ sessionsWithoutTimeline: { family: "reading", readBy: ["diagnostic"] },
547
569
  sessionsWithOnlyInheritedLines: {
570
+ family: "reading",
548
571
  readBy: ["diagnostic"],
549
572
  note: "Claude Code transcripts holding nothing but a copy of an ancestor's history, so no line's instant is theirs and no session is emitted for them. Excluded by rule, not a read failure: the work is in the transcript that owns it."
550
573
  },
551
- emptyComposers: { readBy: ["diagnostic"] },
552
- apiErrorCount: { readBy: ["diagnostic"] },
553
- assistantTurns: { readBy: ["diagnostic"] },
554
- compactionAutoCount: { readBy: ["diagnostic"] },
555
- compactionManualCount: { readBy: ["diagnostic"] },
556
- editDayCount: { readBy: ["diagnostic"] },
557
- emptyChatSessions: { readBy: ["diagnostic"] },
558
- gitBranch: { readBy: ["diagnostic"] },
559
- linesChanged: { readBy: ["diagnostic"] },
560
- malformedChatSessionLines: { readBy: ["diagnostic"] },
561
- malformedHistoryEntries: { readBy: ["diagnostic"] },
562
- mode: { readBy: ["diagnostic"] },
563
- modelCount: { readBy: ["diagnostic"] },
564
- modelSwitchCount: { readBy: ["diagnostic"] },
565
- rapidRepromptCount: { readBy: ["diagnostic"] },
566
- schemaUnreadable: { readBy: ["diagnostic"] },
567
- sessionCount: { readBy: ["diagnostic"] },
568
- sessionsFromBubbleTimeline: { readBy: ["diagnostic"] },
569
- sessionsFromCheckpointTimeline: { readBy: ["diagnostic"] },
570
- sessionsFromRecencyTimeline: { readBy: ["diagnostic"] },
571
- subagentAssistantTurns: { readBy: ["diagnostic"] },
572
- subagentPrompts: { readBy: ["diagnostic"] },
573
- subagentTokensTotal: { readBy: ["diagnostic"] },
574
+ emptyComposers: { family: "reading", readBy: ["diagnostic"] },
575
+ apiErrorCount: { family: "outcome", readBy: ["diagnostic"] },
576
+ assistantTurns: { family: "counts", readBy: ["diagnostic"] },
577
+ compactionAutoCount: { family: "context", readBy: ["diagnostic"] },
578
+ compactionManualCount: { family: "context", readBy: ["diagnostic"] },
579
+ editDayCount: { family: "clock", readBy: ["diagnostic"] },
580
+ emptyChatSessions: { family: "reading", readBy: ["diagnostic"] },
581
+ gitBranch: { family: "repo", readBy: ["diagnostic"] },
582
+ linesChanged: { family: "edits", readBy: ["diagnostic"] },
583
+ malformedChatSessionLines: { family: "reading", readBy: ["diagnostic"] },
584
+ malformedHistoryEntries: { family: "reading", readBy: ["diagnostic"] },
585
+ mode: { family: "posture", readBy: ["diagnostic"] },
586
+ modelCount: { family: "model", readBy: ["diagnostic"] },
587
+ modelSwitchCount: { family: "model", readBy: ["diagnostic"] },
588
+ rapidRepromptCount: { family: "counts", readBy: ["diagnostic"] },
589
+ schemaUnreadable: { family: "reading", readBy: ["diagnostic"] },
590
+ sessionCount: { family: "session", readBy: ["diagnostic"] },
591
+ sessionsFromBubbleTimeline: { family: "reading", readBy: ["diagnostic"] },
592
+ sessionsFromCheckpointTimeline: { family: "reading", readBy: ["diagnostic"] },
593
+ sessionsFromRecencyTimeline: { family: "reading", readBy: ["diagnostic"] },
594
+ subagentAssistantTurns: { family: "counts", readBy: ["diagnostic"] },
595
+ subagentPrompts: { family: "counts", readBy: ["diagnostic"] },
596
+ subagentTokensTotal: { family: "context", readBy: ["diagnostic"] },
574
597
  toolName: {
575
- readBy: ["diagnostic"],
576
- note: "Set per ai_tool_call_started event by #43's extractors and shipped in wire metadata, but no reader resolves it server-side yet (the backend's ToolName column is MCP audit, not telemetry). Registered after the fact: #38 and #43 merged past each other, and the union caught it on the next compile \u2014 metaLines all over again."
598
+ family: "tools",
599
+ readBy: ["backend"],
600
+ backendAliases: ["toolName", "tool_name"],
601
+ note: "Set per ai_tool_call_started event by #43's extractors. Declared diagnostic until 23 Sep 2026 on the belief that nothing resolved it server-side; two backend readers do \u2014 one to see a sub-agent dispatch, one composing per-tool metrics. This is the inverse of the mismatch this module was written for: contextUsagePercent was a key nobody read, and a key a reader resolves without being declared drops nothing, so it has no symptom at all. What it costs is that readBy stops being a true census of what the server sees, which is what you consult when deciding what a collector should stop sending. Registered after the fact in the first place: #38 and #43 merged past each other, and the union caught it on the next compile \u2014 metaLines all over again."
577
602
  },
578
- toolResultCount: { readBy: ["diagnostic"] },
579
- toolResultErrorCount: { readBy: ["diagnostic"] },
580
- unknownBubbles: { readBy: ["diagnostic"] },
581
- unknownLines: { readBy: ["diagnostic"] },
603
+ toolResultCount: { family: "tools", readBy: ["diagnostic"] },
604
+ toolResultErrorCount: { family: "outcome", readBy: ["diagnostic"] },
605
+ unknownBubbles: { family: "reading", readBy: ["diagnostic"] },
606
+ unknownLines: { family: "reading", readBy: ["diagnostic"] },
582
607
  metaLines: {
608
+ family: "reading",
583
609
  readBy: ["diagnostic"],
584
610
  note: 'Recognised-but-skipped transcript machinery (file-history-snapshot, queued-command, \u2026). Split out of unknownLines by #43 so that number keeps meaning "a type nobody has looked at". Registered here after the fact: #41 and #43 merged past each other, and the union caught it on the next compile \u2014 which is this module doing its job.'
585
611
  },
586
- unparsedBubbles: { readBy: ["diagnostic"] },
587
- unparsedChatSessionFiles: { readBy: ["diagnostic"] },
588
- unparsedHistoryFiles: { readBy: ["diagnostic"] },
589
- unparsedLines: { readBy: ["diagnostic"] },
590
- unreadableChatSessionFiles: { readBy: ["diagnostic"] },
591
- unreadableHistoryFiles: { readBy: ["diagnostic"] },
612
+ unparsedBubbles: { family: "reading", readBy: ["diagnostic"] },
613
+ unparsedChatSessionFiles: { family: "reading", readBy: ["diagnostic"] },
614
+ unparsedHistoryFiles: { family: "reading", readBy: ["diagnostic"] },
615
+ unparsedLines: { family: "reading", readBy: ["diagnostic"] },
616
+ unreadableChatSessionFiles: { family: "reading", readBy: ["diagnostic"] },
617
+ unreadableHistoryFiles: { family: "reading", readBy: ["diagnostic"] },
592
618
  unreadableRolloutFiles: {
619
+ family: "reading",
593
620
  readBy: ["diagnostic"],
594
621
  note: "Codex only: rollout files the extractor meant to read and could not open. Summed into the import's read-failure warning, so a store that is partly unreadable says so rather than reporting a short window as the whole."
595
622
  },
596
- unrecognisedChatSessionFiles: { readBy: ["diagnostic"] }
623
+ unrecognisedChatSessionFiles: { family: "reading", readBy: ["diagnostic"] }
597
624
  };
598
625
  function backendMetricKeys() {
599
626
  return Object.entries(exports.METRIC_KEYS).filter(([, spec]) => spec.readBy.includes("backend")).map(([key, spec]) => [key, spec.backendAliases ?? [key]]);
@@ -606,7 +633,7 @@ var require_out = __commonJS({
606
633
  "../packages/tool-contract/out/index.js"(exports) {
607
634
  "use strict";
608
635
  Object.defineProperty(exports, "__esModule", { value: true });
609
- exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.EVENT_METADATA_FIELDS = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
636
+ exports.backendMetricKeys = exports.METRIC_KEYS = exports.ASCENDA_SEMANTIC_PROVENANCE = exports.ASCENDA_HISTORICAL_CONSENT_SCOPE = exports.ASCENDA_COLLABORATION_CONSENT_SCOPE = exports.ASCENDA_SEMANTIC_CONSENT_SCOPE = exports.ASCENDA_PROVENANCE = exports.ASCENDA_CONSENT_SCOPE = exports.EVENT_WORKLOAD_CATEGORY = exports.TOOL_EVENT_DELIVERED_STATUSES = exports.IDEMPOTENCY_KEY_MAX_LENGTH = exports.EVENT_METADATA_FIELDS = exports.EVENT_METADATA_DISCLOSURE = exports.COLLABORATION_EVENT_TYPES = exports.SEMANTIC_WORK_SIGNAL_EVENT_TYPES = exports.ASCENDA_ELAPSED_QUANTITIES = exports.ASCENDA_ACTIVE_TIME_QUANTITIES = exports.ASCENDA_TOOL_TYPES = exports.ASCENDA_TELEMETRY_SOURCES = void 0;
610
637
  exports.combineDisjointHalves = combineDisjointHalves;
611
638
  exports.requireComparableQuantities = requireComparableQuantities;
612
639
  exports.ASCENDA_TELEMETRY_SOURCES = [
@@ -674,6 +701,55 @@ var require_out = __commonJS({
674
701
  "review_given",
675
702
  "pull_request_opened"
676
703
  ];
704
+ exports.EVENT_METADATA_DISCLOSURE = {
705
+ language: "edits",
706
+ fileType: "edits",
707
+ durationBucket: "session",
708
+ tokenPressureBucket: "context",
709
+ linesChangedBucket: "edits",
710
+ commandClass: "counts",
711
+ gitAction: "git",
712
+ milestoneKind: "git",
713
+ branchHash: "repo",
714
+ autonomyMode: "posture",
715
+ modelClass: "model",
716
+ modelId: "model",
717
+ userModified: "edits",
718
+ outcome: "outcome",
719
+ trigger: "outcome",
720
+ promptClass: "counts",
721
+ reason: "outcome",
722
+ afterHours: "clock",
723
+ activity: "counts",
724
+ // One constant word, from the agent itself. The session sentence names it.
725
+ sessionEndReason: "session",
726
+ interruptionKind: "waiting",
727
+ // Claude Code's own opaque id for one subagent, and the class it belongs
728
+ // to. Never the agent's name or anything it was asked.
729
+ subagentId: "subagents",
730
+ subagentClass: "subagents",
731
+ // Free text by type, and written by no hook mapper — the IDE extension's
732
+ // test signal is the only producer. The setup disclosure's third refusal
733
+ // line says as much, and tool-kit's guard test fails if a mapper starts.
734
+ message: "counts",
735
+ host: "session",
736
+ // One constant word from the host's own environment: this machine, or a
737
+ // hosted session. The session sentence names it.
738
+ runtime: "session",
739
+ toolName: "tools",
740
+ simulated: "transport",
741
+ relatedEventType: "transport",
742
+ skillVersion: "transport",
743
+ // A hash computed before it reaches any collector; the task itself is never
744
+ // seen by this code, so there is nothing about the work here to disclose.
745
+ taskFingerprint: "transport",
746
+ importKey: "transport",
747
+ extractionId: "transport",
748
+ importSchema: "transport",
749
+ // The version of the Ascenda collector that sent this event. Names the
750
+ // build, and nothing about the work it observed.
751
+ collectorVersion: "transport"
752
+ };
677
753
  exports.EVENT_METADATA_FIELDS = [
678
754
  "language",
679
755
  "fileType",
@@ -697,13 +773,19 @@ var require_out = __commonJS({
697
773
  "message",
698
774
  "host",
699
775
  "toolName",
776
+ "runtime",
777
+ "sessionEndReason",
778
+ "interruptionKind",
779
+ "subagentId",
780
+ "subagentClass",
700
781
  "simulated",
701
782
  "relatedEventType",
702
783
  "skillVersion",
703
784
  "taskFingerprint",
704
785
  "importKey",
705
786
  "extractionId",
706
- "importSchema"
787
+ "importSchema",
788
+ "collectorVersion"
707
789
  ];
708
790
  exports.IDEMPOTENCY_KEY_MAX_LENGTH = 128;
709
791
  exports.TOOL_EVENT_DELIVERED_STATUSES = ["accepted", "duplicate"];
@@ -743,6 +825,12 @@ var require_out = __commonJS({
743
825
  // `ai_prompt_submitted` closes. Neutral so a marker sent once per turn
744
826
  // doesn't weigh on any workload leg.
745
827
  ai_turn_completed: "neutral",
828
+ // A subagent began or finished under a session. Boundaries, not work: the
829
+ // subagent's own tool calls and edits arrive as their own events and carry
830
+ // their own categories. A reader pairs these on `subagentId` to count how
831
+ // many agents ran at once; neutral so that count weighs on no workload leg.
832
+ subagent_started: "neutral",
833
+ subagent_stopped: "neutral",
746
834
  // The agent stopped and is waiting on the person: Claude Code's
747
835
  // `Notification`, Codex's `PermissionRequest`. Supervision, beside the other
748
836
  // oversight overhead, because that is what it is — time the person spends
@@ -869,6 +957,21 @@ var require_payload = __commonJS({
869
957
  }
870
958
  });
871
959
 
960
+ // ../packages/tool-kit/out/collectorVersion.js
961
+ var require_collectorVersion = __commonJS({
962
+ "../packages/tool-kit/out/collectorVersion.js"(exports) {
963
+ "use strict";
964
+ Object.defineProperty(exports, "__esModule", { value: true });
965
+ exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
966
+ exports.describeCollectorVersion = describeCollectorVersion;
967
+ exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
968
+ exports.COLLECTOR_VERSION = "0.1.33" ? "0.1.33" : exports.UNRELEASED_COLLECTOR_VERSION;
969
+ function describeCollectorVersion(version2 = exports.COLLECTOR_VERSION) {
970
+ return version2 === exports.UNRELEASED_COLLECTOR_VERSION ? `${version2} (built from a checkout, not a release)` : version2;
971
+ }
972
+ }
973
+ });
974
+
872
975
  // ../packages/tool-kit/out/eventLog.js
873
976
  var require_eventLog = __commonJS({
874
977
  "../packages/tool-kit/out/eventLog.js"(exports) {
@@ -964,6 +1067,12 @@ var require_http = __commonJS({
964
1067
  exports.AscendaApiError = void 0;
965
1068
  exports.createPairingSession = createPairingSession;
966
1069
  exports.getPairingStatus = getPairingStatus;
1070
+ exports.startStudyJoin = startStudyJoin;
1071
+ exports.getStudyJoinStatus = getStudyJoinStatus;
1072
+ exports.readInitiatives = readInitiatives;
1073
+ exports.readStudyNotices = readStudyNotices;
1074
+ exports.setStudyObjection = setStudyObjection;
1075
+ exports.markStudyNoticeShown = markStudyNoticeShown;
967
1076
  exports.renewToolToken = renewToolToken;
968
1077
  exports.isRetryableStatus = isRetryableStatus;
969
1078
  exports.postToolEvent = postToolEvent;
@@ -1000,6 +1109,108 @@ var require_http = __commonJS({
1000
1109
  throw new AscendaApiError(response.status, void 0, await response.text());
1001
1110
  return await response.json();
1002
1111
  }
1112
+ async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
1113
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
1114
+ method: "POST",
1115
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
1116
+ body: JSON.stringify({ joinCode, mode })
1117
+ });
1118
+ if (!response.ok)
1119
+ throw await apiError(response);
1120
+ return await response.json();
1121
+ }
1122
+ async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
1123
+ const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
1124
+ method: "GET",
1125
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
1126
+ });
1127
+ if (!response.ok)
1128
+ throw await apiError(response);
1129
+ return await response.json();
1130
+ }
1131
+ async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
1132
+ let response;
1133
+ try {
1134
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
1135
+ method: "GET",
1136
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1137
+ signal
1138
+ });
1139
+ } catch (error2) {
1140
+ return { kind: "failed", reason: error2 instanceof Error && error2.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1141
+ }
1142
+ if (response.status === 401)
1143
+ return { kind: "rejected", httpStatus: 401 };
1144
+ if (!response.ok)
1145
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1146
+ let body;
1147
+ try {
1148
+ body = await response.json();
1149
+ } catch {
1150
+ return { kind: "failed", reason: "the reply was not readable" };
1151
+ }
1152
+ if (!Array.isArray(body))
1153
+ return { kind: "failed", reason: "the reply was not a list" };
1154
+ return { kind: "ok", initiatives: body };
1155
+ }
1156
+ async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
1157
+ let response;
1158
+ try {
1159
+ response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
1160
+ method: "GET",
1161
+ headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
1162
+ signal
1163
+ });
1164
+ } catch (error2) {
1165
+ return { kind: "failed", reason: error2 instanceof Error && error2.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
1166
+ }
1167
+ if (response.status === 404)
1168
+ return { kind: "absent" };
1169
+ if (response.status === 401)
1170
+ return { kind: "rejected", httpStatus: 401 };
1171
+ if (!response.ok)
1172
+ return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
1173
+ let body;
1174
+ try {
1175
+ body = await response.json();
1176
+ } catch {
1177
+ return { kind: "absent" };
1178
+ }
1179
+ if (!Array.isArray(body))
1180
+ return { kind: "absent" };
1181
+ return { kind: "ok", notices: body };
1182
+ }
1183
+ async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
1184
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
1185
+ method: objected ? "POST" : "DELETE",
1186
+ headers: { Authorization: `Bearer ${eventWriteToken}` }
1187
+ });
1188
+ if (!response.ok)
1189
+ throw await apiError(response);
1190
+ }
1191
+ async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
1192
+ try {
1193
+ const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
1194
+ method: "POST",
1195
+ headers: { Authorization: `Bearer ${eventWriteToken}` },
1196
+ signal
1197
+ });
1198
+ return response.ok;
1199
+ } catch {
1200
+ return false;
1201
+ }
1202
+ }
1203
+ async function apiError(response) {
1204
+ const body = await response.text();
1205
+ let errorCode;
1206
+ try {
1207
+ const parsed = JSON.parse(body);
1208
+ errorCode = parsed.code ?? parsed.error;
1209
+ } catch {
1210
+ errorCode = void 0;
1211
+ }
1212
+ return new AscendaApiError(response.status, errorCode, body);
1213
+ }
1003
1214
  async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
1004
1215
  const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
1005
1216
  method: "POST",
@@ -1142,9 +1353,12 @@ var require_tokenStore = __commonJS({
1142
1353
  };
1143
1354
  }();
1144
1355
  Object.defineProperty(exports, "__esModule", { value: true });
1356
+ exports.EVENT_TOKEN_TTL_MS = void 0;
1145
1357
  exports.ascendaHome = ascendaHome;
1146
1358
  exports.defaultTokenFilePath = defaultTokenFilePath2;
1359
+ exports.tokenExpiryFilePath = tokenExpiryFilePath;
1147
1360
  exports.persistEventWriteToken = persistEventWriteToken2;
1361
+ exports.readTokenExpiry = readTokenExpiry;
1148
1362
  exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
1149
1363
  exports.readTokenFile = readTokenFile2;
1150
1364
  exports.sanitizeFilePart = sanitizeFilePart;
@@ -1157,7 +1371,10 @@ var require_tokenStore = __commonJS({
1157
1371
  function defaultTokenFilePath2(toolInstallationId) {
1158
1372
  return path.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
1159
1373
  }
1160
- function persistEventWriteToken2(tokenFilePath, token) {
1374
+ function tokenExpiryFilePath(tokenFilePath) {
1375
+ return path.join(path.dirname(tokenFilePath), "expiry", path.basename(tokenFilePath));
1376
+ }
1377
+ function persistEventWriteToken2(tokenFilePath, token, expiresAt) {
1161
1378
  const dir = path.dirname(tokenFilePath);
1162
1379
  fs.mkdirSync(dir, { recursive: true, mode: 448 });
1163
1380
  fs.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
@@ -1165,6 +1382,30 @@ var require_tokenStore = __commonJS({
1165
1382
  fs.chmodSync(dir, 448);
1166
1383
  fs.chmodSync(tokenFilePath, 384);
1167
1384
  }
1385
+ const expiryFile = tokenExpiryFilePath(tokenFilePath);
1386
+ try {
1387
+ if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
1388
+ fs.mkdirSync(path.dirname(expiryFile), { recursive: true, mode: 448 });
1389
+ fs.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
1390
+ } else {
1391
+ fs.rmSync(expiryFile, { force: true });
1392
+ }
1393
+ } catch {
1394
+ }
1395
+ }
1396
+ exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1397
+ function readTokenExpiry(tokenFilePath) {
1398
+ try {
1399
+ const recorded = Date.parse(fs.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
1400
+ if (Number.isFinite(recorded))
1401
+ return recorded;
1402
+ } catch {
1403
+ }
1404
+ try {
1405
+ return fs.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
1406
+ } catch {
1407
+ return void 0;
1408
+ }
1168
1409
  }
1169
1410
  function listPersistedToolInstallationIds(toolType) {
1170
1411
  const prefix = `${sanitizeFilePart(toolType)}_`;
@@ -1611,7 +1852,7 @@ var require_eventSender = __commonJS({
1611
1852
  "../packages/tool-kit/out/eventSender.js"(exports) {
1612
1853
  "use strict";
1613
1854
  Object.defineProperty(exports, "__esModule", { value: true });
1614
- exports.AscendaEventSender = exports.AscendaSemanticEventError = void 0;
1855
+ exports.AscendaEventSender = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = void 0;
1615
1856
  exports.buildEventPayload = buildEventPayload;
1616
1857
  var afterHours_1 = require_afterHours();
1617
1858
  var tool_contract_1 = require_out();
@@ -1622,6 +1863,7 @@ var require_eventSender = __commonJS({
1622
1863
  var tokenStore_1 = require_tokenStore();
1623
1864
  var stateStore_1 = require_stateStore();
1624
1865
  var payload_1 = require_payload();
1866
+ var collectorVersion_1 = require_collectorVersion();
1625
1867
  var AscendaSemanticEventError = class extends Error {
1626
1868
  constructor(message) {
1627
1869
  super(message);
@@ -1643,11 +1885,15 @@ var require_eventSender = __commonJS({
1643
1885
  provenance: tool_contract_1.ASCENDA_PROVENANCE,
1644
1886
  privacyMode: "metadata_only",
1645
1887
  ...mapped,
1646
- metadata: mapped.metadata ?? {}
1888
+ metadata: withCollectorVersion(mapped.metadata)
1647
1889
  };
1648
1890
  }
1891
+ function withCollectorVersion(metadata) {
1892
+ return { ...metadata, collectorVersion: collectorVersion_1.COLLECTOR_VERSION };
1893
+ }
1649
1894
  var DEFAULT_TIMEOUT_MS = 5e3;
1650
1895
  var RETRY_DELAY_MS = 250;
1896
+ exports.TOKEN_RENEW_LEAD_MS = 21 * 24 * 60 * 60 * 1e3;
1651
1897
  var AscendaEventSender2 = class {
1652
1898
  config;
1653
1899
  eventWriteToken;
@@ -1655,6 +1901,8 @@ var require_eventSender = __commonJS({
1655
1901
  lastDrain;
1656
1902
  /** One outbox pass per sender, i.e. per hook process. The hook is on the user's critical path. */
1657
1903
  outboxServiced = false;
1904
+ /** One look at the token's expiry per sender, for the same reason. */
1905
+ expiryChecked = false;
1658
1906
  /** Resolved once, so every clock read in one pass sees the same instant. */
1659
1907
  time;
1660
1908
  constructor(config2) {
@@ -1665,6 +1913,30 @@ var require_eventSender = __commonJS({
1665
1913
  async send(mapped) {
1666
1914
  return this.post(buildEventPayload(this.config, mapped));
1667
1915
  }
1916
+ /**
1917
+ * Writes the event to the outbox and returns without touching the network.
1918
+ * The next outbox pass delivers it, from whichever hook of this
1919
+ * installation sends next.
1920
+ *
1921
+ * For a hook whose host is exiting. A process the host may kill at any
1922
+ * moment can't wait on a send, and one killed mid-send dies before
1923
+ * {@link post} gets to queue the payload, so the event goes with it. Here
1924
+ * the payload is on disk before anything can go wrong.
1925
+ *
1926
+ * Returns whether it is. When the write fails the journal says the event
1927
+ * was lost; nothing else could have kept it.
1928
+ */
1929
+ queue(mapped) {
1930
+ const payload = buildEventPayload(this.config, mapped);
1931
+ const queued = this.enqueue(payload);
1932
+ if (!queued) {
1933
+ this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, "other", {
1934
+ detail: `${payload.eventType}: outbox write failed, event lost`
1935
+ });
1936
+ }
1937
+ this.log(payload, "not_sent", queued ? "queued" : void 0);
1938
+ return queued;
1939
+ }
1668
1940
  /**
1669
1941
  * Sends one of the six agent-observed types (dark-flow-gap-analysis §2.1).
1670
1942
  * Distinct from {@link send} rather than an option on it, because the
@@ -1705,7 +1977,7 @@ var require_eventSender = __commonJS({
1705
1977
  consentScope: tool_contract_1.ASCENDA_SEMANTIC_CONSENT_SCOPE,
1706
1978
  provenance: tool_contract_1.ASCENDA_SEMANTIC_PROVENANCE,
1707
1979
  privacyMode: "metadata_only",
1708
- metadata: mapped.metadata
1980
+ metadata: withCollectorVersion(mapped.metadata)
1709
1981
  };
1710
1982
  return this.post(payload);
1711
1983
  }
@@ -1736,7 +2008,7 @@ var require_eventSender = __commonJS({
1736
2008
  consentScope: tool_contract_1.ASCENDA_COLLABORATION_CONSENT_SCOPE,
1737
2009
  provenance: tool_contract_1.ASCENDA_PROVENANCE,
1738
2010
  privacyMode: "metadata_only",
1739
- metadata: mapped.metadata ?? {}
2011
+ metadata: withCollectorVersion(mapped.metadata)
1740
2012
  };
1741
2013
  return this.post(payload);
1742
2014
  }
@@ -1754,6 +2026,7 @@ var require_eventSender = __commonJS({
1754
2026
  * hook during an outage to one bounded round trip instead of three.
1755
2027
  */
1756
2028
  async post(payload) {
2029
+ await this.renewIfExpiring();
1757
2030
  const halted = await this.serviceOutbox();
1758
2031
  let outcome;
1759
2032
  let queued = false;
@@ -1959,19 +2232,49 @@ var require_eventSender = __commonJS({
1959
2232
  return;
1960
2233
  (0, eventLog_1.appendEventLog)(logFile, { loggedAt: (/* @__PURE__ */ new Date()).toISOString(), delivery, payload, ...outbox ? { outbox } : {} });
1961
2234
  }
1962
- /** Never throws: a renewal that errors is a failed renewal, not a failed turn. */
2235
+ /**
2236
+ * Renews ahead of expiry, at most once per sender. Waiting for the 401
2237
+ * doesn't work: by then the token has expired, and the server won't renew
2238
+ * an expired token.
2239
+ */
2240
+ async renewIfExpiring() {
2241
+ if (this.expiryChecked || this.config.renewToken === false)
2242
+ return;
2243
+ this.expiryChecked = true;
2244
+ const expiresAt = (0, tokenStore_1.readTokenExpiry)(this.config.tokenFilePath);
2245
+ if (expiresAt === void 0 || this.time.now() < expiresAt - exports.TOKEN_RENEW_LEAD_MS)
2246
+ return;
2247
+ await this.renewEventToken();
2248
+ }
2249
+ /**
2250
+ * Never throws: a renewal that errors is a failed renewal, not a failed turn.
2251
+ *
2252
+ * A refused renewal usually means another process got there first. Hooks
2253
+ * and the MCP server share one token file, and renewing revokes the token
2254
+ * it replaces, so the loser holds a revoked token while the winner's
2255
+ * replacement is already on disk. Adopting that counts as a renewal.
2256
+ */
1963
2257
  async renewEventToken() {
2258
+ if (this.config.renewToken === false)
2259
+ return false;
1964
2260
  try {
1965
2261
  const renewed = await (0, http_1.renewToolToken)(this.config.apiBaseUrl, this.eventWriteToken, this.signal());
1966
2262
  if (!renewed)
1967
- return false;
2263
+ return this.adoptPersistedToken();
1968
2264
  this.eventWriteToken = renewed.eventWriteToken;
1969
- (0, tokenStore_1.persistEventWriteToken)(this.config.tokenFilePath, renewed.eventWriteToken);
2265
+ (0, tokenStore_1.persistEventWriteToken)(this.config.tokenFilePath, renewed.eventWriteToken, renewed.expiresAt);
1970
2266
  return true;
1971
2267
  } catch {
1972
2268
  return false;
1973
2269
  }
1974
2270
  }
2271
+ adoptPersistedToken() {
2272
+ const persisted = (0, tokenStore_1.readTokenFile)(this.config.tokenFilePath);
2273
+ if (!persisted || persisted === this.eventWriteToken)
2274
+ return false;
2275
+ this.eventWriteToken = persisted;
2276
+ return true;
2277
+ }
1975
2278
  signal() {
1976
2279
  return AbortSignal.timeout(this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS);
1977
2280
  }
@@ -2173,6 +2476,7 @@ var require_credentials = __commonJS({
2173
2476
  exports.readMachineCredentials = readMachineCredentials;
2174
2477
  exports.writeMachineCredentials = writeMachineCredentials;
2175
2478
  exports.writeTopLevelCredentials = writeTopLevelCredentials;
2479
+ exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
2176
2480
  exports.readHostCredentials = readHostCredentials;
2177
2481
  exports.writeHostCredentials = writeHostCredentials;
2178
2482
  exports.removeHostCredentials = removeHostCredentials;
@@ -2209,6 +2513,14 @@ var require_credentials = __commonJS({
2209
2513
  const existing = readMachineCredentials();
2210
2514
  writeMachineCredentials({ ...credentials, ...existing?.tools ? { tools: existing.tools } : {} });
2211
2515
  }
2516
+ function isLocalOnlyHostInstall(host, hasToken) {
2517
+ const credentials = readHostCredentials(host);
2518
+ if (!credentials?.localOnly)
2519
+ return false;
2520
+ if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
2521
+ return false;
2522
+ return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
2523
+ }
2212
2524
  function readHostCredentials(host) {
2213
2525
  const entry = readMachineCredentials()?.tools?.[host];
2214
2526
  if (!entry || typeof entry !== "object" || Array.isArray(entry))
@@ -2777,6 +3089,9 @@ var require_hookAdapter = __commonJS({
2777
3089
  if (events.length === 0)
2778
3090
  return;
2779
3091
  const notice = options.onNotice ?? ((message) => console.error(message));
3092
+ const hasToken = (id) => (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0;
3093
+ if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken))
3094
+ return;
2780
3095
  let config2;
2781
3096
  try {
2782
3097
  config2 = loadCliAgentConfig(options.toolType, options.sessionId, options.cwd, options);
@@ -2842,6 +3157,728 @@ var require_hookAdapter = __commonJS({
2842
3157
  }
2843
3158
  });
2844
3159
 
3160
+ // ../packages/tool-kit/out/hookSet.js
3161
+ var require_hookSet = __commonJS({
3162
+ "../packages/tool-kit/out/hookSet.js"(exports) {
3163
+ "use strict";
3164
+ Object.defineProperty(exports, "__esModule", { value: true });
3165
+ exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = void 0;
3166
+ exports.hookSetArgument = hookSetArgument;
3167
+ exports.readHookSet = readHookSet;
3168
+ exports.isHookSet = isHookSet;
3169
+ exports.readViaPlugin = readViaPlugin;
3170
+ exports.hookSetOfCommand = hookSetOfCommand;
3171
+ exports.hookSetChanges = hookSetChanges;
3172
+ exports.describeHookSetChanges = describeHookSetChanges;
3173
+ exports.HOOK_SET_FLAG = "--hook-set";
3174
+ exports.UNVERSIONED_HOOK_SET = 1;
3175
+ function hookSetArgument(hookSet) {
3176
+ return hookSet === void 0 ? "" : ` ${exports.HOOK_SET_FLAG} ${hookSet}`;
3177
+ }
3178
+ function readHookSet(argv) {
3179
+ const index = argv.indexOf(exports.HOOK_SET_FLAG);
3180
+ if (index === -1)
3181
+ return void 0;
3182
+ const raw = argv[index + 1];
3183
+ if (raw === void 0 || !/^[1-9]\d*$/.test(raw))
3184
+ return void 0;
3185
+ const value = Number(raw);
3186
+ return isHookSet(value) ? value : void 0;
3187
+ }
3188
+ function isHookSet(value) {
3189
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
3190
+ }
3191
+ function readViaPlugin(env) {
3192
+ return env.CLAUDE_PLUGIN_ROOT ? true : void 0;
3193
+ }
3194
+ function hookSetOfCommand(command) {
3195
+ const match = command.match(/--hook-set\s+(\d+)/);
3196
+ return match ? Number(match[1]) : exports.UNVERSIONED_HOOK_SET;
3197
+ }
3198
+ function hookSetChanges(before, events) {
3199
+ const added = events.filter((event) => !before.has(event));
3200
+ const sets = [...before.values()];
3201
+ return sets.length ? { added, previousSet: Math.min(...sets) } : { added };
3202
+ }
3203
+ function describeHookSetChanges(changes, hookSet) {
3204
+ if (changes.previousSet === void 0)
3205
+ return void 0;
3206
+ const parts = [];
3207
+ if (changes.added.length)
3208
+ parts.push(`added ${changes.added.join(", ")}`);
3209
+ if (changes.previousSet < hookSet)
3210
+ parts.push(`hook set ${changes.previousSet} \u2192 ${hookSet}`);
3211
+ return parts.length ? `upgraded: ${parts.join("; ")}` : void 0;
3212
+ }
3213
+ }
3214
+ });
3215
+
3216
+ // ../packages/tool-kit/out/studyJoin.js
3217
+ var require_studyJoin = __commonJS({
3218
+ "../packages/tool-kit/out/studyJoin.js"(exports) {
3219
+ "use strict";
3220
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
3221
+ if (k2 === void 0) k2 = k;
3222
+ var desc = Object.getOwnPropertyDescriptor(m, k);
3223
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
3224
+ desc = { enumerable: true, get: function() {
3225
+ return m[k];
3226
+ } };
3227
+ }
3228
+ Object.defineProperty(o, k2, desc);
3229
+ } : function(o, m, k, k2) {
3230
+ if (k2 === void 0) k2 = k;
3231
+ o[k2] = m[k];
3232
+ });
3233
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
3234
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
3235
+ } : function(o, v) {
3236
+ o["default"] = v;
3237
+ });
3238
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
3239
+ var ownKeys = function(o) {
3240
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
3241
+ var ar = [];
3242
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
3243
+ return ar;
3244
+ };
3245
+ return ownKeys(o);
3246
+ };
3247
+ return function(mod) {
3248
+ if (mod && mod.__esModule) return mod;
3249
+ var result = {};
3250
+ if (mod != null) {
3251
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
3252
+ }
3253
+ __setModuleDefault(result, mod);
3254
+ return result;
3255
+ };
3256
+ }();
3257
+ Object.defineProperty(exports, "__esModule", { value: true });
3258
+ exports.runStudyJoin = runStudyJoin;
3259
+ exports.formatWindow = formatWindow;
3260
+ var readline = __importStar(__require("node:readline"));
3261
+ var http_1 = require_http();
3262
+ var STUDY_JOIN_MODE = "report";
3263
+ var POLL_INTERVAL_MS = 3e3;
3264
+ var POLL_TIMEOUT_MS = 11 * 60 * 1e3;
3265
+ async function runStudyJoin(ctx) {
3266
+ const stdin = ctx.stdin ?? process.stdin;
3267
+ const stdout = ctx.stdout ?? process.stdout;
3268
+ const stderr = ctx.stderr ?? process.stderr;
3269
+ const print = (line) => stdout.write(`${line}
3270
+ `);
3271
+ if (!stdin.isTTY || !stdout.isTTY) {
3272
+ stderr.write("join needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
3273
+ return 0;
3274
+ }
3275
+ if (!ctx.joinCode) {
3276
+ stderr.write("Usage: join <code>\n");
3277
+ return 1;
3278
+ }
3279
+ let start;
3280
+ try {
3281
+ start = await (0, http_1.startStudyJoin)(ctx.apiBaseUrl, ctx.eventWriteToken, ctx.joinCode, STUDY_JOIN_MODE);
3282
+ } catch (error2) {
3283
+ stderr.write(`${describeStartError(error2)}
3284
+ `);
3285
+ return 1;
3286
+ }
3287
+ print("");
3288
+ print(`${start.organisationName}: ${describeStudyKind(start.studyKind)}`);
3289
+ print(formatWindow(start.windowStartUtc, start.windowEndUtc));
3290
+ print("");
3291
+ print("Report (30 days) grants:");
3292
+ for (const grant of start.grants)
3293
+ print(` ${describeGrant(grant)}`);
3294
+ print("");
3295
+ print("Study mode needs the Ascenda app. Open the app to join that way instead.");
3296
+ print("");
3297
+ print("Join in:");
3298
+ print(" 1) Report (30 days)");
3299
+ print(" 2) Not now");
3300
+ print("");
3301
+ const answer = await askChoice(stdin, stdout);
3302
+ if (!/^(1|report)$/i.test(answer)) {
3303
+ print("Not now.");
3304
+ return 0;
3305
+ }
3306
+ print("");
3307
+ print(`Confirm in the Ascenda app with code ${start.deviceCode}`);
3308
+ print(`Waiting for confirmation (expires ${formatLocalTime(start.expiresAt)})...`);
3309
+ const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
3310
+ const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
3311
+ while (Date.now() < deadline) {
3312
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
3313
+ let poll;
3314
+ try {
3315
+ poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
3316
+ } catch (error2) {
3317
+ if (isRetryablePollError(error2))
3318
+ continue;
3319
+ stderr.write(`${describeStartError(error2)}
3320
+ `);
3321
+ return 1;
3322
+ }
3323
+ if (poll.status === "pending")
3324
+ continue;
3325
+ if (poll.status === "confirmed") {
3326
+ const granted = poll.granted ?? [];
3327
+ if (granted.length === 0) {
3328
+ print("");
3329
+ print("Nothing was granted. Run join again, or check with your organisation.");
3330
+ return 1;
3331
+ }
3332
+ print("");
3333
+ print("Joined. Granted:");
3334
+ for (const grant of granted)
3335
+ print(` ${describeGrant(grant)}`);
3336
+ print("");
3337
+ print("Each of these can be turned off separately, in the app's consent settings.");
3338
+ print("The organisation sees group counts, never who joined.");
3339
+ return 0;
3340
+ }
3341
+ if (poll.status === "expired") {
3342
+ print("");
3343
+ print("This code expired before it was confirmed. Run join again for a fresh code.");
3344
+ return 1;
3345
+ }
3346
+ if (poll.refusedReason === "grant_failed") {
3347
+ print("");
3348
+ print("Join failed partway through. Some grants may not have gone through.");
3349
+ const granted = poll.granted ?? [];
3350
+ if (granted.length > 0) {
3351
+ print("");
3352
+ print("Granted before the failure:");
3353
+ for (const grant of granted)
3354
+ print(` ${describeGrant(grant)}`);
3355
+ print("");
3356
+ print("Each of these can be turned off separately, in the app's consent settings.");
3357
+ }
3358
+ print("Run join again, or check with your organisation.");
3359
+ return 1;
3360
+ }
3361
+ print("");
3362
+ print(describeRefusal(poll.refusedReason));
3363
+ return 1;
3364
+ }
3365
+ print("");
3366
+ print("Timed out waiting for confirmation. Run join again for a fresh code.");
3367
+ return 1;
3368
+ }
3369
+ function isRetryablePollError(error2) {
3370
+ if (error2 instanceof http_1.AscendaApiError)
3371
+ return error2.status >= 500 && error2.status <= 599;
3372
+ return true;
3373
+ }
3374
+ function askChoice(stdin, stdout) {
3375
+ return new Promise((resolve) => {
3376
+ const rl = readline.createInterface({ input: stdin, output: stdout });
3377
+ let settled = false;
3378
+ const finish = (value) => {
3379
+ if (settled)
3380
+ return;
3381
+ settled = true;
3382
+ rl.close();
3383
+ resolve(value.trim());
3384
+ };
3385
+ rl.question("Choice [Not now]: ", finish);
3386
+ rl.once("close", () => finish(""));
3387
+ });
3388
+ }
3389
+ function formatLocalTime(iso) {
3390
+ const date3 = new Date(iso);
3391
+ if (Number.isNaN(date3.getTime()))
3392
+ return iso;
3393
+ return new Intl.DateTimeFormat(void 0, { day: "numeric", month: "short", hour: "numeric", minute: "2-digit" }).format(date3);
3394
+ }
3395
+ function formatWindow(startUtc, endUtc) {
3396
+ const start = new Date(startUtc);
3397
+ const end = new Date(endUtc);
3398
+ const sameYear = start.getUTCFullYear() === end.getUTCFullYear();
3399
+ const dayMonth = { day: "numeric", month: "short", timeZone: "UTC" };
3400
+ const withYear = { ...dayMonth, year: "numeric" };
3401
+ const startFmt = new Intl.DateTimeFormat("en-GB", sameYear ? dayMonth : withYear);
3402
+ const endFmt = new Intl.DateTimeFormat("en-GB", withYear);
3403
+ return `${startFmt.format(start)} \u2013 ${endFmt.format(end)}`;
3404
+ }
3405
+ var GRANT_SENTENCES = {
3406
+ 501: "AI assistant data processing consent",
3407
+ 507: "Import of the AI-work history already on your machine"
3408
+ };
3409
+ function describeGrant(grant) {
3410
+ return GRANT_SENTENCES[grant.code] ?? humanise(grant.name);
3411
+ }
3412
+ var STUDY_KIND_SENTENCES = {
3413
+ Report30: "a 30-day report",
3414
+ Study90: "a 90-day study"
3415
+ };
3416
+ function describeStudyKind(studyKind) {
3417
+ return STUDY_KIND_SENTENCES[studyKind] ?? humanise(studyKind);
3418
+ }
3419
+ function humanise(name) {
3420
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").trim() || name;
3421
+ }
3422
+ var REFUSED_REASON_MESSAGES = {
3423
+ study_no_longer_live: "That study is no longer open to join.",
3424
+ withdrawn: "You're no longer an active participant in that study.",
3425
+ // Handled as its own branch above, with its granted list, before this
3426
+ // table is ever consulted — present so the type stays exhaustive, and as
3427
+ // a plain fallback should something call this function with it directly.
3428
+ grant_failed: "Join failed partway through. Some grants may not have gone through.",
3429
+ declined: "You declined in the app. Nothing was granted.",
3430
+ not_enrolled: "That study couldn't enrol you, so nothing was granted."
3431
+ };
3432
+ function describeRefusal(refusedReason) {
3433
+ if (refusedReason && REFUSED_REASON_MESSAGES[refusedReason])
3434
+ return REFUSED_REASON_MESSAGES[refusedReason];
3435
+ return "The join didn't go through. Nothing new was granted.";
3436
+ }
3437
+ var START_ERROR_MESSAGES = {
3438
+ join_code_not_found: "That code is not a study anyone can join. Check it and try again.",
3439
+ unknown_mode: "This tool only offers Report mode from the command line.",
3440
+ no_live_study: "There's nothing open to join with that code right now.",
3441
+ too_many_open_sessions: "This tool has too many joins waiting to be confirmed. Confirm one, or let one expire, then try again.",
3442
+ unknown_session: "That join can no longer be found. Run join again for a fresh code."
3443
+ };
3444
+ function describeStartError(error2) {
3445
+ if (error2 instanceof http_1.AscendaApiError) {
3446
+ if (error2.errorCode && START_ERROR_MESSAGES[error2.errorCode])
3447
+ return START_ERROR_MESSAGES[error2.errorCode];
3448
+ if (error2.status === 401)
3449
+ return "This tool's pairing was rejected. Re-pair it, then try again.";
3450
+ return `Could not reach the join code (HTTP ${error2.status}).`;
3451
+ }
3452
+ return error2 instanceof Error ? error2.message : String(error2);
3453
+ }
3454
+ }
3455
+ });
3456
+
3457
+ // ../packages/tool-kit/out/initiatives.js
3458
+ var require_initiatives = __commonJS({
3459
+ "../packages/tool-kit/out/initiatives.js"(exports) {
3460
+ "use strict";
3461
+ Object.defineProperty(exports, "__esModule", { value: true });
3462
+ exports.INITIATIVE_COPY = void 0;
3463
+ exports.initiativesStatusLines = initiativesStatusLines;
3464
+ exports.renderInitiatives = renderInitiatives;
3465
+ var http_1 = require_http();
3466
+ var studyJoin_1 = require_studyJoin();
3467
+ var READ_TIMEOUT_MS = 5e3;
3468
+ exports.INITIATIVE_COPY = {
3469
+ outcomes: {
3470
+ moved_as_declared: "Moved the way declared, beyond the cohort's own variation",
3471
+ moved_against_declared: "Moved the other way, beyond the cohort's own variation",
3472
+ moved_no_direction_declared: "Moved beyond the cohort's own variation; no direction was declared",
3473
+ within_own_variation: "No further from the baseline than the cohort's own week-to-week variation",
3474
+ withheld: "Withheld"
3475
+ },
3476
+ withheldReasons: {
3477
+ cohort_below_minimum: "the cohort was too small to report on when the scoring window closed",
3478
+ below_minimum_cohort: "the cohort was too small to report on when the scoring window closed",
3479
+ below_minimum_cohort_size: "the cohort was too small to report on when the scoring window closed",
3480
+ baseline_withheld: "the baseline was withheld"
3481
+ }
3482
+ };
3483
+ var OUTCOME_EMPTY = "Not stated";
3484
+ var OUTCOME_UNKNOWN = "An outcome this app does not recognise";
3485
+ var WITHHELD_UNKNOWN = "Withheld, for a reason this version of the app doesn't name yet.";
3486
+ var DIRECTION_WORDS = {
3487
+ up: "Expected to rise",
3488
+ down: "Expected to fall",
3489
+ none_declared: "No direction declared"
3490
+ };
3491
+ var DIRECTION_UNKNOWN = "A direction this app does not recognise";
3492
+ async function initiativesStatusLines(ctx) {
3493
+ const heading = "Changes your organisation has published to you";
3494
+ if (!ctx.eventWriteToken) {
3495
+ return [heading, " Not checked: this install holds no token, so nothing was fetched."];
3496
+ }
3497
+ const read = await (0, http_1.readInitiatives)(ctx.apiBaseUrl, ctx.eventWriteToken, AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS));
3498
+ if (read.kind === "rejected") {
3499
+ return [
3500
+ heading,
3501
+ ` Couldn't check: the server turned this install's request down. If that keeps happening, pair again with \`${ctx.pairCommand}\`.`
3502
+ ];
3503
+ }
3504
+ if (read.kind === "failed") {
3505
+ return [heading, ` Couldn't check: ${read.reason}. Run status again to retry.`];
3506
+ }
3507
+ return [heading, ...renderInitiatives(read.initiatives)];
3508
+ }
3509
+ function renderInitiatives(entries, copy = exports.INITIATIVE_COPY) {
3510
+ if (entries.length === 0)
3511
+ return [" None published to you."];
3512
+ const lines = [];
3513
+ let unreadable = 0;
3514
+ for (const entry of entries) {
3515
+ const initiative = asInitiative(entry);
3516
+ if (!initiative) {
3517
+ unreadable += 1;
3518
+ continue;
3519
+ }
3520
+ lines.push(...renderOne(initiative, copy));
3521
+ }
3522
+ if (unreadable > 0) {
3523
+ lines.push(` ${unreadable === 1 ? "1 entry" : `${unreadable} entries`} in the list couldn't be read by this version of the tool.`);
3524
+ }
3525
+ return lines;
3526
+ }
3527
+ function renderOne(initiative, copy) {
3528
+ const lines = [` ${initiative.organisationName}: ${initiative.title}`];
3529
+ lines.push(` ${describeStatus(initiative)}`);
3530
+ if (initiative.summaryForCohort) {
3531
+ for (const line of initiative.summaryForCohort.split(/\r?\n/))
3532
+ lines.push(` ${line}`);
3533
+ }
3534
+ if (initiative.direction)
3535
+ lines.push(` ${DIRECTION_WORDS[initiative.direction] ?? DIRECTION_UNKNOWN}`);
3536
+ lines.push(` Scoring window: ${formatWindowOrRaw(initiative.scoringStartUtc, initiative.scoringEndUtc)}`);
3537
+ if (initiative.result)
3538
+ lines.push(...renderResult(initiative.result, initiative.measureUnit, copy));
3539
+ lines.push("");
3540
+ return lines;
3541
+ }
3542
+ function describeStatus(initiative) {
3543
+ switch (initiative.status) {
3544
+ case "published":
3545
+ return "Published, not scored yet.";
3546
+ case "scored":
3547
+ return "Scored.";
3548
+ case "withdrawn":
3549
+ return initiative.withdrawnUtc ? `Withdrawn on ${formatDay(initiative.withdrawnUtc)}. It won't be scored.` : "Withdrawn. It won't be scored.";
3550
+ default:
3551
+ return "Status not recognised.";
3552
+ }
3553
+ }
3554
+ function renderResult(result, unit, copy) {
3555
+ const lines = [];
3556
+ const show = (n) => unit ? `${figure(n)} ${unit}` : figure(n);
3557
+ if (result.value === null) {
3558
+ const why = copy.withheldReasons[result.withheldReason ?? ""];
3559
+ lines.push(` ${why ? `Withheld: ${why}.` : WITHHELD_UNKNOWN}`);
3560
+ return lines;
3561
+ }
3562
+ lines.push(` Result: ${show(result.value)}`);
3563
+ lines.push(` ${movementLine(result)}`);
3564
+ lines.push(` ${result.outcome ? copy.outcomes[result.outcome] ?? OUTCOME_UNKNOWN : OUTCOME_EMPTY}`);
3565
+ return lines;
3566
+ }
3567
+ function movementLine(result) {
3568
+ if (result.outcome === "within_own_variation")
3569
+ return "No material change against frozen baseline";
3570
+ if (result.delta === null)
3571
+ return "No reading";
3572
+ if (result.delta > 0)
3573
+ return `Up ${figure(result.delta)} against frozen baseline`;
3574
+ if (result.delta < 0)
3575
+ return `Down ${figure(Math.abs(result.delta))} against frozen baseline`;
3576
+ return "No change against frozen baseline";
3577
+ }
3578
+ function figure(n) {
3579
+ return String(Number(n.toPrecision(12)));
3580
+ }
3581
+ function asInitiative(value) {
3582
+ if (!value || typeof value !== "object")
3583
+ return void 0;
3584
+ const o = value;
3585
+ if (typeof o.title !== "string" || typeof o.status !== "string")
3586
+ return void 0;
3587
+ return {
3588
+ id: typeof o.id === "string" ? o.id : "",
3589
+ organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
3590
+ title: o.title,
3591
+ summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
3592
+ measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
3593
+ scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
3594
+ scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
3595
+ withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
3596
+ status: o.status,
3597
+ direction: typeof o.direction === "string" ? o.direction : null,
3598
+ result: asResult(o.result)
3599
+ };
3600
+ }
3601
+ function asResult(value) {
3602
+ if (!value || typeof value !== "object")
3603
+ return null;
3604
+ const r = value;
3605
+ const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
3606
+ return {
3607
+ scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
3608
+ value: num(r.value),
3609
+ baselineValue: num(r.baselineValue),
3610
+ delta: num(r.delta),
3611
+ movement: typeof r.movement === "string" ? r.movement : null,
3612
+ outcome: typeof r.outcome === "string" ? r.outcome : "",
3613
+ withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
3614
+ basis: typeof r.basis === "string" ? r.basis : null
3615
+ };
3616
+ }
3617
+ function formatWindowOrRaw(startUtc, endUtc) {
3618
+ if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
3619
+ return "not given";
3620
+ return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
3621
+ }
3622
+ function formatDay(iso) {
3623
+ const date3 = new Date(iso);
3624
+ if (Number.isNaN(date3.getTime()))
3625
+ return iso;
3626
+ return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date3);
3627
+ }
3628
+ }
3629
+ });
3630
+
3631
+ // ../packages/tool-kit/out/setupDisclosure.js
3632
+ var require_setupDisclosure = __commonJS({
3633
+ "../packages/tool-kit/out/setupDisclosure.js"(exports) {
3634
+ "use strict";
3635
+ Object.defineProperty(exports, "__esModule", { value: true });
3636
+ exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
3637
+ exports.renderSetupDisclosure = renderSetupDisclosure;
3638
+ exports.FAMILY_SENTENCES = {
3639
+ session: "when a session starts and ends, the one-word reason for the end if your agent gives one, how long each turn took, and whether it ran on this machine or in a hosted cloud session",
3640
+ counts: "how many prompts you sent, how many replies came back, and what class of command ran in a terminal \u2014 test, lint, build, git and so on",
3641
+ tools: "the name of each tool your agent calls",
3642
+ outcome: "whether a call succeeded, failed, or was interrupted",
3643
+ clock: "your machine's offset from UTC, so an evening is read as an evening",
3644
+ repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
3645
+ model: "which model served the session, by name and by tier",
3646
+ posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
3647
+ git: "that a commit, push or revert happened, and when a pull request opened or merged",
3648
+ edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
3649
+ context: "how full the context window got",
3650
+ waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
3651
+ subagents: "when a subagent starts and stops, the id your agent gives it, and whether it was built in, from a plugin or one you defined \u2014 never its name or what it was asked",
3652
+ reading: "what the reader could not make sense of \u2014 lines it failed to parse, files it could not open, and prompts it judged machine-written rather than typed"
3653
+ };
3654
+ exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
3655
+ exports.REFUSALS = [
3656
+ "Never your prompts, your agent's replies, or anything inside a file.",
3657
+ "Never a file path, a command line, or a repository or branch name.",
3658
+ "Content is read here only to choose one of a fixed set of labels, then discarded. No mapper writes it to an event, and a test fails the build if one starts."
3659
+ ];
3660
+ exports.FREE_TEXT_KEYS = ["message"];
3661
+ function renderSetupDisclosure({ sends, displayName }) {
3662
+ const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
3663
+ const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
3664
+ const lines = [
3665
+ `What this sends from ${displayName}, once paired:`,
3666
+ ...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
3667
+ "",
3668
+ ...exports.REFUSALS.map((line) => ` ${line}`),
3669
+ "",
3670
+ " Turn it off by revoking this tool in the Ascenda app."
3671
+ ];
3672
+ return lines.join("\n");
3673
+ }
3674
+ }
3675
+ });
3676
+
3677
+ // ../packages/tool-kit/out/studyNotices.js
3678
+ var require_studyNotices = __commonJS({
3679
+ "../packages/tool-kit/out/studyNotices.js"(exports) {
3680
+ "use strict";
3681
+ Object.defineProperty(exports, "__esModule", { value: true });
3682
+ exports.NOTICED_PURPOSES = void 0;
3683
+ exports.studyNoticeStatus = studyNoticeStatus;
3684
+ exports.renderStudyNotices = renderStudyNotices;
3685
+ exports.runStudyObjection = runStudyObjection;
3686
+ var http_1 = require_http();
3687
+ var READ_TIMEOUT_MS = 5e3;
3688
+ var NOTICE_LABEL = "Counted unless you object";
3689
+ var PROCESSOR = "Ascenda";
3690
+ exports.NOTICED_PURPOSES = [
3691
+ { code: 501, slug: "telemetry", title: "Live tool telemetry" },
3692
+ { code: 507, slug: "import", title: "One-time import of past AI work" },
3693
+ { code: 11, slug: "work-patterns", title: "Work-pattern axes in the group figures" }
3694
+ ];
3695
+ var BASIS_WORDS = {
3696
+ legitimate_interests: "legitimate interests",
3697
+ collective_agreement: "a collective agreement"
3698
+ };
3699
+ async function studyNoticeStatus(ctx) {
3700
+ const nothing = { lines: [], markShown: async () => {
3701
+ } };
3702
+ const token = ctx.eventWriteToken;
3703
+ if (!token)
3704
+ return nothing;
3705
+ const read = await (0, http_1.readStudyNotices)(ctx.apiBaseUrl, token, AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS));
3706
+ if (read.kind !== "ok")
3707
+ return nothing;
3708
+ const lines = renderStudyNotices(read.notices, ctx.commandPrefix, ctx.now);
3709
+ if (lines.length === 0)
3710
+ return nothing;
3711
+ const unshown = shownPurposes(read.notices).filter((n) => !n.noticeFromUtc && n.organisationId);
3712
+ return {
3713
+ lines,
3714
+ markShown: async () => {
3715
+ const signal = AbortSignal.timeout(ctx.fetchTimeoutMs ?? READ_TIMEOUT_MS);
3716
+ await Promise.all(unshown.map((n) => (0, http_1.markStudyNoticeShown)(ctx.apiBaseUrl, token, n.organisationId, n.code, signal)));
3717
+ }
3718
+ };
3719
+ }
3720
+ function shownPurposes(entries) {
3721
+ return entries.map(asNotice).filter((n) => n !== void 0 && exports.NOTICED_PURPOSES.some((p) => p.code === n.code));
3722
+ }
3723
+ function renderStudyNotices(entries, commandPrefix, now = /* @__PURE__ */ new Date()) {
3724
+ const body = [];
3725
+ let unreadable = 0;
3726
+ for (const entry of entries) {
3727
+ const notice = asNotice(entry);
3728
+ const purpose = notice && exports.NOTICED_PURPOSES.find((p) => p.code === notice.code);
3729
+ if (!notice || !purpose) {
3730
+ unreadable += 1;
3731
+ continue;
3732
+ }
3733
+ body.push(...renderOne(notice, purpose, commandPrefix, now));
3734
+ }
3735
+ if (body.length === 0)
3736
+ return [];
3737
+ if (unreadable > 0) {
3738
+ body.push(` ${unreadable === 1 ? "1 entry" : `${unreadable} entries`} in the list couldn't be read by this version of the tool.`);
3739
+ }
3740
+ return ["", "Your organisation's study", ...body];
3741
+ }
3742
+ function renderOne(notice, purpose, commandPrefix, now) {
3743
+ const org = notice.organisationName;
3744
+ const command = `${commandPrefix} object ${purpose.slug}`;
3745
+ const lines = [` ${org}: ${purpose.title}`];
3746
+ lines.push(` ${notice.label || NOTICE_LABEL}`);
3747
+ lines.push(` ${basisLine(notice)}`);
3748
+ if (notice.signatoryName)
3749
+ lines.push(` Recorded by ${notice.signatoryName}.`);
3750
+ lines.push(` ${notice.processor || PROCESSOR} processes this for ${org}.`);
3751
+ if (notice.objected === true) {
3752
+ lines.push(" You objected. You are left out from the next report on.");
3753
+ lines.push(` To undo: ${command} --undo`);
3754
+ } else if (notice.objected === false) {
3755
+ lines.push(" You haven't objected.");
3756
+ if (notice.noticeFromUtc && isDate(notice.noticeFromUtc)) {
3757
+ const starts = notice.countingFromUtc && isDate(notice.countingFromUtc) ? notice.countingFromUtc : new Date(Date.parse(notice.noticeFromUtc) + NOTICE_PERIOD_MS).toISOString();
3758
+ if (Date.parse(starts) > now.getTime()) {
3759
+ lines.push(` Notice given ${formatDay(notice.noticeFromUtc)}. Counting starts ${formatDay(starts)}.`);
3760
+ }
3761
+ }
3762
+ lines.push(` To object: ${command}. No reason is asked. You are left out from the next report on, and earlier reports stay as they were.`);
3763
+ } else {
3764
+ lines.push(" This version of the tool couldn't read whether you've objected. Run status again.");
3765
+ lines.push(` To object: ${command}`);
3766
+ lines.push(` To undo: ${command} --undo`);
3767
+ }
3768
+ lines.push("");
3769
+ return lines;
3770
+ }
3771
+ function basisLine(notice) {
3772
+ const words = notice.basisLabel ?? BASIS_WORDS[notice.basis];
3773
+ const head = words ? `${notice.organisationName}'s basis is ${words}.` : `${notice.organisationName}'s basis is one this version of the tool can't name.`;
3774
+ const dated = notice.documentDate && isDate(notice.documentDate) ? formatDay(notice.documentDate) : null;
3775
+ const ref = notice.documentReference ? `ref ${notice.documentReference}` : null;
3776
+ const title = notice.documentTitle ? dated ? `${notice.documentTitle} (${dated})` : notice.documentTitle : null;
3777
+ const document = [title, ref].filter((part) => Boolean(part)).join(", ");
3778
+ return document ? `${head} Document: ${document}.` : head;
3779
+ }
3780
+ var NOTICE_PERIOD_MS = 14 * 24 * 60 * 60 * 1e3;
3781
+ function asNotice(value) {
3782
+ if (!value || typeof value !== "object")
3783
+ return void 0;
3784
+ const o = value;
3785
+ if (typeof o.code !== "number")
3786
+ return void 0;
3787
+ if (typeof o.mode === "string" && o.mode.trim().toLowerCase() !== "notice")
3788
+ return void 0;
3789
+ const str = (x) => typeof x === "string" && x.trim() ? x : null;
3790
+ return {
3791
+ organisationId: str(o.organisationId),
3792
+ organisationName: str(o.organisationName) ?? "Your organisation",
3793
+ code: o.code,
3794
+ name: str(o.name),
3795
+ label: str(o.label),
3796
+ processor: str(o.processor),
3797
+ basis: typeof o.basis === "string" ? o.basis : "",
3798
+ basisLabel: str(o.basisLabel),
3799
+ documentTitle: str(o.documentTitle),
3800
+ documentDate: str(o.documentDate),
3801
+ documentReference: str(o.documentReference),
3802
+ signatoryName: str(o.signatoryName),
3803
+ objected: typeof o.objected === "boolean" ? o.objected : null,
3804
+ objectedAtUtc: str(o.objectedAtUtc),
3805
+ noticeFromUtc: str(o.noticeFromUtc),
3806
+ countingFromUtc: str(o.countingFromUtc)
3807
+ };
3808
+ }
3809
+ async function runStudyObjection(ctx) {
3810
+ const stdin = ctx.stdin ?? process.stdin;
3811
+ const stdout = ctx.stdout ?? process.stdout;
3812
+ const stderr = ctx.stderr ?? process.stderr;
3813
+ const print = (line) => stdout.write(`${line}
3814
+ `);
3815
+ if (!stdin.isTTY || !stdout.isTTY) {
3816
+ stderr.write("object needs an interactive terminal (stdin and stdout). Run it directly, not from a script or a pipe.\n");
3817
+ return 1;
3818
+ }
3819
+ const undo = ctx.argv.includes("--undo");
3820
+ const rest = ctx.argv.filter((a) => a !== "--undo");
3821
+ const purpose = rest.length === 1 ? exports.NOTICED_PURPOSES.find((p) => p.slug === rest[0]) : void 0;
3822
+ if (!purpose) {
3823
+ stderr.write(objectionUsage(ctx.commandPrefix));
3824
+ return 1;
3825
+ }
3826
+ if (!ctx.eventWriteToken) {
3827
+ stderr.write(`This install isn't paired, so there's nothing to object to. Pair with \`${ctx.pairCommand}\`.
3828
+ `);
3829
+ return 1;
3830
+ }
3831
+ const command = `${ctx.commandPrefix} object ${purpose.slug}`;
3832
+ try {
3833
+ await (0, http_1.setStudyObjection)(ctx.apiBaseUrl, ctx.eventWriteToken, purpose.code, !undo);
3834
+ } catch (error2) {
3835
+ stderr.write(`${describeObjectionError(error2, purpose, undo, ctx.pairCommand)}
3836
+ `);
3837
+ return 1;
3838
+ }
3839
+ if (undo) {
3840
+ print(`Objection withdrawn: ${purpose.title}.`);
3841
+ print("You're counted again from the next report.");
3842
+ print(`To object again: ${command}`);
3843
+ } else {
3844
+ print(`Objected: ${purpose.title}.`);
3845
+ print("You objected. You are left out from the next report on, and earlier reports stay as they were.");
3846
+ print(`To undo: ${command} --undo`);
3847
+ }
3848
+ return 0;
3849
+ }
3850
+ function objectionUsage(commandPrefix) {
3851
+ const lines = [`Usage: ${commandPrefix} object <purpose> [--undo]`, "", "Purposes:"];
3852
+ for (const p of exports.NOTICED_PURPOSES)
3853
+ lines.push(` ${p.slug.padEnd(14)}${p.title}`);
3854
+ lines.push("", "status shows which of these your organisation counts unless you object.");
3855
+ return `${lines.join("\n")}
3856
+ `;
3857
+ }
3858
+ function describeObjectionError(error2, purpose, undo, pairCommand) {
3859
+ if (error2 instanceof http_1.AscendaApiError) {
3860
+ if (error2.status === 404 && error2.errorCode === "not_noticed") {
3861
+ return undo ? `Your organisation doesn't count you for ${purpose.title} unless you object, so there's no objection to undo.` : `Your organisation doesn't count you for ${purpose.title} unless you object, so there's nothing to object to.`;
3862
+ }
3863
+ if (error2.status === 401)
3864
+ return `The server turned this install's request down. If that keeps happening, pair again with \`${pairCommand}\`.`;
3865
+ if (error2.status === 404)
3866
+ return "This server doesn't take objections yet. Nothing changed.";
3867
+ return `Couldn't record that (HTTP ${error2.status}). Nothing changed. Run it again to retry.`;
3868
+ }
3869
+ return "Couldn't reach the server. Nothing changed. Run it again to retry.";
3870
+ }
3871
+ function isDate(iso) {
3872
+ return !Number.isNaN(Date.parse(iso));
3873
+ }
3874
+ var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
3875
+ function formatDay(iso) {
3876
+ const date3 = new Date(iso);
3877
+ return `${date3.getUTCDate()} ${MONTHS[date3.getUTCMonth()]} ${date3.getUTCFullYear()}`;
3878
+ }
3879
+ }
3880
+ });
3881
+
2845
3882
  // ../packages/tool-kit/out/cliAgentSetup.js
2846
3883
  var require_cliAgentSetup = __commonJS({
2847
3884
  "../packages/tool-kit/out/cliAgentSetup.js"(exports) {
@@ -2888,16 +3925,24 @@ var require_cliAgentSetup = __commonJS({
2888
3925
  exports.cliAgentHookBinPath = cliAgentHookBinPath;
2889
3926
  exports.runCliAgentSetup = runCliAgentSetup;
2890
3927
  exports.writeHookSettings = writeHookSettings;
3928
+ exports.registeredHookSets = registeredHookSets;
2891
3929
  exports.findStaleHookCommands = findStaleHookCommands;
2892
3930
  var crypto = __importStar(__require("crypto"));
2893
3931
  var fs = __importStar(__require("fs"));
2894
3932
  var os = __importStar(__require("os"));
2895
3933
  var path = __importStar(__require("path"));
3934
+ var collectorVersion_1 = require_collectorVersion();
2896
3935
  var credentials_1 = require_credentials();
2897
3936
  var hookAdapter_1 = require_hookAdapter();
2898
3937
  var http_1 = require_http();
3938
+ var hookSet_1 = require_hookSet();
3939
+ var initiatives_1 = require_initiatives();
3940
+ var setupDisclosure_1 = require_setupDisclosure();
3941
+ var stateStore_1 = require_stateStore();
3942
+ var studyJoin_1 = require_studyJoin();
3943
+ var studyNotices_1 = require_studyNotices();
2899
3944
  var tokenStore_1 = require_tokenStore();
2900
- var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "-h", "--help"]);
3945
+ var MANAGEMENT_COMMANDS = /* @__PURE__ */ new Set(["setup", "install", "status", "uninstall", "join", "object", "-h", "--help"]);
2901
3946
  function isCliAgentManagementCommand(argument) {
2902
3947
  return argument !== void 0 && MANAGEMENT_COMMANDS.has(argument);
2903
3948
  }
@@ -2910,12 +3955,15 @@ var require_cliAgentSetup = __commonJS({
2910
3955
  npx ${spec.packageName} setup [options]
2911
3956
  npx ${spec.packageName} status
2912
3957
  npx ${spec.packageName} uninstall
3958
+ npx ${spec.packageName} join <code>
3959
+ npx ${spec.packageName} object <purpose> [--undo]
2913
3960
 
2914
3961
  Options
2915
3962
  --api-base-url <url> ingest host (default ${hookAdapter_1.DEFAULT_API_BASE_URL})
2916
3963
  --local [port] shorthand for the local dev server (default port 4477)
2917
3964
  --tool-installation-id <id> reuse an existing pairing instead of creating one
2918
3965
  --token <eventWriteToken> reuse an existing token (stored 0600, never printed)
3966
+ --no-pair install without pairing: local features on, nothing sent
2919
3967
  --scope project|user where hooks are registered (default project)
2920
3968
  --project-dir <path> project root for --scope project (default cwd)
2921
3969
  --dry-run print what would change, write nothing
@@ -2923,6 +3971,10 @@ Options
2923
3971
  `;
2924
3972
  }
2925
3973
  async function runCliAgentSetup(argv, spec) {
3974
+ if (argv[0] === "join")
3975
+ return runCliAgentStudyJoin(argv.slice(1), spec);
3976
+ if (argv[0] === "object")
3977
+ return runCliAgentStudyObjection(argv.slice(1), spec);
2926
3978
  let options;
2927
3979
  try {
2928
3980
  options = parseArgs(argv, spec);
@@ -2935,32 +3987,60 @@ Options
2935
3987
  return 0;
2936
3988
  }
2937
3989
  if (options.action === "status")
2938
- return printStatus(options, spec);
3990
+ return await printStatus(options, spec);
2939
3991
  if (options.action === "uninstall")
2940
3992
  return uninstall(options, spec);
2941
3993
  const apiBaseUrl = (options.apiBaseUrl ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
2942
3994
  console.log(`Ascenda setup for ${spec.displayName} \u2014 ${apiBaseUrl}`);
2943
- const identity = await resolveIdentity(apiBaseUrl, options, spec);
2944
- if (!identity)
2945
- return 1;
2946
- console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
3995
+ console.log(`
3996
+ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName: spec.displayName })}
3997
+ `);
3998
+ let identity;
3999
+ let unpairedReason;
4000
+ if (options.skipPairing) {
4001
+ unpairedReason = "asked not to pair (--no-pair)";
4002
+ } else {
4003
+ identity = await resolveIdentity(apiBaseUrl, options, spec);
4004
+ if (identity) {
4005
+ console.log(` pairing ${identity.toolInstallationId}${identity.paired ? " (new)" : " (existing)"}`);
4006
+ } else {
4007
+ unpairedReason = "pairing did not finish \u2014 installing the local half anyway";
4008
+ }
4009
+ }
4010
+ if (unpairedReason) {
4011
+ console.log(` pairing none: ${unpairedReason}`);
4012
+ console.log(" local features on, nothing is sent");
4013
+ }
2947
4014
  const binary = installBinary(spec, options.dryRun);
2948
4015
  console.log(` hook binary ${binary}`);
2949
4016
  if (!options.dryRun) {
2950
- (0, credentials_1.writeHostCredentials)(spec.host, { apiBaseUrl, toolInstallationId: identity.toolInstallationId, pairedAt: (/* @__PURE__ */ new Date()).toISOString() });
4017
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4018
+ const toolInstallationId = identity?.toolInstallationId ?? options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId ?? `${spec.toolType}:${crypto.randomUUID()}`;
4019
+ (0, credentials_1.writeHostCredentials)(spec.host, {
4020
+ apiBaseUrl,
4021
+ toolInstallationId,
4022
+ ...identity ? { pairedAt: now } : { localOnly: true, installedAt: now }
4023
+ });
2951
4024
  }
2952
4025
  console.log(` credentials ${(0, credentials_1.credentialsFilePath)()} (tools.${spec.host})`);
2953
4026
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
4027
+ const before = registeredHookSets(readSettings(settingsFile), spec);
2954
4028
  const written = writeHookSettings(settingsFile, binary, spec, options.dryRun);
2955
4029
  if (written === null)
2956
4030
  return 1;
2957
4031
  console.log(` hooks ${settingsFile} (${spec.hookEvents.length} events${written ? "" : ", already current"})`);
4032
+ const changes = spec.hookSet === void 0 ? void 0 : (0, hookSet_1.describeHookSetChanges)((0, hookSet_1.hookSetChanges)(before, spec.hookEvents), spec.hookSet);
4033
+ if (changes)
4034
+ console.log(` ${changes}`);
2958
4035
  if (options.dryRun) {
2959
4036
  console.log("\nDry run \u2014 nothing was written.");
2960
4037
  return 0;
2961
4038
  }
2962
4039
  console.log(`
2963
4040
  Done. ${spec.restartHint}`);
4041
+ if (!identity) {
4042
+ console.log(`Pair later: npx ${spec.packageName} setup`);
4043
+ }
2964
4044
  console.log(`Check anytime: npx ${spec.packageName} status`);
2965
4045
  return 0;
2966
4046
  }
@@ -2969,6 +4049,7 @@ Done. ${spec.restartHint}`);
2969
4049
  scope: "project",
2970
4050
  projectDir: process.cwd(),
2971
4051
  dryRun: false,
4052
+ skipPairing: false,
2972
4053
  action: "install"
2973
4054
  };
2974
4055
  for (let i = 0; i < argv.length; i++) {
@@ -3018,6 +4099,14 @@ Done. ${spec.restartHint}`);
3018
4099
  case "--dry-run":
3019
4100
  options.dryRun = true;
3020
4101
  break;
4102
+ case "--no-pair":
4103
+ // `--no-pairing` is the spelling this landed under first. Both appeared
4104
+ // only in an unreleased changelog, so this alias exists to spare anyone
4105
+ // reading that draft, and `--no-pair` — the Claude Code adapter's own
4106
+ // spelling — is the documented one.
4107
+ case "--no-pairing":
4108
+ options.skipPairing = true;
4109
+ break;
3021
4110
  case "-h":
3022
4111
  case "--help":
3023
4112
  options.action = "help";
@@ -3030,6 +4119,45 @@ ${usage(spec)}`);
3030
4119
  }
3031
4120
  return options;
3032
4121
  }
4122
+ async function runCliAgentStudyJoin(argv, spec) {
4123
+ const joinCode = argv[0];
4124
+ if (!joinCode || joinCode.startsWith("-")) {
4125
+ console.error(`Usage: npx ${spec.packageName} join <code>`);
4126
+ return 1;
4127
+ }
4128
+ const pairing = resolvePairedToken(spec);
4129
+ if (!pairing)
4130
+ return 1;
4131
+ return (0, studyJoin_1.runStudyJoin)({ ...pairing, displayName: spec.displayName, joinCode });
4132
+ }
4133
+ async function runCliAgentStudyObjection(argv, spec) {
4134
+ const pairing = resolvePairedToken(spec);
4135
+ if (!pairing)
4136
+ return 1;
4137
+ return (0, studyNotices_1.runStudyObjection)({
4138
+ ...pairing,
4139
+ commandPrefix: `npx ${spec.packageName}`,
4140
+ pairCommand: `npx ${spec.packageName} setup`,
4141
+ argv
4142
+ });
4143
+ }
4144
+ function resolvePairedToken(spec) {
4145
+ const setupCommand = `npx ${spec.packageName} setup`;
4146
+ let toolInstallationId;
4147
+ try {
4148
+ ({ toolInstallationId } = (0, hookAdapter_1.resolveCliAgentInstallationId)(spec.toolType, { host: spec.host, setupCommand }));
4149
+ } catch (error2) {
4150
+ console.error(error2 instanceof hookAdapter_1.MissingInstallationIdError ? error2.message : error2 instanceof Error ? error2.message : String(error2));
4151
+ return void 0;
4152
+ }
4153
+ const eventWriteToken = (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(toolInstallationId)) ?? process.env.ASCENDA_EVENT_WRITE_TOKEN;
4154
+ if (!eventWriteToken) {
4155
+ console.error(`Not paired: no write token for ${toolInstallationId}. Run: ${setupCommand}`);
4156
+ return void 0;
4157
+ }
4158
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? (0, credentials_1.readHostCredentials)(spec.host)?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
4159
+ return { apiBaseUrl, eventWriteToken };
4160
+ }
3033
4161
  async function resolveIdentity(apiBaseUrl, options, spec) {
3034
4162
  const existingId = options.toolInstallationId ?? (0, credentials_1.readHostCredentials)(spec.host)?.toolInstallationId;
3035
4163
  if (existingId && options.token) {
@@ -3037,8 +4165,13 @@ ${usage(spec)}`);
3037
4165
  (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(existingId), options.token);
3038
4166
  return { toolInstallationId: existingId, paired: false };
3039
4167
  }
3040
- if (existingId && (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(existingId))) {
3041
- return { toolInstallationId: existingId, paired: false };
4168
+ const existingToken = existingId ? (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(existingId)) : void 0;
4169
+ if (existingId && existingToken) {
4170
+ const check2 = await checkSavedToken(apiBaseUrl, existingId, existingToken);
4171
+ if (check2 === "keep")
4172
+ return { toolInstallationId: existingId, paired: false };
4173
+ console.log(`
4174
+ The saved token for ${existingId} isn't accepted any more. Pairing again.`);
3042
4175
  }
3043
4176
  if (options.dryRun) {
3044
4177
  return { toolInstallationId: existingId ?? `${spec.toolType}:<paired at run time>`, paired: false };
@@ -3059,6 +4192,18 @@ Could not reach ${apiBaseUrl} to pair: ${error2 instanceof Error ? error2.messag
3059
4192
  (0, tokenStore_1.persistEventWriteToken)((0, tokenStore_1.defaultTokenFilePath)(toolInstallationId), token);
3060
4193
  return { toolInstallationId, paired: true };
3061
4194
  }
4195
+ var TOKEN_CHECK_TIMEOUT_MS = 5e3;
4196
+ async function checkSavedToken(apiBaseUrl, toolInstallationId, token) {
4197
+ const read = await (0, http_1.readInitiatives)(apiBaseUrl, token, AbortSignal.timeout(TOKEN_CHECK_TIMEOUT_MS));
4198
+ if (read.kind === "rejected")
4199
+ return "repair";
4200
+ if (read.kind === "failed" && (0, stateStore_1.readCollectorState)((0, stateStore_1.defaultStateFilePath)(toolInstallationId))?.lastOutcome === "auth_failed") {
4201
+ console.log(`
4202
+ Couldn't check the saved token (${read.reason}), and the last send was refused.`);
4203
+ console.log(" Keeping it for now. Run setup again once the server is reachable.");
4204
+ }
4205
+ return "keep";
4206
+ }
3062
4207
  async function pollForToken(apiBaseUrl, pairingSessionId, code, expiresAt) {
3063
4208
  const deadline = Math.min(Date.parse(expiresAt) || Date.now() + 3e5, Date.now() + 3e5);
3064
4209
  let announced = false;
@@ -3110,7 +4255,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
3110
4255
  }
3111
4256
  }
3112
4257
  }
3113
- const command = hookCommand(binary);
4258
+ const command = hookCommand(binary, spec);
3114
4259
  const hooks = { ...settings.hooks ?? {} };
3115
4260
  for (const event of spec.hookEvents) {
3116
4261
  const kept = (hooks[event] ?? []).filter((entry) => !isOurs(entry, spec));
@@ -3133,8 +4278,20 @@ ${serialised}`);
3133
4278
  fs.writeFileSync(settingsFile, serialised, "utf8");
3134
4279
  return true;
3135
4280
  }
3136
- function hookCommand(binary) {
3137
- return `"${process.execPath}" "${binary}"`;
4281
+ function hookCommand(binary, spec) {
4282
+ return `"${process.execPath}" "${binary}"${(0, hookSet_1.hookSetArgument)(spec.hookSet)}`;
4283
+ }
4284
+ function registeredHookSets(settings, spec) {
4285
+ const sets = /* @__PURE__ */ new Map();
4286
+ for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
4287
+ for (const entry of entries ?? []) {
4288
+ if (!isOurs(entry, spec))
4289
+ continue;
4290
+ const set = (0, hookSet_1.hookSetOfCommand)(spec.settings.commandOf(entry));
4291
+ sets.set(event, Math.min(set, sets.get(event) ?? set));
4292
+ }
4293
+ }
4294
+ return sets;
3138
4295
  }
3139
4296
  function isOurs(entry, spec) {
3140
4297
  const command = spec.settings.commandOf(entry);
@@ -3161,7 +4318,7 @@ ${serialised}`);
3161
4318
  return {};
3162
4319
  }
3163
4320
  }
3164
- function printStatus(options, spec) {
4321
+ async function printStatus(options, spec) {
3165
4322
  const credentials = (0, credentials_1.readHostCredentials)(spec.host);
3166
4323
  const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
3167
4324
  const binary = cliAgentHookBinPath(spec.binaryName);
@@ -3169,18 +4326,39 @@ ${serialised}`);
3169
4326
  const settings = readSettings(settingsFile);
3170
4327
  const registered = spec.hookEvents.filter((event) => (settings.hooks?.[event] ?? []).some((entry) => isOurs(entry, spec))).length;
3171
4328
  const stale = findStaleHookCommands(settings, binary, spec);
4329
+ const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
4330
+ console.log(`version ${(0, collectorVersion_1.describeCollectorVersion)()}`);
3172
4331
  console.log(`api base url ${credentials?.apiBaseUrl ?? "\u2014 not configured"}`);
3173
- console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}`);
3174
- console.log(`token ${tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
4332
+ console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
4333
+ console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
3175
4334
  console.log(`hook binary ${fs.existsSync(binary) ? binary : "\u2014 not installed"}`);
3176
4335
  console.log(`hooks ${registered}/${spec.hookEvents.length} registered in ${settingsFile}`);
4336
+ if (spec.hookSet !== void 0 && registered > 0) {
4337
+ const sets = [...registeredHookSets(settings, spec).values()];
4338
+ const oldest = Math.min(...sets);
4339
+ console.log(oldest < spec.hookSet ? `hook set ${oldest}, this version registers ${spec.hookSet}. Upgrade: npx ${spec.packageName} setup${options.scope === "user" ? " --scope user" : ""}` : `hook set ${spec.hookSet} (current)`);
4340
+ }
3177
4341
  if (stale.length) {
3178
4342
  console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
3179
4343
  for (const command of stale)
3180
4344
  console.log(` ${command}`);
3181
4345
  console.log(` Remove them from ${settingsFile} by hand; setup cannot tell them from a hook you wrote.`);
3182
4346
  }
3183
- const healthy = credentials?.toolInstallationId && registered === spec.hookEvents.length && fs.existsSync(binary) && !stale.length;
4347
+ const tokenValue = localOnly ? void 0 : (tokenFile ? (0, tokenStore_1.readTokenFile)(tokenFile) : void 0) ?? (process.env.ASCENDA_EVENT_WRITE_TOKEN?.trim() || void 0);
4348
+ const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? hookAdapter_1.DEFAULT_API_BASE_URL).replace(/\/$/, "");
4349
+ const [initiativeLines, notices] = await Promise.all([
4350
+ (0, initiatives_1.initiativesStatusLines)({ apiBaseUrl, eventWriteToken: tokenValue, pairCommand: `npx ${spec.packageName} setup` }),
4351
+ (0, studyNotices_1.studyNoticeStatus)({ apiBaseUrl, eventWriteToken: tokenValue, commandPrefix: `npx ${spec.packageName}` })
4352
+ ]);
4353
+ console.log("");
4354
+ for (const line of initiativeLines)
4355
+ console.log(line);
4356
+ for (const line of notices.lines)
4357
+ console.log(line);
4358
+ if (process.stdout.isTTY)
4359
+ await notices.markShown();
4360
+ const paired = localOnly || credentials?.toolInstallationId !== void 0;
4361
+ const healthy = paired && registered === spec.hookEvents.length && fs.existsSync(binary) && !stale.length;
3184
4362
  return healthy ? 0 : 1;
3185
4363
  }
3186
4364
  function uninstall(options, spec) {
@@ -3345,6 +4523,7 @@ var require_liveBus = __commonJS({
3345
4523
  };
3346
4524
  }();
3347
4525
  Object.defineProperty(exports, "__esModule", { value: true });
4526
+ exports.LIVE_BUS_BACKGROUND_TRUST_MS = void 0;
3348
4527
  exports.liveBusSocketCandidates = liveBusSocketCandidates;
3349
4528
  exports.liveBusSocketPath = liveBusSocketPath;
3350
4529
  exports.bucketPromptSize = bucketPromptSize;
@@ -3353,7 +4532,9 @@ var require_liveBus = __commonJS({
3353
4532
  var net = __importStar(__require("net"));
3354
4533
  var os = __importStar(__require("os"));
3355
4534
  var path = __importStar(__require("path"));
4535
+ var hookSet_1 = require_hookSet();
3356
4536
  var WRITE_TIMEOUT_MS = 50;
4537
+ exports.LIVE_BUS_BACKGROUND_TRUST_MS = 60 * 60 * 1e3;
3357
4538
  var APP_BUNDLE_ID = "one.ascenda.ascendaMissionControl";
3358
4539
  var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
3359
4540
  function liveBusSocketCandidates() {
@@ -3393,6 +4574,14 @@ var require_liveBus = __commonJS({
3393
4574
  return "xl";
3394
4575
  }
3395
4576
  var NOBODY_LISTENING = /* @__PURE__ */ new Set(["ECONNREFUSED", "ENOENT"]);
4577
+ function onTheWire(signal) {
4578
+ const out = { ...signal };
4579
+ if ("hookSet" in out && !(0, hookSet_1.isHookSet)(out.hookSet))
4580
+ delete out.hookSet;
4581
+ if ("viaPlugin" in out && out.viaPlugin !== true)
4582
+ delete out.viaPlugin;
4583
+ return out;
4584
+ }
3396
4585
  function emitLiveSignal(signal) {
3397
4586
  return new Promise((resolve) => {
3398
4587
  const candidates = existingSocketCandidates();
@@ -3453,7 +4642,7 @@ var require_liveBus = __commonJS({
3453
4642
  return;
3454
4643
  connected = true;
3455
4644
  try {
3456
- attempt.write(`${JSON.stringify(signal)}
4645
+ attempt.write(`${JSON.stringify(onTheWire(signal))}
3457
4646
  `, done);
3458
4647
  } catch {
3459
4648
  done();
@@ -3466,14 +4655,153 @@ var require_liveBus = __commonJS({
3466
4655
  }
3467
4656
  });
3468
4657
 
4658
+ // ../packages/tool-kit/out/agentProcess.js
4659
+ var require_agentProcess = __commonJS({
4660
+ "../packages/tool-kit/out/agentProcess.js"(exports) {
4661
+ "use strict";
4662
+ var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
4663
+ if (k2 === void 0) k2 = k;
4664
+ var desc = Object.getOwnPropertyDescriptor(m, k);
4665
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
4666
+ desc = { enumerable: true, get: function() {
4667
+ return m[k];
4668
+ } };
4669
+ }
4670
+ Object.defineProperty(o, k2, desc);
4671
+ } : function(o, m, k, k2) {
4672
+ if (k2 === void 0) k2 = k;
4673
+ o[k2] = m[k];
4674
+ });
4675
+ var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
4676
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
4677
+ } : function(o, v) {
4678
+ o["default"] = v;
4679
+ });
4680
+ var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
4681
+ var ownKeys = function(o) {
4682
+ ownKeys = Object.getOwnPropertyNames || function(o2) {
4683
+ var ar = [];
4684
+ for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
4685
+ return ar;
4686
+ };
4687
+ return ownKeys(o);
4688
+ };
4689
+ return function(mod) {
4690
+ if (mod && mod.__esModule) return mod;
4691
+ var result = {};
4692
+ if (mod != null) {
4693
+ for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
4694
+ }
4695
+ __setModuleDefault(result, mod);
4696
+ return result;
4697
+ };
4698
+ }();
4699
+ Object.defineProperty(exports, "__esModule", { value: true });
4700
+ exports.psArgsLookup = exports.psLookup = exports.AGENT_PROCESS = void 0;
4701
+ exports.scriptMarkerIn = scriptMarkerIn;
4702
+ exports.findAgentProcess = findAgentProcess;
4703
+ exports.findAgentPid = findAgentPid;
4704
+ exports.livePidFields = livePidFields;
4705
+ var child_process_1 = __require("child_process");
4706
+ var path = __importStar(__require("path"));
4707
+ exports.AGENT_PROCESS = {
4708
+ claude_code: {
4709
+ executable: (command) => path.basename(command) === "claude" || /\/claude\/versions\/[^/]+$/.test(command) || /\/@anthropic-ai\/claude-code\/bin\/claude\.exe$/.test(command),
4710
+ scriptMarkers: ["@anthropic-ai/claude-code"]
4711
+ },
4712
+ codex: {
4713
+ executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(path.basename(command)),
4714
+ args: (args) => !/\s(app-server|mcp-server)(\s|$)/.test(args)
4715
+ },
4716
+ gemini_cli: {
4717
+ executable: () => false,
4718
+ args: (args) => !/\s--(experimental-)?acp(\s|=|$)/.test(args),
4719
+ scriptMarkers: ["@google/gemini-cli"]
4720
+ }
4721
+ };
4722
+ var SCRIPT_RUNTIME = /^(node|bun|deno)$/;
4723
+ function scriptMarkerIn(args, markers) {
4724
+ return markers.find((marker) => args.includes(`/${marker}/`));
4725
+ }
4726
+ var MAX_DEPTH = 6;
4727
+ var PS_TIMEOUT_MS = 100;
4728
+ function ps(columns, pid) {
4729
+ try {
4730
+ const result = (0, child_process_1.spawnSync)("/bin/ps", ["-o", columns, "-p", String(pid)], {
4731
+ encoding: "utf8",
4732
+ timeout: PS_TIMEOUT_MS
4733
+ });
4734
+ if (result.status !== 0 || typeof result.stdout !== "string")
4735
+ return void 0;
4736
+ const line = result.stdout.trim();
4737
+ return line === "" ? void 0 : line;
4738
+ } catch {
4739
+ return void 0;
4740
+ }
4741
+ }
4742
+ var psLookup = (pid) => {
4743
+ const line = ps("ppid=,comm=", pid);
4744
+ const match = line ? /^(\d+)\s+(.+)$/.exec(line) : null;
4745
+ return match ? { ppid: Number(match[1]), command: match[2] } : void 0;
4746
+ };
4747
+ exports.psLookup = psLookup;
4748
+ var psArgsLookup = (pid) => ps("args=", pid);
4749
+ exports.psArgsLookup = psArgsLookup;
4750
+ function findAgentProcess(rule, options = {}) {
4751
+ if (!rule)
4752
+ return void 0;
4753
+ if ((options.platform ?? process.platform) !== "darwin")
4754
+ return void 0;
4755
+ const lookup = options.lookup ?? exports.psLookup;
4756
+ const argsLookup = options.argsLookup ?? exports.psArgsLookup;
4757
+ const markers = rule.scriptMarkers ?? [];
4758
+ let pid = options.startPid ?? process.ppid;
4759
+ for (let depth = 0; depth < MAX_DEPTH && pid > 1; depth++) {
4760
+ const info = lookup(pid);
4761
+ if (!info)
4762
+ return void 0;
4763
+ if (pid !== process.pid) {
4764
+ if (rule.executable(info.command)) {
4765
+ return accepts(rule, rule.args ? argsLookup(pid) : "") ? { pid, match: "executable" } : void 0;
4766
+ }
4767
+ if (markers.length > 0 && SCRIPT_RUNTIME.test(path.basename(info.command))) {
4768
+ const args = argsLookup(pid);
4769
+ const marker = args === void 0 ? void 0 : scriptMarkerIn(args, markers);
4770
+ if (marker !== void 0) {
4771
+ return accepts(rule, args) ? { pid, match: "path", marker } : void 0;
4772
+ }
4773
+ }
4774
+ }
4775
+ pid = info.ppid;
4776
+ }
4777
+ return void 0;
4778
+ }
4779
+ function accepts(rule, args) {
4780
+ if (!rule.args)
4781
+ return true;
4782
+ return args !== void 0 && rule.args(args);
4783
+ }
4784
+ function findAgentPid(rule, options = {}) {
4785
+ return findAgentProcess(rule, options)?.pid;
4786
+ }
4787
+ function livePidFields(match) {
4788
+ if (!match)
4789
+ return {};
4790
+ if (match.match === "executable")
4791
+ return { pid: match.pid };
4792
+ return { pid: match.pid, pidMatch: "path", pidMarker: match.marker };
4793
+ }
4794
+ }
4795
+ });
4796
+
3469
4797
  // ../packages/tool-kit/out/index.js
3470
4798
  var require_out2 = __commonJS({
3471
4799
  "../packages/tool-kit/out/index.js"(exports) {
3472
4800
  "use strict";
3473
4801
  Object.defineProperty(exports, "__esModule", { value: true });
3474
- exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.credentialsFilePath = exports.writeHookSettings = exports.runCliAgentSetup = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.expandUserPath = exports.appendEventLog = exports.EVENT_LOG_ENV_VAR = exports.buildEventPayload = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.mintIdempotencyKey = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.classifyModelClass = exports.autonomyBand = exports.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
3475
- exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = exports.unresolvedStateFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.readTokenFile = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.recordTurnStart = void 0;
3476
- exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = void 0;
4802
+ exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.runCliAgentSetup = exports.registeredHookSets = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.loadCliAgentConfig = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = exports.expandUserPath = exports.appendEventLog = exports.EVENT_LOG_ENV_VAR = exports.buildEventPayload = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.describeCollectorVersion = exports.UNRELEASED_COLLECTOR_VERSION = exports.COLLECTOR_VERSION = exports.mintIdempotencyKey = exports.looksLikeCorrection = exports.outcomeForHook = exports.inferOutcome = exports.getNestedNumber = exports.getNestedString = exports.getNested = exports.getNumber = exports.getString = exports.localHourAt = exports.utcOffsetMinutesAt = exports.BUSINESS_DAY = exports.isOutsideBusinessHours = exports.isAfterHours = exports.bucketDurationMs = exports.bucketLinesChanged = exports.classifyModelClass = exports.autonomyBand = exports.invitesDebrief = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
4803
+ exports.recordWorkContextAlias = exports.recordWorkContext = exports.readBranchName = exports.normalizeBranchName = exports.deriveBranchHashForCwd = exports.deriveBranchHash = exports.deriveWorkContext = exports.hashWithMachineSalt = exports.readOrCreateMachineSalt = exports.machineSaltFilePath = exports.fixedTimeProvider = exports.systemTimeProvider = exports.enforceOutboxBounds = exports.claimOutbox = exports.readOutboxSummary = exports.appendToOutbox = exports.defaultOutboxFilePath = exports.outboxDrainEnabled = exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = exports.recordOutboxDiscard = exports.unresolvedToolInstallationId = exports.unresolvedStateFilePath = exports.markFailureNotified = exports.shouldAnnounceFailure = exports.recordSendOutcome = exports.readCollectorState = exports.defaultStateFilePath = exports.tokenExpiryFilePath = exports.readTokenFile = exports.readTokenExpiry = exports.persistEventWriteToken = exports.listPersistedToolInstallationIds = exports.defaultTokenFilePath = exports.ascendaHome = exports.EVENT_TOKEN_TTL_MS = exports.recordTurnStart = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = void 0;
4804
+ exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = exports.startStudyJoin = exports.setStudyObjection = exports.markStudyNoticeShown = exports.readStudyNotices = exports.readInitiatives = exports.isRetryableStatus = exports.parseIngestResponse = exports.postToolEventsBatch = exports.postToolEvent = exports.renewToolToken = exports.getStudyJoinStatus = exports.getPairingStatus = exports.createPairingSession = exports.AscendaApiError = exports.scriptMarkerIn = exports.psLookup = exports.psArgsLookup = exports.livePidFields = exports.findAgentProcess = exports.findAgentPid = exports.AGENT_PROCESS = exports.readViaPlugin = exports.readHookSet = exports.isHookSet = exports.hookSetOfCommand = exports.hookSetChanges = exports.hookSetArgument = exports.describeHookSetChanges = exports.UNVERSIONED_HOOK_SET = exports.HOOK_SET_FLAG = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.emitLiveSignal = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeProjectHash = exports.workContextRegistryFilePath = exports.readWorkContextRegistry = void 0;
3477
4805
  var commandClassifier_1 = require_commandClassifier();
3478
4806
  Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
3479
4807
  return commandClassifier_1.classifyCommand;
@@ -3554,6 +4882,16 @@ var require_out2 = __commonJS({
3554
4882
  Object.defineProperty(exports, "mintIdempotencyKey", { enumerable: true, get: function() {
3555
4883
  return payload_1.mintIdempotencyKey;
3556
4884
  } });
4885
+ var collectorVersion_1 = require_collectorVersion();
4886
+ Object.defineProperty(exports, "COLLECTOR_VERSION", { enumerable: true, get: function() {
4887
+ return collectorVersion_1.COLLECTOR_VERSION;
4888
+ } });
4889
+ Object.defineProperty(exports, "UNRELEASED_COLLECTOR_VERSION", { enumerable: true, get: function() {
4890
+ return collectorVersion_1.UNRELEASED_COLLECTOR_VERSION;
4891
+ } });
4892
+ Object.defineProperty(exports, "describeCollectorVersion", { enumerable: true, get: function() {
4893
+ return collectorVersion_1.describeCollectorVersion;
4894
+ } });
3557
4895
  var eventSender_1 = require_eventSender();
3558
4896
  Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
3559
4897
  return eventSender_1.AscendaEventSender;
@@ -3561,6 +4899,9 @@ var require_out2 = __commonJS({
3561
4899
  Object.defineProperty(exports, "AscendaSemanticEventError", { enumerable: true, get: function() {
3562
4900
  return eventSender_1.AscendaSemanticEventError;
3563
4901
  } });
4902
+ Object.defineProperty(exports, "TOKEN_RENEW_LEAD_MS", { enumerable: true, get: function() {
4903
+ return eventSender_1.TOKEN_RENEW_LEAD_MS;
4904
+ } });
3564
4905
  Object.defineProperty(exports, "buildEventPayload", { enumerable: true, get: function() {
3565
4906
  return eventSender_1.buildEventPayload;
3566
4907
  } });
@@ -3606,16 +4947,38 @@ var require_out2 = __commonJS({
3606
4947
  Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
3607
4948
  return cliAgentSetup_1.isCliAgentManagementCommand;
3608
4949
  } });
4950
+ Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
4951
+ return cliAgentSetup_1.registeredHookSets;
4952
+ } });
3609
4953
  Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
3610
4954
  return cliAgentSetup_1.runCliAgentSetup;
3611
4955
  } });
3612
4956
  Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
3613
4957
  return cliAgentSetup_1.writeHookSettings;
3614
4958
  } });
4959
+ var setupDisclosure_1 = require_setupDisclosure();
4960
+ Object.defineProperty(exports, "ALWAYS_SENT", { enumerable: true, get: function() {
4961
+ return setupDisclosure_1.ALWAYS_SENT;
4962
+ } });
4963
+ Object.defineProperty(exports, "FAMILY_SENTENCES", { enumerable: true, get: function() {
4964
+ return setupDisclosure_1.FAMILY_SENTENCES;
4965
+ } });
4966
+ Object.defineProperty(exports, "FREE_TEXT_KEYS", { enumerable: true, get: function() {
4967
+ return setupDisclosure_1.FREE_TEXT_KEYS;
4968
+ } });
4969
+ Object.defineProperty(exports, "REFUSALS", { enumerable: true, get: function() {
4970
+ return setupDisclosure_1.REFUSALS;
4971
+ } });
4972
+ Object.defineProperty(exports, "renderSetupDisclosure", { enumerable: true, get: function() {
4973
+ return setupDisclosure_1.renderSetupDisclosure;
4974
+ } });
3615
4975
  var credentials_1 = require_credentials();
3616
4976
  Object.defineProperty(exports, "credentialsFilePath", { enumerable: true, get: function() {
3617
4977
  return credentials_1.credentialsFilePath;
3618
4978
  } });
4979
+ Object.defineProperty(exports, "isLocalOnlyHostInstall", { enumerable: true, get: function() {
4980
+ return credentials_1.isLocalOnlyHostInstall;
4981
+ } });
3619
4982
  Object.defineProperty(exports, "readHostCredentials", { enumerable: true, get: function() {
3620
4983
  return credentials_1.readHostCredentials;
3621
4984
  } });
@@ -3642,6 +5005,9 @@ var require_out2 = __commonJS({
3642
5005
  return turnState_1.recordTurnStart;
3643
5006
  } });
3644
5007
  var tokenStore_1 = require_tokenStore();
5008
+ Object.defineProperty(exports, "EVENT_TOKEN_TTL_MS", { enumerable: true, get: function() {
5009
+ return tokenStore_1.EVENT_TOKEN_TTL_MS;
5010
+ } });
3645
5011
  Object.defineProperty(exports, "ascendaHome", { enumerable: true, get: function() {
3646
5012
  return tokenStore_1.ascendaHome;
3647
5013
  } });
@@ -3654,9 +5020,15 @@ var require_out2 = __commonJS({
3654
5020
  Object.defineProperty(exports, "persistEventWriteToken", { enumerable: true, get: function() {
3655
5021
  return tokenStore_1.persistEventWriteToken;
3656
5022
  } });
5023
+ Object.defineProperty(exports, "readTokenExpiry", { enumerable: true, get: function() {
5024
+ return tokenStore_1.readTokenExpiry;
5025
+ } });
3657
5026
  Object.defineProperty(exports, "readTokenFile", { enumerable: true, get: function() {
3658
5027
  return tokenStore_1.readTokenFile;
3659
5028
  } });
5029
+ Object.defineProperty(exports, "tokenExpiryFilePath", { enumerable: true, get: function() {
5030
+ return tokenStore_1.tokenExpiryFilePath;
5031
+ } });
3660
5032
  var stateStore_1 = require_stateStore();
3661
5033
  Object.defineProperty(exports, "defaultStateFilePath", { enumerable: true, get: function() {
3662
5034
  return stateStore_1.defaultStateFilePath;
@@ -3788,6 +5160,59 @@ var require_out2 = __commonJS({
3788
5160
  Object.defineProperty(exports, "liveBusSocketCandidates", { enumerable: true, get: function() {
3789
5161
  return liveBus_1.liveBusSocketCandidates;
3790
5162
  } });
5163
+ Object.defineProperty(exports, "LIVE_BUS_BACKGROUND_TRUST_MS", { enumerable: true, get: function() {
5164
+ return liveBus_1.LIVE_BUS_BACKGROUND_TRUST_MS;
5165
+ } });
5166
+ var hookSet_1 = require_hookSet();
5167
+ Object.defineProperty(exports, "HOOK_SET_FLAG", { enumerable: true, get: function() {
5168
+ return hookSet_1.HOOK_SET_FLAG;
5169
+ } });
5170
+ Object.defineProperty(exports, "UNVERSIONED_HOOK_SET", { enumerable: true, get: function() {
5171
+ return hookSet_1.UNVERSIONED_HOOK_SET;
5172
+ } });
5173
+ Object.defineProperty(exports, "describeHookSetChanges", { enumerable: true, get: function() {
5174
+ return hookSet_1.describeHookSetChanges;
5175
+ } });
5176
+ Object.defineProperty(exports, "hookSetArgument", { enumerable: true, get: function() {
5177
+ return hookSet_1.hookSetArgument;
5178
+ } });
5179
+ Object.defineProperty(exports, "hookSetChanges", { enumerable: true, get: function() {
5180
+ return hookSet_1.hookSetChanges;
5181
+ } });
5182
+ Object.defineProperty(exports, "hookSetOfCommand", { enumerable: true, get: function() {
5183
+ return hookSet_1.hookSetOfCommand;
5184
+ } });
5185
+ Object.defineProperty(exports, "isHookSet", { enumerable: true, get: function() {
5186
+ return hookSet_1.isHookSet;
5187
+ } });
5188
+ Object.defineProperty(exports, "readHookSet", { enumerable: true, get: function() {
5189
+ return hookSet_1.readHookSet;
5190
+ } });
5191
+ Object.defineProperty(exports, "readViaPlugin", { enumerable: true, get: function() {
5192
+ return hookSet_1.readViaPlugin;
5193
+ } });
5194
+ var agentProcess_1 = require_agentProcess();
5195
+ Object.defineProperty(exports, "AGENT_PROCESS", { enumerable: true, get: function() {
5196
+ return agentProcess_1.AGENT_PROCESS;
5197
+ } });
5198
+ Object.defineProperty(exports, "findAgentPid", { enumerable: true, get: function() {
5199
+ return agentProcess_1.findAgentPid;
5200
+ } });
5201
+ Object.defineProperty(exports, "findAgentProcess", { enumerable: true, get: function() {
5202
+ return agentProcess_1.findAgentProcess;
5203
+ } });
5204
+ Object.defineProperty(exports, "livePidFields", { enumerable: true, get: function() {
5205
+ return agentProcess_1.livePidFields;
5206
+ } });
5207
+ Object.defineProperty(exports, "psArgsLookup", { enumerable: true, get: function() {
5208
+ return agentProcess_1.psArgsLookup;
5209
+ } });
5210
+ Object.defineProperty(exports, "psLookup", { enumerable: true, get: function() {
5211
+ return agentProcess_1.psLookup;
5212
+ } });
5213
+ Object.defineProperty(exports, "scriptMarkerIn", { enumerable: true, get: function() {
5214
+ return agentProcess_1.scriptMarkerIn;
5215
+ } });
3791
5216
  var http_1 = require_http();
3792
5217
  Object.defineProperty(exports, "AscendaApiError", { enumerable: true, get: function() {
3793
5218
  return http_1.AscendaApiError;
@@ -3798,6 +5223,9 @@ var require_out2 = __commonJS({
3798
5223
  Object.defineProperty(exports, "getPairingStatus", { enumerable: true, get: function() {
3799
5224
  return http_1.getPairingStatus;
3800
5225
  } });
5226
+ Object.defineProperty(exports, "getStudyJoinStatus", { enumerable: true, get: function() {
5227
+ return http_1.getStudyJoinStatus;
5228
+ } });
3801
5229
  Object.defineProperty(exports, "renewToolToken", { enumerable: true, get: function() {
3802
5230
  return http_1.renewToolToken;
3803
5231
  } });
@@ -3813,6 +5241,48 @@ var require_out2 = __commonJS({
3813
5241
  Object.defineProperty(exports, "isRetryableStatus", { enumerable: true, get: function() {
3814
5242
  return http_1.isRetryableStatus;
3815
5243
  } });
5244
+ Object.defineProperty(exports, "readInitiatives", { enumerable: true, get: function() {
5245
+ return http_1.readInitiatives;
5246
+ } });
5247
+ Object.defineProperty(exports, "readStudyNotices", { enumerable: true, get: function() {
5248
+ return http_1.readStudyNotices;
5249
+ } });
5250
+ Object.defineProperty(exports, "markStudyNoticeShown", { enumerable: true, get: function() {
5251
+ return http_1.markStudyNoticeShown;
5252
+ } });
5253
+ Object.defineProperty(exports, "setStudyObjection", { enumerable: true, get: function() {
5254
+ return http_1.setStudyObjection;
5255
+ } });
5256
+ Object.defineProperty(exports, "startStudyJoin", { enumerable: true, get: function() {
5257
+ return http_1.startStudyJoin;
5258
+ } });
5259
+ var initiatives_1 = require_initiatives();
5260
+ Object.defineProperty(exports, "INITIATIVE_COPY", { enumerable: true, get: function() {
5261
+ return initiatives_1.INITIATIVE_COPY;
5262
+ } });
5263
+ Object.defineProperty(exports, "initiativesStatusLines", { enumerable: true, get: function() {
5264
+ return initiatives_1.initiativesStatusLines;
5265
+ } });
5266
+ Object.defineProperty(exports, "renderInitiatives", { enumerable: true, get: function() {
5267
+ return initiatives_1.renderInitiatives;
5268
+ } });
5269
+ var studyNotices_1 = require_studyNotices();
5270
+ Object.defineProperty(exports, "NOTICED_PURPOSES", { enumerable: true, get: function() {
5271
+ return studyNotices_1.NOTICED_PURPOSES;
5272
+ } });
5273
+ Object.defineProperty(exports, "renderStudyNotices", { enumerable: true, get: function() {
5274
+ return studyNotices_1.renderStudyNotices;
5275
+ } });
5276
+ Object.defineProperty(exports, "runStudyObjection", { enumerable: true, get: function() {
5277
+ return studyNotices_1.runStudyObjection;
5278
+ } });
5279
+ Object.defineProperty(exports, "studyNoticeStatus", { enumerable: true, get: function() {
5280
+ return studyNotices_1.studyNoticeStatus;
5281
+ } });
5282
+ var studyJoin_1 = require_studyJoin();
5283
+ Object.defineProperty(exports, "runStudyJoin", { enumerable: true, get: function() {
5284
+ return studyJoin_1.runStudyJoin;
5285
+ } });
3816
5286
  }
3817
5287
  });
3818
5288
 
@@ -24986,7 +26456,7 @@ var inputShape = {
24986
26456
  evidenceFlags: external_exports.record(evidenceKeySchema, external_exports.boolean()).optional().describe('Named booleans, e.g. { "originalGoalRetained": false }. No free text.')
24987
26457
  };
24988
26458
  function buildServer(config2) {
24989
- const server = new McpServer({ name: "ascenda-agent-mcp", version: "0.1.0" });
26459
+ const server = new McpServer({ name: "ascenda-agent-mcp", version: import_tool_kit2.COLLECTOR_VERSION });
24990
26460
  const sender = new import_tool_kit2.AscendaEventSender({
24991
26461
  apiBaseUrl: config2.apiBaseUrl,
24992
26462
  toolInstallationId: config2.toolInstallationId,