@ascenda-one/codex-hooks 0.1.35 → 0.1.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -4
- package/dist/cli.js +2070 -1052
- package/dist/cli.js.map +1 -1
- package/dist/hookTrust.js +87 -0
- package/dist/hookTrust.js.map +1 -0
- package/dist/liveSignal.js +4 -0
- package/dist/liveSignal.js.map +1 -1
- package/dist/mapCodexEvent.js +64 -5
- package/dist/mapCodexEvent.js.map +1 -1
- package/dist/setup.js +31 -11
- package/dist/setup.js.map +1 -1
- package/examples/hooks.json +2 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -149,25 +149,66 @@ var require_gitActionClassifier = __commonJS({
|
|
|
149
149
|
if (!/\bgit\b/.test(value))
|
|
150
150
|
return void 0;
|
|
151
151
|
const heads = (0, commandHeads_1.commandHeads)(value);
|
|
152
|
-
|
|
152
|
+
const commands = heads.map(parseGitCommand).filter((c) => c !== void 0);
|
|
153
|
+
if (commands.some((c) => c.verb === "commit" && c.args.includes("--amend")))
|
|
153
154
|
return "amend";
|
|
154
|
-
if (
|
|
155
|
+
if (commands.some((c) => c.verb === "revert"))
|
|
155
156
|
return "revert";
|
|
156
|
-
if (
|
|
157
|
+
if (commands.some((c) => c.verb === "reset" && c.args.includes("--hard")))
|
|
157
158
|
return "reset_hard";
|
|
158
|
-
if (
|
|
159
|
+
if (commands.some(discardsWork))
|
|
159
160
|
return "restore";
|
|
160
|
-
if (
|
|
161
|
-
return "restore";
|
|
162
|
-
if (heads.some((h) => /^git\s+push\b/.test(h)))
|
|
161
|
+
if (commands.some((c) => c.verb === "push"))
|
|
163
162
|
return "push";
|
|
164
|
-
if (
|
|
163
|
+
if (commands.some((c) => c.verb === "commit"))
|
|
165
164
|
return "commit";
|
|
166
165
|
return void 0;
|
|
167
166
|
}
|
|
168
167
|
function isReworkGitAction(action) {
|
|
169
168
|
return action === "revert" || action === "reset_hard" || action === "restore";
|
|
170
169
|
}
|
|
170
|
+
var GLOBAL_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--config-env", "--exec-path"]);
|
|
171
|
+
function parseGitCommand(head) {
|
|
172
|
+
const words = head.split(/\s+/);
|
|
173
|
+
if (words[0] !== "git")
|
|
174
|
+
return void 0;
|
|
175
|
+
let i = 1;
|
|
176
|
+
while (i < words.length && words[i].startsWith("-")) {
|
|
177
|
+
i += GLOBAL_OPTIONS_WITH_VALUE.has(words[i]) ? 2 : 1;
|
|
178
|
+
}
|
|
179
|
+
if (i >= words.length)
|
|
180
|
+
return void 0;
|
|
181
|
+
return { verb: words[i], args: words.slice(i + 1) };
|
|
182
|
+
}
|
|
183
|
+
function discardsWork({ verb, args }) {
|
|
184
|
+
switch (verb) {
|
|
185
|
+
case "restore":
|
|
186
|
+
return !args.includes("--staged");
|
|
187
|
+
case "switch":
|
|
188
|
+
return args.includes("--discard-changes") || args.includes("--force") || args.includes("-f");
|
|
189
|
+
case "clean": {
|
|
190
|
+
const flags = args.filter((a) => /^-[a-z]+$/.test(a)).join("");
|
|
191
|
+
const dryRun = args.includes("--dry-run") || flags.includes("n");
|
|
192
|
+
return !dryRun && (args.includes("--force") || flags.includes("f"));
|
|
193
|
+
}
|
|
194
|
+
case "checkout":
|
|
195
|
+
return checkoutDiscards(args);
|
|
196
|
+
default:
|
|
197
|
+
return false;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
function checkoutDiscards(args) {
|
|
201
|
+
if (args.includes("--"))
|
|
202
|
+
return true;
|
|
203
|
+
if (args.some((a) => ["-b", "--orphan", "--detach", "-d", "-t", "--track", "-B"].includes(a)))
|
|
204
|
+
return false;
|
|
205
|
+
const words = args.filter((a) => !a.startsWith("-"));
|
|
206
|
+
if (words.length >= 2)
|
|
207
|
+
return true;
|
|
208
|
+
if (words.length === 1)
|
|
209
|
+
return /^\.{1,2}(\/|$)|\/$|[*?]|\.[a-z][a-z0-9]*$/.test(words[0]);
|
|
210
|
+
return false;
|
|
211
|
+
}
|
|
171
212
|
}
|
|
172
213
|
});
|
|
173
214
|
|
|
@@ -178,6 +219,7 @@ var require_workMilestoneClassifier = __commonJS({
|
|
|
178
219
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
179
220
|
exports.classifyWorkMilestone = classifyWorkMilestone;
|
|
180
221
|
exports.invitesDebrief = invitesDebrief;
|
|
222
|
+
exports.classifyMcpWorkMilestone = classifyMcpWorkMilestone;
|
|
181
223
|
var commandHeads_1 = require_commandHeads();
|
|
182
224
|
function classifyWorkMilestone(command) {
|
|
183
225
|
if (!command)
|
|
@@ -197,6 +239,41 @@ var require_workMilestoneClassifier = __commonJS({
|
|
|
197
239
|
function invitesDebrief(kind) {
|
|
198
240
|
return kind === "pr_merged" || kind === "issue_closed";
|
|
199
241
|
}
|
|
242
|
+
function classifyMcpWorkMilestone(toolName) {
|
|
243
|
+
if (!toolName)
|
|
244
|
+
return void 0;
|
|
245
|
+
const parts = toolName.toLowerCase().split("__");
|
|
246
|
+
if (parts[0] !== "mcp" || parts.length < 3)
|
|
247
|
+
return void 0;
|
|
248
|
+
const tool = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
|
|
249
|
+
if (/^(merge|accept)(pullrequest|mergerequest)$/.test(tool))
|
|
250
|
+
return "pr_merged";
|
|
251
|
+
if (/^closeissue$/.test(tool))
|
|
252
|
+
return "issue_closed";
|
|
253
|
+
if (/^(create|open)(pullrequest|mergerequest)$/.test(tool))
|
|
254
|
+
return "pr_opened";
|
|
255
|
+
return void 0;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
// ../packages/tool-kit/out/shellFacts.js
|
|
261
|
+
var require_shellFacts = __commonJS({
|
|
262
|
+
"../packages/tool-kit/out/shellFacts.js"(exports) {
|
|
263
|
+
"use strict";
|
|
264
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
265
|
+
exports.shellCommandFacts = shellCommandFacts2;
|
|
266
|
+
var gitActionClassifier_1 = require_gitActionClassifier();
|
|
267
|
+
var workMilestoneClassifier_1 = require_workMilestoneClassifier();
|
|
268
|
+
function shellCommandFacts2(command) {
|
|
269
|
+
const gitAction = (0, gitActionClassifier_1.classifyGitAction)(command);
|
|
270
|
+
const milestoneKind = (0, workMilestoneClassifier_1.classifyWorkMilestone)(command);
|
|
271
|
+
return {
|
|
272
|
+
...gitAction !== void 0 ? { gitAction } : {},
|
|
273
|
+
...(0, gitActionClassifier_1.isReworkGitAction)(gitAction) ? { activity: "rework_reversion" } : {},
|
|
274
|
+
...milestoneKind !== void 0 ? { milestoneKind } : {}
|
|
275
|
+
};
|
|
276
|
+
}
|
|
200
277
|
}
|
|
201
278
|
});
|
|
202
279
|
|
|
@@ -590,6 +667,61 @@ var require_metricKeys = __commonJS({
|
|
|
590
667
|
subagentAssistantTurns: { family: "counts", readBy: ["diagnostic"] },
|
|
591
668
|
subagentPrompts: { family: "counts", readBy: ["diagnostic"] },
|
|
592
669
|
subagentTokensTotal: { family: "context", readBy: ["diagnostic"] },
|
|
670
|
+
advisorMessageCount: {
|
|
671
|
+
family: "counts",
|
|
672
|
+
readBy: ["diagnostic"],
|
|
673
|
+
note: "Claude Code only: advisor calls (a second model consulted inside one API message). Their tokens and models are already folded into the session totals and model mix, and this is the receipt for how much of that they are."
|
|
674
|
+
},
|
|
675
|
+
advisorTokensTotal: {
|
|
676
|
+
family: "context",
|
|
677
|
+
readBy: ["diagnostic"],
|
|
678
|
+
unit: "tokens",
|
|
679
|
+
note: "Claude Code only: input, output and cache tokens spent by advisor calls. A part of the session totals, not an addition to them."
|
|
680
|
+
},
|
|
681
|
+
cacheCreationTokens: {
|
|
682
|
+
family: "context",
|
|
683
|
+
readBy: ["diagnostic"],
|
|
684
|
+
unit: "tokens",
|
|
685
|
+
note: "Prompt-cache writes, summed once per API message. Absent where the store never wrote the figure, which is not the same as none written."
|
|
686
|
+
},
|
|
687
|
+
cacheCreation5mTokens: {
|
|
688
|
+
family: "context",
|
|
689
|
+
readBy: ["diagnostic"],
|
|
690
|
+
unit: "tokens",
|
|
691
|
+
note: "The part of cacheCreationTokens written with the 5-minute lifetime. Absent on transcripts that only record the total."
|
|
692
|
+
},
|
|
693
|
+
cacheCreation1hTokens: {
|
|
694
|
+
family: "context",
|
|
695
|
+
readBy: ["diagnostic"],
|
|
696
|
+
unit: "tokens",
|
|
697
|
+
note: "The part of cacheCreationTokens written with the 1-hour lifetime. Absent on transcripts that only record the total."
|
|
698
|
+
},
|
|
699
|
+
headlessPromptLines: {
|
|
700
|
+
family: "reading",
|
|
701
|
+
readBy: ["diagnostic"],
|
|
702
|
+
unit: "lines",
|
|
703
|
+
note: "Claude Code only: user lines written by the Agent SDK or a headless run (entrypoint sdk-*). Nobody typed them, so promptCount leaves them out. Counted once per line across the store."
|
|
704
|
+
},
|
|
705
|
+
tokensNotCollected: {
|
|
706
|
+
family: "context",
|
|
707
|
+
readBy: ["diagnostic"],
|
|
708
|
+
note: "True when the store recorded no token figures for this session (Cursor builds that write a zero tokenCount, Codex rollouts from before token_count events). The token keys are then left off the event instead of being sent as 0, so absent and zero stay apart. Metrics are flat scalars with no null, so a flag beside the missing keys is the marker the contract allows."
|
|
709
|
+
},
|
|
710
|
+
unattributedSubagentTranscripts: {
|
|
711
|
+
family: "reading",
|
|
712
|
+
readBy: ["diagnostic"],
|
|
713
|
+
note: "Claude Code only: flat subagent transcripts whose lines name no parent session, so they could not be folded anywhere."
|
|
714
|
+
},
|
|
715
|
+
duplicateChatSessions: {
|
|
716
|
+
family: "reading",
|
|
717
|
+
readBy: ["diagnostic"],
|
|
718
|
+
note: "VS Code only: chat sessions seen in more than one place (a transferred session also in a workspace). Counted once."
|
|
719
|
+
},
|
|
720
|
+
sessionsStartedFromBubble: {
|
|
721
|
+
family: "reading",
|
|
722
|
+
readBy: ["diagnostic"],
|
|
723
|
+
note: "Cursor only: sessions whose start is the earliest message rather than the header's createdAt, which can sit months before anyone typed."
|
|
724
|
+
},
|
|
593
725
|
toolName: {
|
|
594
726
|
family: "tools",
|
|
595
727
|
readBy: ["backend"],
|
|
@@ -697,7 +829,9 @@ var require_out = __commonJS({
|
|
|
697
829
|
exports.COLLABORATION_EVENT_TYPES = [
|
|
698
830
|
"review_requested_of_me",
|
|
699
831
|
"review_given",
|
|
700
|
-
"pull_request_opened"
|
|
832
|
+
"pull_request_opened",
|
|
833
|
+
"pull_request_closed",
|
|
834
|
+
"pull_request_merged"
|
|
701
835
|
];
|
|
702
836
|
exports.EVENT_METADATA_DISCLOSURE = {
|
|
703
837
|
language: "edits",
|
|
@@ -709,6 +843,13 @@ var require_out = __commonJS({
|
|
|
709
843
|
gitAction: "git",
|
|
710
844
|
milestoneKind: "git",
|
|
711
845
|
branchHash: "repo",
|
|
846
|
+
repoKey: "forge",
|
|
847
|
+
headRepoKey: "forge",
|
|
848
|
+
prCreatedAt: "git",
|
|
849
|
+
prClosedAt: "git",
|
|
850
|
+
prMergedAt: "git",
|
|
851
|
+
branchKey: "forge",
|
|
852
|
+
promptId: "turns",
|
|
712
853
|
autonomyMode: "posture",
|
|
713
854
|
modelClass: "model",
|
|
714
855
|
modelId: "model",
|
|
@@ -758,6 +899,13 @@ var require_out = __commonJS({
|
|
|
758
899
|
"gitAction",
|
|
759
900
|
"milestoneKind",
|
|
760
901
|
"branchHash",
|
|
902
|
+
"repoKey",
|
|
903
|
+
"headRepoKey",
|
|
904
|
+
"prCreatedAt",
|
|
905
|
+
"prClosedAt",
|
|
906
|
+
"prMergedAt",
|
|
907
|
+
"branchKey",
|
|
908
|
+
"promptId",
|
|
761
909
|
"autonomyMode",
|
|
762
910
|
"modelClass",
|
|
763
911
|
"modelId",
|
|
@@ -827,6 +975,10 @@ var require_out = __commonJS({
|
|
|
827
975
|
review_requested_of_me: "supervision",
|
|
828
976
|
review_given: "supervision",
|
|
829
977
|
pull_request_opened: "creation",
|
|
978
|
+
// Where a pull request of yours ended up. A boundary like a turn ending, not
|
|
979
|
+
// work in itself, so neutral: it must not weigh on any workload leg.
|
|
980
|
+
pull_request_closed: "neutral",
|
|
981
|
+
pull_request_merged: "neutral",
|
|
830
982
|
context_pressure_high: "risk",
|
|
831
983
|
agent_loop_long: "risk",
|
|
832
984
|
after_hours_ai_session: "risk",
|
|
@@ -857,6 +1009,16 @@ var require_out = __commonJS({
|
|
|
857
1009
|
// step toward an interruption count becoming a score, a streak, or something
|
|
858
1010
|
// that fires on a miss. It must never become any of those.
|
|
859
1011
|
supervision_interruption: "supervision",
|
|
1012
|
+
// The agent asked to run a tool, and the auto-mode classifier refused one.
|
|
1013
|
+
// Claude Code's `PermissionRequest` and `PermissionDenied` hooks. Neutral,
|
|
1014
|
+
// because the Notification for the same prompt is already counted above as
|
|
1015
|
+
// `supervision_interruption`, and counting both would weigh one prompt
|
|
1016
|
+
// twice. These rows exist for the public event stream: which tool asked, and
|
|
1017
|
+
// under which posture. `permission_requested` fires before the person
|
|
1018
|
+
// answers and no hook reports their answer, so neither event says whether
|
|
1019
|
+
// the request was granted.
|
|
1020
|
+
permission_requested: "neutral",
|
|
1021
|
+
permission_denied: "neutral",
|
|
860
1022
|
// Semantic (agent-observed) — see SEMANTIC_WORK_SIGNAL_EVENT_TYPES.
|
|
861
1023
|
approach_churn_detected: "risk",
|
|
862
1024
|
goal_drift_detected: "risk",
|
|
@@ -919,9 +1081,9 @@ var require_payload = __commonJS({
|
|
|
919
1081
|
}
|
|
920
1082
|
return void 0;
|
|
921
1083
|
}
|
|
922
|
-
function getNested2(input,
|
|
1084
|
+
function getNested2(input, path3) {
|
|
923
1085
|
let current = input;
|
|
924
|
-
for (const segment of
|
|
1086
|
+
for (const segment of path3) {
|
|
925
1087
|
if (!current || typeof current !== "object")
|
|
926
1088
|
return void 0;
|
|
927
1089
|
current = current[segment];
|
|
@@ -929,16 +1091,16 @@ var require_payload = __commonJS({
|
|
|
929
1091
|
return current;
|
|
930
1092
|
}
|
|
931
1093
|
function getNestedString3(input, paths) {
|
|
932
|
-
for (const
|
|
933
|
-
const value = getNested2(input,
|
|
1094
|
+
for (const path3 of paths) {
|
|
1095
|
+
const value = getNested2(input, path3);
|
|
934
1096
|
if (typeof value === "string" && value.trim())
|
|
935
1097
|
return value;
|
|
936
1098
|
}
|
|
937
1099
|
return void 0;
|
|
938
1100
|
}
|
|
939
1101
|
function getNestedNumber(input, paths) {
|
|
940
|
-
for (const
|
|
941
|
-
const value = getNested2(input,
|
|
1102
|
+
for (const path3 of paths) {
|
|
1103
|
+
const value = getNested2(input, path3);
|
|
942
1104
|
if (typeof value === "number" && Number.isFinite(value))
|
|
943
1105
|
return value;
|
|
944
1106
|
}
|
|
@@ -981,122 +1143,13 @@ var require_collectorVersion = __commonJS({
|
|
|
981
1143
|
exports.COLLECTOR_VERSION = exports.UNRELEASED_COLLECTOR_VERSION = void 0;
|
|
982
1144
|
exports.describeCollectorVersion = describeCollectorVersion;
|
|
983
1145
|
exports.UNRELEASED_COLLECTOR_VERSION = "unreleased";
|
|
984
|
-
exports.COLLECTOR_VERSION = "0.1.
|
|
1146
|
+
exports.COLLECTOR_VERSION = "0.1.36" ? "0.1.36" : exports.UNRELEASED_COLLECTOR_VERSION;
|
|
985
1147
|
function describeCollectorVersion(version = exports.COLLECTOR_VERSION) {
|
|
986
1148
|
return version === exports.UNRELEASED_COLLECTOR_VERSION ? `${version} (built from a checkout, not a release)` : version;
|
|
987
1149
|
}
|
|
988
1150
|
}
|
|
989
1151
|
});
|
|
990
1152
|
|
|
991
|
-
// ../packages/agent-events/out/index.js
|
|
992
|
-
var require_out2 = __commonJS({
|
|
993
|
-
"../packages/agent-events/out/index.js"(exports) {
|
|
994
|
-
"use strict";
|
|
995
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
996
|
-
exports.KNOWN_AGENTS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
|
|
997
|
-
exports.isAgentEventV0 = isAgentEventV0;
|
|
998
|
-
exports.parseEventLogLine = parseEventLogLine;
|
|
999
|
-
exports.normaliseKind = normaliseKind;
|
|
1000
|
-
exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
|
|
1001
|
-
exports.AGENT_EVENT_KINDS = [
|
|
1002
|
-
"session.started",
|
|
1003
|
-
"session.ended",
|
|
1004
|
-
"prompt.submitted",
|
|
1005
|
-
"tool.started",
|
|
1006
|
-
"tool.completed",
|
|
1007
|
-
"tool.failed",
|
|
1008
|
-
"turn.completed",
|
|
1009
|
-
"agent.waiting",
|
|
1010
|
-
"context.compacted",
|
|
1011
|
-
"subagent.started",
|
|
1012
|
-
"subagent.stopped",
|
|
1013
|
-
"other"
|
|
1014
|
-
];
|
|
1015
|
-
exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
|
|
1016
|
-
function isAgentEventV0(value) {
|
|
1017
|
-
if (!value || typeof value !== "object")
|
|
1018
|
-
return false;
|
|
1019
|
-
const e = value;
|
|
1020
|
-
return e.schema === exports.AGENT_EVENT_SCHEMA && typeof e.id === "string" && e.id.length > 0 && typeof e.time === "string" && !Number.isNaN(Date.parse(e.time)) && typeof e.agent === "string" && e.agent.length > 0 && typeof e.kind === "string";
|
|
1021
|
-
}
|
|
1022
|
-
function parseEventLogLine(line) {
|
|
1023
|
-
if (!line.trim())
|
|
1024
|
-
return void 0;
|
|
1025
|
-
try {
|
|
1026
|
-
const parsed = JSON.parse(line);
|
|
1027
|
-
return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
|
|
1028
|
-
} catch {
|
|
1029
|
-
return void 0;
|
|
1030
|
-
}
|
|
1031
|
-
}
|
|
1032
|
-
function normaliseKind(kind) {
|
|
1033
|
-
return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
});
|
|
1037
|
-
|
|
1038
|
-
// ../packages/tool-kit/out/agentEvent.js
|
|
1039
|
-
var require_agentEvent = __commonJS({
|
|
1040
|
-
"../packages/tool-kit/out/agentEvent.js"(exports) {
|
|
1041
|
-
"use strict";
|
|
1042
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1043
|
-
exports.toAgentEvent = toAgentEvent;
|
|
1044
|
-
var agent_events_1 = require_out2();
|
|
1045
|
-
var KIND_BY_TYPE = {
|
|
1046
|
-
create_focus_session: "session.started",
|
|
1047
|
-
recovery_offline_period: "session.ended",
|
|
1048
|
-
ai_prompt_submitted: "prompt.submitted",
|
|
1049
|
-
ai_tool_call_started: "tool.started",
|
|
1050
|
-
ai_tool_call_completed: "tool.completed",
|
|
1051
|
-
ai_file_write: "tool.completed",
|
|
1052
|
-
ai_file_edit: "tool.completed",
|
|
1053
|
-
editor_verification_activity: "tool.completed",
|
|
1054
|
-
ai_tool_call_failed: "tool.failed",
|
|
1055
|
-
compile_error: "tool.failed",
|
|
1056
|
-
tool_failure: "tool.failed",
|
|
1057
|
-
ai_turn_completed: "turn.completed",
|
|
1058
|
-
supervision_interruption: "agent.waiting",
|
|
1059
|
-
context_compression_manual: "context.compacted",
|
|
1060
|
-
context_compression_auto: "context.compacted",
|
|
1061
|
-
subagent_started: "subagent.started",
|
|
1062
|
-
subagent_stopped: "subagent.stopped"
|
|
1063
|
-
};
|
|
1064
|
-
function agentOf(payload) {
|
|
1065
|
-
const host = stringField(payload.metadata?.host);
|
|
1066
|
-
if (host)
|
|
1067
|
-
return host;
|
|
1068
|
-
return payload.source === "vscode_extension" ? "vscode" : payload.source;
|
|
1069
|
-
}
|
|
1070
|
-
function stringField(value) {
|
|
1071
|
-
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
1072
|
-
}
|
|
1073
|
-
function toAgentEvent(payload) {
|
|
1074
|
-
const metadata = payload.metadata ?? {};
|
|
1075
|
-
const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
|
|
1076
|
-
const tool = kind.startsWith("tool.") ? stringField(metadata.toolName) : void 0;
|
|
1077
|
-
const outcome = stringField(metadata.outcome);
|
|
1078
|
-
return {
|
|
1079
|
-
schema: agent_events_1.AGENT_EVENT_SCHEMA,
|
|
1080
|
-
id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
|
|
1081
|
-
time: payload.occurredAt,
|
|
1082
|
-
// `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
|
|
1083
|
-
// writes anyway; without it the event in memory and the one on disk differ.
|
|
1084
|
-
...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
|
|
1085
|
-
agent: agentOf(payload),
|
|
1086
|
-
kind,
|
|
1087
|
-
...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
|
|
1088
|
-
...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
|
|
1089
|
-
...tool ? { tool } : {},
|
|
1090
|
-
...outcome && outcome !== "unknown" ? { outcome } : {},
|
|
1091
|
-
...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
|
|
1092
|
-
...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
|
|
1093
|
-
...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
|
|
1094
|
-
sourceType: payload.eventType
|
|
1095
|
-
};
|
|
1096
|
-
}
|
|
1097
|
-
}
|
|
1098
|
-
});
|
|
1099
|
-
|
|
1100
1153
|
// ../packages/tool-kit/out/tokenStore.js
|
|
1101
1154
|
var require_tokenStore = __commonJS({
|
|
1102
1155
|
"../packages/tool-kit/out/tokenStore.js"(exports) {
|
|
@@ -1148,33 +1201,33 @@ var require_tokenStore = __commonJS({
|
|
|
1148
1201
|
exports.listPersistedToolInstallationIds = listPersistedToolInstallationIds;
|
|
1149
1202
|
exports.readTokenFile = readTokenFile;
|
|
1150
1203
|
exports.sanitizeFilePart = sanitizeFilePart;
|
|
1151
|
-
var
|
|
1204
|
+
var fs2 = __importStar(__require("fs"));
|
|
1152
1205
|
var os2 = __importStar(__require("os"));
|
|
1153
|
-
var
|
|
1206
|
+
var path3 = __importStar(__require("path"));
|
|
1154
1207
|
function ascendaHome(home = os2.homedir()) {
|
|
1155
|
-
return process.env.ASCENDA_HOME ??
|
|
1208
|
+
return process.env.ASCENDA_HOME ?? path3.join(home, ".ascenda");
|
|
1156
1209
|
}
|
|
1157
1210
|
function defaultTokenFilePath(toolInstallationId) {
|
|
1158
|
-
return
|
|
1211
|
+
return path3.join(ascendaHome(), "tokens", sanitizeFilePart(toolInstallationId));
|
|
1159
1212
|
}
|
|
1160
1213
|
function tokenExpiryFilePath(tokenFilePath) {
|
|
1161
|
-
return
|
|
1214
|
+
return path3.join(path3.dirname(tokenFilePath), "expiry", path3.basename(tokenFilePath));
|
|
1162
1215
|
}
|
|
1163
1216
|
function persistEventWriteToken(tokenFilePath, token, expiresAt) {
|
|
1164
|
-
const dir =
|
|
1165
|
-
|
|
1166
|
-
|
|
1217
|
+
const dir = path3.dirname(tokenFilePath);
|
|
1218
|
+
fs2.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1219
|
+
fs2.writeFileSync(tokenFilePath, token, { encoding: "utf8", mode: 384 });
|
|
1167
1220
|
if (process.platform !== "win32") {
|
|
1168
|
-
|
|
1169
|
-
|
|
1221
|
+
fs2.chmodSync(dir, 448);
|
|
1222
|
+
fs2.chmodSync(tokenFilePath, 384);
|
|
1170
1223
|
}
|
|
1171
1224
|
const expiryFile = tokenExpiryFilePath(tokenFilePath);
|
|
1172
1225
|
try {
|
|
1173
1226
|
if (expiresAt && Number.isFinite(Date.parse(expiresAt))) {
|
|
1174
|
-
|
|
1175
|
-
|
|
1227
|
+
fs2.mkdirSync(path3.dirname(expiryFile), { recursive: true, mode: 448 });
|
|
1228
|
+
fs2.writeFileSync(expiryFile, expiresAt, { encoding: "utf8", mode: 384 });
|
|
1176
1229
|
} else {
|
|
1177
|
-
|
|
1230
|
+
fs2.rmSync(expiryFile, { force: true });
|
|
1178
1231
|
}
|
|
1179
1232
|
} catch {
|
|
1180
1233
|
}
|
|
@@ -1182,23 +1235,23 @@ var require_tokenStore = __commonJS({
|
|
|
1182
1235
|
exports.EVENT_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
1183
1236
|
function readTokenExpiry(tokenFilePath) {
|
|
1184
1237
|
try {
|
|
1185
|
-
const recorded = Date.parse(
|
|
1238
|
+
const recorded = Date.parse(fs2.readFileSync(tokenExpiryFilePath(tokenFilePath), "utf8").trim());
|
|
1186
1239
|
if (Number.isFinite(recorded))
|
|
1187
1240
|
return recorded;
|
|
1188
1241
|
} catch {
|
|
1189
1242
|
}
|
|
1190
1243
|
try {
|
|
1191
|
-
return
|
|
1244
|
+
return fs2.statSync(tokenFilePath).mtimeMs + exports.EVENT_TOKEN_TTL_MS;
|
|
1192
1245
|
} catch {
|
|
1193
1246
|
return void 0;
|
|
1194
1247
|
}
|
|
1195
1248
|
}
|
|
1196
1249
|
function listPersistedToolInstallationIds(toolType) {
|
|
1197
1250
|
const prefix = `${sanitizeFilePart(toolType)}_`;
|
|
1198
|
-
const dir =
|
|
1251
|
+
const dir = path3.join(ascendaHome(), "tokens");
|
|
1199
1252
|
let names;
|
|
1200
1253
|
try {
|
|
1201
|
-
names =
|
|
1254
|
+
names = fs2.readdirSync(dir);
|
|
1202
1255
|
} catch {
|
|
1203
1256
|
return [];
|
|
1204
1257
|
}
|
|
@@ -1206,9 +1259,9 @@ var require_tokenStore = __commonJS({
|
|
|
1206
1259
|
for (const name of names.sort()) {
|
|
1207
1260
|
if (!name.startsWith(prefix) || name.length === prefix.length)
|
|
1208
1261
|
continue;
|
|
1209
|
-
const file =
|
|
1262
|
+
const file = path3.join(dir, name);
|
|
1210
1263
|
try {
|
|
1211
|
-
if (!
|
|
1264
|
+
if (!fs2.statSync(file).isFile())
|
|
1212
1265
|
continue;
|
|
1213
1266
|
} catch {
|
|
1214
1267
|
continue;
|
|
@@ -1221,9 +1274,9 @@ var require_tokenStore = __commonJS({
|
|
|
1221
1274
|
}
|
|
1222
1275
|
function readTokenFile(tokenFilePath) {
|
|
1223
1276
|
try {
|
|
1224
|
-
if (!
|
|
1277
|
+
if (!fs2.existsSync(tokenFilePath))
|
|
1225
1278
|
return void 0;
|
|
1226
|
-
const value =
|
|
1279
|
+
const value = fs2.readFileSync(tokenFilePath, "utf8").trim();
|
|
1227
1280
|
return value || void 0;
|
|
1228
1281
|
} catch {
|
|
1229
1282
|
return void 0;
|
|
@@ -1235,9 +1288,9 @@ var require_tokenStore = __commonJS({
|
|
|
1235
1288
|
}
|
|
1236
1289
|
});
|
|
1237
1290
|
|
|
1238
|
-
// ../packages/tool-kit/out/
|
|
1239
|
-
var
|
|
1240
|
-
"../packages/tool-kit/out/
|
|
1291
|
+
// ../packages/tool-kit/out/stateStore.js
|
|
1292
|
+
var require_stateStore = __commonJS({
|
|
1293
|
+
"../packages/tool-kit/out/stateStore.js"(exports) {
|
|
1241
1294
|
"use strict";
|
|
1242
1295
|
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
1243
1296
|
if (k2 === void 0) k2 = k;
|
|
@@ -1277,94 +1330,124 @@ var require_credentials = __commonJS({
|
|
|
1277
1330
|
};
|
|
1278
1331
|
}();
|
|
1279
1332
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1280
|
-
exports.
|
|
1281
|
-
exports.
|
|
1282
|
-
exports.
|
|
1283
|
-
exports.
|
|
1284
|
-
exports.
|
|
1285
|
-
exports.
|
|
1286
|
-
exports.
|
|
1287
|
-
exports.
|
|
1288
|
-
|
|
1289
|
-
var
|
|
1290
|
-
var path2 = __importStar(__require("path"));
|
|
1333
|
+
exports.defaultStateFilePath = defaultStateFilePath;
|
|
1334
|
+
exports.unresolvedToolInstallationId = unresolvedToolInstallationId;
|
|
1335
|
+
exports.unresolvedStateFilePath = unresolvedStateFilePath;
|
|
1336
|
+
exports.readCollectorState = readCollectorState;
|
|
1337
|
+
exports.recordSendOutcome = recordSendOutcome;
|
|
1338
|
+
exports.recordOutboxDiscard = recordOutboxDiscard;
|
|
1339
|
+
exports.shouldAnnounceFailure = shouldAnnounceFailure;
|
|
1340
|
+
exports.markFailureNotified = markFailureNotified;
|
|
1341
|
+
var fs2 = __importStar(__require("fs"));
|
|
1342
|
+
var path3 = __importStar(__require("path"));
|
|
1291
1343
|
var tokenStore_1 = require_tokenStore();
|
|
1292
|
-
function
|
|
1293
|
-
|
|
1344
|
+
function defaultStateFilePath(toolInstallationId) {
|
|
1345
|
+
const dir = process.env.ASCENDA_STATE_DIR?.trim();
|
|
1346
|
+
const base = dir ? dir : path3.join((0, tokenStore_1.ascendaHome)(), "state");
|
|
1347
|
+
return path3.join(base, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.json`);
|
|
1294
1348
|
}
|
|
1295
|
-
function
|
|
1349
|
+
function unresolvedToolInstallationId(toolType) {
|
|
1350
|
+
return `${toolType}:unresolved`;
|
|
1351
|
+
}
|
|
1352
|
+
function unresolvedStateFilePath(toolType) {
|
|
1353
|
+
return defaultStateFilePath(unresolvedToolInstallationId(toolType));
|
|
1354
|
+
}
|
|
1355
|
+
function readCollectorState(stateFilePath) {
|
|
1296
1356
|
try {
|
|
1297
|
-
|
|
1357
|
+
if (!fs2.existsSync(stateFilePath))
|
|
1358
|
+
return void 0;
|
|
1359
|
+
const raw = fs2.readFileSync(stateFilePath, "utf8").trim();
|
|
1298
1360
|
if (!raw)
|
|
1299
1361
|
return void 0;
|
|
1300
1362
|
const parsed = JSON.parse(raw);
|
|
1301
|
-
if (!parsed || typeof parsed !== "object"
|
|
1363
|
+
if (!parsed || typeof parsed !== "object")
|
|
1302
1364
|
return void 0;
|
|
1303
1365
|
return parsed;
|
|
1304
1366
|
} catch {
|
|
1305
1367
|
return void 0;
|
|
1306
1368
|
}
|
|
1307
1369
|
}
|
|
1308
|
-
function
|
|
1309
|
-
const
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
...
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1370
|
+
function recordSendOutcome(stateFilePath, toolInstallationId, outcome, detail = {}) {
|
|
1371
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1372
|
+
const previous = readCollectorState(stateFilePath);
|
|
1373
|
+
const accepted = outcome === "accepted";
|
|
1374
|
+
const next = {
|
|
1375
|
+
toolInstallationId,
|
|
1376
|
+
lastAttemptAt: now,
|
|
1377
|
+
lastSuccessAt: accepted ? now : previous?.lastSuccessAt,
|
|
1378
|
+
lastOutcome: outcome,
|
|
1379
|
+
consecutiveFailures: accepted ? 0 : (previous?.consecutiveFailures ?? 0) + 1,
|
|
1380
|
+
...detail.httpStatus !== void 0 ? { httpStatus: detail.httpStatus } : {},
|
|
1381
|
+
...detail.errorCode !== void 0 ? { errorCode: detail.errorCode } : {},
|
|
1382
|
+
...detail.detail !== void 0 ? { detail: truncate(detail.detail) } : {},
|
|
1383
|
+
// A success closes the episode; a failure either opens one or continues
|
|
1384
|
+
// the one already open. Carrying `notifiedFailingSince` across a
|
|
1385
|
+
// continuing episode is what keeps the notice to once per outage.
|
|
1386
|
+
...accepted ? {} : { failingSince: previous?.failingSince ?? now },
|
|
1387
|
+
...accepted ? {} : previous?.notifiedFailingSince !== void 0 ? { notifiedFailingSince: previous.notifiedFailingSince } : {},
|
|
1388
|
+
// Cumulative by design: a send outcome, success included, never erases
|
|
1389
|
+
// the record of what the outbox had to throw away.
|
|
1390
|
+
...previous?.outboxDiscarded !== void 0 ? { outboxDiscarded: previous.outboxDiscarded } : {}
|
|
1391
|
+
};
|
|
1392
|
+
writeStateFile(stateFilePath, next);
|
|
1393
|
+
return next;
|
|
1330
1394
|
}
|
|
1331
|
-
function
|
|
1332
|
-
const
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1395
|
+
function recordOutboxDiscard(stateFilePath, toolInstallationId, discard) {
|
|
1396
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1397
|
+
const previous = readCollectorState(stateFilePath);
|
|
1398
|
+
const next = {
|
|
1399
|
+
...previous ?? { lastAttemptAt: now, consecutiveFailures: 0 },
|
|
1400
|
+
toolInstallationId,
|
|
1401
|
+
lastOutcome: "outbox_discarded",
|
|
1402
|
+
outboxDiscarded: {
|
|
1403
|
+
total: (previous?.outboxDiscarded?.total ?? 0) + discard.count,
|
|
1404
|
+
lastAt: now,
|
|
1405
|
+
lastCount: discard.count,
|
|
1406
|
+
lastReasons: discard.reasons,
|
|
1407
|
+
...discard.oldestQueuedAt !== void 0 ? { lastOldestQueuedAt: discard.oldestQueuedAt } : {}
|
|
1408
|
+
}
|
|
1409
|
+
};
|
|
1410
|
+
writeStateFile(stateFilePath, next);
|
|
1411
|
+
return next;
|
|
1344
1412
|
}
|
|
1345
|
-
function
|
|
1346
|
-
|
|
1347
|
-
|
|
1413
|
+
function shouldAnnounceFailure(state) {
|
|
1414
|
+
if (!state || state.consecutiveFailures === 0 || !state.failingSince)
|
|
1415
|
+
return false;
|
|
1416
|
+
return state.notifiedFailingSince !== state.failingSince;
|
|
1348
1417
|
}
|
|
1349
|
-
function
|
|
1350
|
-
|
|
1351
|
-
if (!existing?.tools || !(host in existing.tools))
|
|
1418
|
+
function markFailureNotified(stateFilePath, state) {
|
|
1419
|
+
if (!state.failingSince)
|
|
1352
1420
|
return;
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1421
|
+
writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
|
|
1422
|
+
}
|
|
1423
|
+
function writeStateFile(stateFilePath, state) {
|
|
1424
|
+
const temporaryPath = `${stateFilePath}.${process.pid}.tmp`;
|
|
1425
|
+
try {
|
|
1426
|
+
const dir = path3.dirname(stateFilePath);
|
|
1427
|
+
fs2.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1428
|
+
fs2.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
|
|
1429
|
+
`, { encoding: "utf8", mode: 384 });
|
|
1430
|
+
fs2.renameSync(temporaryPath, stateFilePath);
|
|
1431
|
+
if (process.platform !== "win32")
|
|
1432
|
+
fs2.chmodSync(stateFilePath, 384);
|
|
1433
|
+
} catch {
|
|
1434
|
+
try {
|
|
1435
|
+
if (fs2.existsSync(temporaryPath))
|
|
1436
|
+
fs2.unlinkSync(temporaryPath);
|
|
1437
|
+
} catch {
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
}
|
|
1441
|
+
function truncate(value) {
|
|
1442
|
+
const collapsed = value.replace(/\s+/g, " ").trim();
|
|
1443
|
+
return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
|
|
1361
1444
|
}
|
|
1362
1445
|
}
|
|
1363
1446
|
});
|
|
1364
1447
|
|
|
1365
|
-
// ../packages/tool-kit/out/
|
|
1366
|
-
var
|
|
1367
|
-
"../packages/tool-kit/out/
|
|
1448
|
+
// ../packages/tool-kit/out/outbox.js
|
|
1449
|
+
var require_outbox = __commonJS({
|
|
1450
|
+
"../packages/tool-kit/out/outbox.js"(exports) {
|
|
1368
1451
|
"use strict";
|
|
1369
1452
|
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
1370
1453
|
if (k2 === void 0) k2 = k;
|
|
@@ -1404,354 +1487,189 @@ var require_eventLog = __commonJS({
|
|
|
1404
1487
|
};
|
|
1405
1488
|
}();
|
|
1406
1489
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1407
|
-
exports.
|
|
1408
|
-
exports.
|
|
1409
|
-
exports.
|
|
1410
|
-
exports.
|
|
1411
|
-
exports.
|
|
1412
|
-
exports.
|
|
1413
|
-
exports.
|
|
1414
|
-
|
|
1415
|
-
var
|
|
1416
|
-
var
|
|
1417
|
-
var path2 = __importStar(__require("path"));
|
|
1418
|
-
var agentEvent_1 = require_agentEvent();
|
|
1419
|
-
var credentials_1 = require_credentials();
|
|
1490
|
+
exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = exports.DEFAULT_OUTBOX_MAX_AGE_MS = exports.DEFAULT_OUTBOX_MAX_ENTRIES = exports.OUTBOX_DRAIN_ENV_VAR = void 0;
|
|
1491
|
+
exports.outboxDrainEnabled = outboxDrainEnabled;
|
|
1492
|
+
exports.defaultOutboxFilePath = defaultOutboxFilePath;
|
|
1493
|
+
exports.appendToOutbox = appendToOutbox;
|
|
1494
|
+
exports.readOutboxSummary = readOutboxSummary;
|
|
1495
|
+
exports.claimOutbox = claimOutbox;
|
|
1496
|
+
exports.enforceOutboxBounds = enforceOutboxBounds;
|
|
1497
|
+
var fs2 = __importStar(__require("fs"));
|
|
1498
|
+
var path3 = __importStar(__require("path"));
|
|
1499
|
+
var stateStore_1 = require_stateStore();
|
|
1420
1500
|
var tokenStore_1 = require_tokenStore();
|
|
1421
|
-
exports.
|
|
1422
|
-
exports.
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
return path2.resolve(value);
|
|
1501
|
+
exports.OUTBOX_DRAIN_ENV_VAR = "ASCENDA_OUTBOX_DRAIN";
|
|
1502
|
+
exports.DEFAULT_OUTBOX_MAX_ENTRIES = 1e4;
|
|
1503
|
+
exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
1504
|
+
exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
|
|
1505
|
+
var ORPHANED_CLAIM_AGE_MS = 6e4;
|
|
1506
|
+
var CLAIM_SUFFIX = ".draining";
|
|
1507
|
+
function outboxDrainEnabled(env = process.env) {
|
|
1508
|
+
const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
|
|
1509
|
+
if (value === void 0 || value === "")
|
|
1510
|
+
return true;
|
|
1511
|
+
return !(value === "0" || value === "false" || value === "no" || value === "off");
|
|
1433
1512
|
}
|
|
1434
|
-
function
|
|
1435
|
-
|
|
1513
|
+
function defaultOutboxFilePath(toolInstallationId) {
|
|
1514
|
+
const dir = path3.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
|
|
1515
|
+
return path3.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
|
|
1436
1516
|
}
|
|
1437
|
-
function
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1517
|
+
function appendToOutbox(outboxFilePath, payload, now = /* @__PURE__ */ new Date()) {
|
|
1518
|
+
try {
|
|
1519
|
+
const dir = path3.dirname(outboxFilePath);
|
|
1520
|
+
fs2.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1521
|
+
const entry = { queuedAt: now.toISOString(), payload };
|
|
1522
|
+
fs2.appendFileSync(outboxFilePath, `${JSON.stringify(entry)}
|
|
1523
|
+
`, { encoding: "utf8", mode: 384 });
|
|
1524
|
+
if (process.platform !== "win32")
|
|
1525
|
+
fs2.chmodSync(outboxFilePath, 384);
|
|
1526
|
+
return true;
|
|
1527
|
+
} catch {
|
|
1528
|
+
return false;
|
|
1448
1529
|
}
|
|
1449
|
-
if (options.localOnly)
|
|
1450
|
-
return { path: defaultEventLogPath(), source: "unpaired-default" };
|
|
1451
|
-
return { path: void 0, source: "off" };
|
|
1452
1530
|
}
|
|
1453
|
-
function
|
|
1454
|
-
|
|
1531
|
+
function readOutboxSummary(outboxFilePath) {
|
|
1532
|
+
const files = [outboxFilePath, ...listClaimFiles(outboxFilePath)].filter((file) => fs2.existsSync(file));
|
|
1533
|
+
if (files.length === 0)
|
|
1534
|
+
return void 0;
|
|
1535
|
+
let depth = 0;
|
|
1536
|
+
let unreadableLines = 0;
|
|
1537
|
+
let oldestQueuedAt;
|
|
1538
|
+
for (const file of files) {
|
|
1539
|
+
const { entries, unreadable } = readEntries(file);
|
|
1540
|
+
depth += entries.length;
|
|
1541
|
+
unreadableLines += unreadable;
|
|
1542
|
+
for (const entry of entries) {
|
|
1543
|
+
if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
|
|
1544
|
+
oldestQueuedAt = entry.queuedAt;
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
return { depth, unreadableLines, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} };
|
|
1455
1548
|
}
|
|
1456
|
-
function
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1549
|
+
function claimOutbox(outboxFilePath, now = Date.now()) {
|
|
1550
|
+
const claimPath = `${outboxFilePath}.${process.pid}${CLAIM_SUFFIX}`;
|
|
1551
|
+
const claimed = [];
|
|
1552
|
+
try {
|
|
1553
|
+
fs2.renameSync(outboxFilePath, claimPath);
|
|
1554
|
+
claimed.push(claimPath);
|
|
1555
|
+
} catch {
|
|
1556
|
+
}
|
|
1557
|
+
let orphanIndex = 0;
|
|
1558
|
+
for (const orphan of listClaimFiles(outboxFilePath)) {
|
|
1559
|
+
if (claimed.includes(orphan))
|
|
1560
|
+
continue;
|
|
1561
|
+
try {
|
|
1562
|
+
if (now - fs2.statSync(orphan).mtimeMs < ORPHANED_CLAIM_AGE_MS)
|
|
1563
|
+
continue;
|
|
1564
|
+
const mine = `${claimPath}.${orphanIndex++}`;
|
|
1565
|
+
fs2.renameSync(orphan, mine);
|
|
1566
|
+
claimed.push(mine);
|
|
1567
|
+
} catch {
|
|
1568
|
+
}
|
|
1468
1569
|
}
|
|
1570
|
+
if (claimed.length === 0)
|
|
1571
|
+
return void 0;
|
|
1572
|
+
const entries = [];
|
|
1573
|
+
let unreadable = 0;
|
|
1574
|
+
for (const file of claimed) {
|
|
1575
|
+
const read = readEntries(file);
|
|
1576
|
+
entries.push(...read.entries);
|
|
1577
|
+
unreadable += read.unreadable;
|
|
1578
|
+
}
|
|
1579
|
+
entries.sort((a, b) => a.queuedAt < b.queuedAt ? -1 : a.queuedAt > b.queuedAt ? 1 : 0);
|
|
1580
|
+
let released = false;
|
|
1581
|
+
return {
|
|
1582
|
+
entries,
|
|
1583
|
+
unreadable,
|
|
1584
|
+
release(remainder) {
|
|
1585
|
+
if (released)
|
|
1586
|
+
return;
|
|
1587
|
+
released = true;
|
|
1588
|
+
if (remainder.length > 0) {
|
|
1589
|
+
try {
|
|
1590
|
+
fs2.mkdirSync(path3.dirname(outboxFilePath), { recursive: true, mode: 448 });
|
|
1591
|
+
fs2.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
|
|
1592
|
+
`).join(""), { encoding: "utf8", mode: 384 });
|
|
1593
|
+
if (process.platform !== "win32")
|
|
1594
|
+
fs2.chmodSync(outboxFilePath, 384);
|
|
1595
|
+
} catch {
|
|
1596
|
+
return;
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
for (const file of claimed) {
|
|
1600
|
+
try {
|
|
1601
|
+
fs2.unlinkSync(file);
|
|
1602
|
+
} catch {
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
};
|
|
1469
1607
|
}
|
|
1470
|
-
function
|
|
1471
|
-
const
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1608
|
+
function enforceOutboxBounds(entries, bounds, now = Date.now()) {
|
|
1609
|
+
const reasons = {};
|
|
1610
|
+
let oldestQueuedAt;
|
|
1611
|
+
const cutoff = new Date(now - bounds.maxAgeMs).toISOString();
|
|
1612
|
+
const fresh = [];
|
|
1613
|
+
for (const entry of entries) {
|
|
1614
|
+
if (entry.queuedAt < cutoff) {
|
|
1615
|
+
reasons.age = (reasons.age ?? 0) + 1;
|
|
1616
|
+
if (oldestQueuedAt === void 0 || entry.queuedAt < oldestQueuedAt)
|
|
1617
|
+
oldestQueuedAt = entry.queuedAt;
|
|
1618
|
+
} else {
|
|
1619
|
+
fresh.push(entry);
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
const excess = Math.max(0, fresh.length - bounds.maxEntries);
|
|
1623
|
+
if (excess > 0) {
|
|
1624
|
+
reasons.count = excess;
|
|
1625
|
+
const first = fresh[0]?.queuedAt;
|
|
1626
|
+
if (first !== void 0 && (oldestQueuedAt === void 0 || first < oldestQueuedAt))
|
|
1627
|
+
oldestQueuedAt = first;
|
|
1628
|
+
}
|
|
1629
|
+
const kept = excess > 0 ? fresh.slice(excess) : fresh;
|
|
1630
|
+
const count = Object.values(reasons).reduce((sum, n) => sum + (n ?? 0), 0);
|
|
1631
|
+
return { kept, discarded: { count, reasons, ...oldestQueuedAt !== void 0 ? { oldestQueuedAt } : {} } };
|
|
1475
1632
|
}
|
|
1476
|
-
function
|
|
1633
|
+
function listClaimFiles(outboxFilePath) {
|
|
1634
|
+
const dir = path3.dirname(outboxFilePath);
|
|
1635
|
+
const prefix = `${path3.basename(outboxFilePath)}.`;
|
|
1477
1636
|
try {
|
|
1478
|
-
|
|
1479
|
-
const dir = path2.dirname(logFilePath);
|
|
1480
|
-
fs.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
1481
|
-
const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
|
|
1482
|
-
fs.appendFileSync(logFilePath, `${JSON.stringify(line)}
|
|
1483
|
-
`, { encoding: "utf8", mode: 384 });
|
|
1484
|
-
if (process.platform !== "win32")
|
|
1485
|
-
fs.chmodSync(logFilePath, 384);
|
|
1637
|
+
return fs2.readdirSync(dir).filter((name) => name.startsWith(prefix) && name.includes(CLAIM_SUFFIX)).map((name) => path3.join(dir, name)).sort();
|
|
1486
1638
|
} catch {
|
|
1639
|
+
return [];
|
|
1487
1640
|
}
|
|
1488
1641
|
}
|
|
1489
|
-
function
|
|
1642
|
+
function readEntries(file) {
|
|
1643
|
+
let raw;
|
|
1490
1644
|
try {
|
|
1491
|
-
|
|
1492
|
-
return;
|
|
1493
|
-
fs.renameSync(logFilePath, `${logFilePath}.1`);
|
|
1645
|
+
raw = fs2.readFileSync(file, "utf8");
|
|
1494
1646
|
} catch {
|
|
1647
|
+
return { entries: [], unreadable: 0 };
|
|
1495
1648
|
}
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
// ../packages/tool-kit/out/http.js
|
|
1501
|
-
var require_http = __commonJS({
|
|
1502
|
-
"../packages/tool-kit/out/http.js"(exports) {
|
|
1503
|
-
"use strict";
|
|
1504
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1505
|
-
exports.AscendaApiError = void 0;
|
|
1506
|
-
exports.createPairingSession = createPairingSession;
|
|
1507
|
-
exports.getPairingStatus = getPairingStatus;
|
|
1508
|
-
exports.startStudyJoin = startStudyJoin;
|
|
1509
|
-
exports.getStudyJoinStatus = getStudyJoinStatus;
|
|
1510
|
-
exports.readInitiatives = readInitiatives;
|
|
1511
|
-
exports.readStudyNotices = readStudyNotices;
|
|
1512
|
-
exports.setStudyObjection = setStudyObjection;
|
|
1513
|
-
exports.markStudyNoticeShown = markStudyNoticeShown;
|
|
1514
|
-
exports.renewToolToken = renewToolToken;
|
|
1515
|
-
exports.isRetryableStatus = isRetryableStatus;
|
|
1516
|
-
exports.postToolEvent = postToolEvent;
|
|
1517
|
-
exports.postToolEventsBatch = postToolEventsBatch;
|
|
1518
|
-
exports.parseIngestResponse = parseIngestResponse;
|
|
1519
|
-
var tool_contract_1 = require_out();
|
|
1520
|
-
var AscendaApiError = class extends Error {
|
|
1521
|
-
status;
|
|
1522
|
-
errorCode;
|
|
1523
|
-
constructor(status, errorCode, body) {
|
|
1524
|
-
super(body ?? `Ascenda API error ${status}`);
|
|
1525
|
-
this.status = status;
|
|
1526
|
-
this.errorCode = errorCode;
|
|
1527
|
-
this.name = "AscendaApiError";
|
|
1528
|
-
}
|
|
1529
|
-
};
|
|
1530
|
-
exports.AscendaApiError = AscendaApiError;
|
|
1531
|
-
async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
|
|
1532
|
-
const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
|
|
1533
|
-
method: "POST",
|
|
1534
|
-
headers: { "Content-Type": "application/json" },
|
|
1535
|
-
body: JSON.stringify({ toolInstallationId, toolType, displayName })
|
|
1536
|
-
});
|
|
1537
|
-
if (!response.ok)
|
|
1538
|
-
throw new AscendaApiError(response.status, void 0, await response.text());
|
|
1539
|
-
return await response.json();
|
|
1540
|
-
}
|
|
1541
|
-
async function getPairingStatus(apiBaseUrl, pairingSessionId) {
|
|
1542
|
-
const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
|
|
1543
|
-
method: "GET",
|
|
1544
|
-
headers: { Accept: "application/json" }
|
|
1545
|
-
});
|
|
1546
|
-
if (!response.ok)
|
|
1547
|
-
throw new AscendaApiError(response.status, void 0, await response.text());
|
|
1548
|
-
return await response.json();
|
|
1549
|
-
}
|
|
1550
|
-
async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
|
|
1551
|
-
const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
|
|
1552
|
-
method: "POST",
|
|
1553
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
|
|
1554
|
-
body: JSON.stringify({ joinCode, mode })
|
|
1555
|
-
});
|
|
1556
|
-
if (!response.ok)
|
|
1557
|
-
throw await apiError(response);
|
|
1558
|
-
return await response.json();
|
|
1559
|
-
}
|
|
1560
|
-
async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
|
|
1561
|
-
const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
|
|
1562
|
-
method: "GET",
|
|
1563
|
-
headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
|
|
1564
|
-
});
|
|
1565
|
-
if (!response.ok)
|
|
1566
|
-
throw await apiError(response);
|
|
1567
|
-
return await response.json();
|
|
1568
|
-
}
|
|
1569
|
-
async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
|
|
1570
|
-
let response;
|
|
1571
|
-
try {
|
|
1572
|
-
response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
|
|
1573
|
-
method: "GET",
|
|
1574
|
-
headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
|
|
1575
|
-
signal
|
|
1576
|
-
});
|
|
1577
|
-
} catch (error) {
|
|
1578
|
-
return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
|
|
1579
|
-
}
|
|
1580
|
-
if (response.status === 401)
|
|
1581
|
-
return { kind: "rejected", httpStatus: 401 };
|
|
1582
|
-
if (!response.ok)
|
|
1583
|
-
return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
|
|
1584
|
-
let body;
|
|
1585
|
-
try {
|
|
1586
|
-
body = await response.json();
|
|
1587
|
-
} catch {
|
|
1588
|
-
return { kind: "failed", reason: "the reply was not readable" };
|
|
1589
|
-
}
|
|
1590
|
-
if (!Array.isArray(body))
|
|
1591
|
-
return { kind: "failed", reason: "the reply was not a list" };
|
|
1592
|
-
return { kind: "ok", initiatives: body };
|
|
1593
|
-
}
|
|
1594
|
-
async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
|
|
1595
|
-
let response;
|
|
1596
|
-
try {
|
|
1597
|
-
response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
|
|
1598
|
-
method: "GET",
|
|
1599
|
-
headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
|
|
1600
|
-
signal
|
|
1601
|
-
});
|
|
1602
|
-
} catch (error) {
|
|
1603
|
-
return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
|
|
1604
|
-
}
|
|
1605
|
-
if (response.status === 404)
|
|
1606
|
-
return { kind: "absent" };
|
|
1607
|
-
if (response.status === 401)
|
|
1608
|
-
return { kind: "rejected", httpStatus: 401 };
|
|
1609
|
-
if (!response.ok)
|
|
1610
|
-
return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
|
|
1611
|
-
let body;
|
|
1612
|
-
try {
|
|
1613
|
-
body = await response.json();
|
|
1614
|
-
} catch {
|
|
1615
|
-
return { kind: "absent" };
|
|
1616
|
-
}
|
|
1617
|
-
if (!Array.isArray(body))
|
|
1618
|
-
return { kind: "absent" };
|
|
1619
|
-
return { kind: "ok", notices: body };
|
|
1620
|
-
}
|
|
1621
|
-
async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
|
|
1622
|
-
const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
|
|
1623
|
-
method: objected ? "POST" : "DELETE",
|
|
1624
|
-
headers: { Authorization: `Bearer ${eventWriteToken}` }
|
|
1625
|
-
});
|
|
1626
|
-
if (!response.ok)
|
|
1627
|
-
throw await apiError(response);
|
|
1628
|
-
}
|
|
1629
|
-
async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
|
|
1630
|
-
try {
|
|
1631
|
-
const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
|
|
1632
|
-
method: "POST",
|
|
1633
|
-
headers: { Authorization: `Bearer ${eventWriteToken}` },
|
|
1634
|
-
signal
|
|
1635
|
-
});
|
|
1636
|
-
return response.ok;
|
|
1637
|
-
} catch {
|
|
1638
|
-
return false;
|
|
1639
|
-
}
|
|
1640
|
-
}
|
|
1641
|
-
async function apiError(response) {
|
|
1642
|
-
const body = await response.text();
|
|
1643
|
-
let errorCode;
|
|
1644
|
-
try {
|
|
1645
|
-
const parsed = JSON.parse(body);
|
|
1646
|
-
errorCode = parsed.code ?? parsed.error;
|
|
1647
|
-
} catch {
|
|
1648
|
-
errorCode = void 0;
|
|
1649
|
-
}
|
|
1650
|
-
return new AscendaApiError(response.status, errorCode, body);
|
|
1651
|
-
}
|
|
1652
|
-
async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
|
|
1653
|
-
const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
|
|
1654
|
-
method: "POST",
|
|
1655
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
|
|
1656
|
-
signal
|
|
1657
|
-
});
|
|
1658
|
-
if (response.status === 401)
|
|
1659
|
-
return null;
|
|
1660
|
-
if (!response.ok)
|
|
1661
|
-
throw new AscendaApiError(response.status, void 0, await response.text());
|
|
1662
|
-
return await response.json();
|
|
1663
|
-
}
|
|
1664
|
-
function isDeliveredStatus(value) {
|
|
1665
|
-
return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
|
|
1666
|
-
}
|
|
1667
|
-
function readSuccessBody(body) {
|
|
1668
|
-
let parsed;
|
|
1669
|
-
try {
|
|
1670
|
-
parsed = JSON.parse(body);
|
|
1671
|
-
} catch {
|
|
1672
|
-
return { duplicates: 0 };
|
|
1673
|
-
}
|
|
1674
|
-
if (!parsed || typeof parsed !== "object")
|
|
1675
|
-
return { duplicates: 0 };
|
|
1676
|
-
const single = parsed.status;
|
|
1677
|
-
if (isDeliveredStatus(single))
|
|
1678
|
-
return { duplicates: single === "duplicate" ? 1 : 0 };
|
|
1679
|
-
const raw = parsed.results;
|
|
1680
|
-
if (!Array.isArray(raw))
|
|
1681
|
-
return { duplicates: 0 };
|
|
1682
|
-
const results = [];
|
|
1683
|
-
for (const item of raw) {
|
|
1684
|
-
if (!item || typeof item !== "object")
|
|
1685
|
-
continue;
|
|
1686
|
-
const { index, status, reason } = item;
|
|
1687
|
-
if (typeof index !== "number" || typeof status !== "string")
|
|
1649
|
+
const entries = [];
|
|
1650
|
+
let unreadable = 0;
|
|
1651
|
+
for (const line of raw.split("\n")) {
|
|
1652
|
+
if (!line.trim())
|
|
1688
1653
|
continue;
|
|
1689
|
-
results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
|
|
1690
|
-
}
|
|
1691
|
-
return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
|
|
1692
|
-
}
|
|
1693
|
-
function isRetryableStatus(status) {
|
|
1694
|
-
return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
|
|
1695
|
-
}
|
|
1696
|
-
async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
|
|
1697
|
-
return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
|
|
1698
|
-
}
|
|
1699
|
-
async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
|
|
1700
|
-
return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
|
|
1701
|
-
}
|
|
1702
|
-
async function sendIngest(url, eventWriteToken, body, signal) {
|
|
1703
|
-
try {
|
|
1704
|
-
const response = await fetch(url, {
|
|
1705
|
-
method: "POST",
|
|
1706
|
-
headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
|
|
1707
|
-
body,
|
|
1708
|
-
signal
|
|
1709
|
-
});
|
|
1710
|
-
return parseIngestResponse(response);
|
|
1711
|
-
} catch (error) {
|
|
1712
|
-
return {
|
|
1713
|
-
result: "transport_error",
|
|
1714
|
-
detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
|
|
1715
|
-
};
|
|
1716
|
-
}
|
|
1717
|
-
}
|
|
1718
|
-
async function parseIngestResponse(response) {
|
|
1719
|
-
if (response.ok) {
|
|
1720
|
-
const outcome = { result: "accepted", httpStatus: response.status };
|
|
1721
|
-
let read = { duplicates: 0 };
|
|
1722
1654
|
try {
|
|
1723
|
-
|
|
1655
|
+
const parsed = JSON.parse(line);
|
|
1656
|
+
if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
|
|
1657
|
+
unreadable += 1;
|
|
1658
|
+
continue;
|
|
1659
|
+
}
|
|
1660
|
+
entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
|
|
1724
1661
|
} catch {
|
|
1725
|
-
|
|
1662
|
+
unreadable += 1;
|
|
1726
1663
|
}
|
|
1727
|
-
return {
|
|
1728
|
-
...outcome,
|
|
1729
|
-
...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
|
|
1730
|
-
...read.results !== void 0 ? { results: read.results } : {}
|
|
1731
|
-
};
|
|
1732
|
-
}
|
|
1733
|
-
const body = await response.text();
|
|
1734
|
-
let errorCode;
|
|
1735
|
-
try {
|
|
1736
|
-
errorCode = JSON.parse(body).error;
|
|
1737
|
-
} catch {
|
|
1738
|
-
errorCode = void 0;
|
|
1739
1664
|
}
|
|
1740
|
-
|
|
1741
|
-
if (response.status === 401)
|
|
1742
|
-
return { ...base, result: "auth_failed" };
|
|
1743
|
-
if (response.status === 403 && errorCode === "consent_missing_or_expired")
|
|
1744
|
-
return { ...base, result: "consent_missing" };
|
|
1745
|
-
if (response.status === 400 || response.status === 422)
|
|
1746
|
-
return { ...base, result: "validation_failed" };
|
|
1747
|
-
return { ...base, result: "transport_error" };
|
|
1665
|
+
return { entries, unreadable };
|
|
1748
1666
|
}
|
|
1749
1667
|
}
|
|
1750
1668
|
});
|
|
1751
1669
|
|
|
1752
|
-
// ../packages/tool-kit/out/
|
|
1753
|
-
var
|
|
1754
|
-
"../packages/tool-kit/out/
|
|
1670
|
+
// ../packages/tool-kit/out/backgroundDelivery.js
|
|
1671
|
+
var require_backgroundDelivery = __commonJS({
|
|
1672
|
+
"../packages/tool-kit/out/backgroundDelivery.js"(exports) {
|
|
1755
1673
|
"use strict";
|
|
1756
1674
|
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
1757
1675
|
if (k2 === void 0) k2 = k;
|
|
@@ -1791,124 +1709,270 @@ var require_stateStore = __commonJS({
|
|
|
1791
1709
|
};
|
|
1792
1710
|
}();
|
|
1793
1711
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1794
|
-
exports.
|
|
1795
|
-
exports.
|
|
1796
|
-
exports.
|
|
1797
|
-
exports.
|
|
1798
|
-
exports.
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
return
|
|
1712
|
+
exports.FLUSH_LOCK_FRESH_MS = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = void 0;
|
|
1713
|
+
exports.hookDeliveryInline = hookDeliveryInline;
|
|
1714
|
+
exports.flushLockPath = flushLockPath;
|
|
1715
|
+
exports.startBackgroundFlush = startBackgroundFlush;
|
|
1716
|
+
exports.runOutboxFlush = runOutboxFlush;
|
|
1717
|
+
var fs2 = __importStar(__require("fs"));
|
|
1718
|
+
var child_process_1 = __require("child_process");
|
|
1719
|
+
var outbox_1 = require_outbox();
|
|
1720
|
+
exports.HOOK_DELIVERY_ENV_VAR = "ASCENDA_HOOK_DELIVERY";
|
|
1721
|
+
exports.OUTBOX_FLUSH_COMMAND = "__flush-outbox";
|
|
1722
|
+
exports.FLUSH_LOCK_FRESH_MS = 2e4;
|
|
1723
|
+
var FLUSH_MAX_PASSES = 20;
|
|
1724
|
+
var FLUSH_MAX_RUN_MS = 6e4;
|
|
1725
|
+
function hookDeliveryInline(env = process.env) {
|
|
1726
|
+
return env[exports.HOOK_DELIVERY_ENV_VAR]?.trim().toLowerCase() === "inline" || !(0, outbox_1.outboxDrainEnabled)(env);
|
|
1727
|
+
}
|
|
1728
|
+
function flushLockPath(outboxFilePath) {
|
|
1729
|
+
return `${outboxFilePath}.flushing`;
|
|
1730
|
+
}
|
|
1731
|
+
function lockIsFresh(lockPath, now) {
|
|
1732
|
+
try {
|
|
1733
|
+
return now - fs2.statSync(lockPath).mtimeMs < exports.FLUSH_LOCK_FRESH_MS;
|
|
1734
|
+
} catch {
|
|
1735
|
+
return false;
|
|
1736
|
+
}
|
|
1809
1737
|
}
|
|
1810
|
-
function
|
|
1811
|
-
|
|
1738
|
+
function touchLock(lockPath) {
|
|
1739
|
+
try {
|
|
1740
|
+
fs2.writeFileSync(lockPath, `${process.pid}
|
|
1741
|
+
`, { encoding: "utf8", mode: 384 });
|
|
1742
|
+
} catch {
|
|
1743
|
+
}
|
|
1812
1744
|
}
|
|
1813
|
-
function
|
|
1814
|
-
|
|
1745
|
+
function removeLock(lockPath) {
|
|
1746
|
+
try {
|
|
1747
|
+
fs2.unlinkSync(lockPath);
|
|
1748
|
+
} catch {
|
|
1749
|
+
}
|
|
1815
1750
|
}
|
|
1816
|
-
function
|
|
1751
|
+
function outboxHasEntries(outboxFilePath) {
|
|
1817
1752
|
try {
|
|
1818
|
-
|
|
1819
|
-
return void 0;
|
|
1820
|
-
const raw = fs.readFileSync(stateFilePath, "utf8").trim();
|
|
1821
|
-
if (!raw)
|
|
1822
|
-
return void 0;
|
|
1823
|
-
const parsed = JSON.parse(raw);
|
|
1824
|
-
if (!parsed || typeof parsed !== "object")
|
|
1825
|
-
return void 0;
|
|
1826
|
-
return parsed;
|
|
1753
|
+
return fs2.statSync(outboxFilePath).size > 0;
|
|
1827
1754
|
} catch {
|
|
1828
|
-
return
|
|
1755
|
+
return false;
|
|
1829
1756
|
}
|
|
1830
1757
|
}
|
|
1831
|
-
function
|
|
1832
|
-
const
|
|
1833
|
-
const
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
return next;
|
|
1758
|
+
function startBackgroundFlush(options) {
|
|
1759
|
+
const lockPath = flushLockPath(options.outboxFilePath);
|
|
1760
|
+
const now = options.now ?? Date.now();
|
|
1761
|
+
if (lockIsFresh(lockPath, now))
|
|
1762
|
+
return false;
|
|
1763
|
+
const script = options.script ?? process.argv[1];
|
|
1764
|
+
if (!script)
|
|
1765
|
+
return false;
|
|
1766
|
+
try {
|
|
1767
|
+
touchLock(lockPath);
|
|
1768
|
+
const child = (0, child_process_1.spawn)(process.execPath, [script, exports.OUTBOX_FLUSH_COMMAND], {
|
|
1769
|
+
detached: true,
|
|
1770
|
+
stdio: "ignore",
|
|
1771
|
+
windowsHide: true,
|
|
1772
|
+
env: process.env
|
|
1773
|
+
});
|
|
1774
|
+
child.on("error", () => removeLock(lockPath));
|
|
1775
|
+
child.unref();
|
|
1776
|
+
return true;
|
|
1777
|
+
} catch {
|
|
1778
|
+
removeLock(lockPath);
|
|
1779
|
+
return false;
|
|
1780
|
+
}
|
|
1855
1781
|
}
|
|
1856
|
-
function
|
|
1857
|
-
const
|
|
1858
|
-
const
|
|
1859
|
-
const
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1782
|
+
async function runOutboxFlush(sender, now = Date.now) {
|
|
1783
|
+
const outboxFilePath = sender.outboxFilePath();
|
|
1784
|
+
const lockPath = flushLockPath(outboxFilePath);
|
|
1785
|
+
const started = now();
|
|
1786
|
+
let last;
|
|
1787
|
+
let passes = 0;
|
|
1788
|
+
const drain = async () => {
|
|
1789
|
+
while (passes < FLUSH_MAX_PASSES && now() - started < FLUSH_MAX_RUN_MS) {
|
|
1790
|
+
passes += 1;
|
|
1791
|
+
touchLock(lockPath);
|
|
1792
|
+
last = await sender.flushOutbox();
|
|
1793
|
+
if (!last || last.found === 0 || last.halted || !last.sendEnabled)
|
|
1794
|
+
return;
|
|
1795
|
+
if (last.delivered === 0 && last.discarded === 0)
|
|
1796
|
+
return;
|
|
1869
1797
|
}
|
|
1870
1798
|
};
|
|
1871
|
-
|
|
1872
|
-
|
|
1799
|
+
try {
|
|
1800
|
+
await drain();
|
|
1801
|
+
removeLock(lockPath);
|
|
1802
|
+
if (!last?.halted && last?.sendEnabled !== false && outboxHasEntries(outboxFilePath)) {
|
|
1803
|
+
touchLock(lockPath);
|
|
1804
|
+
await drain();
|
|
1805
|
+
removeLock(lockPath);
|
|
1806
|
+
}
|
|
1807
|
+
} catch {
|
|
1808
|
+
removeLock(lockPath);
|
|
1809
|
+
}
|
|
1810
|
+
return last;
|
|
1873
1811
|
}
|
|
1874
|
-
|
|
1875
|
-
|
|
1812
|
+
}
|
|
1813
|
+
});
|
|
1814
|
+
|
|
1815
|
+
// ../packages/agent-events/out/index.js
|
|
1816
|
+
var require_out2 = __commonJS({
|
|
1817
|
+
"../packages/agent-events/out/index.js"(exports) {
|
|
1818
|
+
"use strict";
|
|
1819
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1820
|
+
exports.KNOWN_AGENTS = exports.WAIT_REASONS = exports.VCS_ACTIONS = exports.AGENT_EVENT_KINDS = exports.AGENT_EVENT_SCHEMA = void 0;
|
|
1821
|
+
exports.isAgentEventV0 = isAgentEventV0;
|
|
1822
|
+
exports.parseEventLogLine = parseEventLogLine;
|
|
1823
|
+
exports.normaliseKind = normaliseKind;
|
|
1824
|
+
exports.AGENT_EVENT_SCHEMA = "agent-event/v0";
|
|
1825
|
+
exports.AGENT_EVENT_KINDS = [
|
|
1826
|
+
"session.started",
|
|
1827
|
+
"session.ended",
|
|
1828
|
+
"prompt.submitted",
|
|
1829
|
+
"tool.started",
|
|
1830
|
+
"tool.completed",
|
|
1831
|
+
"tool.failed",
|
|
1832
|
+
"turn.completed",
|
|
1833
|
+
"agent.waiting",
|
|
1834
|
+
"permission.requested",
|
|
1835
|
+
"permission.denied",
|
|
1836
|
+
"context.compacted",
|
|
1837
|
+
"subagent.started",
|
|
1838
|
+
"subagent.stopped",
|
|
1839
|
+
"pull_request.opened",
|
|
1840
|
+
"pull_request.closed",
|
|
1841
|
+
"pull_request.merged",
|
|
1842
|
+
"other"
|
|
1843
|
+
];
|
|
1844
|
+
exports.VCS_ACTIONS = ["commit", "push", "pr_created", "pr_merged"];
|
|
1845
|
+
exports.WAIT_REASONS = ["permission", "idle", "input", "other"];
|
|
1846
|
+
exports.KNOWN_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "windsurf", "vscode"];
|
|
1847
|
+
function isAgentEventV0(value) {
|
|
1848
|
+
if (!value || typeof value !== "object")
|
|
1876
1849
|
return false;
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
function markFailureNotified(stateFilePath, state) {
|
|
1880
|
-
if (!state.failingSince)
|
|
1881
|
-
return;
|
|
1882
|
-
writeStateFile(stateFilePath, { ...state, notifiedFailingSince: state.failingSince });
|
|
1850
|
+
const e = value;
|
|
1851
|
+
return e.schema === exports.AGENT_EVENT_SCHEMA && typeof e.id === "string" && e.id.length > 0 && typeof e.time === "string" && !Number.isNaN(Date.parse(e.time)) && typeof e.agent === "string" && e.agent.length > 0 && typeof e.kind === "string";
|
|
1883
1852
|
}
|
|
1884
|
-
function
|
|
1885
|
-
|
|
1853
|
+
function parseEventLogLine(line) {
|
|
1854
|
+
if (!line.trim())
|
|
1855
|
+
return void 0;
|
|
1886
1856
|
try {
|
|
1887
|
-
const
|
|
1888
|
-
|
|
1889
|
-
fs.writeFileSync(temporaryPath, `${JSON.stringify(state, null, 2)}
|
|
1890
|
-
`, { encoding: "utf8", mode: 384 });
|
|
1891
|
-
fs.renameSync(temporaryPath, stateFilePath);
|
|
1892
|
-
if (process.platform !== "win32")
|
|
1893
|
-
fs.chmodSync(stateFilePath, 384);
|
|
1857
|
+
const parsed = JSON.parse(line);
|
|
1858
|
+
return isAgentEventV0(parsed?.event) ? parsed.event : void 0;
|
|
1894
1859
|
} catch {
|
|
1895
|
-
|
|
1896
|
-
if (fs.existsSync(temporaryPath))
|
|
1897
|
-
fs.unlinkSync(temporaryPath);
|
|
1898
|
-
} catch {
|
|
1899
|
-
}
|
|
1860
|
+
return void 0;
|
|
1900
1861
|
}
|
|
1901
1862
|
}
|
|
1902
|
-
function
|
|
1903
|
-
|
|
1904
|
-
return collapsed.length > 200 ? `${collapsed.slice(0, 197)}...` : collapsed;
|
|
1863
|
+
function normaliseKind(kind) {
|
|
1864
|
+
return exports.AGENT_EVENT_KINDS.includes(kind) ? kind : "other";
|
|
1905
1865
|
}
|
|
1906
1866
|
}
|
|
1907
1867
|
});
|
|
1908
1868
|
|
|
1909
|
-
// ../packages/tool-kit/out/
|
|
1910
|
-
var
|
|
1911
|
-
"../packages/tool-kit/out/
|
|
1869
|
+
// ../packages/tool-kit/out/agentEvent.js
|
|
1870
|
+
var require_agentEvent = __commonJS({
|
|
1871
|
+
"../packages/tool-kit/out/agentEvent.js"(exports) {
|
|
1872
|
+
"use strict";
|
|
1873
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1874
|
+
exports.toAgentEvent = toAgentEvent;
|
|
1875
|
+
var agent_events_1 = require_out2();
|
|
1876
|
+
var KIND_BY_TYPE = {
|
|
1877
|
+
create_focus_session: "session.started",
|
|
1878
|
+
recovery_offline_period: "session.ended",
|
|
1879
|
+
ai_prompt_submitted: "prompt.submitted",
|
|
1880
|
+
ai_tool_call_started: "tool.started",
|
|
1881
|
+
ai_tool_call_completed: "tool.completed",
|
|
1882
|
+
ai_file_write: "tool.completed",
|
|
1883
|
+
ai_file_edit: "tool.completed",
|
|
1884
|
+
editor_verification_activity: "tool.completed",
|
|
1885
|
+
ai_tool_call_failed: "tool.failed",
|
|
1886
|
+
compile_error: "tool.failed",
|
|
1887
|
+
tool_failure: "tool.failed",
|
|
1888
|
+
ai_turn_completed: "turn.completed",
|
|
1889
|
+
supervision_interruption: "agent.waiting",
|
|
1890
|
+
permission_requested: "permission.requested",
|
|
1891
|
+
permission_denied: "permission.denied",
|
|
1892
|
+
context_compression_manual: "context.compacted",
|
|
1893
|
+
context_compression_auto: "context.compacted",
|
|
1894
|
+
subagent_started: "subagent.started",
|
|
1895
|
+
subagent_stopped: "subagent.stopped",
|
|
1896
|
+
pull_request_opened: "pull_request.opened",
|
|
1897
|
+
pull_request_closed: "pull_request.closed",
|
|
1898
|
+
pull_request_merged: "pull_request.merged"
|
|
1899
|
+
};
|
|
1900
|
+
function agentOf(payload) {
|
|
1901
|
+
const host = stringField(payload.metadata?.host);
|
|
1902
|
+
if (host)
|
|
1903
|
+
return host;
|
|
1904
|
+
return payload.source === "vscode_extension" ? "vscode" : payload.source;
|
|
1905
|
+
}
|
|
1906
|
+
function vcsActionOf(metadata) {
|
|
1907
|
+
const milestone = stringField(metadata.milestoneKind);
|
|
1908
|
+
if (milestone === "pr_opened")
|
|
1909
|
+
return "pr_created";
|
|
1910
|
+
if (milestone === "pr_merged")
|
|
1911
|
+
return "pr_merged";
|
|
1912
|
+
const git = stringField(metadata.gitAction);
|
|
1913
|
+
return git === "commit" || git === "push" ? git : void 0;
|
|
1914
|
+
}
|
|
1915
|
+
function waitReasonOf(metadata) {
|
|
1916
|
+
switch (stringField(metadata.interruptionKind)) {
|
|
1917
|
+
case "permission_request":
|
|
1918
|
+
return "permission";
|
|
1919
|
+
case "input_request":
|
|
1920
|
+
return "input";
|
|
1921
|
+
case "idle_prompt":
|
|
1922
|
+
return "idle";
|
|
1923
|
+
case void 0:
|
|
1924
|
+
return void 0;
|
|
1925
|
+
default:
|
|
1926
|
+
return "other";
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
function stringField(value) {
|
|
1930
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
1931
|
+
}
|
|
1932
|
+
function toAgentEvent(payload) {
|
|
1933
|
+
const metadata = payload.metadata ?? {};
|
|
1934
|
+
const kind = KIND_BY_TYPE[payload.eventType] ?? "other";
|
|
1935
|
+
const tool = kind.startsWith("tool.") || kind.startsWith("permission.") ? stringField(metadata.toolName) : void 0;
|
|
1936
|
+
const outcome = stringField(metadata.outcome);
|
|
1937
|
+
const vcsAction = kind === "tool.completed" ? vcsActionOf(metadata) : void 0;
|
|
1938
|
+
const reason = kind === "agent.waiting" ? waitReasonOf(metadata) : void 0;
|
|
1939
|
+
const model = kind === "session.started" ? stringField(metadata.modelId) : void 0;
|
|
1940
|
+
return {
|
|
1941
|
+
schema: agent_events_1.AGENT_EVENT_SCHEMA,
|
|
1942
|
+
id: payload.idempotencyKey ?? `${payload.toolInstallationId}:${payload.occurredAt}:${payload.eventType}`,
|
|
1943
|
+
time: payload.occurredAt,
|
|
1944
|
+
// `+ 0` turns the -0 a UTC machine computes into 0, which is what JSON
|
|
1945
|
+
// writes anyway; without it the event in memory and the one on disk differ.
|
|
1946
|
+
...typeof payload.utcOffsetMinutes === "number" ? { utcOffsetMinutes: payload.utcOffsetMinutes + 0 } : {},
|
|
1947
|
+
agent: agentOf(payload),
|
|
1948
|
+
kind,
|
|
1949
|
+
...stringField(payload.sessionId) ? { sessionId: payload.sessionId } : {},
|
|
1950
|
+
...stringField(metadata.subagentId) ? { subagentId: metadata.subagentId } : {},
|
|
1951
|
+
...tool ? { tool } : {},
|
|
1952
|
+
...outcome && outcome !== "unknown" ? { outcome } : {},
|
|
1953
|
+
...stringField(metadata.durationBucket) ? { durationBucket: metadata.durationBucket } : {},
|
|
1954
|
+
...stringField(payload.projectHash) ? { projectHash: payload.projectHash } : {},
|
|
1955
|
+
...stringField(metadata.repoKey) ? { repoKey: metadata.repoKey } : {},
|
|
1956
|
+
...stringField(metadata.branchKey) ? { branchKey: metadata.branchKey } : {},
|
|
1957
|
+
...stringField(metadata.autonomyMode) ? { permissionMode: metadata.autonomyMode } : {},
|
|
1958
|
+
...stringField(metadata.headRepoKey) ? { headRepoKey: metadata.headRepoKey } : {},
|
|
1959
|
+
...stringField(metadata.prCreatedAt) ? { prCreatedAt: metadata.prCreatedAt } : {},
|
|
1960
|
+
...stringField(metadata.prClosedAt) ? { prClosedAt: metadata.prClosedAt } : {},
|
|
1961
|
+
...stringField(metadata.prMergedAt) ? { prMergedAt: metadata.prMergedAt } : {},
|
|
1962
|
+
...stringField(metadata.promptId) ? { promptId: metadata.promptId } : {},
|
|
1963
|
+
...vcsAction ? { vcsAction } : {},
|
|
1964
|
+
...reason ? { reason } : {},
|
|
1965
|
+
...model ? { model } : {},
|
|
1966
|
+
...stringField(metadata.collectorVersion) ? { collectorVersion: metadata.collectorVersion } : {},
|
|
1967
|
+
sourceType: payload.eventType
|
|
1968
|
+
};
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
});
|
|
1972
|
+
|
|
1973
|
+
// ../packages/tool-kit/out/credentials.js
|
|
1974
|
+
var require_credentials = __commonJS({
|
|
1975
|
+
"../packages/tool-kit/out/credentials.js"(exports) {
|
|
1912
1976
|
"use strict";
|
|
1913
1977
|
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
1914
1978
|
if (k2 === void 0) k2 = k;
|
|
@@ -1948,182 +2012,482 @@ var require_outbox = __commonJS({
|
|
|
1948
2012
|
};
|
|
1949
2013
|
}();
|
|
1950
2014
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
1951
|
-
exports.
|
|
1952
|
-
exports.
|
|
1953
|
-
exports.
|
|
1954
|
-
exports.
|
|
1955
|
-
exports.
|
|
1956
|
-
exports.
|
|
1957
|
-
exports.
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
2015
|
+
exports.credentialsFilePath = credentialsFilePath;
|
|
2016
|
+
exports.readMachineCredentials = readMachineCredentials;
|
|
2017
|
+
exports.writeMachineCredentials = writeMachineCredentials;
|
|
2018
|
+
exports.writeTopLevelCredentials = writeTopLevelCredentials;
|
|
2019
|
+
exports.writeRepoKeysSetting = writeRepoKeysSetting;
|
|
2020
|
+
exports.writeEventLogSetting = writeEventLogSetting;
|
|
2021
|
+
exports.isLocalOnlyHostInstall = isLocalOnlyHostInstall;
|
|
2022
|
+
exports.readHostCredentials = readHostCredentials;
|
|
2023
|
+
exports.writeHostCredentials = writeHostCredentials;
|
|
2024
|
+
exports.removeHostCredentials = removeHostCredentials;
|
|
2025
|
+
var fs2 = __importStar(__require("fs"));
|
|
2026
|
+
var path3 = __importStar(__require("path"));
|
|
1961
2027
|
var tokenStore_1 = require_tokenStore();
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
exports.DEFAULT_OUTBOX_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
1965
|
-
exports.DEFAULT_OUTBOX_DRAIN_BATCH_SIZE = 100;
|
|
1966
|
-
var ORPHANED_CLAIM_AGE_MS = 6e4;
|
|
1967
|
-
var CLAIM_SUFFIX = ".draining";
|
|
1968
|
-
function outboxDrainEnabled(env = process.env) {
|
|
1969
|
-
const value = env[exports.OUTBOX_DRAIN_ENV_VAR]?.trim().toLowerCase();
|
|
1970
|
-
if (value === void 0 || value === "")
|
|
1971
|
-
return true;
|
|
1972
|
-
return !(value === "0" || value === "false" || value === "no" || value === "off");
|
|
1973
|
-
}
|
|
1974
|
-
function defaultOutboxFilePath(toolInstallationId) {
|
|
1975
|
-
const dir = path2.dirname((0, stateStore_1.defaultStateFilePath)(toolInstallationId));
|
|
1976
|
-
return path2.join(dir, `${(0, tokenStore_1.sanitizeFilePart)(toolInstallationId)}.outbox.jsonl`);
|
|
2028
|
+
function credentialsFilePath() {
|
|
2029
|
+
return path3.join((0, tokenStore_1.ascendaHome)(), "credentials.json");
|
|
1977
2030
|
}
|
|
1978
|
-
function
|
|
2031
|
+
function readMachineCredentials() {
|
|
1979
2032
|
try {
|
|
1980
|
-
const
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
return true;
|
|
2033
|
+
const raw = fs2.readFileSync(credentialsFilePath(), "utf8").trim();
|
|
2034
|
+
if (!raw)
|
|
2035
|
+
return void 0;
|
|
2036
|
+
const parsed = JSON.parse(raw);
|
|
2037
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
2038
|
+
return void 0;
|
|
2039
|
+
return parsed;
|
|
1988
2040
|
} catch {
|
|
1989
|
-
return
|
|
2041
|
+
return void 0;
|
|
1990
2042
|
}
|
|
1991
2043
|
}
|
|
1992
|
-
function
|
|
1993
|
-
const
|
|
1994
|
-
|
|
2044
|
+
function writeMachineCredentials(credentials) {
|
|
2045
|
+
const file = credentialsFilePath();
|
|
2046
|
+
fs2.mkdirSync(path3.dirname(file), { recursive: true, mode: 448 });
|
|
2047
|
+
fs2.writeFileSync(file, `${JSON.stringify(credentials, null, 2)}
|
|
2048
|
+
`, { encoding: "utf8", mode: 384 });
|
|
2049
|
+
if (process.platform !== "win32") {
|
|
2050
|
+
fs2.chmodSync(path3.dirname(file), 448);
|
|
2051
|
+
fs2.chmodSync(file, 384);
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
function writeTopLevelCredentials(credentials) {
|
|
2055
|
+
const existing = readMachineCredentials();
|
|
2056
|
+
const eventLogPath = credentials.eventLogPath ?? existing?.eventLogPath;
|
|
2057
|
+
const repoKeys = credentials.repoKeys ?? existing?.repoKeys;
|
|
2058
|
+
writeMachineCredentials({
|
|
2059
|
+
...credentials,
|
|
2060
|
+
...eventLogPath ? { eventLogPath } : {},
|
|
2061
|
+
...repoKeys === false ? { repoKeys } : {},
|
|
2062
|
+
...existing?.tools ? { tools: existing.tools } : {}
|
|
2063
|
+
});
|
|
2064
|
+
}
|
|
2065
|
+
function writeRepoKeysSetting(on) {
|
|
2066
|
+
const existing = readMachineCredentials() ?? {};
|
|
2067
|
+
const { repoKeys: _dropped, ...rest } = existing;
|
|
2068
|
+
writeMachineCredentials(on ? rest : { ...rest, repoKeys: false });
|
|
2069
|
+
}
|
|
2070
|
+
function writeEventLogSetting(value) {
|
|
2071
|
+
const existing = readMachineCredentials() ?? {};
|
|
2072
|
+
writeMachineCredentials({ ...existing, eventLogPath: value });
|
|
2073
|
+
}
|
|
2074
|
+
function isLocalOnlyHostInstall(host, hasToken) {
|
|
2075
|
+
const credentials = readHostCredentials(host);
|
|
2076
|
+
if (!credentials?.localOnly)
|
|
2077
|
+
return false;
|
|
2078
|
+
if (process.env.ASCENDA_EVENT_WRITE_TOKEN)
|
|
2079
|
+
return false;
|
|
2080
|
+
return !(credentials.toolInstallationId && hasToken(credentials.toolInstallationId));
|
|
2081
|
+
}
|
|
2082
|
+
function readHostCredentials(host) {
|
|
2083
|
+
const entry = readMachineCredentials()?.tools?.[host];
|
|
2084
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
1995
2085
|
return void 0;
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2086
|
+
return entry;
|
|
2087
|
+
}
|
|
2088
|
+
function writeHostCredentials(host, credentials) {
|
|
2089
|
+
const existing = readMachineCredentials() ?? {};
|
|
2090
|
+
writeMachineCredentials({ ...existing, tools: { ...existing.tools ?? {}, [host]: credentials } });
|
|
2091
|
+
}
|
|
2092
|
+
function removeHostCredentials(host) {
|
|
2093
|
+
const existing = readMachineCredentials();
|
|
2094
|
+
if (!existing?.tools || !(host in existing.tools))
|
|
2095
|
+
return;
|
|
2096
|
+
const tools = { ...existing.tools };
|
|
2097
|
+
delete tools[host];
|
|
2098
|
+
const next = { ...existing };
|
|
2099
|
+
if (Object.keys(tools).length)
|
|
2100
|
+
next.tools = tools;
|
|
2101
|
+
else
|
|
2102
|
+
delete next.tools;
|
|
2103
|
+
writeMachineCredentials(next);
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
});
|
|
2107
|
+
|
|
2108
|
+
// ../packages/tool-kit/out/eventLog.js
|
|
2109
|
+
var require_eventLog = __commonJS({
|
|
2110
|
+
"../packages/tool-kit/out/eventLog.js"(exports) {
|
|
2111
|
+
"use strict";
|
|
2112
|
+
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
2113
|
+
if (k2 === void 0) k2 = k;
|
|
2114
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
2115
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
2116
|
+
desc = { enumerable: true, get: function() {
|
|
2117
|
+
return m[k];
|
|
2118
|
+
} };
|
|
2119
|
+
}
|
|
2120
|
+
Object.defineProperty(o, k2, desc);
|
|
2121
|
+
} : function(o, m, k, k2) {
|
|
2122
|
+
if (k2 === void 0) k2 = k;
|
|
2123
|
+
o[k2] = m[k];
|
|
2124
|
+
});
|
|
2125
|
+
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
|
|
2126
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
2127
|
+
} : function(o, v) {
|
|
2128
|
+
o["default"] = v;
|
|
2129
|
+
});
|
|
2130
|
+
var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
|
|
2131
|
+
var ownKeys = function(o) {
|
|
2132
|
+
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
2133
|
+
var ar = [];
|
|
2134
|
+
for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
|
|
2135
|
+
return ar;
|
|
2136
|
+
};
|
|
2137
|
+
return ownKeys(o);
|
|
2138
|
+
};
|
|
2139
|
+
return function(mod) {
|
|
2140
|
+
if (mod && mod.__esModule) return mod;
|
|
2141
|
+
var result = {};
|
|
2142
|
+
if (mod != null) {
|
|
2143
|
+
for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
2006
2144
|
}
|
|
2145
|
+
__setModuleDefault(result, mod);
|
|
2146
|
+
return result;
|
|
2147
|
+
};
|
|
2148
|
+
}();
|
|
2149
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
2150
|
+
exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = void 0;
|
|
2151
|
+
exports.expandUserPath = expandUserPath;
|
|
2152
|
+
exports.defaultEventLogPath = defaultEventLogPath;
|
|
2153
|
+
exports.resolveEventLog = resolveEventLog;
|
|
2154
|
+
exports.resolveEventLogPath = resolveEventLogPath;
|
|
2155
|
+
exports.describeEventLog = describeEventLog;
|
|
2156
|
+
exports.parseEventLogFlag = parseEventLogFlag;
|
|
2157
|
+
exports.appendEventLog = appendEventLog;
|
|
2158
|
+
var fs2 = __importStar(__require("fs"));
|
|
2159
|
+
var os2 = __importStar(__require("os"));
|
|
2160
|
+
var path3 = __importStar(__require("path"));
|
|
2161
|
+
var agentEvent_1 = require_agentEvent();
|
|
2162
|
+
var credentials_1 = require_credentials();
|
|
2163
|
+
var tokenStore_1 = require_tokenStore();
|
|
2164
|
+
exports.EVENT_LOG_ENV_VAR = "ASCENDA_EVENT_LOG_FILE";
|
|
2165
|
+
exports.EVENT_LOG_OFF = "off";
|
|
2166
|
+
var MAX_BYTES = 5 * 1024 * 1024;
|
|
2167
|
+
function expandUserPath(configured) {
|
|
2168
|
+
const value = configured?.trim();
|
|
2169
|
+
if (!value)
|
|
2170
|
+
return void 0;
|
|
2171
|
+
if (value === "~")
|
|
2172
|
+
return os2.homedir();
|
|
2173
|
+
if (value.startsWith("~/"))
|
|
2174
|
+
return path3.join(os2.homedir(), value.slice(2));
|
|
2175
|
+
return path3.resolve(value);
|
|
2176
|
+
}
|
|
2177
|
+
function defaultEventLogPath() {
|
|
2178
|
+
return path3.join((0, tokenStore_1.ascendaHome)(), "events.jsonl");
|
|
2179
|
+
}
|
|
2180
|
+
function resolveEventLog(options = {}) {
|
|
2181
|
+
for (const [source, raw] of [
|
|
2182
|
+
["env", process.env[exports.EVENT_LOG_ENV_VAR]],
|
|
2183
|
+
["credentials", (0, credentials_1.readMachineCredentials)()?.eventLogPath]
|
|
2184
|
+
]) {
|
|
2185
|
+
const value = raw?.trim();
|
|
2186
|
+
if (!value)
|
|
2187
|
+
continue;
|
|
2188
|
+
if (value.toLowerCase() === exports.EVENT_LOG_OFF)
|
|
2189
|
+
return { path: void 0, source: "disabled" };
|
|
2190
|
+
return { path: expandUserPath(value), source };
|
|
2007
2191
|
}
|
|
2008
|
-
|
|
2192
|
+
if (options.localOnly)
|
|
2193
|
+
return { path: defaultEventLogPath(), source: "unpaired-default" };
|
|
2194
|
+
return { path: void 0, source: "off" };
|
|
2009
2195
|
}
|
|
2010
|
-
function
|
|
2011
|
-
|
|
2012
|
-
|
|
2196
|
+
function resolveEventLogPath(options = {}) {
|
|
2197
|
+
return resolveEventLog(options).path;
|
|
2198
|
+
}
|
|
2199
|
+
function describeEventLog(setting, command) {
|
|
2200
|
+
switch (setting.source) {
|
|
2201
|
+
case "env":
|
|
2202
|
+
return `${setting.path} (from ${exports.EVENT_LOG_ENV_VAR})`;
|
|
2203
|
+
case "credentials":
|
|
2204
|
+
return `${setting.path} (set by ${command} --event-log)`;
|
|
2205
|
+
case "unpaired-default":
|
|
2206
|
+
return `${setting.path} (on because this install isn't paired; ${command} --event-log off to stop)`;
|
|
2207
|
+
case "disabled":
|
|
2208
|
+
return `off (turned off; ${command} --event-log to turn it on)`;
|
|
2209
|
+
case "off":
|
|
2210
|
+
return `off (${command} --event-log to keep a local copy of every event)`;
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
function parseEventLogFlag(argv, index) {
|
|
2214
|
+
const peek = argv[index + 1];
|
|
2215
|
+
if (peek !== void 0 && !peek.startsWith("-"))
|
|
2216
|
+
return { value: peek, consumed: 1 };
|
|
2217
|
+
return { value: defaultEventLogPath(), consumed: 0 };
|
|
2218
|
+
}
|
|
2219
|
+
function appendEventLog(logFilePath, entry) {
|
|
2013
2220
|
try {
|
|
2014
|
-
|
|
2015
|
-
|
|
2221
|
+
rotateIfLarge(logFilePath);
|
|
2222
|
+
const dir = path3.dirname(logFilePath);
|
|
2223
|
+
fs2.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
2224
|
+
const line = { ...entry, event: entry.event ?? (0, agentEvent_1.toAgentEvent)(entry.payload) };
|
|
2225
|
+
fs2.appendFileSync(logFilePath, `${JSON.stringify(line)}
|
|
2226
|
+
`, { encoding: "utf8", mode: 384 });
|
|
2227
|
+
if (process.platform !== "win32")
|
|
2228
|
+
fs2.chmodSync(logFilePath, 384);
|
|
2016
2229
|
} catch {
|
|
2017
2230
|
}
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
const mine = `${claimPath}.${orphanIndex++}`;
|
|
2026
|
-
fs.renameSync(orphan, mine);
|
|
2027
|
-
claimed.push(mine);
|
|
2028
|
-
} catch {
|
|
2029
|
-
}
|
|
2231
|
+
}
|
|
2232
|
+
function rotateIfLarge(logFilePath) {
|
|
2233
|
+
try {
|
|
2234
|
+
if (fs2.statSync(logFilePath).size < MAX_BYTES)
|
|
2235
|
+
return;
|
|
2236
|
+
fs2.renameSync(logFilePath, `${logFilePath}.1`);
|
|
2237
|
+
} catch {
|
|
2030
2238
|
}
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
});
|
|
2242
|
+
|
|
2243
|
+
// ../packages/tool-kit/out/http.js
|
|
2244
|
+
var require_http = __commonJS({
|
|
2245
|
+
"../packages/tool-kit/out/http.js"(exports) {
|
|
2246
|
+
"use strict";
|
|
2247
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
2248
|
+
exports.AscendaApiError = void 0;
|
|
2249
|
+
exports.createPairingSession = createPairingSession;
|
|
2250
|
+
exports.getPairingStatus = getPairingStatus;
|
|
2251
|
+
exports.startStudyJoin = startStudyJoin;
|
|
2252
|
+
exports.getStudyJoinStatus = getStudyJoinStatus;
|
|
2253
|
+
exports.readInitiatives = readInitiatives;
|
|
2254
|
+
exports.readStudyNotices = readStudyNotices;
|
|
2255
|
+
exports.setStudyObjection = setStudyObjection;
|
|
2256
|
+
exports.markStudyNoticeShown = markStudyNoticeShown;
|
|
2257
|
+
exports.renewToolToken = renewToolToken;
|
|
2258
|
+
exports.isRetryableStatus = isRetryableStatus;
|
|
2259
|
+
exports.postToolEvent = postToolEvent;
|
|
2260
|
+
exports.postToolEventsBatch = postToolEventsBatch;
|
|
2261
|
+
exports.parseIngestResponse = parseIngestResponse;
|
|
2262
|
+
var tool_contract_1 = require_out();
|
|
2263
|
+
var AscendaApiError = class extends Error {
|
|
2264
|
+
status;
|
|
2265
|
+
errorCode;
|
|
2266
|
+
constructor(status, errorCode, body) {
|
|
2267
|
+
super(body ?? `Ascenda API error ${status}`);
|
|
2268
|
+
this.status = status;
|
|
2269
|
+
this.errorCode = errorCode;
|
|
2270
|
+
this.name = "AscendaApiError";
|
|
2039
2271
|
}
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
fs.mkdirSync(path2.dirname(outboxFilePath), { recursive: true, mode: 448 });
|
|
2052
|
-
fs.appendFileSync(outboxFilePath, remainder.map((entry) => `${JSON.stringify(entry)}
|
|
2053
|
-
`).join(""), { encoding: "utf8", mode: 384 });
|
|
2054
|
-
if (process.platform !== "win32")
|
|
2055
|
-
fs.chmodSync(outboxFilePath, 384);
|
|
2056
|
-
} catch {
|
|
2057
|
-
return;
|
|
2058
|
-
}
|
|
2059
|
-
}
|
|
2060
|
-
for (const file of claimed) {
|
|
2061
|
-
try {
|
|
2062
|
-
fs.unlinkSync(file);
|
|
2063
|
-
} catch {
|
|
2064
|
-
}
|
|
2065
|
-
}
|
|
2066
|
-
}
|
|
2067
|
-
};
|
|
2272
|
+
};
|
|
2273
|
+
exports.AscendaApiError = AscendaApiError;
|
|
2274
|
+
async function createPairingSession(apiBaseUrl, toolInstallationId, toolType, displayName) {
|
|
2275
|
+
const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions`, {
|
|
2276
|
+
method: "POST",
|
|
2277
|
+
headers: { "Content-Type": "application/json" },
|
|
2278
|
+
body: JSON.stringify({ toolInstallationId, toolType, displayName })
|
|
2279
|
+
});
|
|
2280
|
+
if (!response.ok)
|
|
2281
|
+
throw new AscendaApiError(response.status, void 0, await response.text());
|
|
2282
|
+
return await response.json();
|
|
2068
2283
|
}
|
|
2069
|
-
function
|
|
2070
|
-
const
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
}
|
|
2284
|
+
async function getPairingStatus(apiBaseUrl, pairingSessionId) {
|
|
2285
|
+
const response = await fetch(`${apiBaseUrl}/v1/tool-pairing-sessions/${encodeURIComponent(pairingSessionId)}/status`, {
|
|
2286
|
+
method: "GET",
|
|
2287
|
+
headers: { Accept: "application/json" }
|
|
2288
|
+
});
|
|
2289
|
+
if (!response.ok)
|
|
2290
|
+
throw new AscendaApiError(response.status, void 0, await response.text());
|
|
2291
|
+
return await response.json();
|
|
2292
|
+
}
|
|
2293
|
+
async function startStudyJoin(apiBaseUrl, eventWriteToken, joinCode, mode) {
|
|
2294
|
+
const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions`, {
|
|
2295
|
+
method: "POST",
|
|
2296
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
|
|
2297
|
+
body: JSON.stringify({ joinCode, mode })
|
|
2298
|
+
});
|
|
2299
|
+
if (!response.ok)
|
|
2300
|
+
throw await apiError(response);
|
|
2301
|
+
return await response.json();
|
|
2302
|
+
}
|
|
2303
|
+
async function getStudyJoinStatus(apiBaseUrl, eventWriteToken, joinSessionId) {
|
|
2304
|
+
const response = await fetch(`${apiBaseUrl}/v1/org-study-join-sessions/${encodeURIComponent(joinSessionId)}/status`, {
|
|
2305
|
+
method: "GET",
|
|
2306
|
+
headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` }
|
|
2307
|
+
});
|
|
2308
|
+
if (!response.ok)
|
|
2309
|
+
throw await apiError(response);
|
|
2310
|
+
return await response.json();
|
|
2311
|
+
}
|
|
2312
|
+
async function readInitiatives(apiBaseUrl, eventWriteToken, signal) {
|
|
2313
|
+
let response;
|
|
2314
|
+
try {
|
|
2315
|
+
response = await fetch(`${apiBaseUrl}/v1/tool-installations/initiatives`, {
|
|
2316
|
+
method: "GET",
|
|
2317
|
+
headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
|
|
2318
|
+
signal
|
|
2319
|
+
});
|
|
2320
|
+
} catch (error) {
|
|
2321
|
+
return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
|
|
2082
2322
|
}
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2323
|
+
if (response.status === 401)
|
|
2324
|
+
return { kind: "rejected", httpStatus: 401 };
|
|
2325
|
+
if (!response.ok)
|
|
2326
|
+
return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
|
|
2327
|
+
let body;
|
|
2328
|
+
try {
|
|
2329
|
+
body = await response.json();
|
|
2330
|
+
} catch {
|
|
2331
|
+
return { kind: "failed", reason: "the reply was not readable" };
|
|
2089
2332
|
}
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
return {
|
|
2333
|
+
if (!Array.isArray(body))
|
|
2334
|
+
return { kind: "failed", reason: "the reply was not a list" };
|
|
2335
|
+
return { kind: "ok", initiatives: body };
|
|
2093
2336
|
}
|
|
2094
|
-
function
|
|
2095
|
-
|
|
2096
|
-
const prefix = `${path2.basename(outboxFilePath)}.`;
|
|
2337
|
+
async function readStudyNotices(apiBaseUrl, eventWriteToken, signal) {
|
|
2338
|
+
let response;
|
|
2097
2339
|
try {
|
|
2098
|
-
|
|
2340
|
+
response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices`, {
|
|
2341
|
+
method: "GET",
|
|
2342
|
+
headers: { Accept: "application/json", Authorization: `Bearer ${eventWriteToken}` },
|
|
2343
|
+
signal
|
|
2344
|
+
});
|
|
2345
|
+
} catch (error) {
|
|
2346
|
+
return { kind: "failed", reason: error instanceof Error && error.name === "TimeoutError" ? "the request timed out" : "the server could not be reached" };
|
|
2347
|
+
}
|
|
2348
|
+
if (response.status === 404)
|
|
2349
|
+
return { kind: "absent" };
|
|
2350
|
+
if (response.status === 401)
|
|
2351
|
+
return { kind: "rejected", httpStatus: 401 };
|
|
2352
|
+
if (!response.ok)
|
|
2353
|
+
return { kind: "failed", reason: `the server answered HTTP ${response.status}` };
|
|
2354
|
+
let body;
|
|
2355
|
+
try {
|
|
2356
|
+
body = await response.json();
|
|
2099
2357
|
} catch {
|
|
2100
|
-
return
|
|
2358
|
+
return { kind: "absent" };
|
|
2359
|
+
}
|
|
2360
|
+
if (!Array.isArray(body))
|
|
2361
|
+
return { kind: "absent" };
|
|
2362
|
+
return { kind: "ok", notices: body };
|
|
2363
|
+
}
|
|
2364
|
+
async function setStudyObjection(apiBaseUrl, eventWriteToken, code, objected) {
|
|
2365
|
+
const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(String(code))}/objection`, {
|
|
2366
|
+
method: objected ? "POST" : "DELETE",
|
|
2367
|
+
headers: { Authorization: `Bearer ${eventWriteToken}` }
|
|
2368
|
+
});
|
|
2369
|
+
if (!response.ok)
|
|
2370
|
+
throw await apiError(response);
|
|
2371
|
+
}
|
|
2372
|
+
async function markStudyNoticeShown(apiBaseUrl, eventWriteToken, organisationId, code, signal) {
|
|
2373
|
+
try {
|
|
2374
|
+
const response = await fetch(`${apiBaseUrl}/v1/tool-installations/study-notices/${encodeURIComponent(organisationId)}/${encodeURIComponent(String(code))}/shown`, {
|
|
2375
|
+
method: "POST",
|
|
2376
|
+
headers: { Authorization: `Bearer ${eventWriteToken}` },
|
|
2377
|
+
signal
|
|
2378
|
+
});
|
|
2379
|
+
return response.ok;
|
|
2380
|
+
} catch {
|
|
2381
|
+
return false;
|
|
2101
2382
|
}
|
|
2102
2383
|
}
|
|
2103
|
-
function
|
|
2104
|
-
|
|
2384
|
+
async function apiError(response) {
|
|
2385
|
+
const body = await response.text();
|
|
2386
|
+
let errorCode;
|
|
2387
|
+
try {
|
|
2388
|
+
const parsed = JSON.parse(body);
|
|
2389
|
+
errorCode = parsed.code ?? parsed.error;
|
|
2390
|
+
} catch {
|
|
2391
|
+
errorCode = void 0;
|
|
2392
|
+
}
|
|
2393
|
+
return new AscendaApiError(response.status, errorCode, body);
|
|
2394
|
+
}
|
|
2395
|
+
async function renewToolToken(apiBaseUrl, eventWriteToken, signal) {
|
|
2396
|
+
const response = await fetch(`${apiBaseUrl}/v1/tool-events/renew-token`, {
|
|
2397
|
+
method: "POST",
|
|
2398
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
|
|
2399
|
+
signal
|
|
2400
|
+
});
|
|
2401
|
+
if (response.status === 401)
|
|
2402
|
+
return null;
|
|
2403
|
+
if (!response.ok)
|
|
2404
|
+
throw new AscendaApiError(response.status, void 0, await response.text());
|
|
2405
|
+
return await response.json();
|
|
2406
|
+
}
|
|
2407
|
+
function isDeliveredStatus(value) {
|
|
2408
|
+
return typeof value === "string" && tool_contract_1.TOOL_EVENT_DELIVERED_STATUSES.includes(value);
|
|
2409
|
+
}
|
|
2410
|
+
function readSuccessBody(body) {
|
|
2411
|
+
let parsed;
|
|
2412
|
+
try {
|
|
2413
|
+
parsed = JSON.parse(body);
|
|
2414
|
+
} catch {
|
|
2415
|
+
return { duplicates: 0 };
|
|
2416
|
+
}
|
|
2417
|
+
if (!parsed || typeof parsed !== "object")
|
|
2418
|
+
return { duplicates: 0 };
|
|
2419
|
+
const single = parsed.status;
|
|
2420
|
+
if (isDeliveredStatus(single))
|
|
2421
|
+
return { duplicates: single === "duplicate" ? 1 : 0 };
|
|
2422
|
+
const raw = parsed.results;
|
|
2423
|
+
if (!Array.isArray(raw))
|
|
2424
|
+
return { duplicates: 0 };
|
|
2425
|
+
const results = [];
|
|
2426
|
+
for (const item of raw) {
|
|
2427
|
+
if (!item || typeof item !== "object")
|
|
2428
|
+
continue;
|
|
2429
|
+
const { index, status, reason } = item;
|
|
2430
|
+
if (typeof index !== "number" || typeof status !== "string")
|
|
2431
|
+
continue;
|
|
2432
|
+
results.push({ index, status, ...typeof reason === "string" ? { reason } : {} });
|
|
2433
|
+
}
|
|
2434
|
+
return { duplicates: results.filter((item) => item.status === "duplicate").length, results };
|
|
2435
|
+
}
|
|
2436
|
+
function isRetryableStatus(status) {
|
|
2437
|
+
return status === 408 || status === 429 || status !== void 0 && status >= 500 && status <= 599;
|
|
2438
|
+
}
|
|
2439
|
+
async function postToolEvent(apiBaseUrl, eventWriteToken, payload, signal) {
|
|
2440
|
+
return sendIngest(`${apiBaseUrl}/v1/tool-events`, eventWriteToken, JSON.stringify(payload), signal);
|
|
2441
|
+
}
|
|
2442
|
+
async function postToolEventsBatch(apiBaseUrl, eventWriteToken, payloads, signal) {
|
|
2443
|
+
return sendIngest(`${apiBaseUrl}/v1/tool-events/batch`, eventWriteToken, JSON.stringify({ events: payloads }), signal);
|
|
2444
|
+
}
|
|
2445
|
+
async function sendIngest(url, eventWriteToken, body, signal) {
|
|
2105
2446
|
try {
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2447
|
+
const response = await fetch(url, {
|
|
2448
|
+
method: "POST",
|
|
2449
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${eventWriteToken}` },
|
|
2450
|
+
body,
|
|
2451
|
+
signal
|
|
2452
|
+
});
|
|
2453
|
+
return parseIngestResponse(response);
|
|
2454
|
+
} catch (error) {
|
|
2455
|
+
return {
|
|
2456
|
+
result: "transport_error",
|
|
2457
|
+
detail: error instanceof Error ? `${error.name}: ${error.message}` : String(error)
|
|
2458
|
+
};
|
|
2109
2459
|
}
|
|
2110
|
-
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2460
|
+
}
|
|
2461
|
+
async function parseIngestResponse(response) {
|
|
2462
|
+
if (response.ok) {
|
|
2463
|
+
const outcome = { result: "accepted", httpStatus: response.status };
|
|
2464
|
+
let read = { duplicates: 0 };
|
|
2115
2465
|
try {
|
|
2116
|
-
|
|
2117
|
-
if (!parsed || typeof parsed !== "object" || typeof parsed.queuedAt !== "string" || !parsed.payload || typeof parsed.payload !== "object") {
|
|
2118
|
-
unreadable += 1;
|
|
2119
|
-
continue;
|
|
2120
|
-
}
|
|
2121
|
-
entries.push({ queuedAt: parsed.queuedAt, payload: parsed.payload });
|
|
2466
|
+
read = readSuccessBody(await response.text());
|
|
2122
2467
|
} catch {
|
|
2123
|
-
|
|
2468
|
+
read = { duplicates: 0 };
|
|
2124
2469
|
}
|
|
2470
|
+
return {
|
|
2471
|
+
...outcome,
|
|
2472
|
+
...read.duplicates > 0 ? { duplicates: read.duplicates } : {},
|
|
2473
|
+
...read.results !== void 0 ? { results: read.results } : {}
|
|
2474
|
+
};
|
|
2125
2475
|
}
|
|
2126
|
-
|
|
2476
|
+
const body = await response.text();
|
|
2477
|
+
let errorCode;
|
|
2478
|
+
try {
|
|
2479
|
+
errorCode = JSON.parse(body).error;
|
|
2480
|
+
} catch {
|
|
2481
|
+
errorCode = void 0;
|
|
2482
|
+
}
|
|
2483
|
+
const base = { httpStatus: response.status, errorCode, detail: body || void 0 };
|
|
2484
|
+
if (response.status === 401)
|
|
2485
|
+
return { ...base, result: "auth_failed" };
|
|
2486
|
+
if (response.status === 403 && errorCode === "consent_missing_or_expired")
|
|
2487
|
+
return { ...base, result: "consent_missing" };
|
|
2488
|
+
if (response.status === 400 || response.status === 422)
|
|
2489
|
+
return { ...base, result: "validation_failed" };
|
|
2490
|
+
return { ...base, result: "transport_error" };
|
|
2127
2491
|
}
|
|
2128
2492
|
}
|
|
2129
2493
|
});
|
|
@@ -2371,11 +2735,34 @@ var require_eventSender = __commonJS({
|
|
|
2371
2735
|
return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
|
|
2372
2736
|
}
|
|
2373
2737
|
if (this.isRetryable(outcome)) {
|
|
2374
|
-
await new Promise((
|
|
2738
|
+
await new Promise((resolve3) => setTimeout(resolve3, RETRY_DELAY_MS));
|
|
2375
2739
|
return (0, http_1.postToolEvent)(this.config.apiBaseUrl, this.eventWriteToken, payload, this.signal());
|
|
2376
2740
|
}
|
|
2377
2741
|
return outcome;
|
|
2378
2742
|
}
|
|
2743
|
+
/**
|
|
2744
|
+
* One outbox pass with nothing live to send: what a background flusher runs,
|
|
2745
|
+
* once per batch. Unlike the pass {@link post} makes, it may run more than
|
|
2746
|
+
* once per sender, because a flusher isn't on anyone's critical path.
|
|
2747
|
+
*
|
|
2748
|
+
* A halted pass is journaled here. Inside {@link post} the live send that
|
|
2749
|
+
* follows journals it, and a flusher has no live send, so without this an
|
|
2750
|
+
* outage would never reach the journal `doctor` and the notices read.
|
|
2751
|
+
*/
|
|
2752
|
+
async flushOutbox() {
|
|
2753
|
+
await this.renewIfExpiring();
|
|
2754
|
+
this.outboxServiced = false;
|
|
2755
|
+
this.lastDrain = void 0;
|
|
2756
|
+
const halted = await this.serviceOutbox();
|
|
2757
|
+
if (halted) {
|
|
2758
|
+
this.lastState = (0, stateStore_1.recordSendOutcome)(this.stateFilePath(), this.config.toolInstallationId, halted.result, {
|
|
2759
|
+
httpStatus: halted.httpStatus,
|
|
2760
|
+
errorCode: halted.errorCode,
|
|
2761
|
+
detail: withNote(halted.detail, "kept in outbox")
|
|
2762
|
+
});
|
|
2763
|
+
}
|
|
2764
|
+
return this.lastDrain;
|
|
2765
|
+
}
|
|
2379
2766
|
/** A failure that never reached a verdict. Replaying can change the answer. */
|
|
2380
2767
|
isRetryable(outcome) {
|
|
2381
2768
|
return outcome.result === "transport_error" && (outcome.httpStatus === void 0 || (0, http_1.isRetryableStatus)(outcome.httpStatus));
|
|
@@ -2634,16 +3021,16 @@ var require_contextRegistry = __commonJS({
|
|
|
2634
3021
|
exports.readWorkContextRegistry = readWorkContextRegistry;
|
|
2635
3022
|
exports.recordWorkContext = recordWorkContext;
|
|
2636
3023
|
exports.recordWorkContextAlias = recordWorkContextAlias;
|
|
2637
|
-
var
|
|
3024
|
+
var fs2 = __importStar(__require("fs"));
|
|
2638
3025
|
var os2 = __importStar(__require("os"));
|
|
2639
|
-
var
|
|
3026
|
+
var path3 = __importStar(__require("path"));
|
|
2640
3027
|
var MAX_PATHS_PER_ENTRY = 8;
|
|
2641
3028
|
function workContextRegistryFilePath() {
|
|
2642
|
-
return
|
|
3029
|
+
return path3.join(os2.homedir(), ".ascenda", "work-contexts.json");
|
|
2643
3030
|
}
|
|
2644
3031
|
function readWorkContextRegistry(registryFilePath = workContextRegistryFilePath()) {
|
|
2645
3032
|
try {
|
|
2646
|
-
const parsed = JSON.parse(
|
|
3033
|
+
const parsed = JSON.parse(fs2.readFileSync(registryFilePath, "utf8"));
|
|
2647
3034
|
if (parsed && parsed.version === 1 && parsed.contexts && typeof parsed.contexts === "object") {
|
|
2648
3035
|
return parsed;
|
|
2649
3036
|
}
|
|
@@ -2719,14 +3106,14 @@ var require_contextRegistry = __commonJS({
|
|
|
2719
3106
|
return iso.slice(0, 10);
|
|
2720
3107
|
}
|
|
2721
3108
|
function writeRegistry(registryFilePath, registry) {
|
|
2722
|
-
const dir =
|
|
2723
|
-
|
|
3109
|
+
const dir = path3.dirname(registryFilePath);
|
|
3110
|
+
fs2.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
2724
3111
|
const tmp = `${registryFilePath}.${process.pid}.tmp`;
|
|
2725
|
-
|
|
3112
|
+
fs2.writeFileSync(tmp, `${JSON.stringify(registry, null, 2)}
|
|
2726
3113
|
`, { encoding: "utf8", mode: 384 });
|
|
2727
|
-
|
|
3114
|
+
fs2.renameSync(tmp, registryFilePath);
|
|
2728
3115
|
if (process.platform !== "win32") {
|
|
2729
|
-
|
|
3116
|
+
fs2.chmodSync(registryFilePath, 384);
|
|
2730
3117
|
}
|
|
2731
3118
|
}
|
|
2732
3119
|
}
|
|
@@ -2775,12 +3162,14 @@ var require_forgeProject = __commonJS({
|
|
|
2775
3162
|
}();
|
|
2776
3163
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
2777
3164
|
exports.forgeProjectHash = forgeProjectHash;
|
|
3165
|
+
exports.forgeRepoKey = forgeRepoKey;
|
|
3166
|
+
exports.forgeBranchKey = forgeBranchKey;
|
|
2778
3167
|
exports.parseForgeFullName = parseForgeFullName;
|
|
2779
3168
|
exports.readForgeFullName = readForgeFullName;
|
|
2780
3169
|
exports.forgeFullNameFromConfig = forgeFullNameFromConfig;
|
|
2781
3170
|
exports.recordForgeProjectAlias = recordForgeProjectAlias;
|
|
2782
|
-
var
|
|
2783
|
-
var
|
|
3171
|
+
var fs2 = __importStar(__require("fs"));
|
|
3172
|
+
var path3 = __importStar(__require("path"));
|
|
2784
3173
|
var contextRegistry_1 = require_contextRegistry();
|
|
2785
3174
|
function forgeProjectHash(value) {
|
|
2786
3175
|
let h = 2166136261;
|
|
@@ -2790,6 +3179,19 @@ var require_forgeProject = __commonJS({
|
|
|
2790
3179
|
}
|
|
2791
3180
|
return h.toString(16).padStart(8, "0");
|
|
2792
3181
|
}
|
|
3182
|
+
function forgeRepoKey(fullName) {
|
|
3183
|
+
return forgeProjectHash(fullName.toLowerCase());
|
|
3184
|
+
}
|
|
3185
|
+
function forgeBranchKey(fullName, branch) {
|
|
3186
|
+
const input = `${fullName.toLowerCase()}
|
|
3187
|
+
${branch}`;
|
|
3188
|
+
let h = 0xcbf29ce484222325n;
|
|
3189
|
+
for (const byte of Buffer.from(input, "utf8")) {
|
|
3190
|
+
h ^= BigInt(byte);
|
|
3191
|
+
h = BigInt.asUintN(64, h * 0x100000001b3n);
|
|
3192
|
+
}
|
|
3193
|
+
return h.toString(16).padStart(16, "0");
|
|
3194
|
+
}
|
|
2793
3195
|
function parseForgeFullName(remoteUrl) {
|
|
2794
3196
|
if (!remoteUrl)
|
|
2795
3197
|
return null;
|
|
@@ -2826,7 +3228,7 @@ var require_forgeProject = __commonJS({
|
|
|
2826
3228
|
return null;
|
|
2827
3229
|
let config;
|
|
2828
3230
|
try {
|
|
2829
|
-
config =
|
|
3231
|
+
config = fs2.readFileSync(path3.join(repositoryRoot, ".git", "config"), "utf8");
|
|
2830
3232
|
} catch {
|
|
2831
3233
|
return null;
|
|
2832
3234
|
}
|
|
@@ -2933,31 +3335,31 @@ var require_salt = __commonJS({
|
|
|
2933
3335
|
exports.readOrCreateMachineSalt = readOrCreateMachineSalt;
|
|
2934
3336
|
exports.hashWithMachineSalt = hashWithMachineSalt;
|
|
2935
3337
|
var crypto = __importStar(__require("crypto"));
|
|
2936
|
-
var
|
|
2937
|
-
var
|
|
3338
|
+
var fs2 = __importStar(__require("fs"));
|
|
3339
|
+
var path3 = __importStar(__require("path"));
|
|
2938
3340
|
var tokenStore_1 = require_tokenStore();
|
|
2939
3341
|
function machineSaltFilePath() {
|
|
2940
|
-
return
|
|
3342
|
+
return path3.join((0, tokenStore_1.ascendaHome)(), "salt");
|
|
2941
3343
|
}
|
|
2942
3344
|
var cache = /* @__PURE__ */ new Map();
|
|
2943
3345
|
function readOrCreateMachineSalt(saltFilePath = machineSaltFilePath()) {
|
|
2944
3346
|
const hit = cache.get(saltFilePath);
|
|
2945
3347
|
if (hit)
|
|
2946
3348
|
return hit;
|
|
2947
|
-
const dir =
|
|
2948
|
-
|
|
3349
|
+
const dir = path3.dirname(saltFilePath);
|
|
3350
|
+
fs2.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
2949
3351
|
let salt;
|
|
2950
3352
|
try {
|
|
2951
3353
|
salt = crypto.randomBytes(32).toString("hex");
|
|
2952
|
-
|
|
3354
|
+
fs2.writeFileSync(saltFilePath, salt, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
2953
3355
|
} catch (error) {
|
|
2954
3356
|
if (error.code !== "EEXIST")
|
|
2955
3357
|
throw error;
|
|
2956
|
-
salt =
|
|
3358
|
+
salt = fs2.readFileSync(saltFilePath, "utf8").trim();
|
|
2957
3359
|
}
|
|
2958
3360
|
if (process.platform !== "win32") {
|
|
2959
|
-
|
|
2960
|
-
|
|
3361
|
+
fs2.chmodSync(dir, 448);
|
|
3362
|
+
fs2.chmodSync(saltFilePath, 384);
|
|
2961
3363
|
}
|
|
2962
3364
|
cache.set(saltFilePath, salt);
|
|
2963
3365
|
return salt;
|
|
@@ -3017,8 +3419,8 @@ var require_workContext = __commonJS({
|
|
|
3017
3419
|
exports.deriveBranchHash = deriveBranchHash;
|
|
3018
3420
|
exports.readBranchName = readBranchName;
|
|
3019
3421
|
exports.deriveBranchHashForCwd = deriveBranchHashForCwd2;
|
|
3020
|
-
var
|
|
3021
|
-
var
|
|
3422
|
+
var fs2 = __importStar(__require("fs"));
|
|
3423
|
+
var path3 = __importStar(__require("path"));
|
|
3022
3424
|
var salt_1 = require_salt();
|
|
3023
3425
|
var MAX_WALK_DEPTH = 64;
|
|
3024
3426
|
function deriveWorkContext(cwd, saltFilePath) {
|
|
@@ -3049,14 +3451,14 @@ var require_workContext = __commonJS({
|
|
|
3049
3451
|
};
|
|
3050
3452
|
}
|
|
3051
3453
|
function resolveRepositoryRoots(startDir) {
|
|
3052
|
-
if (!
|
|
3454
|
+
if (!fs2.existsSync(startDir))
|
|
3053
3455
|
return null;
|
|
3054
3456
|
let dir = startDir;
|
|
3055
3457
|
for (let depth = 0; depth < MAX_WALK_DEPTH; depth++) {
|
|
3056
|
-
const dotGit =
|
|
3458
|
+
const dotGit = path3.join(dir, ".git");
|
|
3057
3459
|
let stat = null;
|
|
3058
3460
|
try {
|
|
3059
|
-
stat =
|
|
3461
|
+
stat = fs2.statSync(dotGit);
|
|
3060
3462
|
} catch {
|
|
3061
3463
|
stat = null;
|
|
3062
3464
|
}
|
|
@@ -3067,7 +3469,7 @@ var require_workContext = __commonJS({
|
|
|
3067
3469
|
const canonicalRoot = (gitDir ? worktreeParentRoot(gitDir) : null) ?? dir;
|
|
3068
3470
|
return { checkoutRoot: dir, canonicalRoot, gitDir };
|
|
3069
3471
|
}
|
|
3070
|
-
const parent =
|
|
3472
|
+
const parent = path3.dirname(dir);
|
|
3071
3473
|
if (parent === dir)
|
|
3072
3474
|
return null;
|
|
3073
3475
|
dir = parent;
|
|
@@ -3076,16 +3478,16 @@ var require_workContext = __commonJS({
|
|
|
3076
3478
|
}
|
|
3077
3479
|
function readGitdirPointer(dotGitFile, containingDir) {
|
|
3078
3480
|
try {
|
|
3079
|
-
const match = /^gitdir:\s*(.+)\s*$/m.exec(
|
|
3481
|
+
const match = /^gitdir:\s*(.+)\s*$/m.exec(fs2.readFileSync(dotGitFile, "utf8"));
|
|
3080
3482
|
if (!match)
|
|
3081
3483
|
return null;
|
|
3082
|
-
return
|
|
3484
|
+
return path3.resolve(containingDir, match[1].trim());
|
|
3083
3485
|
} catch {
|
|
3084
3486
|
return null;
|
|
3085
3487
|
}
|
|
3086
3488
|
}
|
|
3087
3489
|
function worktreeParentRoot(resolvedGitDir) {
|
|
3088
|
-
const marker = `${
|
|
3490
|
+
const marker = `${path3.sep}.git${path3.sep}worktrees${path3.sep}`;
|
|
3089
3491
|
const idx = resolvedGitDir.indexOf(marker);
|
|
3090
3492
|
if (idx === -1)
|
|
3091
3493
|
return null;
|
|
@@ -3095,12 +3497,12 @@ var require_workContext = __commonJS({
|
|
|
3095
3497
|
const sep = startPath.includes("\\") && !startPath.includes("/") ? "\\" : "/";
|
|
3096
3498
|
const leading = /^[\\/]/.test(startPath) ? sep : "";
|
|
3097
3499
|
const segments = startPath.split(/[\\/]/).filter(Boolean);
|
|
3098
|
-
const
|
|
3500
|
+
const join3 = (count) => leading + segments.slice(0, count).join(sep);
|
|
3099
3501
|
for (let i = 0; i + 2 < segments.length; i++) {
|
|
3100
3502
|
if (segments[i] === ".claude" && segments[i + 1] === "worktrees") {
|
|
3101
3503
|
if (i === 0)
|
|
3102
3504
|
return null;
|
|
3103
|
-
return { checkoutRoot:
|
|
3505
|
+
return { checkoutRoot: join3(i + 3), canonicalRoot: join3(i), gitDir: null };
|
|
3104
3506
|
}
|
|
3105
3507
|
}
|
|
3106
3508
|
for (let i = 0; i + 1 < segments.length; i++) {
|
|
@@ -3110,7 +3512,7 @@ var require_workContext = __commonJS({
|
|
|
3110
3512
|
continue;
|
|
3111
3513
|
const repoName = folder.slice(0, -suffix.length);
|
|
3112
3514
|
const canonicalRoot = leading + [...segments.slice(0, i), repoName].join(sep);
|
|
3113
|
-
return { checkoutRoot:
|
|
3515
|
+
return { checkoutRoot: join3(i + 2), canonicalRoot, gitDir: null };
|
|
3114
3516
|
}
|
|
3115
3517
|
return null;
|
|
3116
3518
|
}
|
|
@@ -3158,7 +3560,7 @@ var require_workContext = __commonJS({
|
|
|
3158
3560
|
return null;
|
|
3159
3561
|
let head;
|
|
3160
3562
|
try {
|
|
3161
|
-
head =
|
|
3563
|
+
head = fs2.readFileSync(path3.join(gitDir, "HEAD"), "utf8").trim();
|
|
3162
3564
|
} catch {
|
|
3163
3565
|
return null;
|
|
3164
3566
|
}
|
|
@@ -3176,6 +3578,95 @@ var require_workContext = __commonJS({
|
|
|
3176
3578
|
}
|
|
3177
3579
|
});
|
|
3178
3580
|
|
|
3581
|
+
// ../packages/tool-kit/out/forgeKeys.js
|
|
3582
|
+
var require_forgeKeys = __commonJS({
|
|
3583
|
+
"../packages/tool-kit/out/forgeKeys.js"(exports) {
|
|
3584
|
+
"use strict";
|
|
3585
|
+
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
3586
|
+
if (k2 === void 0) k2 = k;
|
|
3587
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
3588
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
3589
|
+
desc = { enumerable: true, get: function() {
|
|
3590
|
+
return m[k];
|
|
3591
|
+
} };
|
|
3592
|
+
}
|
|
3593
|
+
Object.defineProperty(o, k2, desc);
|
|
3594
|
+
} : function(o, m, k, k2) {
|
|
3595
|
+
if (k2 === void 0) k2 = k;
|
|
3596
|
+
o[k2] = m[k];
|
|
3597
|
+
});
|
|
3598
|
+
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
|
|
3599
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
3600
|
+
} : function(o, v) {
|
|
3601
|
+
o["default"] = v;
|
|
3602
|
+
});
|
|
3603
|
+
var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
|
|
3604
|
+
var ownKeys = function(o) {
|
|
3605
|
+
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
3606
|
+
var ar = [];
|
|
3607
|
+
for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
|
|
3608
|
+
return ar;
|
|
3609
|
+
};
|
|
3610
|
+
return ownKeys(o);
|
|
3611
|
+
};
|
|
3612
|
+
return function(mod) {
|
|
3613
|
+
if (mod && mod.__esModule) return mod;
|
|
3614
|
+
var result = {};
|
|
3615
|
+
if (mod != null) {
|
|
3616
|
+
for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
3617
|
+
}
|
|
3618
|
+
__setModuleDefault(result, mod);
|
|
3619
|
+
return result;
|
|
3620
|
+
};
|
|
3621
|
+
}();
|
|
3622
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3623
|
+
exports.REPO_KEYS_ENV_VAR = void 0;
|
|
3624
|
+
exports.repoKeysEnabled = repoKeysEnabled;
|
|
3625
|
+
exports.deriveForgeKeysForCwd = deriveForgeKeysForCwd;
|
|
3626
|
+
var fs2 = __importStar(__require("fs"));
|
|
3627
|
+
var path3 = __importStar(__require("path"));
|
|
3628
|
+
var credentials_1 = require_credentials();
|
|
3629
|
+
var forgeProject_1 = require_forgeProject();
|
|
3630
|
+
var workContext_1 = require_workContext();
|
|
3631
|
+
exports.REPO_KEYS_ENV_VAR = "ASCENDA_REPO_KEYS";
|
|
3632
|
+
function repoKeysEnabled() {
|
|
3633
|
+
const env = process.env[exports.REPO_KEYS_ENV_VAR]?.trim().toLowerCase();
|
|
3634
|
+
if (env === "off" || env === "0" || env === "false")
|
|
3635
|
+
return false;
|
|
3636
|
+
if (env === "on" || env === "1" || env === "true")
|
|
3637
|
+
return true;
|
|
3638
|
+
return (0, credentials_1.readMachineCredentials)()?.repoKeys !== false;
|
|
3639
|
+
}
|
|
3640
|
+
function readDefaultBranch(repositoryRoot) {
|
|
3641
|
+
try {
|
|
3642
|
+
const head = fs2.readFileSync(path3.join(repositoryRoot, ".git", "refs", "remotes", "origin", "HEAD"), "utf8").trim();
|
|
3643
|
+
const match = /^ref:\s*refs\/remotes\/origin\/(.+)$/.exec(head);
|
|
3644
|
+
return match ? (0, workContext_1.normalizeBranchName)(match[1]) : null;
|
|
3645
|
+
} catch {
|
|
3646
|
+
return null;
|
|
3647
|
+
}
|
|
3648
|
+
}
|
|
3649
|
+
function deriveForgeKeysForCwd(cwd) {
|
|
3650
|
+
try {
|
|
3651
|
+
if (!cwd || !repoKeysEnabled())
|
|
3652
|
+
return {};
|
|
3653
|
+
const root = (0, workContext_1.deriveWorkContext)(cwd)?.projectPath;
|
|
3654
|
+
const fullName = (0, forgeProject_1.readForgeFullName)(root);
|
|
3655
|
+
if (!root || !fullName)
|
|
3656
|
+
return {};
|
|
3657
|
+
const branch = (0, workContext_1.readBranchName)(cwd);
|
|
3658
|
+
const onDefault = branch !== null && branch === readDefaultBranch(root);
|
|
3659
|
+
return {
|
|
3660
|
+
repoKey: (0, forgeProject_1.forgeRepoKey)(fullName),
|
|
3661
|
+
...branch && !onDefault ? { branchKey: (0, forgeProject_1.forgeBranchKey)(fullName, branch) } : {}
|
|
3662
|
+
};
|
|
3663
|
+
} catch {
|
|
3664
|
+
return {};
|
|
3665
|
+
}
|
|
3666
|
+
}
|
|
3667
|
+
}
|
|
3668
|
+
});
|
|
3669
|
+
|
|
3179
3670
|
// ../packages/tool-kit/out/hookAdapter.js
|
|
3180
3671
|
var require_hookAdapter = __commonJS({
|
|
3181
3672
|
"../packages/tool-kit/out/hookAdapter.js"(exports) {
|
|
@@ -3185,13 +3676,18 @@ var require_hookAdapter = __commonJS({
|
|
|
3185
3676
|
exports.resolveCliAgentInstallationId = resolveCliAgentInstallationId;
|
|
3186
3677
|
exports.resolveContextHashes = resolveContextHashes;
|
|
3187
3678
|
exports.loadCliAgentConfig = loadCliAgentConfig;
|
|
3679
|
+
exports.withForgeKeys = withForgeKeys;
|
|
3680
|
+
exports.withPromptId = withPromptId;
|
|
3188
3681
|
exports.deliverHookEvents = deliverHookEvents2;
|
|
3682
|
+
exports.flushHookOutbox = flushHookOutbox2;
|
|
3189
3683
|
var contextRegistry_1 = require_contextRegistry();
|
|
3190
3684
|
var credentials_1 = require_credentials();
|
|
3191
3685
|
var forgeProject_1 = require_forgeProject();
|
|
3192
3686
|
var eventLog_1 = require_eventLog();
|
|
3687
|
+
var forgeKeys_1 = require_forgeKeys();
|
|
3193
3688
|
var eventSender_1 = require_eventSender();
|
|
3194
3689
|
var stateStore_1 = require_stateStore();
|
|
3690
|
+
var backgroundDelivery_1 = require_backgroundDelivery();
|
|
3195
3691
|
var tokenStore_1 = require_tokenStore();
|
|
3196
3692
|
var workContext_1 = require_workContext();
|
|
3197
3693
|
exports.DEFAULT_API_BASE_URL = "https://api.ascenda.one";
|
|
@@ -3244,6 +3740,19 @@ var require_hookAdapter = __commonJS({
|
|
|
3244
3740
|
};
|
|
3245
3741
|
}
|
|
3246
3742
|
function loadCliAgentConfig(toolType, sessionIdFromHook, cwd, identity = {}) {
|
|
3743
|
+
const pairing = loadCliAgentPairing(toolType, identity);
|
|
3744
|
+
const contextHashes = resolveContextHashes(cwd);
|
|
3745
|
+
return {
|
|
3746
|
+
...pairing,
|
|
3747
|
+
// An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
|
|
3748
|
+
// read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
|
|
3749
|
+
// an empty string, grouping unrelated rows under a value naming no session.
|
|
3750
|
+
sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
|
|
3751
|
+
workspaceHash: contextHashes.workspaceHash,
|
|
3752
|
+
projectHash: contextHashes.projectHash
|
|
3753
|
+
};
|
|
3754
|
+
}
|
|
3755
|
+
function loadCliAgentPairing(toolType, identity) {
|
|
3247
3756
|
const credentials = identity.host ? (0, credentials_1.readHostCredentials)(identity.host) : void 0;
|
|
3248
3757
|
const apiBaseUrl = (process.env.ASCENDA_API_BASE_URL ?? credentials?.apiBaseUrl ?? exports.DEFAULT_API_BASE_URL).replace(/\/$/, "");
|
|
3249
3758
|
const { toolInstallationId } = resolveCliAgentInstallationId(toolType, identity);
|
|
@@ -3254,26 +3763,33 @@ var require_hookAdapter = __commonJS({
|
|
|
3254
3763
|
throw new Error("Missing ASCENDA_EVENT_WRITE_TOKEN (or token file)");
|
|
3255
3764
|
if (!fileToken)
|
|
3256
3765
|
(0, tokenStore_1.persistEventWriteToken)(tokenFilePath, eventWriteToken);
|
|
3257
|
-
const contextHashes = resolveContextHashes(cwd);
|
|
3258
3766
|
return {
|
|
3259
3767
|
apiBaseUrl,
|
|
3260
3768
|
toolInstallationId,
|
|
3261
3769
|
eventWriteToken,
|
|
3262
3770
|
tokenFilePath,
|
|
3263
|
-
// An empty ASCENDA_SESSION_ID is "unset", not "override with nothing":
|
|
3264
|
-
// read raw, `ASCENDA_SESSION_ID=""` beat a real hook session and shipped
|
|
3265
|
-
// an empty string, grouping unrelated rows under a value naming no session.
|
|
3266
|
-
sessionId: process.env.ASCENDA_SESSION_ID?.trim() || sessionIdFromHook || null,
|
|
3267
|
-
workspaceHash: contextHashes.workspaceHash,
|
|
3268
|
-
projectHash: contextHashes.projectHash,
|
|
3269
3771
|
// Agents await command hooks; fail fast rather than stall the user's turn.
|
|
3270
3772
|
timeoutMs: parsePositiveInt(process.env.ASCENDA_HTTP_TIMEOUT_MS) ?? 3e3
|
|
3271
3773
|
};
|
|
3272
3774
|
}
|
|
3775
|
+
function withForgeKeys(events, cwd) {
|
|
3776
|
+
const keys = (0, forgeKeys_1.deriveForgeKeysForCwd)(cwd ?? process.cwd());
|
|
3777
|
+
if (!keys.repoKey)
|
|
3778
|
+
return events;
|
|
3779
|
+
return events.map((event) => ({ ...event, metadata: { ...keys, ...event.metadata } }));
|
|
3780
|
+
}
|
|
3781
|
+
function withPromptId(events, promptId) {
|
|
3782
|
+
if (!promptId)
|
|
3783
|
+
return events;
|
|
3784
|
+
return events.map((event) => ({ ...event, metadata: { promptId, ...event.metadata } }));
|
|
3785
|
+
}
|
|
3273
3786
|
async function deliverHookEvents2(events, options) {
|
|
3274
3787
|
if (events.length === 0)
|
|
3275
3788
|
return;
|
|
3276
|
-
|
|
3789
|
+
events = withPromptId(events, options.promptId);
|
|
3790
|
+
if (options.forgeKeys)
|
|
3791
|
+
events = withForgeKeys(events, options.cwd);
|
|
3792
|
+
const notice = options.onNotice ?? ((message2) => console.error(message2));
|
|
3277
3793
|
const hasToken = (id) => (0, tokenStore_1.readTokenFile)(process.env.ASCENDA_EVENT_WRITE_TOKEN_FILE ?? (0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0;
|
|
3278
3794
|
if (options.host && (0, credentials_1.isLocalOnlyHostInstall)(options.host, hasToken)) {
|
|
3279
3795
|
const logFile = (0, eventLog_1.resolveEventLogPath)({ localOnly: true });
|
|
@@ -3304,21 +3820,55 @@ var require_hookAdapter = __commonJS({
|
|
|
3304
3820
|
projectHash: config.projectHash,
|
|
3305
3821
|
timeoutMs: config.timeoutMs
|
|
3306
3822
|
});
|
|
3307
|
-
|
|
3308
|
-
const
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
notice("Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.");
|
|
3317
|
-
} else {
|
|
3318
|
-
notice(`Ascenda telemetry rejected: ${result}`);
|
|
3823
|
+
if ((0, backgroundDelivery_1.hookDeliveryInline)()) {
|
|
3824
|
+
for (const event of events) {
|
|
3825
|
+
const result = await sender.send(event);
|
|
3826
|
+
if (result === "accepted")
|
|
3827
|
+
continue;
|
|
3828
|
+
const message2 = noticeFor(result);
|
|
3829
|
+
if (message2)
|
|
3830
|
+
notice(message2);
|
|
3831
|
+
return;
|
|
3319
3832
|
}
|
|
3320
3833
|
return;
|
|
3321
3834
|
}
|
|
3835
|
+
for (const event of events)
|
|
3836
|
+
sender.queue(event);
|
|
3837
|
+
(0, backgroundDelivery_1.startBackgroundFlush)({ outboxFilePath: sender.outboxFilePath() });
|
|
3838
|
+
const last = (0, stateStore_1.readCollectorState)(sender.stateFilePath())?.lastOutcome;
|
|
3839
|
+
const message = last ? noticeFor(last) : void 0;
|
|
3840
|
+
if (message)
|
|
3841
|
+
notice(message);
|
|
3842
|
+
}
|
|
3843
|
+
function noticeFor(result) {
|
|
3844
|
+
if (result === "accepted" || result === "duplicate")
|
|
3845
|
+
return void 0;
|
|
3846
|
+
if (result === "consent_missing")
|
|
3847
|
+
return "Ascenda telemetry paused: renew IDE telemetry consent in the Ascenda app.";
|
|
3848
|
+
if (result === "auth_failed")
|
|
3849
|
+
return "Ascenda telemetry paused: connection revoked or expired. Re-pair via an Ascenda IDE extension or pairing-sim.";
|
|
3850
|
+
if (result === "transport_error")
|
|
3851
|
+
return "Ascenda telemetry paused: the ingest endpoint could not be reached; the event is kept in the outbox. Your work is unaffected.";
|
|
3852
|
+
if (result === "outbox_discarded")
|
|
3853
|
+
return void 0;
|
|
3854
|
+
return `Ascenda telemetry rejected: ${result}`;
|
|
3855
|
+
}
|
|
3856
|
+
async function flushHookOutbox2(options) {
|
|
3857
|
+
let config;
|
|
3858
|
+
try {
|
|
3859
|
+
config = loadCliAgentPairing(options.toolType, options);
|
|
3860
|
+
} catch {
|
|
3861
|
+
return;
|
|
3862
|
+
}
|
|
3863
|
+
const sender = new eventSender_1.AscendaEventSender({
|
|
3864
|
+
apiBaseUrl: config.apiBaseUrl,
|
|
3865
|
+
toolInstallationId: config.toolInstallationId,
|
|
3866
|
+
source: options.source,
|
|
3867
|
+
eventWriteToken: config.eventWriteToken,
|
|
3868
|
+
tokenFilePath: config.tokenFilePath,
|
|
3869
|
+
timeoutMs: config.timeoutMs
|
|
3870
|
+
});
|
|
3871
|
+
await (0, backgroundDelivery_1.runOutboxFlush)(sender);
|
|
3322
3872
|
}
|
|
3323
3873
|
function logUnsent(logFile, events, options) {
|
|
3324
3874
|
const contextHashes = resolveContextHashes(options.cwd);
|
|
@@ -3501,7 +4051,7 @@ var require_studyJoin = __commonJS({
|
|
|
3501
4051
|
const pollIntervalMs = ctx.pollIntervalMs ?? POLL_INTERVAL_MS;
|
|
3502
4052
|
const deadline = Math.min(Date.parse(start.expiresAt) || Date.now() + POLL_TIMEOUT_MS, Date.now() + POLL_TIMEOUT_MS);
|
|
3503
4053
|
while (Date.now() < deadline) {
|
|
3504
|
-
await new Promise((
|
|
4054
|
+
await new Promise((resolve3) => setTimeout(resolve3, pollIntervalMs));
|
|
3505
4055
|
let poll;
|
|
3506
4056
|
try {
|
|
3507
4057
|
poll = await (0, http_1.getStudyJoinStatus)(ctx.apiBaseUrl, ctx.eventWriteToken, start.joinSessionId);
|
|
@@ -3564,7 +4114,7 @@ var require_studyJoin = __commonJS({
|
|
|
3564
4114
|
return true;
|
|
3565
4115
|
}
|
|
3566
4116
|
function askChoice(stdin, stdout) {
|
|
3567
|
-
return new Promise((
|
|
4117
|
+
return new Promise((resolve3) => {
|
|
3568
4118
|
const rl = readline.createInterface({ input: stdin, output: stdout });
|
|
3569
4119
|
let settled = false;
|
|
3570
4120
|
const finish = (value) => {
|
|
@@ -3572,7 +4122,7 @@ var require_studyJoin = __commonJS({
|
|
|
3572
4122
|
return;
|
|
3573
4123
|
settled = true;
|
|
3574
4124
|
rl.close();
|
|
3575
|
-
|
|
4125
|
+
resolve3(value.trim());
|
|
3576
4126
|
};
|
|
3577
4127
|
rl.question("Choice [Not now]: ", finish);
|
|
3578
4128
|
rl.once("close", () => finish(""));
|
|
@@ -3776,92 +4326,46 @@ var require_initiatives = __commonJS({
|
|
|
3776
4326
|
const o = value;
|
|
3777
4327
|
if (typeof o.title !== "string" || typeof o.status !== "string")
|
|
3778
4328
|
return void 0;
|
|
3779
|
-
return {
|
|
3780
|
-
id: typeof o.id === "string" ? o.id : "",
|
|
3781
|
-
organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
|
|
3782
|
-
title: o.title,
|
|
3783
|
-
summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
|
|
3784
|
-
measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
|
|
3785
|
-
scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
|
|
3786
|
-
scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
|
|
3787
|
-
withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
|
|
3788
|
-
status: o.status,
|
|
3789
|
-
direction: typeof o.direction === "string" ? o.direction : null,
|
|
3790
|
-
result: asResult(o.result)
|
|
3791
|
-
};
|
|
3792
|
-
}
|
|
3793
|
-
function asResult(value) {
|
|
3794
|
-
if (!value || typeof value !== "object")
|
|
3795
|
-
return null;
|
|
3796
|
-
const r = value;
|
|
3797
|
-
const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
|
|
3798
|
-
return {
|
|
3799
|
-
scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
|
|
3800
|
-
value: num(r.value),
|
|
3801
|
-
baselineValue: num(r.baselineValue),
|
|
3802
|
-
delta: num(r.delta),
|
|
3803
|
-
movement: typeof r.movement === "string" ? r.movement : null,
|
|
3804
|
-
outcome: typeof r.outcome === "string" ? r.outcome : "",
|
|
3805
|
-
withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
|
|
3806
|
-
basis: typeof r.basis === "string" ? r.basis : null
|
|
3807
|
-
};
|
|
3808
|
-
}
|
|
3809
|
-
function formatWindowOrRaw(startUtc, endUtc) {
|
|
3810
|
-
if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
|
|
3811
|
-
return "not given";
|
|
3812
|
-
return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
|
|
3813
|
-
}
|
|
3814
|
-
function formatDay(iso) {
|
|
3815
|
-
const date = new Date(iso);
|
|
3816
|
-
if (Number.isNaN(date.getTime()))
|
|
3817
|
-
return iso;
|
|
3818
|
-
return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date);
|
|
3819
|
-
}
|
|
3820
|
-
}
|
|
3821
|
-
});
|
|
3822
|
-
|
|
3823
|
-
// ../packages/tool-kit/out/setupDisclosure.js
|
|
3824
|
-
var require_setupDisclosure = __commonJS({
|
|
3825
|
-
"../packages/tool-kit/out/setupDisclosure.js"(exports) {
|
|
3826
|
-
"use strict";
|
|
3827
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3828
|
-
exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
|
|
3829
|
-
exports.renderSetupDisclosure = renderSetupDisclosure;
|
|
3830
|
-
exports.FAMILY_SENTENCES = {
|
|
3831
|
-
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",
|
|
3832
|
-
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",
|
|
3833
|
-
tools: "the name of each tool your agent calls",
|
|
3834
|
-
outcome: "whether a call succeeded, failed, or was interrupted",
|
|
3835
|
-
clock: "your machine's offset from UTC, so an evening is read as an evening",
|
|
3836
|
-
repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
|
|
3837
|
-
model: "which model served the session, by name and by tier",
|
|
3838
|
-
posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
|
|
3839
|
-
git: "that a commit, push or revert happened, and when a pull request opened or merged",
|
|
3840
|
-
edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
|
|
3841
|
-
context: "how full the context window got",
|
|
3842
|
-
waiting: "that your agent stopped and waited for you, as one word: permission_request, idle_prompt, or other",
|
|
3843
|
-
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",
|
|
3844
|
-
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"
|
|
3845
|
-
};
|
|
3846
|
-
exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
|
|
3847
|
-
exports.REFUSALS = [
|
|
3848
|
-
"Never your prompts, your agent's replies, or anything inside a file.",
|
|
3849
|
-
"Never a file path, a command line, or a repository or branch name.",
|
|
3850
|
-
"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."
|
|
3851
|
-
];
|
|
3852
|
-
exports.FREE_TEXT_KEYS = ["message"];
|
|
3853
|
-
function renderSetupDisclosure({ sends, displayName }) {
|
|
3854
|
-
const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
|
|
3855
|
-
const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
|
|
3856
|
-
const lines = [
|
|
3857
|
-
`What this sends from ${displayName}, once paired:`,
|
|
3858
|
-
...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
|
|
3859
|
-
"",
|
|
3860
|
-
...exports.REFUSALS.map((line) => ` ${line}`),
|
|
3861
|
-
"",
|
|
3862
|
-
" Turn it off by revoking this tool in the Ascenda app."
|
|
3863
|
-
];
|
|
3864
|
-
return lines.join("\n");
|
|
4329
|
+
return {
|
|
4330
|
+
id: typeof o.id === "string" ? o.id : "",
|
|
4331
|
+
organisationName: typeof o.organisationName === "string" ? o.organisationName : "Your organisation",
|
|
4332
|
+
title: o.title,
|
|
4333
|
+
summaryForCohort: typeof o.summaryForCohort === "string" ? o.summaryForCohort : "",
|
|
4334
|
+
measureUnit: typeof o.measureUnit === "string" ? o.measureUnit : null,
|
|
4335
|
+
scoringStartUtc: typeof o.scoringStartUtc === "string" ? o.scoringStartUtc : "",
|
|
4336
|
+
scoringEndUtc: typeof o.scoringEndUtc === "string" ? o.scoringEndUtc : "",
|
|
4337
|
+
withdrawnUtc: typeof o.withdrawnUtc === "string" ? o.withdrawnUtc : null,
|
|
4338
|
+
status: o.status,
|
|
4339
|
+
direction: typeof o.direction === "string" ? o.direction : null,
|
|
4340
|
+
result: asResult(o.result)
|
|
4341
|
+
};
|
|
4342
|
+
}
|
|
4343
|
+
function asResult(value) {
|
|
4344
|
+
if (!value || typeof value !== "object")
|
|
4345
|
+
return null;
|
|
4346
|
+
const r = value;
|
|
4347
|
+
const num = (x) => typeof x === "number" && Number.isFinite(x) ? x : null;
|
|
4348
|
+
return {
|
|
4349
|
+
scoredAtUtc: typeof r.scoredAtUtc === "string" ? r.scoredAtUtc : "",
|
|
4350
|
+
value: num(r.value),
|
|
4351
|
+
baselineValue: num(r.baselineValue),
|
|
4352
|
+
delta: num(r.delta),
|
|
4353
|
+
movement: typeof r.movement === "string" ? r.movement : null,
|
|
4354
|
+
outcome: typeof r.outcome === "string" ? r.outcome : "",
|
|
4355
|
+
withheldReason: typeof r.withheldReason === "string" ? r.withheldReason : null,
|
|
4356
|
+
basis: typeof r.basis === "string" ? r.basis : null
|
|
4357
|
+
};
|
|
4358
|
+
}
|
|
4359
|
+
function formatWindowOrRaw(startUtc, endUtc) {
|
|
4360
|
+
if (Number.isNaN(Date.parse(startUtc)) || Number.isNaN(Date.parse(endUtc)))
|
|
4361
|
+
return "not given";
|
|
4362
|
+
return (0, studyJoin_1.formatWindow)(startUtc, endUtc);
|
|
4363
|
+
}
|
|
4364
|
+
function formatDay(iso) {
|
|
4365
|
+
const date = new Date(iso);
|
|
4366
|
+
if (Number.isNaN(date.getTime()))
|
|
4367
|
+
return iso;
|
|
4368
|
+
return new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" }).format(date);
|
|
3865
4369
|
}
|
|
3866
4370
|
}
|
|
3867
4371
|
});
|
|
@@ -3910,9 +4414,11 @@ var require_hookRunner = __commonJS({
|
|
|
3910
4414
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3911
4415
|
exports.hookRunnerPaths = hookRunnerPaths;
|
|
3912
4416
|
exports.hookLauncherScript = hookLauncherScript;
|
|
4417
|
+
exports.isDowngrade = isDowngrade;
|
|
3913
4418
|
exports.installHookRunner = installHookRunner;
|
|
3914
4419
|
exports.removeHookRunner = removeHookRunner;
|
|
3915
4420
|
exports.hookRunnerCommand = hookRunnerCommand;
|
|
4421
|
+
exports.writeAtomically = writeAtomically;
|
|
3916
4422
|
exports.lastHookPath = lastHookPath;
|
|
3917
4423
|
exports.stampLastHook = stampLastHook2;
|
|
3918
4424
|
exports.readLastHook = readLastHook;
|
|
@@ -3920,12 +4426,13 @@ var require_hookRunner = __commonJS({
|
|
|
3920
4426
|
exports.resolveHookNode = resolveHookNode;
|
|
3921
4427
|
exports.tidyHomePath = tidyHomePath;
|
|
3922
4428
|
var child_process_1 = __require("child_process");
|
|
3923
|
-
var
|
|
3924
|
-
var
|
|
4429
|
+
var fs2 = __importStar(__require("fs"));
|
|
4430
|
+
var path3 = __importStar(__require("path"));
|
|
4431
|
+
var collectorVersion_1 = require_collectorVersion();
|
|
3925
4432
|
var tokenStore_1 = require_tokenStore();
|
|
3926
4433
|
function hookRunnerPaths(binaryName) {
|
|
3927
|
-
const launcher =
|
|
3928
|
-
return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node` };
|
|
4434
|
+
const launcher = path3.join((0, tokenStore_1.ascendaHome)(), "bin", binaryName);
|
|
4435
|
+
return { launcher, bundle: `${launcher}.mjs`, record: `${launcher}.node`, noNode: `${launcher}.no-node`, version: `${launcher}.version` };
|
|
3929
4436
|
}
|
|
3930
4437
|
var LAUNCHER_MANAGEMENT_COMMANDS = ["setup", "install", "status", "uninstall", "doctor", "pair", "join", "object", "-h", "--help"];
|
|
3931
4438
|
function hookLauncherScript(options) {
|
|
@@ -4019,62 +4526,98 @@ var require_hookRunner = __commonJS({
|
|
|
4019
4526
|
""
|
|
4020
4527
|
].join("\n");
|
|
4021
4528
|
}
|
|
4529
|
+
function releaseOf(version) {
|
|
4530
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec((version ?? "").trim());
|
|
4531
|
+
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : void 0;
|
|
4532
|
+
}
|
|
4533
|
+
function isDowngrade(installed, incoming) {
|
|
4534
|
+
const have = releaseOf(installed);
|
|
4535
|
+
const want = releaseOf(incoming);
|
|
4536
|
+
if (!have || !want)
|
|
4537
|
+
return false;
|
|
4538
|
+
for (let i = 0; i < 3; i++) {
|
|
4539
|
+
if (have[i] !== want[i])
|
|
4540
|
+
return have[i] > want[i];
|
|
4541
|
+
}
|
|
4542
|
+
return false;
|
|
4543
|
+
}
|
|
4544
|
+
function readInstalledVersion(file) {
|
|
4545
|
+
try {
|
|
4546
|
+
return fs2.readFileSync(file, "utf8").trim() || void 0;
|
|
4547
|
+
} catch {
|
|
4548
|
+
return void 0;
|
|
4549
|
+
}
|
|
4550
|
+
}
|
|
4022
4551
|
function installHookRunner(options) {
|
|
4023
4552
|
const paths = hookRunnerPaths(options.binaryName);
|
|
4024
4553
|
if (options.dryRun)
|
|
4025
4554
|
return paths.launcher;
|
|
4026
|
-
const source =
|
|
4027
|
-
|
|
4555
|
+
const source = path3.resolve(options.source ?? process.argv[1]);
|
|
4556
|
+
const incoming = options.version ?? collectorVersion_1.COLLECTOR_VERSION;
|
|
4557
|
+
const installed = readInstalledVersion(paths.version);
|
|
4558
|
+
const installedFile = process.platform === "win32" ? paths.launcher : paths.bundle;
|
|
4559
|
+
if (installed && fs2.existsSync(installedFile) && isDowngrade(installed, incoming)) {
|
|
4560
|
+
options.onKeptNewer?.(installed, incoming);
|
|
4561
|
+
if (process.platform !== "win32" && !fs2.existsSync(paths.launcher))
|
|
4562
|
+
writeAtomically(paths.launcher, hookLauncherScript(options), 493);
|
|
4563
|
+
return paths.launcher;
|
|
4564
|
+
}
|
|
4565
|
+
fs2.mkdirSync(path3.dirname(paths.launcher), { recursive: true });
|
|
4028
4566
|
if (process.platform === "win32") {
|
|
4029
|
-
if (source !==
|
|
4030
|
-
|
|
4567
|
+
if (source !== path3.resolve(paths.launcher))
|
|
4568
|
+
fs2.copyFileSync(source, paths.launcher);
|
|
4569
|
+
writeAtomically(paths.version, `${incoming}
|
|
4570
|
+
`, 420);
|
|
4031
4571
|
return paths.launcher;
|
|
4032
4572
|
}
|
|
4033
|
-
if (source !==
|
|
4034
|
-
writeAtomically(paths.bundle,
|
|
4573
|
+
if (source !== path3.resolve(paths.bundle))
|
|
4574
|
+
writeAtomically(paths.bundle, fs2.readFileSync(source), 493);
|
|
4035
4575
|
writeAtomically(paths.launcher, hookLauncherScript(options), 493);
|
|
4036
4576
|
writeAtomically(paths.record, `${process.execPath}
|
|
4037
4577
|
`, 420);
|
|
4038
|
-
|
|
4578
|
+
if (source !== path3.resolve(paths.bundle))
|
|
4579
|
+
writeAtomically(paths.version, `${incoming}
|
|
4580
|
+
`, 420);
|
|
4581
|
+
fs2.rmSync(paths.noNode, { force: true });
|
|
4039
4582
|
return paths.launcher;
|
|
4040
4583
|
}
|
|
4041
4584
|
function removeHookRunner(binaryName) {
|
|
4042
4585
|
const removed = [];
|
|
4043
4586
|
for (const file of Object.values(hookRunnerPaths(binaryName))) {
|
|
4044
|
-
if (!
|
|
4587
|
+
if (!fs2.existsSync(file))
|
|
4045
4588
|
continue;
|
|
4046
|
-
|
|
4589
|
+
fs2.rmSync(file, { force: true });
|
|
4047
4590
|
removed.push(file);
|
|
4048
4591
|
}
|
|
4049
4592
|
return removed;
|
|
4050
4593
|
}
|
|
4051
|
-
function hookRunnerCommand(launcher) {
|
|
4052
|
-
return
|
|
4594
|
+
function hookRunnerCommand(launcher, platform = process.platform) {
|
|
4595
|
+
return platform === "win32" ? `"${process.execPath}" "${launcher}"` : `"${launcher}"`;
|
|
4053
4596
|
}
|
|
4054
4597
|
function writeAtomically(target, contents, mode) {
|
|
4055
4598
|
const tmp = `${target}.${process.pid}.tmp`;
|
|
4056
|
-
|
|
4057
|
-
|
|
4058
|
-
|
|
4599
|
+
fs2.writeFileSync(tmp, contents, { mode });
|
|
4600
|
+
fs2.chmodSync(tmp, mode);
|
|
4601
|
+
fs2.renameSync(tmp, target);
|
|
4059
4602
|
}
|
|
4060
|
-
var stateDir = () => process.env.ASCENDA_STATE_DIR ??
|
|
4603
|
+
var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path3.join((0, tokenStore_1.ascendaHome)(), "state");
|
|
4061
4604
|
function lastHookPath(tool) {
|
|
4062
|
-
return
|
|
4605
|
+
return path3.join(stateDir(), `${tool}-last-hook.json`);
|
|
4063
4606
|
}
|
|
4064
4607
|
function stampLastHook2(tool, event, now = /* @__PURE__ */ new Date()) {
|
|
4065
4608
|
try {
|
|
4066
|
-
|
|
4609
|
+
fs2.mkdirSync(stateDir(), { recursive: true });
|
|
4067
4610
|
const file = lastHookPath(tool);
|
|
4068
4611
|
const tmp = `${file}.${process.pid}.tmp`;
|
|
4069
|
-
|
|
4612
|
+
fs2.writeFileSync(tmp, `${JSON.stringify({ event, at: now.toISOString() })}
|
|
4070
4613
|
`, { mode: 384 });
|
|
4071
|
-
|
|
4614
|
+
fs2.renameSync(tmp, file);
|
|
4072
4615
|
} catch {
|
|
4073
4616
|
}
|
|
4074
4617
|
}
|
|
4075
4618
|
function readLastHook(tool) {
|
|
4076
4619
|
try {
|
|
4077
|
-
const parsed = JSON.parse(
|
|
4620
|
+
const parsed = JSON.parse(fs2.readFileSync(lastHookPath(tool), "utf8"));
|
|
4078
4621
|
if (typeof parsed.event !== "string" || typeof parsed.at !== "string")
|
|
4079
4622
|
return void 0;
|
|
4080
4623
|
return { event: parsed.event, at: parsed.at };
|
|
@@ -4097,7 +4640,7 @@ var require_hookRunner = __commonJS({
|
|
|
4097
4640
|
return `${Math.round(hours / 24)} days ago`;
|
|
4098
4641
|
}
|
|
4099
4642
|
function resolveHookNode(launcher) {
|
|
4100
|
-
if (!
|
|
4643
|
+
if (!fs2.existsSync(launcher))
|
|
4101
4644
|
return { problem: "the hook launcher is not installed" };
|
|
4102
4645
|
const probe = (0, child_process_1.spawnSync)("/bin/sh", [launcher], {
|
|
4103
4646
|
encoding: "utf8",
|
|
@@ -4119,6 +4662,115 @@ var require_hookRunner = __commonJS({
|
|
|
4119
4662
|
}
|
|
4120
4663
|
});
|
|
4121
4664
|
|
|
4665
|
+
// ../packages/tool-kit/out/settingsFile.js
|
|
4666
|
+
var require_settingsFile = __commonJS({
|
|
4667
|
+
"../packages/tool-kit/out/settingsFile.js"(exports) {
|
|
4668
|
+
"use strict";
|
|
4669
|
+
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
|
|
4670
|
+
if (k2 === void 0) k2 = k;
|
|
4671
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
4672
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
4673
|
+
desc = { enumerable: true, get: function() {
|
|
4674
|
+
return m[k];
|
|
4675
|
+
} };
|
|
4676
|
+
}
|
|
4677
|
+
Object.defineProperty(o, k2, desc);
|
|
4678
|
+
} : function(o, m, k, k2) {
|
|
4679
|
+
if (k2 === void 0) k2 = k;
|
|
4680
|
+
o[k2] = m[k];
|
|
4681
|
+
});
|
|
4682
|
+
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
|
|
4683
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
4684
|
+
} : function(o, v) {
|
|
4685
|
+
o["default"] = v;
|
|
4686
|
+
});
|
|
4687
|
+
var __importStar = exports && exports.__importStar || /* @__PURE__ */ function() {
|
|
4688
|
+
var ownKeys = function(o) {
|
|
4689
|
+
ownKeys = Object.getOwnPropertyNames || function(o2) {
|
|
4690
|
+
var ar = [];
|
|
4691
|
+
for (var k in o2) if (Object.prototype.hasOwnProperty.call(o2, k)) ar[ar.length] = k;
|
|
4692
|
+
return ar;
|
|
4693
|
+
};
|
|
4694
|
+
return ownKeys(o);
|
|
4695
|
+
};
|
|
4696
|
+
return function(mod) {
|
|
4697
|
+
if (mod && mod.__esModule) return mod;
|
|
4698
|
+
var result = {};
|
|
4699
|
+
if (mod != null) {
|
|
4700
|
+
for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
4701
|
+
}
|
|
4702
|
+
__setModuleDefault(result, mod);
|
|
4703
|
+
return result;
|
|
4704
|
+
};
|
|
4705
|
+
}();
|
|
4706
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4707
|
+
exports.replaceSettingsFile = replaceSettingsFile;
|
|
4708
|
+
var fs2 = __importStar(__require("fs"));
|
|
4709
|
+
var path3 = __importStar(__require("path"));
|
|
4710
|
+
var hookRunner_1 = require_hookRunner();
|
|
4711
|
+
function replaceSettingsFile(settingsFile, contents) {
|
|
4712
|
+
const exists = fs2.existsSync(settingsFile);
|
|
4713
|
+
const target = exists ? fs2.realpathSync(settingsFile) : settingsFile;
|
|
4714
|
+
if (exists) {
|
|
4715
|
+
const backup = `${settingsFile}.ascenda-backup`;
|
|
4716
|
+
if (!fs2.existsSync(backup))
|
|
4717
|
+
fs2.copyFileSync(target, backup);
|
|
4718
|
+
}
|
|
4719
|
+
fs2.mkdirSync(path3.dirname(target), { recursive: true });
|
|
4720
|
+
const mode = exists ? fs2.statSync(target).mode & 511 : 420;
|
|
4721
|
+
(0, hookRunner_1.writeAtomically)(target, contents, mode);
|
|
4722
|
+
}
|
|
4723
|
+
}
|
|
4724
|
+
});
|
|
4725
|
+
|
|
4726
|
+
// ../packages/tool-kit/out/setupDisclosure.js
|
|
4727
|
+
var require_setupDisclosure = __commonJS({
|
|
4728
|
+
"../packages/tool-kit/out/setupDisclosure.js"(exports) {
|
|
4729
|
+
"use strict";
|
|
4730
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4731
|
+
exports.FREE_TEXT_KEYS = exports.REFUSALS = exports.ALWAYS_SENT = exports.FAMILY_SENTENCES = void 0;
|
|
4732
|
+
exports.renderSetupDisclosure = renderSetupDisclosure;
|
|
4733
|
+
exports.FAMILY_SENTENCES = {
|
|
4734
|
+
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",
|
|
4735
|
+
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",
|
|
4736
|
+
tools: "the name of each tool your agent calls",
|
|
4737
|
+
outcome: "whether a call succeeded, failed, or was interrupted",
|
|
4738
|
+
clock: "your machine's offset from UTC, so an evening is read as an evening",
|
|
4739
|
+
repo: "your project and branch as digests computed on this machine \u2014 never the names themselves",
|
|
4740
|
+
model: "which model served the session, by name and by tier",
|
|
4741
|
+
posture: "the permission posture your agent was working under \u2014 asking each time, accepting edits, and so on",
|
|
4742
|
+
git: "that a commit, push or revert happened, and when a pull request opened or merged",
|
|
4743
|
+
edits: "roughly how much a file changed, as a bucket, and whether you edited it after the agent wrote it",
|
|
4744
|
+
context: "how full the context window got",
|
|
4745
|
+
waiting: "that your agent stopped and waited for you, as one word: permission_request, input_request, idle_prompt, or other, and that it asked permission for a tool or had one refused in auto mode, with the tool's name",
|
|
4746
|
+
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",
|
|
4747
|
+
forge: "for a GitHub repository, one digest of owner/repo and one of the branch, which anyone who guesses the names can reproduce, so a pull request can be matched to your session (turn off with setup --no-repo-keys)",
|
|
4748
|
+
turns: "an opaque id your agent gives each prompt, so one turn's events group together",
|
|
4749
|
+
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"
|
|
4750
|
+
};
|
|
4751
|
+
exports.ALWAYS_SENT = ["session", "counts", "tools", "outcome", "repo", "clock"];
|
|
4752
|
+
exports.REFUSALS = [
|
|
4753
|
+
"Never your prompts, your agent's replies, or anything inside a file.",
|
|
4754
|
+
"Never a file path, a command line, or a repository or branch name.",
|
|
4755
|
+
"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."
|
|
4756
|
+
];
|
|
4757
|
+
exports.FREE_TEXT_KEYS = ["message"];
|
|
4758
|
+
function renderSetupDisclosure({ sends, displayName }) {
|
|
4759
|
+
const declared = /* @__PURE__ */ new Set([...exports.ALWAYS_SENT, ...sends]);
|
|
4760
|
+
const ordered = Object.keys(exports.FAMILY_SENTENCES).filter((family) => declared.has(family));
|
|
4761
|
+
const lines = [
|
|
4762
|
+
`What this sends from ${displayName}, once paired:`,
|
|
4763
|
+
...ordered.map((family) => ` \xB7 ${exports.FAMILY_SENTENCES[family]}`),
|
|
4764
|
+
"",
|
|
4765
|
+
...exports.REFUSALS.map((line) => ` ${line}`),
|
|
4766
|
+
"",
|
|
4767
|
+
" Turn it off by revoking this tool in the Ascenda app."
|
|
4768
|
+
];
|
|
4769
|
+
return lines.join("\n");
|
|
4770
|
+
}
|
|
4771
|
+
}
|
|
4772
|
+
});
|
|
4773
|
+
|
|
4122
4774
|
// ../packages/tool-kit/out/saverHandoff.js
|
|
4123
4775
|
var require_saverHandoff = __commonJS({
|
|
4124
4776
|
"../packages/tool-kit/out/saverHandoff.js"(exports) {
|
|
@@ -4170,22 +4822,22 @@ var require_saverHandoff = __commonJS({
|
|
|
4170
4822
|
exports.heldForSaver = heldForSaver;
|
|
4171
4823
|
exports.readSaverStatuses = readSaverStatuses;
|
|
4172
4824
|
exports.probeSocket = probeSocket;
|
|
4173
|
-
var
|
|
4825
|
+
var fs2 = __importStar(__require("fs"));
|
|
4174
4826
|
var net = __importStar(__require("net"));
|
|
4175
4827
|
var os2 = __importStar(__require("os"));
|
|
4176
|
-
var
|
|
4828
|
+
var path3 = __importStar(__require("path"));
|
|
4177
4829
|
var SAVER_HOST_BUNDLE_ID = "com.apple.ScreenSaver.Engine.legacyScreenSaver";
|
|
4178
4830
|
function saverContainerDir() {
|
|
4179
|
-
return process.env.ASCENDA_SAVER_CONTAINER ??
|
|
4831
|
+
return process.env.ASCENDA_SAVER_CONTAINER ?? path3.join(os2.homedir(), "Library", "Containers", SAVER_HOST_BUNDLE_ID, "Data");
|
|
4180
4832
|
}
|
|
4181
4833
|
function saverSupportDir() {
|
|
4182
|
-
return
|
|
4834
|
+
return path3.join(saverContainerDir(), "Library", "Application Support", "AscendaWaterlineSaver");
|
|
4183
4835
|
}
|
|
4184
4836
|
function saverReplayPath() {
|
|
4185
|
-
return
|
|
4837
|
+
return path3.join(saverContainerDir(), "l.replay.json");
|
|
4186
4838
|
}
|
|
4187
4839
|
function saverStatusDir() {
|
|
4188
|
-
return
|
|
4840
|
+
return path3.join(saverSupportDir(), "status");
|
|
4189
4841
|
}
|
|
4190
4842
|
exports.SAVER_REPLAY_WINDOW_MS = 30 * 60 * 1e3;
|
|
4191
4843
|
var SAVER_REPLAY_MAX = 32;
|
|
@@ -4194,7 +4846,7 @@ var require_saverHandoff = __commonJS({
|
|
|
4194
4846
|
try {
|
|
4195
4847
|
if (process.env.ASCENDA_LIVE_BUS_SOCKET && !process.env.ASCENDA_SAVER_CONTAINER)
|
|
4196
4848
|
return;
|
|
4197
|
-
if (!
|
|
4849
|
+
if (!fs2.existsSync(saverSupportDir()))
|
|
4198
4850
|
return;
|
|
4199
4851
|
const wire = signal;
|
|
4200
4852
|
const tool = wire.tool;
|
|
@@ -4208,15 +4860,15 @@ var require_saverHandoff = __commonJS({
|
|
|
4208
4860
|
kept.sort((a, b) => a.at - b.at);
|
|
4209
4861
|
const body = JSON.stringify({ schema: exports.SAVER_REPLAY_SCHEMA, signals: kept.slice(-SAVER_REPLAY_MAX) });
|
|
4210
4862
|
const tmp = `${file}.${process.pid}.tmp`;
|
|
4211
|
-
|
|
4863
|
+
fs2.writeFileSync(tmp, `${body}
|
|
4212
4864
|
`, { mode: 384 });
|
|
4213
|
-
|
|
4865
|
+
fs2.renameSync(tmp, file);
|
|
4214
4866
|
} catch {
|
|
4215
4867
|
}
|
|
4216
4868
|
}
|
|
4217
4869
|
function readHeld(file) {
|
|
4218
4870
|
try {
|
|
4219
|
-
const parsed = JSON.parse(
|
|
4871
|
+
const parsed = JSON.parse(fs2.readFileSync(file, "utf8"));
|
|
4220
4872
|
if (parsed.schema !== exports.SAVER_REPLAY_SCHEMA || !Array.isArray(parsed.signals))
|
|
4221
4873
|
return [];
|
|
4222
4874
|
return parsed.signals.filter((held) => typeof held === "object" && held !== null && typeof held.tool === "string" && typeof held.session === "string" && typeof held.event === "string" && typeof held.at === "number");
|
|
@@ -4233,14 +4885,14 @@ var require_saverHandoff = __commonJS({
|
|
|
4233
4885
|
function readSaverStatuses(now = Date.now()) {
|
|
4234
4886
|
let names;
|
|
4235
4887
|
try {
|
|
4236
|
-
names =
|
|
4888
|
+
names = fs2.readdirSync(saverStatusDir()).filter((name) => name.endsWith(".json"));
|
|
4237
4889
|
} catch {
|
|
4238
4890
|
return [];
|
|
4239
4891
|
}
|
|
4240
4892
|
const readings = [];
|
|
4241
4893
|
for (const name of names) {
|
|
4242
4894
|
try {
|
|
4243
|
-
const status = JSON.parse(
|
|
4895
|
+
const status = JSON.parse(fs2.readFileSync(path3.join(saverStatusDir(), name), "utf8"));
|
|
4244
4896
|
if (typeof status.pid !== "number" || typeof status.updatedAt !== "string")
|
|
4245
4897
|
continue;
|
|
4246
4898
|
readings.push({ ...status, alive: processAlive(status.pid), ageMs: now - Date.parse(status.updatedAt) });
|
|
@@ -4258,14 +4910,14 @@ var require_saverHandoff = __commonJS({
|
|
|
4258
4910
|
}
|
|
4259
4911
|
}
|
|
4260
4912
|
function probeSocket(socketPath, timeoutMs = 300) {
|
|
4261
|
-
return new Promise((
|
|
4913
|
+
return new Promise((resolve3) => {
|
|
4262
4914
|
try {
|
|
4263
|
-
if (!
|
|
4264
|
-
|
|
4915
|
+
if (!fs2.statSync(socketPath).isSocket()) {
|
|
4916
|
+
resolve3("absent");
|
|
4265
4917
|
return;
|
|
4266
4918
|
}
|
|
4267
4919
|
} catch {
|
|
4268
|
-
|
|
4920
|
+
resolve3("absent");
|
|
4269
4921
|
return;
|
|
4270
4922
|
}
|
|
4271
4923
|
let settled = false;
|
|
@@ -4275,7 +4927,7 @@ var require_saverHandoff = __commonJS({
|
|
|
4275
4927
|
settled = true;
|
|
4276
4928
|
clearTimeout(timer);
|
|
4277
4929
|
socket.destroy();
|
|
4278
|
-
|
|
4930
|
+
resolve3(state);
|
|
4279
4931
|
};
|
|
4280
4932
|
const socket = net.createConnection(socketPath);
|
|
4281
4933
|
const timer = setTimeout(() => finish("unreachable"), timeoutMs);
|
|
@@ -4335,10 +4987,10 @@ var require_liveBus = __commonJS({
|
|
|
4335
4987
|
exports.bucketPromptSize = bucketPromptSize2;
|
|
4336
4988
|
exports.emitLiveSignal = emitLiveSignal2;
|
|
4337
4989
|
exports.deliverLine = deliverLine;
|
|
4338
|
-
var
|
|
4990
|
+
var fs2 = __importStar(__require("fs"));
|
|
4339
4991
|
var net = __importStar(__require("net"));
|
|
4340
4992
|
var os2 = __importStar(__require("os"));
|
|
4341
|
-
var
|
|
4993
|
+
var path3 = __importStar(__require("path"));
|
|
4342
4994
|
var hookSet_1 = require_hookSet();
|
|
4343
4995
|
var saverHandoff_1 = require_saverHandoff();
|
|
4344
4996
|
var WRITE_TIMEOUT_MS = 50;
|
|
@@ -4351,9 +5003,9 @@ var require_liveBus = __commonJS({
|
|
|
4351
5003
|
return [override];
|
|
4352
5004
|
const home = os2.homedir();
|
|
4353
5005
|
return [
|
|
4354
|
-
|
|
4355
|
-
|
|
4356
|
-
|
|
5006
|
+
path3.join(home, ".ascenda", "live.sock"),
|
|
5007
|
+
path3.join(home, "Library", "Containers", APP_BUNDLE_ID, "Data", ".ascenda", "live.sock"),
|
|
5008
|
+
path3.join(home, "Library", "Containers", exports.SAVER_HOST_BUNDLE_ID, "Data", "l.sock")
|
|
4357
5009
|
];
|
|
4358
5010
|
}
|
|
4359
5011
|
function existingSocketCandidates() {
|
|
@@ -4362,7 +5014,7 @@ var require_liveBus = __commonJS({
|
|
|
4362
5014
|
return candidates;
|
|
4363
5015
|
return candidates.filter((candidate) => {
|
|
4364
5016
|
try {
|
|
4365
|
-
return
|
|
5017
|
+
return fs2.statSync(candidate).isSocket();
|
|
4366
5018
|
} catch {
|
|
4367
5019
|
return false;
|
|
4368
5020
|
}
|
|
@@ -4399,10 +5051,10 @@ var require_liveBus = __commonJS({
|
|
|
4399
5051
|
});
|
|
4400
5052
|
}
|
|
4401
5053
|
function deliverLine(line) {
|
|
4402
|
-
return new Promise((
|
|
5054
|
+
return new Promise((resolve3) => {
|
|
4403
5055
|
const candidates = existingSocketCandidates();
|
|
4404
5056
|
if (candidates.length === 0) {
|
|
4405
|
-
|
|
5057
|
+
resolve3(void 0);
|
|
4406
5058
|
return;
|
|
4407
5059
|
}
|
|
4408
5060
|
let settled = false;
|
|
@@ -4421,7 +5073,7 @@ var require_liveBus = __commonJS({
|
|
|
4421
5073
|
settled = true;
|
|
4422
5074
|
clearTimeout(timer);
|
|
4423
5075
|
drop();
|
|
4424
|
-
|
|
5076
|
+
resolve3(accepted);
|
|
4425
5077
|
};
|
|
4426
5078
|
const timer = setTimeout(done, WRITE_TIMEOUT_MS);
|
|
4427
5079
|
const tryFrom = (index) => {
|
|
@@ -4621,7 +5273,7 @@ var require_liveSignalDoctor = __commonJS({
|
|
|
4621
5273
|
if (accepted !== saverSocket)
|
|
4622
5274
|
return { tone: "ok", text: `the desktop app took it (${accepted})` };
|
|
4623
5275
|
for (let waited = 0; waited < 2e3; waited += 100) {
|
|
4624
|
-
await new Promise((
|
|
5276
|
+
await new Promise((resolve3) => setTimeout(resolve3, 100));
|
|
4625
5277
|
const answered = (0, saverHandoff_1.readSaverStatuses)().find((status) => status.lastPingSession === session);
|
|
4626
5278
|
if (answered)
|
|
4627
5279
|
return { tone: "ok", text: `OK. The screen saver (pid ${answered.pid}) received it` };
|
|
@@ -4884,12 +5536,14 @@ var require_cliAgentSetup = __commonJS({
|
|
|
4884
5536
|
exports.runCliAgentSetup = runCliAgentSetup2;
|
|
4885
5537
|
exports.writeHookSettings = writeHookSettings;
|
|
4886
5538
|
exports.registeredHookSets = registeredHookSets;
|
|
5539
|
+
exports.ourHookPositions = ourHookPositions;
|
|
5540
|
+
exports.trustProblemLines = trustProblemLines;
|
|
4887
5541
|
exports.findStaleHookCommands = findStaleHookCommands;
|
|
4888
5542
|
exports.cliAgentRegistrations = cliAgentRegistrations;
|
|
4889
5543
|
var crypto = __importStar(__require("crypto"));
|
|
4890
|
-
var
|
|
5544
|
+
var fs2 = __importStar(__require("fs"));
|
|
4891
5545
|
var os2 = __importStar(__require("os"));
|
|
4892
|
-
var
|
|
5546
|
+
var path3 = __importStar(__require("path"));
|
|
4893
5547
|
var collectorVersion_1 = require_collectorVersion();
|
|
4894
5548
|
var credentials_1 = require_credentials();
|
|
4895
5549
|
var eventLog_1 = require_eventLog();
|
|
@@ -4897,6 +5551,7 @@ var require_cliAgentSetup = __commonJS({
|
|
|
4897
5551
|
var http_1 = require_http();
|
|
4898
5552
|
var hookSet_1 = require_hookSet();
|
|
4899
5553
|
var initiatives_1 = require_initiatives();
|
|
5554
|
+
var settingsFile_1 = require_settingsFile();
|
|
4900
5555
|
var setupDisclosure_1 = require_setupDisclosure();
|
|
4901
5556
|
var hookRunner_1 = require_hookRunner();
|
|
4902
5557
|
var liveSignalDoctor_1 = require_liveSignalDoctor();
|
|
@@ -4933,6 +5588,10 @@ Options
|
|
|
4933
5588
|
--no-pair install without pairing: local features on, nothing sent
|
|
4934
5589
|
--event-log [path|off] keep every event in a local JSONL file (default ~/.ascenda/events.jsonl).
|
|
4935
5590
|
On by default when not paired; machine-wide, shared by every agent
|
|
5591
|
+
--no-repo-keys leave the repository and branch keys off every event. On by default: a GitHub
|
|
5592
|
+
repository gets a key and, off its default branch, a branch key, so a pull
|
|
5593
|
+
request can be matched to a session. They are digests anyone who guesses the
|
|
5594
|
+
names can reproduce. Machine-wide. --repo-keys turns them back on
|
|
4936
5595
|
--scope user|project where hooks are registered (default user: every project)
|
|
4937
5596
|
--project-dir <path> project root for --scope project (default cwd)
|
|
4938
5597
|
--dry-run print what would change, write nothing
|
|
@@ -4989,6 +5648,8 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
|
|
|
4989
5648
|
});
|
|
4990
5649
|
if (options.eventLog !== void 0)
|
|
4991
5650
|
(0, credentials_1.writeEventLogSetting)(options.eventLog);
|
|
5651
|
+
if (options.repoKeys !== void 0)
|
|
5652
|
+
(0, credentials_1.writeRepoKeysSetting)(options.repoKeys);
|
|
4992
5653
|
}
|
|
4993
5654
|
if (isHomeProject(options)) {
|
|
4994
5655
|
detail("scope", "user (a project install in the home folder only loads when the agent starts there)");
|
|
@@ -5062,7 +5723,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
|
|
|
5062
5723
|
return 0;
|
|
5063
5724
|
}
|
|
5064
5725
|
function isHomeProject(options) {
|
|
5065
|
-
return options.scope === "project" &&
|
|
5726
|
+
return options.scope === "project" && path3.resolve(options.projectDir) === path3.resolve(os2.homedir());
|
|
5066
5727
|
}
|
|
5067
5728
|
function parseArgs(argv, spec) {
|
|
5068
5729
|
const options = {
|
|
@@ -5117,7 +5778,7 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
|
|
|
5117
5778
|
break;
|
|
5118
5779
|
}
|
|
5119
5780
|
case "--project-dir":
|
|
5120
|
-
options.projectDir =
|
|
5781
|
+
options.projectDir = path3.resolve(next());
|
|
5121
5782
|
break;
|
|
5122
5783
|
case "--dry-run":
|
|
5123
5784
|
options.dryRun = true;
|
|
@@ -5128,6 +5789,12 @@ ${(0, setupDisclosure_1.renderSetupDisclosure)({ sends: spec.sends, displayName:
|
|
|
5128
5789
|
i += consumed;
|
|
5129
5790
|
break;
|
|
5130
5791
|
}
|
|
5792
|
+
case "--repo-keys":
|
|
5793
|
+
options.repoKeys = true;
|
|
5794
|
+
break;
|
|
5795
|
+
case "--no-repo-keys":
|
|
5796
|
+
options.repoKeys = false;
|
|
5797
|
+
break;
|
|
5131
5798
|
case "--no-pair":
|
|
5132
5799
|
// `--no-pairing` is the spelling this landed under first. Both appeared
|
|
5133
5800
|
// only in an unreleased changelog, so this alias exists to spare anyone
|
|
@@ -5251,19 +5918,24 @@ Pairing ${status.status}. Run setup again.`);
|
|
|
5251
5918
|
console.log(" Waiting...");
|
|
5252
5919
|
announced = true;
|
|
5253
5920
|
}
|
|
5254
|
-
await new Promise((
|
|
5921
|
+
await new Promise((resolve3) => setTimeout(resolve3, 2e3));
|
|
5255
5922
|
}
|
|
5256
5923
|
console.error("\nPairing timed out. Run setup again.");
|
|
5257
5924
|
return void 0;
|
|
5258
5925
|
}
|
|
5259
5926
|
function installBinary(spec, dryRun) {
|
|
5260
|
-
return (0, hookRunner_1.installHookRunner)({
|
|
5927
|
+
return (0, hookRunner_1.installHookRunner)({
|
|
5928
|
+
binaryName: spec.binaryName,
|
|
5929
|
+
setupCommand: `npx ${spec.packageName} setup`,
|
|
5930
|
+
dryRun,
|
|
5931
|
+
onKeptNewer: (installed, incoming) => console.log(` Kept the installed hook bundle (${installed}) rather than replace it with this older ${incoming}. Run setup from the newer version to change it.`)
|
|
5932
|
+
});
|
|
5261
5933
|
}
|
|
5262
5934
|
function writeHookSettings(settingsFile, binary, spec, dryRun) {
|
|
5263
5935
|
let settings = { ...spec.settings.scaffold ?? {} };
|
|
5264
|
-
const exists =
|
|
5936
|
+
const exists = fs2.existsSync(settingsFile);
|
|
5265
5937
|
if (exists) {
|
|
5266
|
-
const raw =
|
|
5938
|
+
const raw = fs2.readFileSync(settingsFile, "utf8").trim();
|
|
5267
5939
|
if (raw) {
|
|
5268
5940
|
try {
|
|
5269
5941
|
settings = JSON.parse(raw);
|
|
@@ -5277,13 +5949,12 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
|
|
|
5277
5949
|
const command = hookCommand(binary, spec);
|
|
5278
5950
|
const hooks = { ...settings.hooks ?? {} };
|
|
5279
5951
|
for (const event of spec.hookEvents) {
|
|
5280
|
-
|
|
5281
|
-
hooks[event] = [...kept, spec.settings.entry(command, event)];
|
|
5952
|
+
hooks[event] = placeOurEntry(hooks[event] ?? [], spec.settings.entry(command, event), spec);
|
|
5282
5953
|
}
|
|
5283
5954
|
const updated = { ...settings, hooks };
|
|
5284
5955
|
const serialised = `${JSON.stringify(updated, null, 2)}
|
|
5285
5956
|
`;
|
|
5286
|
-
if (exists &&
|
|
5957
|
+
if (exists && fs2.readFileSync(settingsFile, "utf8") === serialised)
|
|
5287
5958
|
return false;
|
|
5288
5959
|
if (dryRun) {
|
|
5289
5960
|
console.log(`
|
|
@@ -5291,10 +5962,7 @@ ${settingsFile} is not valid JSON. Fix or move it, then run setup again.`);
|
|
|
5291
5962
|
${serialised}`);
|
|
5292
5963
|
return true;
|
|
5293
5964
|
}
|
|
5294
|
-
|
|
5295
|
-
fs.copyFileSync(settingsFile, `${settingsFile}.ascenda-backup`);
|
|
5296
|
-
fs.mkdirSync(path2.dirname(settingsFile), { recursive: true });
|
|
5297
|
-
fs.writeFileSync(settingsFile, serialised, "utf8");
|
|
5965
|
+
(0, settingsFile_1.replaceSettingsFile)(settingsFile, serialised);
|
|
5298
5966
|
return true;
|
|
5299
5967
|
}
|
|
5300
5968
|
function hookCommand(binary, spec) {
|
|
@@ -5304,35 +5972,137 @@ ${serialised}`);
|
|
|
5304
5972
|
const sets = /* @__PURE__ */ new Map();
|
|
5305
5973
|
for (const [event, entries] of Object.entries(settings.hooks ?? {})) {
|
|
5306
5974
|
for (const entry of entries ?? []) {
|
|
5307
|
-
|
|
5308
|
-
|
|
5309
|
-
|
|
5310
|
-
|
|
5975
|
+
for (const command of commandsOf(entry, spec)) {
|
|
5976
|
+
if (!isOurCommand(command, spec))
|
|
5977
|
+
continue;
|
|
5978
|
+
const set = (0, hookSet_1.hookSetOfCommand)(command);
|
|
5979
|
+
sets.set(event, Math.min(set, sets.get(event) ?? set));
|
|
5980
|
+
}
|
|
5311
5981
|
}
|
|
5312
5982
|
}
|
|
5313
5983
|
return sets;
|
|
5314
5984
|
}
|
|
5315
|
-
function
|
|
5985
|
+
function ourHookPositions(settings, spec) {
|
|
5986
|
+
const found = [];
|
|
5987
|
+
for (const [event, groups] of Object.entries(settings.hooks ?? {})) {
|
|
5988
|
+
(groups ?? []).forEach((group, groupIndex) => {
|
|
5989
|
+
const handlers = group?.hooks;
|
|
5990
|
+
if (Array.isArray(handlers)) {
|
|
5991
|
+
handlers.forEach((handler, handlerIndex) => {
|
|
5992
|
+
if (isOurs({ hooks: [handler] }, spec))
|
|
5993
|
+
found.push({ event, group: groupIndex, handler: handlerIndex });
|
|
5994
|
+
});
|
|
5995
|
+
} else if (isOurs(group, spec)) {
|
|
5996
|
+
found.push({ event, group: groupIndex, handler: 0 });
|
|
5997
|
+
}
|
|
5998
|
+
});
|
|
5999
|
+
}
|
|
6000
|
+
return found;
|
|
6001
|
+
}
|
|
6002
|
+
function trustProblemLines(spec, settingsFile, settings, indent) {
|
|
6003
|
+
if (!spec.trust)
|
|
6004
|
+
return [];
|
|
6005
|
+
const ours = ourHookPositions(settings, spec);
|
|
6006
|
+
if (ours.length === 0)
|
|
6007
|
+
return [];
|
|
6008
|
+
const report = spec.trust.check(settingsFile, ours);
|
|
6009
|
+
const where = (0, hookRunner_1.tidyHomePath)(report.approvalsFile, os2.homedir());
|
|
6010
|
+
const lines = [];
|
|
6011
|
+
if (report.unreadable) {
|
|
6012
|
+
lines.push(`${spec.displayName}'s approvals in ${where} could not be read, so whether these hooks are trusted is unknown.`);
|
|
6013
|
+
}
|
|
6014
|
+
if (report.untrusted.length) {
|
|
6015
|
+
const names = [...new Set(report.untrusted.map((position) => position.event))].join(", ");
|
|
6016
|
+
lines.push(`${report.untrusted.length} of ${ours.length} hooks are not approved in ${where} (${names}). ${spec.displayName} skips them without a message, so nothing is sent for those events.`);
|
|
6017
|
+
}
|
|
6018
|
+
for (const entry of report.stale)
|
|
6019
|
+
lines.push(entry);
|
|
6020
|
+
if (lines.length)
|
|
6021
|
+
lines.push(spec.trust.fix);
|
|
6022
|
+
return lines.map((line) => `${indent}${line}`);
|
|
6023
|
+
}
|
|
6024
|
+
function commandsOf(entry, spec) {
|
|
6025
|
+
if (spec.settings.grouped) {
|
|
6026
|
+
return innerHooks(entry).map(commandOfHook).filter((command2) => typeof command2 === "string");
|
|
6027
|
+
}
|
|
5316
6028
|
const command = spec.settings.commandOf(entry);
|
|
5317
|
-
return typeof command === "string"
|
|
6029
|
+
return typeof command === "string" ? [command] : [];
|
|
6030
|
+
}
|
|
6031
|
+
function innerHooks(entry) {
|
|
6032
|
+
const hooks = entry && typeof entry === "object" ? entry.hooks : void 0;
|
|
6033
|
+
return Array.isArray(hooks) ? hooks : [];
|
|
6034
|
+
}
|
|
6035
|
+
function commandOfHook(hook) {
|
|
6036
|
+
return hook && typeof hook === "object" ? hook.command : void 0;
|
|
6037
|
+
}
|
|
6038
|
+
function isOurCommand(command, spec) {
|
|
6039
|
+
return command.includes(spec.binaryName);
|
|
6040
|
+
}
|
|
6041
|
+
function isOurs(entry, spec) {
|
|
6042
|
+
return commandsOf(entry, spec).some((command) => isOurCommand(command, spec));
|
|
6043
|
+
}
|
|
6044
|
+
function isOurInnerHook(hook, spec) {
|
|
6045
|
+
const command = commandOfHook(hook);
|
|
6046
|
+
return typeof command === "string" && isOurCommand(command, spec);
|
|
6047
|
+
}
|
|
6048
|
+
function withoutOurEntries(entries, spec) {
|
|
6049
|
+
if (!spec.settings.grouped)
|
|
6050
|
+
return entries.filter((entry) => !isOurs(entry, spec));
|
|
6051
|
+
const kept = [];
|
|
6052
|
+
for (const entry of entries) {
|
|
6053
|
+
if (!isOurs(entry, spec)) {
|
|
6054
|
+
kept.push(entry);
|
|
6055
|
+
continue;
|
|
6056
|
+
}
|
|
6057
|
+
const others = innerHooks(entry).filter((hook) => !isOurInnerHook(hook, spec));
|
|
6058
|
+
if (others.length)
|
|
6059
|
+
kept.push({ ...entry, hooks: others });
|
|
6060
|
+
}
|
|
6061
|
+
return kept;
|
|
6062
|
+
}
|
|
6063
|
+
function placeOurEntry(entries, wanted, spec) {
|
|
6064
|
+
if (!spec.settings.grouped)
|
|
6065
|
+
return [...withoutOurEntries(entries, spec), wanted];
|
|
6066
|
+
const replacements = innerHooks(wanted);
|
|
6067
|
+
let placed = false;
|
|
6068
|
+
const result = [];
|
|
6069
|
+
for (const entry of entries) {
|
|
6070
|
+
if (!isOurs(entry, spec)) {
|
|
6071
|
+
result.push(entry);
|
|
6072
|
+
continue;
|
|
6073
|
+
}
|
|
6074
|
+
const matcher = entry.matcher;
|
|
6075
|
+
const matchesAll = matcher === void 0 || matcher === "";
|
|
6076
|
+
const next = [];
|
|
6077
|
+
for (const hook of innerHooks(entry)) {
|
|
6078
|
+
if (!isOurInnerHook(hook, spec))
|
|
6079
|
+
next.push(hook);
|
|
6080
|
+
else if (!placed && matchesAll) {
|
|
6081
|
+
next.push(...replacements);
|
|
6082
|
+
placed = true;
|
|
6083
|
+
}
|
|
6084
|
+
}
|
|
6085
|
+
if (next.length)
|
|
6086
|
+
result.push({ ...entry, hooks: next });
|
|
6087
|
+
}
|
|
6088
|
+
return placed ? result : [...result, wanted];
|
|
5318
6089
|
}
|
|
5319
6090
|
function findStaleHookCommands(settings, binary, spec) {
|
|
5320
6091
|
const stale = /* @__PURE__ */ new Set();
|
|
5321
6092
|
for (const entries of Object.values(settings.hooks ?? {})) {
|
|
5322
6093
|
for (const entry of entries ?? []) {
|
|
5323
|
-
const command
|
|
5324
|
-
|
|
5325
|
-
|
|
5326
|
-
|
|
5327
|
-
|
|
5328
|
-
stale.add(command);
|
|
6094
|
+
for (const command of commandsOf(entry, spec)) {
|
|
6095
|
+
if (!/ascenda/i.test(command) || command.includes(binary))
|
|
6096
|
+
continue;
|
|
6097
|
+
stale.add(command);
|
|
6098
|
+
}
|
|
5329
6099
|
}
|
|
5330
6100
|
}
|
|
5331
6101
|
return [...stale];
|
|
5332
6102
|
}
|
|
5333
6103
|
function readSettings(settingsFile) {
|
|
5334
6104
|
try {
|
|
5335
|
-
return JSON.parse(
|
|
6105
|
+
return JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
|
|
5336
6106
|
} catch {
|
|
5337
6107
|
return {};
|
|
5338
6108
|
}
|
|
@@ -5351,7 +6121,7 @@ ${serialised}`);
|
|
|
5351
6121
|
console.log(`pairing ${credentials?.toolInstallationId ?? "\u2014 not paired"}${localOnly ? " (installed, not paired \u2014 local features active, telemetry inactive)" : ""}`);
|
|
5352
6122
|
console.log(`token ${localOnly ? "\u2014 none needed until this install is paired" : tokenFile && (0, tokenStore_1.readTokenFile)(tokenFile) ? "present" : "\u2014 missing"}`);
|
|
5353
6123
|
console.log(`event log ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
|
|
5354
|
-
console.log(`hook binary ${
|
|
6124
|
+
console.log(`hook binary ${fs2.existsSync(binary) ? binary : "\u2014 not installed"}`);
|
|
5355
6125
|
const node = process.platform === "win32" ? void 0 : (0, hookRunner_1.resolveHookNode)(binary);
|
|
5356
6126
|
if (node) {
|
|
5357
6127
|
console.log(node.problem ? `node \u2014 ${node.problem}. Install Node 20 or newer, then run setup again` : `node ${node.node} (${node.version}, ${node.how === "recorded" ? "recorded at setup" : "found by the launcher"})`);
|
|
@@ -5369,6 +6139,14 @@ ${serialised}`);
|
|
|
5369
6139
|
const oldest = Math.min(...sets);
|
|
5370
6140
|
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)`);
|
|
5371
6141
|
}
|
|
6142
|
+
const trustLines = trustProblemLines(spec, settingsFile, settings, "");
|
|
6143
|
+
if (trustLines.length) {
|
|
6144
|
+
console.log(`not trusted ${trustLines[0]}`);
|
|
6145
|
+
for (const line of trustLines.slice(1))
|
|
6146
|
+
console.log(` ${line}`);
|
|
6147
|
+
} else if (spec.trust && registered > 0) {
|
|
6148
|
+
console.log("trust every registered hook is approved");
|
|
6149
|
+
}
|
|
5372
6150
|
if (stale.length) {
|
|
5373
6151
|
console.log(`stale hooks ${stale.length} not pointing at the installed binary \u2014 each one fails silently per event:`);
|
|
5374
6152
|
for (const command of stale)
|
|
@@ -5390,7 +6168,7 @@ ${serialised}`);
|
|
|
5390
6168
|
await notices.markShown();
|
|
5391
6169
|
const paired = localOnly || credentials?.toolInstallationId !== void 0;
|
|
5392
6170
|
const wired = registered === spec.hookEvents.length || options.scope === "project" && elsewhere === spec.hookEvents.length;
|
|
5393
|
-
const healthy = paired && wired &&
|
|
6171
|
+
const healthy = paired && wired && fs2.existsSync(binary) && !stale.length && !node?.problem && trustLines.length === 0;
|
|
5394
6172
|
return healthy ? 0 : 1;
|
|
5395
6173
|
}
|
|
5396
6174
|
function countRegistered(settings, spec) {
|
|
@@ -5411,7 +6189,7 @@ ${serialised}`);
|
|
|
5411
6189
|
file: (0, hookRunner_1.tidyHomePath)(file, home),
|
|
5412
6190
|
registered,
|
|
5413
6191
|
scope,
|
|
5414
|
-
homeProject: scope === "project" &&
|
|
6192
|
+
homeProject: scope === "project" && path3.resolve(projectDir) === path3.resolve(home)
|
|
5415
6193
|
});
|
|
5416
6194
|
}
|
|
5417
6195
|
return found;
|
|
@@ -5433,12 +6211,37 @@ ${serialised}`);
|
|
|
5433
6211
|
} catch (error) {
|
|
5434
6212
|
lines.push(` Live signal (could not be checked: ${error instanceof Error ? error.message : String(error)})`);
|
|
5435
6213
|
}
|
|
6214
|
+
if (spec.trust) {
|
|
6215
|
+
const found = trustDoctorLines(spec, options.projectDir, ui);
|
|
6216
|
+
if (found.length)
|
|
6217
|
+
lines.push("", ...found);
|
|
6218
|
+
}
|
|
5436
6219
|
lines.push("", ...accountLines(ui, spec));
|
|
5437
6220
|
const localOnly = (0, credentials_1.isLocalOnlyHostInstall)(spec.host, (id) => (0, tokenStore_1.readTokenFile)((0, tokenStore_1.defaultTokenFilePath)(id)) !== void 0);
|
|
5438
6221
|
lines.push("", ` ${ui.bold("Local events")} ${(0, eventLog_1.describeEventLog)((0, eventLog_1.resolveEventLog)({ localOnly }), `npx ${spec.packageName} setup`)}`);
|
|
5439
6222
|
console.log(lines.join("\n"));
|
|
5440
6223
|
return 0;
|
|
5441
6224
|
}
|
|
6225
|
+
function trustDoctorLines(spec, projectDir, ui) {
|
|
6226
|
+
const userFile = spec.settings.settingsPath("user", projectDir);
|
|
6227
|
+
const projectFile = spec.settings.settingsPath("project", projectDir);
|
|
6228
|
+
const files = userFile === projectFile ? [userFile] : [userFile, projectFile];
|
|
6229
|
+
const out = [];
|
|
6230
|
+
for (const file of files) {
|
|
6231
|
+
const settings = readSettings(file);
|
|
6232
|
+
if (ourHookPositions(settings, spec).length === 0)
|
|
6233
|
+
continue;
|
|
6234
|
+
const problems = trustProblemLines(spec, file, settings, "");
|
|
6235
|
+
if (problems.length === 0) {
|
|
6236
|
+
out.push(` ${ui.mark("ok")} ${"Hook approvals".padEnd(20)} every hook in ${(0, hookRunner_1.tidyHomePath)(file, os2.homedir())} is approved`);
|
|
6237
|
+
continue;
|
|
6238
|
+
}
|
|
6239
|
+
out.push(` ${ui.mark("bad")} ${"Hook approvals".padEnd(20)} ${ui.red(problems[0])}`);
|
|
6240
|
+
for (const line of problems.slice(1))
|
|
6241
|
+
out.push(`${" ".repeat(25)}${line}`);
|
|
6242
|
+
}
|
|
6243
|
+
return out;
|
|
6244
|
+
}
|
|
5442
6245
|
function accountLines(ui, spec) {
|
|
5443
6246
|
const credentials = (0, credentials_1.readHostCredentials)(spec.host);
|
|
5444
6247
|
const id = credentials?.toolInstallationId;
|
|
@@ -5466,13 +6269,13 @@ ${serialised}`);
|
|
|
5466
6269
|
];
|
|
5467
6270
|
}
|
|
5468
6271
|
function removeOurHookEntries(settingsFile, spec) {
|
|
5469
|
-
if (!
|
|
6272
|
+
if (!fs2.existsSync(settingsFile))
|
|
5470
6273
|
return true;
|
|
5471
6274
|
try {
|
|
5472
|
-
const settings = JSON.parse(
|
|
6275
|
+
const settings = JSON.parse(fs2.readFileSync(settingsFile, "utf8"));
|
|
5473
6276
|
const hooks = { ...settings.hooks ?? {} };
|
|
5474
6277
|
for (const event of Object.keys(hooks)) {
|
|
5475
|
-
const kept = hooks[event]
|
|
6278
|
+
const kept = withoutOurEntries(hooks[event], spec);
|
|
5476
6279
|
if (kept.length)
|
|
5477
6280
|
hooks[event] = kept;
|
|
5478
6281
|
else
|
|
@@ -5481,9 +6284,8 @@ ${serialised}`);
|
|
|
5481
6284
|
const updated = { ...settings, hooks };
|
|
5482
6285
|
if (!Object.keys(hooks).length)
|
|
5483
6286
|
delete updated.hooks;
|
|
5484
|
-
|
|
5485
|
-
|
|
5486
|
-
`, "utf8");
|
|
6287
|
+
(0, settingsFile_1.replaceSettingsFile)(settingsFile, `${JSON.stringify(updated, null, 2)}
|
|
6288
|
+
`);
|
|
5487
6289
|
return true;
|
|
5488
6290
|
} catch {
|
|
5489
6291
|
return false;
|
|
@@ -5491,7 +6293,7 @@ ${serialised}`);
|
|
|
5491
6293
|
}
|
|
5492
6294
|
function uninstall(options, spec) {
|
|
5493
6295
|
const settingsFile = spec.settings.settingsPath(options.scope, options.projectDir);
|
|
5494
|
-
if (
|
|
6296
|
+
if (fs2.existsSync(settingsFile)) {
|
|
5495
6297
|
if (!removeOurHookEntries(settingsFile, spec)) {
|
|
5496
6298
|
console.error(`could not parse ${settingsFile} \u2014 remove the ascenda hook entries by hand`);
|
|
5497
6299
|
return 1;
|
|
@@ -5506,7 +6308,7 @@ ${serialised}`);
|
|
|
5506
6308
|
(0, credentials_1.removeHostCredentials)(spec.host);
|
|
5507
6309
|
console.log(`removed tools.${spec.host} from ${(0, credentials_1.credentialsFilePath)()}`);
|
|
5508
6310
|
}
|
|
5509
|
-
console.log(`tokens left in ${
|
|
6311
|
+
console.log(`tokens left in ${path3.join((0, tokenStore_1.ascendaHome)(), "tokens")} \u2014 revoke in the Ascenda app to invalidate them`);
|
|
5510
6312
|
return 0;
|
|
5511
6313
|
}
|
|
5512
6314
|
}
|
|
@@ -5555,24 +6357,39 @@ var require_turnState = __commonJS({
|
|
|
5555
6357
|
}();
|
|
5556
6358
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5557
6359
|
exports.recordTurnStart = recordTurnStart2;
|
|
6360
|
+
exports.readTurnPromptId = readTurnPromptId2;
|
|
5558
6361
|
exports.consumeTurnDurationMs = consumeTurnDurationMs2;
|
|
5559
|
-
var
|
|
5560
|
-
var
|
|
6362
|
+
var crypto_1 = __require("crypto");
|
|
6363
|
+
var fs2 = __importStar(__require("fs"));
|
|
6364
|
+
var path3 = __importStar(__require("path"));
|
|
5561
6365
|
var tokenStore_1 = require_tokenStore();
|
|
5562
|
-
var stateDir = () => process.env.ASCENDA_STATE_DIR ??
|
|
6366
|
+
var stateDir = () => process.env.ASCENDA_STATE_DIR ?? path3.join((0, tokenStore_1.ascendaHome)(), "state");
|
|
5563
6367
|
function turnFile(agent, sessionId) {
|
|
5564
|
-
return
|
|
6368
|
+
return path3.join(stateDir(), `${sanitize(agent)}-turn-${sanitize(sessionId)}`);
|
|
5565
6369
|
}
|
|
5566
6370
|
function sanitize(value) {
|
|
5567
6371
|
return value.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
5568
6372
|
}
|
|
5569
6373
|
function recordTurnStart2(agent, sessionId, now = Date.now()) {
|
|
5570
6374
|
if (!sessionId)
|
|
5571
|
-
return;
|
|
6375
|
+
return void 0;
|
|
6376
|
+
try {
|
|
6377
|
+
const promptId = (0, crypto_1.randomUUID)();
|
|
6378
|
+
fs2.mkdirSync(stateDir(), { recursive: true });
|
|
6379
|
+
fs2.writeFileSync(turnFile(agent, sessionId), `${now} ${promptId}`, { encoding: "utf8", mode: 384 });
|
|
6380
|
+
return promptId;
|
|
6381
|
+
} catch {
|
|
6382
|
+
return void 0;
|
|
6383
|
+
}
|
|
6384
|
+
}
|
|
6385
|
+
function readTurnPromptId2(agent, sessionId) {
|
|
6386
|
+
if (!sessionId)
|
|
6387
|
+
return void 0;
|
|
5572
6388
|
try {
|
|
5573
|
-
|
|
5574
|
-
|
|
6389
|
+
const id = fs2.readFileSync(turnFile(agent, sessionId), "utf8").trim().split(/\s+/)[1];
|
|
6390
|
+
return id && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : void 0;
|
|
5575
6391
|
} catch {
|
|
6392
|
+
return void 0;
|
|
5576
6393
|
}
|
|
5577
6394
|
}
|
|
5578
6395
|
function consumeTurnDurationMs2(agent, sessionId, now = Date.now()) {
|
|
@@ -5580,8 +6397,8 @@ var require_turnState = __commonJS({
|
|
|
5580
6397
|
return void 0;
|
|
5581
6398
|
const file = turnFile(agent, sessionId);
|
|
5582
6399
|
try {
|
|
5583
|
-
const started = Number(
|
|
5584
|
-
|
|
6400
|
+
const started = Number(fs2.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
|
|
6401
|
+
fs2.rmSync(file, { force: true });
|
|
5585
6402
|
if (!Number.isFinite(started) || started <= 0 || started > now)
|
|
5586
6403
|
return void 0;
|
|
5587
6404
|
return now - started;
|
|
@@ -5640,14 +6457,14 @@ var require_agentProcess = __commonJS({
|
|
|
5640
6457
|
exports.findAgentPid = findAgentPid2;
|
|
5641
6458
|
exports.livePidFields = livePidFields;
|
|
5642
6459
|
var child_process_1 = __require("child_process");
|
|
5643
|
-
var
|
|
6460
|
+
var path3 = __importStar(__require("path"));
|
|
5644
6461
|
exports.AGENT_PROCESS = {
|
|
5645
6462
|
claude_code: {
|
|
5646
|
-
executable: (command) =>
|
|
6463
|
+
executable: (command) => path3.basename(command) === "claude" || /\/claude\/versions\/[^/]+$/.test(command) || /\/@anthropic-ai\/claude-code\/bin\/claude\.exe$/.test(command),
|
|
5647
6464
|
scriptMarkers: ["@anthropic-ai/claude-code"]
|
|
5648
6465
|
},
|
|
5649
6466
|
codex: {
|
|
5650
|
-
executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(
|
|
6467
|
+
executable: (command) => /^codex(-(aarch64|x86_64)-apple-darwin)?$/.test(path3.basename(command)),
|
|
5651
6468
|
args: (args) => !/\s(app-server|mcp-server)(\s|$)/.test(args)
|
|
5652
6469
|
},
|
|
5653
6470
|
gemini_cli: {
|
|
@@ -5701,7 +6518,7 @@ var require_agentProcess = __commonJS({
|
|
|
5701
6518
|
if (rule.executable(info.command)) {
|
|
5702
6519
|
return accepts(rule, rule.args ? argsLookup(pid) : "") ? { pid, match: "executable" } : void 0;
|
|
5703
6520
|
}
|
|
5704
|
-
if (markers.length > 0 && SCRIPT_RUNTIME.test(
|
|
6521
|
+
if (markers.length > 0 && SCRIPT_RUNTIME.test(path3.basename(info.command))) {
|
|
5705
6522
|
const args = argsLookup(pid);
|
|
5706
6523
|
const marker = args === void 0 ? void 0 : scriptMarkerIn(args, markers);
|
|
5707
6524
|
if (marker !== void 0) {
|
|
@@ -5736,10 +6553,11 @@ var require_out3 = __commonJS({
|
|
|
5736
6553
|
"../packages/tool-kit/out/index.js"(exports) {
|
|
5737
6554
|
"use strict";
|
|
5738
6555
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5739
|
-
exports.
|
|
5740
|
-
exports.
|
|
5741
|
-
exports.
|
|
5742
|
-
exports.
|
|
6556
|
+
exports.resolveEventLog = exports.parseEventLogFlag = exports.expandUserPath = exports.describeEventLog = exports.defaultEventLogPath = exports.appendEventLog = exports.EVENT_LOG_OFF = exports.EVENT_LOG_ENV_VAR = exports.toAgentEvent = exports.buildEventPayload = exports.buildEventBody = exports.TOKEN_RENEW_LEAD_MS = exports.AscendaSemanticEventError = exports.AscendaEventSender = exports.startBackgroundFlush = exports.runOutboxFlush = exports.hookDeliveryInline = exports.flushLockPath = exports.OUTBOX_FLUSH_COMMAND = exports.HOOK_DELIVERY_ENV_VAR = exports.FLUSH_LOCK_FRESH_MS = 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.shellCommandFacts = exports.invitesDebrief = exports.classifyMcpWorkMilestone = exports.classifyWorkMilestone = exports.isReworkGitAction = exports.classifyGitAction = exports.isVerificationCommand = exports.classifyCommand = void 0;
|
|
6557
|
+
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.readTurnPromptId = exports.consumeTurnDurationMs = exports.writeTopLevelCredentials = exports.writeMachineCredentials = exports.writeRepoKeysSetting = exports.writeEventLogSetting = exports.writeHostCredentials = exports.removeHostCredentials = exports.readMachineCredentials = exports.readHostCredentials = exports.isLocalOnlyHostInstall = exports.credentialsFilePath = exports.renderSetupDisclosure = exports.REFUSALS = exports.FREE_TEXT_KEYS = exports.FAMILY_SENTENCES = exports.ALWAYS_SENT = exports.writeHookSettings = exports.trustProblemLines = exports.runCliAgentSetup = exports.registeredHookSets = exports.ourHookPositions = exports.isCliAgentManagementCommand = exports.findStaleHookCommands = exports.cliAgentHookBinPath = exports.resolveContextHashes = exports.resolveCliAgentInstallationId = exports.withPromptId = exports.withForgeKeys = exports.loadCliAgentConfig = exports.flushHookOutbox = exports.deliverHookEvents = exports.MissingInstallationIdError = exports.DEFAULT_API_BASE_URL = exports.resolveEventLogPath = void 0;
|
|
6558
|
+
exports.saverSupportDir = exports.saverStatusDir = exports.saverReplayPath = exports.saverContainerDir = exports.readSaverStatuses = exports.probeSocket = exports.heldForSaver = exports.holdForSaver = exports.LIVE_BUS_BACKGROUND_TRUST_MS = exports.liveBusSocketCandidates = exports.liveBusSocketPath = exports.bucketPromptSize = exports.deliverLine = exports.emitLiveSignal = exports.repoKeysEnabled = exports.deriveForgeKeysForCwd = exports.REPO_KEYS_ENV_VAR = exports.recordForgeProjectAlias = exports.forgeFullNameFromConfig = exports.readForgeFullName = exports.parseForgeFullName = exports.forgeBranchKey = exports.forgeRepoKey = 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 = void 0;
|
|
6559
|
+
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.liveSignalDoctorLines = exports.doctorRow = exports.DOCTOR_VALUE_COLUMN = exports.replaceSettingsFile = exports.writeAtomically = exports.tidyHomePath = exports.stampLastHook = exports.resolveHookNode = exports.removeHookRunner = exports.readLastHook = exports.lastHookPath = exports.isDowngrade = exports.installHookRunner = exports.hookRunnerPaths = exports.hookRunnerCommand = exports.hookLauncherScript = exports.describeAge = exports.terminalStyle = exports.colourEnabled = exports.SAVER_REPLAY_WINDOW_MS = void 0;
|
|
6560
|
+
exports.runStudyJoin = exports.studyNoticeStatus = exports.runStudyObjection = exports.renderStudyNotices = exports.NOTICED_PURPOSES = exports.renderInitiatives = exports.initiativesStatusLines = exports.INITIATIVE_COPY = void 0;
|
|
5743
6561
|
var commandClassifier_1 = require_commandClassifier();
|
|
5744
6562
|
Object.defineProperty(exports, "classifyCommand", { enumerable: true, get: function() {
|
|
5745
6563
|
return commandClassifier_1.classifyCommand;
|
|
@@ -5758,9 +6576,16 @@ var require_out3 = __commonJS({
|
|
|
5758
6576
|
Object.defineProperty(exports, "classifyWorkMilestone", { enumerable: true, get: function() {
|
|
5759
6577
|
return workMilestoneClassifier_1.classifyWorkMilestone;
|
|
5760
6578
|
} });
|
|
6579
|
+
Object.defineProperty(exports, "classifyMcpWorkMilestone", { enumerable: true, get: function() {
|
|
6580
|
+
return workMilestoneClassifier_1.classifyMcpWorkMilestone;
|
|
6581
|
+
} });
|
|
5761
6582
|
Object.defineProperty(exports, "invitesDebrief", { enumerable: true, get: function() {
|
|
5762
6583
|
return workMilestoneClassifier_1.invitesDebrief;
|
|
5763
6584
|
} });
|
|
6585
|
+
var shellFacts_1 = require_shellFacts();
|
|
6586
|
+
Object.defineProperty(exports, "shellCommandFacts", { enumerable: true, get: function() {
|
|
6587
|
+
return shellFacts_1.shellCommandFacts;
|
|
6588
|
+
} });
|
|
5764
6589
|
var autonomyBand_1 = require_autonomyBand();
|
|
5765
6590
|
Object.defineProperty(exports, "autonomyBand", { enumerable: true, get: function() {
|
|
5766
6591
|
return autonomyBand_1.autonomyBand;
|
|
@@ -5830,6 +6655,28 @@ var require_out3 = __commonJS({
|
|
|
5830
6655
|
Object.defineProperty(exports, "describeCollectorVersion", { enumerable: true, get: function() {
|
|
5831
6656
|
return collectorVersion_1.describeCollectorVersion;
|
|
5832
6657
|
} });
|
|
6658
|
+
var backgroundDelivery_1 = require_backgroundDelivery();
|
|
6659
|
+
Object.defineProperty(exports, "FLUSH_LOCK_FRESH_MS", { enumerable: true, get: function() {
|
|
6660
|
+
return backgroundDelivery_1.FLUSH_LOCK_FRESH_MS;
|
|
6661
|
+
} });
|
|
6662
|
+
Object.defineProperty(exports, "HOOK_DELIVERY_ENV_VAR", { enumerable: true, get: function() {
|
|
6663
|
+
return backgroundDelivery_1.HOOK_DELIVERY_ENV_VAR;
|
|
6664
|
+
} });
|
|
6665
|
+
Object.defineProperty(exports, "OUTBOX_FLUSH_COMMAND", { enumerable: true, get: function() {
|
|
6666
|
+
return backgroundDelivery_1.OUTBOX_FLUSH_COMMAND;
|
|
6667
|
+
} });
|
|
6668
|
+
Object.defineProperty(exports, "flushLockPath", { enumerable: true, get: function() {
|
|
6669
|
+
return backgroundDelivery_1.flushLockPath;
|
|
6670
|
+
} });
|
|
6671
|
+
Object.defineProperty(exports, "hookDeliveryInline", { enumerable: true, get: function() {
|
|
6672
|
+
return backgroundDelivery_1.hookDeliveryInline;
|
|
6673
|
+
} });
|
|
6674
|
+
Object.defineProperty(exports, "runOutboxFlush", { enumerable: true, get: function() {
|
|
6675
|
+
return backgroundDelivery_1.runOutboxFlush;
|
|
6676
|
+
} });
|
|
6677
|
+
Object.defineProperty(exports, "startBackgroundFlush", { enumerable: true, get: function() {
|
|
6678
|
+
return backgroundDelivery_1.startBackgroundFlush;
|
|
6679
|
+
} });
|
|
5833
6680
|
var eventSender_1 = require_eventSender();
|
|
5834
6681
|
Object.defineProperty(exports, "AscendaEventSender", { enumerable: true, get: function() {
|
|
5835
6682
|
return eventSender_1.AscendaEventSender;
|
|
@@ -5888,9 +6735,18 @@ var require_out3 = __commonJS({
|
|
|
5888
6735
|
Object.defineProperty(exports, "deliverHookEvents", { enumerable: true, get: function() {
|
|
5889
6736
|
return hookAdapter_1.deliverHookEvents;
|
|
5890
6737
|
} });
|
|
6738
|
+
Object.defineProperty(exports, "flushHookOutbox", { enumerable: true, get: function() {
|
|
6739
|
+
return hookAdapter_1.flushHookOutbox;
|
|
6740
|
+
} });
|
|
5891
6741
|
Object.defineProperty(exports, "loadCliAgentConfig", { enumerable: true, get: function() {
|
|
5892
6742
|
return hookAdapter_1.loadCliAgentConfig;
|
|
5893
6743
|
} });
|
|
6744
|
+
Object.defineProperty(exports, "withForgeKeys", { enumerable: true, get: function() {
|
|
6745
|
+
return hookAdapter_1.withForgeKeys;
|
|
6746
|
+
} });
|
|
6747
|
+
Object.defineProperty(exports, "withPromptId", { enumerable: true, get: function() {
|
|
6748
|
+
return hookAdapter_1.withPromptId;
|
|
6749
|
+
} });
|
|
5894
6750
|
Object.defineProperty(exports, "resolveCliAgentInstallationId", { enumerable: true, get: function() {
|
|
5895
6751
|
return hookAdapter_1.resolveCliAgentInstallationId;
|
|
5896
6752
|
} });
|
|
@@ -5907,12 +6763,18 @@ var require_out3 = __commonJS({
|
|
|
5907
6763
|
Object.defineProperty(exports, "isCliAgentManagementCommand", { enumerable: true, get: function() {
|
|
5908
6764
|
return cliAgentSetup_1.isCliAgentManagementCommand;
|
|
5909
6765
|
} });
|
|
6766
|
+
Object.defineProperty(exports, "ourHookPositions", { enumerable: true, get: function() {
|
|
6767
|
+
return cliAgentSetup_1.ourHookPositions;
|
|
6768
|
+
} });
|
|
5910
6769
|
Object.defineProperty(exports, "registeredHookSets", { enumerable: true, get: function() {
|
|
5911
6770
|
return cliAgentSetup_1.registeredHookSets;
|
|
5912
6771
|
} });
|
|
5913
6772
|
Object.defineProperty(exports, "runCliAgentSetup", { enumerable: true, get: function() {
|
|
5914
6773
|
return cliAgentSetup_1.runCliAgentSetup;
|
|
5915
6774
|
} });
|
|
6775
|
+
Object.defineProperty(exports, "trustProblemLines", { enumerable: true, get: function() {
|
|
6776
|
+
return cliAgentSetup_1.trustProblemLines;
|
|
6777
|
+
} });
|
|
5916
6778
|
Object.defineProperty(exports, "writeHookSettings", { enumerable: true, get: function() {
|
|
5917
6779
|
return cliAgentSetup_1.writeHookSettings;
|
|
5918
6780
|
} });
|
|
@@ -5954,6 +6816,9 @@ var require_out3 = __commonJS({
|
|
|
5954
6816
|
Object.defineProperty(exports, "writeEventLogSetting", { enumerable: true, get: function() {
|
|
5955
6817
|
return credentials_1.writeEventLogSetting;
|
|
5956
6818
|
} });
|
|
6819
|
+
Object.defineProperty(exports, "writeRepoKeysSetting", { enumerable: true, get: function() {
|
|
6820
|
+
return credentials_1.writeRepoKeysSetting;
|
|
6821
|
+
} });
|
|
5957
6822
|
Object.defineProperty(exports, "writeMachineCredentials", { enumerable: true, get: function() {
|
|
5958
6823
|
return credentials_1.writeMachineCredentials;
|
|
5959
6824
|
} });
|
|
@@ -5964,6 +6829,9 @@ var require_out3 = __commonJS({
|
|
|
5964
6829
|
Object.defineProperty(exports, "consumeTurnDurationMs", { enumerable: true, get: function() {
|
|
5965
6830
|
return turnState_1.consumeTurnDurationMs;
|
|
5966
6831
|
} });
|
|
6832
|
+
Object.defineProperty(exports, "readTurnPromptId", { enumerable: true, get: function() {
|
|
6833
|
+
return turnState_1.readTurnPromptId;
|
|
6834
|
+
} });
|
|
5967
6835
|
Object.defineProperty(exports, "recordTurnStart", { enumerable: true, get: function() {
|
|
5968
6836
|
return turnState_1.recordTurnStart;
|
|
5969
6837
|
} });
|
|
@@ -6098,6 +6966,12 @@ var require_out3 = __commonJS({
|
|
|
6098
6966
|
Object.defineProperty(exports, "forgeProjectHash", { enumerable: true, get: function() {
|
|
6099
6967
|
return forgeProject_1.forgeProjectHash;
|
|
6100
6968
|
} });
|
|
6969
|
+
Object.defineProperty(exports, "forgeRepoKey", { enumerable: true, get: function() {
|
|
6970
|
+
return forgeProject_1.forgeRepoKey;
|
|
6971
|
+
} });
|
|
6972
|
+
Object.defineProperty(exports, "forgeBranchKey", { enumerable: true, get: function() {
|
|
6973
|
+
return forgeProject_1.forgeBranchKey;
|
|
6974
|
+
} });
|
|
6101
6975
|
Object.defineProperty(exports, "parseForgeFullName", { enumerable: true, get: function() {
|
|
6102
6976
|
return forgeProject_1.parseForgeFullName;
|
|
6103
6977
|
} });
|
|
@@ -6110,6 +6984,16 @@ var require_out3 = __commonJS({
|
|
|
6110
6984
|
Object.defineProperty(exports, "recordForgeProjectAlias", { enumerable: true, get: function() {
|
|
6111
6985
|
return forgeProject_1.recordForgeProjectAlias;
|
|
6112
6986
|
} });
|
|
6987
|
+
var forgeKeys_1 = require_forgeKeys();
|
|
6988
|
+
Object.defineProperty(exports, "REPO_KEYS_ENV_VAR", { enumerable: true, get: function() {
|
|
6989
|
+
return forgeKeys_1.REPO_KEYS_ENV_VAR;
|
|
6990
|
+
} });
|
|
6991
|
+
Object.defineProperty(exports, "deriveForgeKeysForCwd", { enumerable: true, get: function() {
|
|
6992
|
+
return forgeKeys_1.deriveForgeKeysForCwd;
|
|
6993
|
+
} });
|
|
6994
|
+
Object.defineProperty(exports, "repoKeysEnabled", { enumerable: true, get: function() {
|
|
6995
|
+
return forgeKeys_1.repoKeysEnabled;
|
|
6996
|
+
} });
|
|
6113
6997
|
var liveBus_1 = require_liveBus();
|
|
6114
6998
|
Object.defineProperty(exports, "emitLiveSignal", { enumerable: true, get: function() {
|
|
6115
6999
|
return liveBus_1.emitLiveSignal;
|
|
@@ -6180,6 +7064,9 @@ var require_out3 = __commonJS({
|
|
|
6180
7064
|
Object.defineProperty(exports, "installHookRunner", { enumerable: true, get: function() {
|
|
6181
7065
|
return hookRunner_1.installHookRunner;
|
|
6182
7066
|
} });
|
|
7067
|
+
Object.defineProperty(exports, "isDowngrade", { enumerable: true, get: function() {
|
|
7068
|
+
return hookRunner_1.isDowngrade;
|
|
7069
|
+
} });
|
|
6183
7070
|
Object.defineProperty(exports, "lastHookPath", { enumerable: true, get: function() {
|
|
6184
7071
|
return hookRunner_1.lastHookPath;
|
|
6185
7072
|
} });
|
|
@@ -6198,6 +7085,13 @@ var require_out3 = __commonJS({
|
|
|
6198
7085
|
Object.defineProperty(exports, "tidyHomePath", { enumerable: true, get: function() {
|
|
6199
7086
|
return hookRunner_1.tidyHomePath;
|
|
6200
7087
|
} });
|
|
7088
|
+
Object.defineProperty(exports, "writeAtomically", { enumerable: true, get: function() {
|
|
7089
|
+
return hookRunner_1.writeAtomically;
|
|
7090
|
+
} });
|
|
7091
|
+
var settingsFile_1 = require_settingsFile();
|
|
7092
|
+
Object.defineProperty(exports, "replaceSettingsFile", { enumerable: true, get: function() {
|
|
7093
|
+
return settingsFile_1.replaceSettingsFile;
|
|
7094
|
+
} });
|
|
6201
7095
|
var liveSignalDoctor_1 = require_liveSignalDoctor();
|
|
6202
7096
|
Object.defineProperty(exports, "DOCTOR_VALUE_COLUMN", { enumerable: true, get: function() {
|
|
6203
7097
|
return liveSignalDoctor_1.DOCTOR_VALUE_COLUMN;
|
|
@@ -6381,6 +7275,12 @@ function mapEvent(hookName, input, turnDurationMs) {
|
|
|
6381
7275
|
// the count is that a gate was reached, when, and in which session.
|
|
6382
7276
|
case "PermissionRequest":
|
|
6383
7277
|
return [{ eventType: "supervision_interruption", severity: "low", metadata: withHost({ interruptionKind: "permission_request" }) }];
|
|
7278
|
+
// Codex 0.146 and later. The session is over, whatever the `reason`: Codex
|
|
7279
|
+
// sends "other" for every ending today, so it is carried only as the
|
|
7280
|
+
// catalog's own word and never branched on. Same row as Claude Code's
|
|
7281
|
+
// `SessionEnd`, so the two sum.
|
|
7282
|
+
case "SessionEnd":
|
|
7283
|
+
return mapSessionEnd(input);
|
|
6384
7284
|
// The subagent lifecycle is still deliberately unmapped: it is not an
|
|
6385
7285
|
// interruption of the person, and it is out of scope here.
|
|
6386
7286
|
case "SubagentStart":
|
|
@@ -6395,6 +7295,17 @@ function mapSessionStart(input) {
|
|
|
6395
7295
|
if (source && source !== "startup" && source !== "resume") return [];
|
|
6396
7296
|
return [{ eventType: "create_focus_session", severity: "low", metadata: withHost({ activity: "session_started", ...autonomyModeMetadata(input) }) }];
|
|
6397
7297
|
}
|
|
7298
|
+
function mapSessionEnd(input) {
|
|
7299
|
+
const raw = input["reason"];
|
|
7300
|
+
return [{
|
|
7301
|
+
eventType: "recovery_offline_period",
|
|
7302
|
+
severity: "low",
|
|
7303
|
+
metadata: withHost({
|
|
7304
|
+
activity: "session_ended",
|
|
7305
|
+
...raw === void 0 || raw === null ? {} : { sessionEndReason: classifySessionEndReason(raw) }
|
|
7306
|
+
})
|
|
7307
|
+
}];
|
|
7308
|
+
}
|
|
6398
7309
|
function mapUserPromptSubmit(input) {
|
|
6399
7310
|
const prompt = (0, import_tool_kit.getString)(input, ["prompt", "userPrompt", "message"]) ?? (0, import_tool_kit.getNestedString)(input, [["payload", "prompt"]]);
|
|
6400
7311
|
const autonomy = autonomyModeMetadata(input);
|
|
@@ -6408,10 +7319,10 @@ function mapPostToolUse(input) {
|
|
|
6408
7319
|
const toolName = getToolName(input);
|
|
6409
7320
|
const safeToolName = sanitiseToolName(toolName);
|
|
6410
7321
|
const outcome = (0, import_tool_kit.inferOutcome)(input);
|
|
6411
|
-
const command = (
|
|
7322
|
+
const command = getCommand(input);
|
|
6412
7323
|
const commandClass = (0, import_tool_kit.classifyCommand)(command);
|
|
6413
7324
|
const lowered = toolName?.toLowerCase();
|
|
6414
|
-
const isShell = lowered === "bash" || lowered === "shell" || lowered === "local_shell";
|
|
7325
|
+
const isShell = lowered === "bash" || lowered === "shell" || lowered === "local_shell" || lowered === "exec_command" || lowered === "shell_command";
|
|
6415
7326
|
const autonomy = autonomyModeMetadata(input);
|
|
6416
7327
|
if (outcome === "failure") {
|
|
6417
7328
|
if (isShell && (0, import_tool_kit.isVerificationCommand)(commandClass)) {
|
|
@@ -6425,7 +7336,8 @@ function mapPostToolUse(input) {
|
|
|
6425
7336
|
if (isShell && (0, import_tool_kit.isVerificationCommand)(commandClass)) {
|
|
6426
7337
|
return [{ eventType: "editor_verification_activity", severity: "low", metadata: withHost({ toolName: safeToolName, commandClass, outcome, activity: "ai_test_or_build_run", ...autonomy }) }];
|
|
6427
7338
|
}
|
|
6428
|
-
|
|
7339
|
+
const facts = isShell && outcome === "success" ? (0, import_tool_kit.shellCommandFacts)(command) : {};
|
|
7340
|
+
return [{ eventType: "ai_tool_call_completed", severity: "low", metadata: withHost({ toolName: safeToolName, commandClass, outcome, ...facts, ...autonomy }) }];
|
|
6429
7341
|
}
|
|
6430
7342
|
function mapPreCompact(input) {
|
|
6431
7343
|
const trigger = (0, import_tool_kit.getString)(input, ["trigger", "reason"]);
|
|
@@ -6468,8 +7380,32 @@ var AUTONOMY_BY_PERMISSION_MODE = {
|
|
|
6468
7380
|
dontask: "dont_ask",
|
|
6469
7381
|
bypasspermissions: "bypass_permissions"
|
|
6470
7382
|
};
|
|
7383
|
+
var SESSION_END_REASONS = ["clear", "resume", "logout", "prompt_input_exit", "other"];
|
|
7384
|
+
function classifySessionEndReason(raw) {
|
|
7385
|
+
if (typeof raw !== "string") return "unknown";
|
|
7386
|
+
const value = raw.trim().toLowerCase();
|
|
7387
|
+
return SESSION_END_REASONS.includes(value) ? value : "unknown";
|
|
7388
|
+
}
|
|
6471
7389
|
function getToolName(input) {
|
|
6472
|
-
return (0, import_tool_kit.getString)(input, ["tool_name", "toolName", "name"]);
|
|
7390
|
+
return (0, import_tool_kit.getString)(input, ["tool_name", "toolName", "name"])?.replace(/^functions\./i, "");
|
|
7391
|
+
}
|
|
7392
|
+
function getCommand(input) {
|
|
7393
|
+
const direct = (0, import_tool_kit.getString)(input, ["command"]);
|
|
7394
|
+
if (direct !== void 0) return unwrapShell(direct);
|
|
7395
|
+
const toolInput = (0, import_tool_kit.getNested)(input, ["tool_input"]) ?? (0, import_tool_kit.getNested)(input, ["input"]);
|
|
7396
|
+
if (!toolInput || typeof toolInput !== "object") return void 0;
|
|
7397
|
+
const raw = toolInput["command"] ?? toolInput["cmd"];
|
|
7398
|
+
if (typeof raw === "string") return unwrapShell(raw);
|
|
7399
|
+
if (Array.isArray(raw) && raw.every((word) => typeof word === "string")) {
|
|
7400
|
+
const argv = raw;
|
|
7401
|
+
const script = argv.length >= 3 && /^-[a-z]*c$/i.test(argv[1]) ? argv[argv.length - 1] : argv.join(" ");
|
|
7402
|
+
return unwrapShell(script);
|
|
7403
|
+
}
|
|
7404
|
+
return void 0;
|
|
7405
|
+
}
|
|
7406
|
+
function unwrapShell(command) {
|
|
7407
|
+
const wrapped = /^\s*(?:\S*\/)?(?:ba|z|da)?sh\s+-[a-z]*c\s+(["'])([\s\S]*)\1\s*$/i.exec(command);
|
|
7408
|
+
return wrapped ? wrapped[2] : command;
|
|
6473
7409
|
}
|
|
6474
7410
|
function sanitiseToolName(toolName) {
|
|
6475
7411
|
if (!toolName) return "unknown";
|
|
@@ -6497,6 +7433,11 @@ function liveSignalFor(hookName, input) {
|
|
|
6497
7433
|
return { event: "stop" };
|
|
6498
7434
|
case "PermissionRequest":
|
|
6499
7435
|
return { event: "awaiting" };
|
|
7436
|
+
// Closing Codex mid-turn runs no `Stop`, so without this the session held
|
|
7437
|
+
// its level until it went stale. A `halted` never creates a session and is
|
|
7438
|
+
// ignored for one that already stopped.
|
|
7439
|
+
case "SessionEnd":
|
|
7440
|
+
return { event: "halted" };
|
|
6500
7441
|
default:
|
|
6501
7442
|
return void 0;
|
|
6502
7443
|
}
|
|
@@ -6504,7 +7445,66 @@ function liveSignalFor(hookName, input) {
|
|
|
6504
7445
|
|
|
6505
7446
|
// src/setup.ts
|
|
6506
7447
|
import * as os from "os";
|
|
7448
|
+
import * as path2 from "path";
|
|
7449
|
+
|
|
7450
|
+
// src/hookTrust.ts
|
|
7451
|
+
import * as fs from "fs";
|
|
6507
7452
|
import * as path from "path";
|
|
7453
|
+
var HEADER = /^\s*\[\s*hooks\s*\.\s*state\s*\.\s*("(?:[^"\\]|\\.)*"|'[^']*')\s*\]/;
|
|
7454
|
+
function parseApprovalKeys(toml) {
|
|
7455
|
+
const keys = [];
|
|
7456
|
+
for (const line of toml.split(/\r?\n/)) {
|
|
7457
|
+
const match = HEADER.exec(line);
|
|
7458
|
+
if (!match) continue;
|
|
7459
|
+
const quoted = match[1];
|
|
7460
|
+
const key = quoted.startsWith("'") ? quoted.slice(1, -1) : unescapeBasicString(quoted.slice(1, -1));
|
|
7461
|
+
const parts = /^(.*):([^:]+):(\d+):(\d+)$/.exec(key);
|
|
7462
|
+
if (!parts) continue;
|
|
7463
|
+
keys.push({ file: parts[1], event: parts[2], group: Number(parts[3]), handler: Number(parts[4]) });
|
|
7464
|
+
}
|
|
7465
|
+
return keys;
|
|
7466
|
+
}
|
|
7467
|
+
function unescapeBasicString(value) {
|
|
7468
|
+
return value.replace(/\\(["\\])/g, "$1");
|
|
7469
|
+
}
|
|
7470
|
+
var eventId = (event) => event.toLowerCase().replace(/[^a-z]/g, "");
|
|
7471
|
+
var fileId = (file) => {
|
|
7472
|
+
const slashed = file.replace(/\\/g, "/");
|
|
7473
|
+
return process.platform === "win32" || /^[A-Za-z]:\//.test(slashed) ? slashed.toLowerCase() : slashed;
|
|
7474
|
+
};
|
|
7475
|
+
function checkCodexHookTrust(settingsFile, ours) {
|
|
7476
|
+
const approvalsFile = path.join(path.dirname(settingsFile), "config.toml");
|
|
7477
|
+
let toml = "";
|
|
7478
|
+
try {
|
|
7479
|
+
toml = fs.readFileSync(approvalsFile, "utf8");
|
|
7480
|
+
} catch (error) {
|
|
7481
|
+
if (error.code !== "ENOENT") return { approvalsFile, untrusted: [], stale: [], unreadable: true };
|
|
7482
|
+
}
|
|
7483
|
+
const here = fileId(path.resolve(settingsFile));
|
|
7484
|
+
const keys = parseApprovalKeys(toml).filter((key) => fileId(key.file) === here);
|
|
7485
|
+
const approved = (position) => keys.some((key) => eventId(key.event) === eventId(position.event) && key.group === position.group && key.handler === position.handler);
|
|
7486
|
+
const untrusted = ours.filter((position) => !approved(position));
|
|
7487
|
+
const ourEvents = new Set(ours.map((position) => eventId(position.event)));
|
|
7488
|
+
const stale = [];
|
|
7489
|
+
for (const key of keys) {
|
|
7490
|
+
if (!ourEvents.has(eventId(key.event))) continue;
|
|
7491
|
+
if (ours.some((position) => eventId(position.event) === eventId(key.event) && position.group === key.group && position.handler === key.handler)) continue;
|
|
7492
|
+
stale.push(`An approval for ${key.event} (group ${key.group}, handler ${key.handler}) points at a hook that has moved or gone.`);
|
|
7493
|
+
}
|
|
7494
|
+
if (untrusted.length === 0 && stale.length === 0 && changedAfterApproval(settingsFile, approvalsFile)) {
|
|
7495
|
+
stale.push("The hooks file was changed after the last approval was recorded, so a changed command may be waiting for re-approval.");
|
|
7496
|
+
}
|
|
7497
|
+
return { approvalsFile, untrusted, stale };
|
|
7498
|
+
}
|
|
7499
|
+
function changedAfterApproval(hooksFile, approvalsFile) {
|
|
7500
|
+
try {
|
|
7501
|
+
return fs.statSync(hooksFile).mtimeMs > fs.statSync(approvalsFile).mtimeMs;
|
|
7502
|
+
} catch {
|
|
7503
|
+
return false;
|
|
7504
|
+
}
|
|
7505
|
+
}
|
|
7506
|
+
|
|
7507
|
+
// src/setup.ts
|
|
6508
7508
|
var HOOK_EVENTS = [
|
|
6509
7509
|
"SessionStart",
|
|
6510
7510
|
"UserPromptSubmit",
|
|
@@ -6513,9 +7513,17 @@ var HOOK_EVENTS = [
|
|
|
6513
7513
|
"PreCompact",
|
|
6514
7514
|
"PostCompact",
|
|
6515
7515
|
"Stop",
|
|
6516
|
-
"PermissionRequest"
|
|
7516
|
+
"PermissionRequest",
|
|
7517
|
+
// Codex 0.146 and later; an older Codex ignores an event it doesn't know.
|
|
7518
|
+
"SessionEnd"
|
|
6517
7519
|
];
|
|
6518
7520
|
var HOOK_TIMEOUT_SECONDS = 10;
|
|
7521
|
+
function codexHome() {
|
|
7522
|
+
const configured = process.env.CODEX_HOME?.trim();
|
|
7523
|
+
return configured ? path2.resolve(configured) : path2.join(os.homedir(), ".codex");
|
|
7524
|
+
}
|
|
7525
|
+
var SESSION_END_TIMEOUT_SECONDS = 3;
|
|
7526
|
+
var hookTimeoutSeconds = (event) => event === "SessionEnd" ? SESSION_END_TIMEOUT_SECONDS : HOOK_TIMEOUT_SECONDS;
|
|
6519
7527
|
var SETUP = {
|
|
6520
7528
|
host: CODEX_HOST,
|
|
6521
7529
|
displayName: "Codex CLI",
|
|
@@ -6524,25 +7532,30 @@ var SETUP = {
|
|
|
6524
7532
|
binaryName: "ascenda-codex-hook",
|
|
6525
7533
|
hookEvents: HOOK_EVENTS,
|
|
6526
7534
|
restartHint: "Restart Codex, then open /hooks to review and trust the Ascenda hooks. Registration alone does not run them.",
|
|
6527
|
-
// Codex reports the posture it was working under
|
|
6528
|
-
//
|
|
6529
|
-
|
|
7535
|
+
// Codex reports the posture it was working under, its approval gate, and
|
|
7536
|
+
// the git action or milestone a shell command reached. It sends no model and
|
|
7537
|
+
// no per-file change size.
|
|
7538
|
+
sends: ["posture", "waiting", "git", "turns", "forge"],
|
|
7539
|
+
trust: {
|
|
7540
|
+
check: checkCodexHookTrust,
|
|
7541
|
+
fix: "Restart Codex and open /hooks, then approve the Ascenda hooks. A hook whose command changed needs approving again."
|
|
7542
|
+
},
|
|
6530
7543
|
settings: {
|
|
6531
|
-
settingsPath: (scope, projectDir) => scope === "user" ?
|
|
7544
|
+
settingsPath: (scope, projectDir) => scope === "user" ? path2.join(codexHome(), "hooks.json") : path2.join(projectDir, ".codex", "hooks.json"),
|
|
6532
7545
|
// Codex nests as Gemini does — each event maps to an array of
|
|
6533
7546
|
// { hooks: [{ type, command }] } — but reads the event from argv rather
|
|
6534
7547
|
// than stdin, so unlike Gemini the name has to be on the command line.
|
|
6535
|
-
entry: (command, event) => ({ hooks: [{ type: "command", command: `${command} ${event}`, timeout:
|
|
6536
|
-
|
|
6537
|
-
const group = entry;
|
|
6538
|
-
const command = group?.hooks?.find((hook) => typeof hook?.command === "string")?.command;
|
|
6539
|
-
return typeof command === "string" ? command : void 0;
|
|
6540
|
-
}
|
|
7548
|
+
entry: (command, event) => ({ hooks: [{ type: "command", command: `${command} ${event}`, timeout: hookTimeoutSeconds(event) }] }),
|
|
7549
|
+
grouped: true
|
|
6541
7550
|
}
|
|
6542
7551
|
};
|
|
6543
7552
|
|
|
6544
7553
|
// src/cli.ts
|
|
6545
7554
|
async function main() {
|
|
7555
|
+
if (process.argv[2] === import_tool_kit3.OUTBOX_FLUSH_COMMAND) {
|
|
7556
|
+
await (0, import_tool_kit3.flushHookOutbox)({ toolType: ASCENDA_TOOL_TYPE, host: CODEX_HOST, source: "cli_agent" });
|
|
7557
|
+
return;
|
|
7558
|
+
}
|
|
6546
7559
|
const command = process.argv[2];
|
|
6547
7560
|
if ((0, import_tool_kit3.isCliAgentManagementCommand)(command)) {
|
|
6548
7561
|
managementExitCode = await (0, import_tool_kit3.runCliAgentSetup)(process.argv.slice(2), SETUP);
|
|
@@ -6557,8 +7570,10 @@ async function main() {
|
|
|
6557
7570
|
const sessionId = typeof input.session_id === "string" ? input.session_id : void 0;
|
|
6558
7571
|
let turnDurationMs;
|
|
6559
7572
|
(0, import_tool_kit3.stampLastHook)(CODEX_HOST, hookName);
|
|
6560
|
-
|
|
7573
|
+
const promptId = hookName === "UserPromptSubmit" ? (0, import_tool_kit3.recordTurnStart)(CODEX_HOST, sessionId) : (0, import_tool_kit3.readTurnPromptId)(CODEX_HOST, sessionId);
|
|
6561
7574
|
if (hookName === "Stop") turnDurationMs = (0, import_tool_kit3.consumeTurnDurationMs)(CODEX_HOST, sessionId);
|
|
7575
|
+
const workDir = typeof input.cwd === "string" ? input.cwd : void 0;
|
|
7576
|
+
if (hookName === "SessionEnd") process.env.ASCENDA_HTTP_TIMEOUT_MS ??= "1500";
|
|
6562
7577
|
await emitLive(hookName, input, sessionId);
|
|
6563
7578
|
await (0, import_tool_kit3.deliverHookEvents)(mapCodexEvent(hookName, input, turnDurationMs), {
|
|
6564
7579
|
toolType: ASCENDA_TOOL_TYPE,
|
|
@@ -6566,6 +7581,9 @@ async function main() {
|
|
|
6566
7581
|
setupCommand: `npx ${SETUP.packageName} setup`,
|
|
6567
7582
|
source: "cli_agent",
|
|
6568
7583
|
sessionId,
|
|
7584
|
+
promptId,
|
|
7585
|
+
cwd: workDir,
|
|
7586
|
+
forgeKeys: true,
|
|
6569
7587
|
onNotice: emitSystemMessage
|
|
6570
7588
|
});
|
|
6571
7589
|
}
|