-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathposthog-client.ts
More file actions
6283 lines (5800 loc) · 194 KB
/
Copy pathposthog-client.ts
File metadata and controls
6283 lines (5800 loc) · 194 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import "./generated.augment";
import { isSupportedReasoningEffort } from "@posthog/agent/adapters/reasoning-effort";
import type {
Adapter,
CloudMcpServerImport,
CloudMcpServerRelayDesignation,
CloudRunSource,
ExecutionMode,
PrAuthorshipMode,
SeatData,
StoredLogEntry,
TaskRunArtifactMetadata,
} from "@posthog/shared";
import {
DISMISSAL_REASON_OPTIONS,
type DismissalReasonOptionValue,
resolveCloudInitialPermissionMode,
SEAT_PRODUCT_KEY,
} from "@posthog/shared";
import type {
AgentAnalyticsData,
AgentApplication,
AgentApplicationSessionDetail,
AgentApplicationSessionsListResponse,
AgentApprovalRequest,
AgentApprovalsListParams,
AgentFleetLiveSessionsResponse,
AgentMemoryFile,
AgentMemorySearchResult,
AgentMemoryTableHeader,
AgentMemoryTableRows,
AgentMemoryTreeNode,
AgentPreviewToken,
AgentRevision,
AgentSessionEvent,
AgentSessionLogEntry,
AgentSessionLogsParams,
AgentSessionsListParams,
AgentSlackManifest,
AgentSpec,
AgentUsersListResponse,
BundleFile,
DecideApprovalRequest,
DryRunToolEnvelope,
DryRunToolRequest,
DryRunToolResult,
ModelCatalog,
ToolCapabilities,
ToolCompileError,
WriteToolRequest,
WriteToolResult,
} from "@posthog/shared/agent-platform-types";
import type {
ActionabilityJudgmentArtefact,
AvailableSuggestedReviewer,
AvailableSuggestedReviewersResponse,
ChannelFeedMessage,
ChannelFeedMessageEvent,
CodeReferenceArtefact,
CommitArtefact,
CommitDiffResponse,
DismissalArtefact,
LineReferenceArtefact,
NoteArtefact,
OrganizationMemberBasic,
PriorityJudgmentArtefact,
RepoSelectionArtefact,
SafetyJudgmentArtefact,
SandboxCustomImage,
SandboxEnvironment,
SandboxEnvironmentInput,
Signal,
SignalFindingArtefact,
SignalProcessingStateResponse,
SignalReport,
SignalReportArtefact,
SignalReportArtefactsResponse,
SignalReportSignalsResponse,
SignalReportStatus,
SignalReportsQueryParams,
SignalReportsResponse,
SignalTeamConfig,
SignalUserAutonomyConfig,
SlackChannelsQueryParams,
SlackChannelsResponse,
SuggestedReviewersArtefact,
SuggestedReviewerWriteEntry,
Task,
TaskChannel,
TaskMention,
TaskRun,
TaskRunArtefact,
TaskThreadMessage,
UserBasic,
} from "@posthog/shared/domain-types";
import {
buildAgentAnalyticsQueries,
type HogQLGrid,
shapeAgentAnalytics,
} from "./agent-analytics";
import { buildApiFetcher } from "./fetcher";
import { createApiClient, type Schemas } from "./generated";
import type { SpendAnalysisResponse } from "./spend-analysis";
export interface ApiClientLogger {
warn(...args: unknown[]): void;
}
let log: ApiClientLogger = { warn: () => {} };
export function setPosthogApiClientLogger(logger: ApiClientLogger): void {
log = logger;
}
// Host build version, set by the host at boot (default "unknown"); avoids a
// build-time global so the package typechecks standalone and across importers.
let clientAppVersion = "unknown";
export function setPosthogApiClientAppVersion(version: string): void {
clientAppVersion = version;
}
export class SeatSubscriptionRequiredError extends Error {
redirectUrl: string;
constructor(redirectUrl: string) {
super("Billing subscription required");
this.name = "SeatSubscriptionRequiredError";
this.redirectUrl = redirectUrl;
}
}
export class SeatPaymentFailedError extends Error {
constructor(message?: string) {
super(message ?? "Payment failed");
this.name = "SeatPaymentFailedError";
}
}
export class SandboxCustomImagesDisabledError extends Error {
constructor(message?: string) {
super(message ?? "Custom sandbox images are not enabled");
this.name = "SandboxCustomImagesDisabledError";
}
}
export type UsageLimitType = "burst" | "sustained" | null;
// Stable message so callers recognize this after a saga reduces the error to a string.
export const CLOUD_USAGE_LIMIT_ERROR_MESSAGE = "Cloud usage limit reached";
export const SESSION_LOGS_MAX_PAGE_SIZE = 5000;
/** Thrown when the backend rejects a cloud run with a 429 usage-limit error. */
export class CloudUsageLimitError extends Error {
limitType: UsageLimitType;
resetAt: string | null;
isPro: boolean;
constructor(params: {
limitType: UsageLimitType;
resetAt: string | null;
isPro: boolean;
}) {
super(CLOUD_USAGE_LIMIT_ERROR_MESSAGE);
this.name = "CloudUsageLimitError";
this.limitType = params.limitType;
this.resetAt = params.resetAt;
this.isPro = params.isPro;
}
}
export const MCP_CATEGORIES = [
{ id: "all", label: "All" },
{ id: "business", label: "Business Operations" },
{ id: "data", label: "Data & Analytics" },
{ id: "design", label: "Design & Content" },
{ id: "dev", label: "Developer Tools & APIs" },
{ id: "infra", label: "Infrastructure" },
{ id: "productivity", label: "Productivity & Collaboration" },
] as const;
import type {
McpApprovalState,
McpAuthType,
McpCategory,
McpInstallationTool,
McpRecommendedServer,
McpServerInstallation,
} from "./types";
export type {
McpApprovalState,
McpAuthType,
McpCategory,
McpInstallationTool,
McpRecommendedServer,
McpServerInstallation,
};
export type Evaluation = Schemas.Evaluation;
export interface UserGitHubIntegration {
id: string;
kind: "github";
installation_id: string;
repository_selection?: string | null;
account?: {
type?: string | null;
name?: string | null;
} | null;
uses_shared_installation?: boolean;
created_at?: string;
}
export interface LlmSkillCreatedBy {
id?: number;
email?: string | null;
first_name?: string | null;
last_name?: string | null;
}
export interface LlmSkillFileManifest {
path: string;
content_type: string;
}
export interface LlmSkillFile {
path: string;
content: string;
content_type: string;
}
export interface LlmSkillListItem {
id: string;
name: string;
description: string;
allowed_tools: unknown[];
metadata: Record<string, unknown>;
version: number;
is_latest: boolean;
latest_version?: number | null;
version_count?: number | null;
created_by: LlmSkillCreatedBy | null;
created_at: string;
updated_at: string;
}
export interface LlmSkill extends LlmSkillListItem {
/** The SKILL.md markdown content. */
body: string;
/** Companion file manifest (paths only; fetch contents separately). */
files: LlmSkillFileManifest[];
}
export interface LlmSkillFileInput {
path: string;
content: string;
content_type?: string;
}
export interface SignalSourceConfig {
id: string;
source_product:
| "session_replay"
| "llm_analytics"
| "github"
| "linear"
| "jira"
| "zendesk"
| "conversations"
| "error_tracking"
| "pganalyze"
| "signals_scout";
source_type:
| "session_analysis_cluster"
| "evaluation"
| "issue"
| "ticket"
| "issue_created"
| "issue_reopened"
| "issue_spiking"
| "cross_source_issue";
enabled: boolean;
config: Record<string, unknown>;
created_at: string;
updated_at: string;
status: "running" | "completed" | "failed" | null;
}
// ── Signals scouts ───────────────────────────────────────────────────────────
// Backend: posthog `products/signals/backend/scout_harness/views.py`.
// Endpoints live under /api/projects/{id}/signals/scout/ and require the
// `signal_scout:read` / `signal_scout:write` scopes.
export interface ScoutConfig {
id: string;
skill_name: string;
enabled: boolean;
/** False means dry-run: the scout runs but findings are not emitted. */
emit: boolean;
/**
* Summary of what the scout investigates, from the skill's description
* metadata. Empty string when the skill is absent or carries no description;
* absent entirely on backends predating the field.
*/
description?: string;
/**
* Where the scout came from: "canonical" for a scout PostHog ships and
* maintains (seeded from products/signals/skills), "custom" for one a team
* hand-authored. The serializer defaults to "custom" when the skill is absent;
* the field itself is absent entirely on backends predating it.
*/
scout_origin?: "canonical" | "custom";
run_interval_minutes: number;
last_run_at: string | null;
created_at: string;
}
/** A team's enforced scout run caps and current usage, as dispatch applies them. */
export interface ScoutLimits {
max_runs_per_tick: number;
/** Null when the daily budget is uncapped. */
max_runs_per_day: number | null;
runs_today: number;
/** Null when the daily budget is uncapped. */
runs_remaining_today: number | null;
}
/**
* Team-scoped scout metadata from the `signals-scout` flag: enrollment, an optional
* announcement banner, and the enforced run limits. `banner_message` is null when unset.
*/
export interface ScoutMetadata {
enrolled: boolean;
banner_message: string | null;
limits: ScoutLimits;
}
export interface ScoutRun {
run_id: string;
skill_name: string;
skill_version: number;
/** TaskRun-derived status, e.g. "completed" | "failed" | "in_progress" | "queued". */
status: string;
started_at: string | null;
completed_at: string | null;
task_id: string | null;
task_run_id: string | null;
/** Relative PostHog cloud path to the backing task run. */
task_url: string | null;
summary: string;
emitted_count: number | null;
emitted_finding_ids: string[];
}
export interface ScoutEmission {
id: string;
run_id: string;
finding_id: string;
description: string;
weight: number;
confidence: number;
severity: string | null;
/** Slug tags the scout attached to this finding (lowercase kebab-case, e.g. `cost-spike`). */
tags?: string[];
source_id: string;
emitted_at: string;
}
/** Minimal inbox report projection paired with a scout finding by the reverse lookup. */
export interface LinkedSignalReport {
id: string;
title: string | null;
status: SignalReportStatus;
}
/**
* One scout finding paired with the inbox report (if any) its signal grouped into.
* `report` is null when the finding hasn't grouped into a report yet, was
* de-duplicated away, or its signal was deleted – the link is best effort.
*/
export interface ScoutEmissionReportLink {
finding_id: string;
source_id: string;
report: LinkedSignalReport | null;
}
export interface ScoutScratchpadEntry {
key: string;
content: string;
created_at: string;
updated_at: string;
created_by_run_id: string | null;
}
export interface ScoutRunsQueryParams {
date_from?: string;
date_to?: string;
text?: string;
emitted?: boolean;
limit?: number;
}
export interface ExternalDataSourceSchema {
id: string;
name: string;
should_sync: boolean;
/** e.g. `full_refresh` (full table replication), `incremental`, `append` */
sync_type?: string | null;
}
export interface ExternalDataSource {
id: string;
source_type: string;
status: string;
// The generated `ExternalDataSourceSerializers` types this as `string`,
// but the actual API returns an array of schema objects
schemas?: ExternalDataSourceSchema[] | string;
}
/**
* Field-config variants for an external data source's connect form, as served
* by the `external_data_sources/wizard/` endpoint. Mirrors PostHog Cloud's
* `SourceFieldConfig` union (`posthog/schema.py`). The backend is the single
* source of truth for which credential fields a source needs, so forms can be
* rendered generically instead of hardcoded per source.
*/
export interface SourceFieldInputConfig {
type:
| "text"
| "email"
| "search"
| "url"
| "password"
| "time"
| "number"
| "textarea";
name: string;
label: string;
required: boolean;
placeholder?: string;
caption?: string | null;
/** Redacted from API responses; render as a password field. */
secret?: boolean;
}
export interface SourceFieldOauthConfig {
type: "oauth";
name: string;
label: string;
kind: string;
required: boolean;
requiredScopes?: string;
}
/**
* A picker whose options are the accounts/resources a connected OAuth integration exposes (loaded
* from the `oauth_accounts` endpoint using the integration's server-side token). Used e.g. for a
* GitHub repository or an ad account.
*/
export interface SourceFieldOauthAccountSelectConfig {
type: "oauth-account-select";
name: string;
label: string;
/** Name of the sibling OAuth id field this selector reads its integration id from. */
integrationField: string;
/** Integration kind used to validate the connected integration, e.g. "github". */
integrationKind: string;
placeholder?: string;
caption?: string;
required?: boolean;
}
/** A selectable account/resource an OAuth integration exposes (shared `IntegrationAccount` shape). */
export interface IntegrationAccount {
value: string;
display_name: string;
is_primary: boolean;
badges: string[];
group: string | null;
secondary_text: string | null;
}
export interface SourceFieldSelectConfigOption {
label: string;
value: string;
fields?: SourceFieldConfig[];
}
export interface SourceFieldSelectConfig {
type: "select";
name: string;
label: string;
required: boolean;
defaultValue?: string;
options: SourceFieldSelectConfigOption[];
}
export interface SourceFieldSwitchGroupConfig {
type: "switch-group";
name: string;
label: string;
caption?: string;
default?: boolean;
fields: SourceFieldConfig[];
}
/** Field types the generic renderer does not (yet) handle inline. */
export interface SourceFieldUnsupportedConfig {
type: "ssh-tunnel" | "file-upload";
name: string;
label: string;
}
export type SourceFieldConfig =
| SourceFieldInputConfig
| SourceFieldOauthConfig
| SourceFieldOauthAccountSelectConfig
| SourceFieldSelectConfig
| SourceFieldSwitchGroupConfig
| SourceFieldUnsupportedConfig;
export interface SourceConfig {
name: string;
label?: string;
caption?: string;
fields: SourceFieldConfig[];
}
export interface FolderInstructionsUser {
id?: number;
uuid?: string;
first_name?: string;
last_name?: string | null;
email?: string;
}
export interface FolderInstructions {
id: string;
content: string;
version: number;
is_latest: boolean;
created_by: FolderInstructionsUser | null;
created_at: string;
updated_at: string;
}
export interface FolderInstructionsVersion {
id: string;
version: number;
is_latest: boolean;
created_by: FolderInstructionsUser | null;
created_at: string;
}
interface PaginatedFolderInstructionsVersions {
count: number;
next: string | null;
previous: string | null;
results: FolderInstructionsVersion[];
}
// Thrown when PUT /instructions/ rejects a publish because the caller's
// `base_version` is older than the current latest. Callers can re-fetch and
// retry against the new latest.
export class FolderInstructionsConflictError extends Error {
status = 409;
constructor(
message = "Folder instructions changed since you started editing",
) {
super(message);
this.name = "FolderInstructionsConflictError";
}
}
export interface TaskArtifactUploadRequest {
name: string;
type: "user_attachment" | "skill_bundle";
size: number;
content_type?: string;
source?: string;
metadata?: TaskRunArtifactMetadata;
}
export interface DirectUploadPresignedPost {
url: string;
fields: Record<string, string>;
}
export interface PreparedTaskArtifactUpload extends TaskArtifactUploadRequest {
id: string;
storage_path: string;
expires_in: number;
presigned_post: DirectUploadPresignedPost;
}
export interface FinalizedTaskArtifactUpload {
id: string;
name: string;
type: string;
source?: string;
size?: number;
content_type?: string;
metadata?: TaskArtifactUploadRequest["metadata"];
storage_path: string;
uploaded_at?: string;
}
interface CloudRunOptions {
adapter?: Adapter;
model?: string;
reasoningLevel?: string;
sandboxEnvironmentId?: string;
customImageId?: string;
prAuthorshipMode?: PrAuthorshipMode;
autoPublish?: boolean;
/** Only false is sent: opts the run out of rtk command-output compression. */
rtkEnabled?: boolean;
runSource?: CloudRunSource;
signalReportId?: string;
initialPermissionMode?: ExecutionMode;
homeQuickAction?: string;
/**
* Local url-based MCP servers to make available inside the sandbox. The
* backend merges these into the agent server's `--mcpServers` at spawn.
*/
importedMcpServers?: CloudMcpServerImport[];
relayedMcpServers?: CloudMcpServerRelayDesignation[];
}
interface CreateTaskRunOptions extends CloudRunOptions {
environment?: "local" | "cloud";
mode?: "interactive" | "background";
branch?: string | null;
}
interface StartTaskRunOptions {
pendingUserMessage?: string;
pendingUserArtifactIds?: string[];
}
function buildCloudRunRequestBody(
options?: CloudRunOptions & {
branch?: string | null;
mode?: "interactive" | "background";
resumeFromRunId?: string;
pendingUserMessage?: string;
pendingUserArtifactIds?: string[];
},
): Record<string, unknown> {
const body: Record<string, unknown> = {
mode: options?.mode ?? "interactive",
};
if (options?.branch) {
body.branch = options.branch;
}
if (options?.adapter) {
body.runtime_adapter = options.adapter;
if (options.model) {
body.model = options.model;
}
if (options.reasoningLevel) {
if (!options.model) {
throw new Error(
"A cloud reasoning level requires a model to be selected.",
);
}
if (
!isSupportedReasoningEffort(
options.adapter,
options.model,
options.reasoningLevel,
)
) {
throw new Error(
`Reasoning effort '${options.reasoningLevel}' is not supported for ${options.adapter} model '${options.model}'.`,
);
}
body.reasoning_effort = options.reasoningLevel;
}
// The API rejects initial_permission_mode without runtime_adapter and validates it per adapter.
if (options.initialPermissionMode) {
body.initial_permission_mode = resolveCloudInitialPermissionMode(
options.adapter,
options.initialPermissionMode,
);
}
}
if (options?.resumeFromRunId) {
body.resume_from_run_id = options.resumeFromRunId;
}
if (options?.pendingUserMessage) {
body.pending_user_message = options.pendingUserMessage;
}
if (options?.pendingUserArtifactIds?.length) {
body.pending_user_artifact_ids = options.pendingUserArtifactIds;
}
if (options?.sandboxEnvironmentId) {
body.sandbox_environment_id = options.sandboxEnvironmentId;
}
if (options?.customImageId) {
body.custom_image_id = options.customImageId;
}
if (options?.prAuthorshipMode) {
body.pr_authorship_mode = options.prAuthorshipMode;
}
if (options?.autoPublish) {
body.auto_publish = options.autoPublish;
}
if (options?.rtkEnabled === false) {
body.rtk_enabled = false;
}
if (options?.runSource) {
body.run_source = options.runSource;
}
if (options?.signalReportId) {
body.signal_report_id = options.signalReportId;
}
if (options?.homeQuickAction) {
body.home_quick_action = options.homeQuickAction;
}
if (options?.importedMcpServers?.length) {
body.imported_mcp_servers = options.importedMcpServers;
}
if (options?.relayedMcpServers?.length) {
body.relayed_mcp_servers = options.relayedMcpServers;
}
return body;
}
function isObjectRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function optionalString(value: unknown): string | null {
return typeof value === "string" ? value : null;
}
/** Unwrap the shared fetcher's `Failed request: [<status>] <json>` into the endpoint's clean message. */
function extractRequestErrorMessage(error: unknown, fallback: string): string {
const raw = error instanceof Error ? error.message : String(error);
const match = raw.match(/^Failed request: \[(\d+)\] (.*)$/s);
if (!match) {
return fallback;
}
try {
const body = JSON.parse(match[2]) as { error?: unknown; detail?: unknown };
const message = body.error ?? body.detail;
if (typeof message === "string" && message.trim()) {
return message;
}
} catch {
// Non-JSON body — fall through to the status-based fallback.
}
return `${fallback} (HTTP ${match[1]})`;
}
/**
* Parse the shared fetcher's `Failed request: [<status>] <json-body>` throw back
* into its status + parsed JSON body, so status-specific responses (422, 429,
* 500, 503) can be handled as data instead of a generic error. Returns null when
* the error isn't that shape (e.g. a network failure).
*/
function parseFailedRequest(
error: unknown,
): { status: number; body: unknown } | null {
const raw = error instanceof Error ? error.message : String(error);
const match = raw.match(/^Failed request: \[(\d+)\] (.*)$/s);
if (!match) {
return null;
}
let body: unknown;
try {
body = JSON.parse(match[2]);
} catch {
body = match[2];
}
return { status: Number(match[1]), body };
}
type AnyArtefact =
| SignalReportArtefact
| PriorityJudgmentArtefact
| ActionabilityJudgmentArtefact
| SafetyJudgmentArtefact
| SignalFindingArtefact
| RepoSelectionArtefact
| SuggestedReviewersArtefact
| DismissalArtefact
| CodeReferenceArtefact
| LineReferenceArtefact
| CommitArtefact
| TaskRunArtefact
| NoteArtefact;
const DISMISSAL_REASONS = new Set<DismissalReasonOptionValue>(
DISMISSAL_REASON_OPTIONS.map((o) => o.value),
);
const PRIORITY_VALUES = new Set(["P0", "P1", "P2", "P3", "P4"]);
function normalizePriorityJudgmentArtefact(
value: Record<string, unknown>,
): PriorityJudgmentArtefact | null {
const id = optionalString(value.id);
if (!id) return null;
const contentValue = isObjectRecord(value.content) ? value.content : null;
if (!contentValue) return null;
const priority = optionalString(contentValue.priority);
if (!priority || !PRIORITY_VALUES.has(priority)) return null;
return {
id,
type: "priority_judgment",
...artefactBase(value),
content: {
explanation: optionalString(contentValue.explanation) ?? "",
priority: priority as PriorityJudgmentArtefact["content"]["priority"],
},
};
}
const ACTIONABILITY_VALUES = new Set([
"immediately_actionable",
"requires_human_input",
"not_actionable",
]);
function normalizeActionabilityJudgmentArtefact(
value: Record<string, unknown>,
): ActionabilityJudgmentArtefact | null {
const id = optionalString(value.id);
if (!id) return null;
const contentValue = isObjectRecord(value.content) ? value.content : null;
if (!contentValue) return null;
// Support both agentic ("actionability") and legacy ("choice") field names
const actionability =
optionalString(contentValue.actionability) ??
optionalString(contentValue.choice);
if (!actionability || !ACTIONABILITY_VALUES.has(actionability)) return null;
return {
id,
type: "actionability_judgment",
...artefactBase(value),
content: {
explanation: optionalString(contentValue.explanation) ?? "",
actionability:
actionability as ActionabilityJudgmentArtefact["content"]["actionability"],
already_addressed:
typeof contentValue.already_addressed === "boolean"
? contentValue.already_addressed
: false,
},
};
}
function normalizeSafetyJudgmentArtefact(
value: Record<string, unknown>,
): SafetyJudgmentArtefact | null {
const id = optionalString(value.id);
if (!id) return null;
const contentValue = isObjectRecord(value.content) ? value.content : null;
if (!contentValue || typeof contentValue.choice !== "boolean") return null;
return {
id,
type: "safety_judgment",
...artefactBase(value),
content: {
choice: contentValue.choice,
explanation: optionalString(contentValue.explanation),
},
};
}
function normalizeSignalFindingArtefact(
value: Record<string, unknown>,
): SignalFindingArtefact | null {
const id = optionalString(value.id);
if (!id) return null;
const contentValue = isObjectRecord(value.content) ? value.content : null;
if (!contentValue) return null;
const signalId = optionalString(contentValue.signal_id);
if (!signalId) return null;
return {
id,
type: "signal_finding",
...artefactBase(value),
content: {
signal_id: signalId,
relevant_code_paths: Array.isArray(contentValue.relevant_code_paths)
? contentValue.relevant_code_paths.filter(
(p: unknown): p is string => typeof p === "string",
)
: [],
relevant_commit_hashes: isObjectRecord(
contentValue.relevant_commit_hashes,
)
? Object.fromEntries(
Object.entries(contentValue.relevant_commit_hashes).filter(
(e): e is [string, string] => typeof e[1] === "string",
),
)
: {},
data_queried: optionalString(contentValue.data_queried) ?? "",
verified:
typeof contentValue.verified === "boolean"
? contentValue.verified
: false,
},
};
}
function normalizeRepoSelectionArtefact(
value: Record<string, unknown>,
): RepoSelectionArtefact | null {
const id = optionalString(value.id);
if (!id) return null;
const contentValue = isObjectRecord(value.content) ? value.content : null;
if (!contentValue) return null;
return {
id,
type: "repo_selection",
...artefactBase(value),
content: {
repository: optionalString(contentValue.repository),
reason: optionalString(contentValue.reason) ?? "",
},
};
}
function normalizeDismissalArtefact(
value: Record<string, unknown>,
): DismissalArtefact | null {
const id = optionalString(value.id);
if (!id) return null;
const contentValue = isObjectRecord(value.content) ? value.content : null;
if (!contentValue) return null;
const rawReason = optionalString(contentValue.reason);
const reason =
rawReason && DISMISSAL_REASONS.has(rawReason as DismissalReasonOptionValue)
? (rawReason as DismissalReasonOptionValue)
: null;
if (reason == null) {
return null;
}
return {
id,
type: "dismissal",
...artefactBase(value),
content: {
reason,
note: optionalString(contentValue.note) ?? "",
user_id:
typeof contentValue.user_id === "number" ? contentValue.user_id : null,
user_uuid: optionalString(contentValue.user_uuid),
},
};
}
// ── Log artefact normalizers ──────────────────────────────────────────────
// The backend stores log-artefact content as a JSON object (not the string-or-
// session_id shape the generic fallback expects), so each type needs an explicit
// normalizer — otherwise it falls through and gets dropped.
/** User the artefact is attributed to, when the row carries a valid `created_by`. */
function normalizeArtefactUser(value: unknown): UserBasic | null {
if (!isObjectRecord(value)) return null;
const id = value.id;
const uuid = optionalString(value.uuid);
const email = optionalString(value.email);
if (typeof id !== "number" || !uuid || !email) return null;
return {
id,
uuid,
email,
first_name: optionalString(value.first_name) ?? undefined,
last_name: optionalString(value.last_name) ?? undefined,
};
}
/** Row-level fields shared by every artefact: timestamps plus user/task attribution. */
function artefactBase(value: Record<string, unknown>): {
created_at: string;
updated_at: string | null;
created_by: UserBasic | null;