-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathopenapi.yaml
More file actions
2171 lines (2064 loc) · 73.9 KB
/
Copy pathopenapi.yaml
File metadata and controls
2171 lines (2064 loc) · 73.9 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
openapi: '3.0.3'
info:
title: NeuroWealth Backend API
version: '1.0.0'
description: |
NeuroWealth autonomous DeFi portfolio manager backend.
Authentication: All protected endpoints require a `Bearer <JWT>` token in the
`Authorization` header, obtained from `POST /api/auth/login`.
servers:
- url: /api/v1
description: Versioned API base (alias of /api for current release)
- url: /api
description: API base
tags:
- name: Network
description: Stellar network fee oracle and congestion (public).
- name: Analytics
description: Portfolio performance and risk analytics
- name: Assistant
description: |
Tool-calling conversational assistant (#318). Replaces the rule-based
NLP parser as the recognition layer for open-ended requests. The model
never moves money or changes state directly — it may only propose a
call from a fixed, allowlisted tool registry, and every non-read-only
tool is dry-run and gated behind an explicit confirmation before it
executes through the same verified, idempotent, audited service paths
every other feature uses.
- name: Agent
description: Explainable rebalance decisions (#343) — the per-decision rationale ledger.
- name: Admin
description: Operational tooling and audit (requires admin-scoped credentials).
- name: Auth
description: Authentication and session management
- name: Portfolio
description: User portfolio management
- name: Realtime
description: |
Authenticated WebSocket streaming (#316). The handshake below is a real
HTTP request and is spec'd here so generated clients know how to open it;
everything after the 101 is the JSON subprotocol described in the
`WebSocket*` schemas and in docs/WEBSOCKET_STREAMING.md.
# ─── Reusable components ──────────────────────────────────────────────────────
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
schemas:
# ── Shared primitives ────────────────────────────────────────────────────
Period:
type: string
enum: ['7d', '30d', '90d']
default: '30d'
description: Analysis time window. Maximum available history is 90 days.
InsufficientHistoryFlag:
type: boolean
description: |
True when the available snapshot history is shorter than the requested
window. Rows/responses with this flag set are excluded from leaderboard
rankings. Never silently serves a truncated window under the requested label.
NullableDecimal:
type: number
format: double
nullable: true
RankedCandidate:
type: object
required: [protocol, eligible]
properties:
protocol:
type: string
apy:
$ref: '#/components/schemas/NullableDecimal'
riskScore:
type: integer
nullable: true
eligible:
type: boolean
rejectionReason:
type: string
nullable: true
description: null on the chosen protocol; otherwise over_risk_ceiling | risk_score_unknown | lower_apy | lower_target_weight | current_position | etc.
RebalanceDecision:
type: object
properties:
id:
type: string
format: uuid
correlationId:
type: string
batchKey:
type: string
fromProtocol:
type: string
toProtocol:
type: string
nullable: true
outcome:
type: string
enum: [REBALANCED, HELD, BLOCKED]
blockedReason:
type: string
nullable: true
description: risk_ceiling | below_min_improvement | cost_exceeds_gain | no_candidates
strategyName:
type: string
nullable: true
strategyIsFollowed:
type: boolean
followedStrategyId:
type: string
format: uuid
nullable: true
thresholds:
type: object
properties:
minimumImprovement:
type: number
maxGasPercent:
type: number
currentApy:
$ref: '#/components/schemas/NullableDecimal'
chosenApy:
$ref: '#/components/schemas/NullableDecimal'
rawImprovement:
$ref: '#/components/schemas/NullableDecimal'
estCostPercent:
$ref: '#/components/schemas/NullableDecimal'
netImprovement:
$ref: '#/components/schemas/NullableDecimal'
candidates:
type: array
items:
$ref: '#/components/schemas/RankedCandidate'
rationale:
type: string
nullable: true
outboxOpId:
type: string
format: uuid
nullable: true
outboxStatus:
type: string
nullable: true
description: Joined from outbox_ops.status when outboxOpId present.
heldSince:
type: string
format: date-time
nullable: true
lastEvaluatedAt:
type: string
format: date-time
nullable: true
createdAt:
type: string
format: date-time
RebalanceDecisionAdmin:
allOf:
- $ref: '#/components/schemas/RebalanceDecision'
- type: object
properties:
affectedUserIds:
type: array
items:
type: string
format: uuid
affectedPositions:
type: integer
StressScenario:
type: object
properties:
id:
type: string
label:
type: string
description:
type: string
shocks:
type: object
provenance:
type: string
StressResult:
type: object
properties:
scenarioId:
type: string
label:
type: string
preValueUsd:
type: number
postValueUsd:
type: number
impactUsd:
type: number
impactPct:
type: number
perPosition:
type: array
items:
type: object
modeledRecoveryDays:
type: integer
nullable: true
permanentImpairment:
type: boolean
caveat:
type: string
asOf:
type: string
format: date-time
# ── Assistant (#318) ─────────────────────────────────────────────────────
AssistantChatRequest:
type: object
required: [message]
additionalProperties: false
properties:
message:
type: string
minLength: 1
maxLength: 2000
targetUserId:
type: string
format: uuid
description: |
Act on this linked sub-account instead of the caller's own
account. Omit (or pass the caller's own id) to act on the
caller's own account.
AssistantChatResponse:
type: object
required: [reply, usedFallback, pendingConfirmation]
properties:
reply:
type: string
description: The assistant's reply, ready to display verbatim.
usedFallback:
type: boolean
description: |
True when the model was unavailable or the token budget was
exhausted and this reply is a graceful degradation rather than a
model-generated answer.
pendingConfirmation:
type: boolean
description: |
True when this reply is a confirmation prompt for a proposed
action. The caller's next message on the same channel/account
must be an affirmative or negative reply — it is interpreted as
the confirmation decision, not a new request.
# ── Strategy What-If simulation (#344) ────────────────────────────────────
StrategySimulateRequest:
type: object
additionalProperties: false
properties:
strategy:
type: string
enum: [MAX_YIELD, TARGET_ALLOCATION, GOAL_TRACKING]
nullable: true
description: Strategy to simulate. Mutually exclusive with followStrategyId.
targetAllocations:
type: object
additionalProperties:
type: number
minimum: 0
maximum: 100
description: |
Protocol name → target weight (%). After config resolution these
must sum to 100 for TARGET_ALLOCATION, enforced in the service.
riskCeiling:
type: integer
minimum: 0
maximum: 100
description: |
Risk ceiling to simulate. Always clamped to the stricter of the
caller's own and any applied ceiling.
followStrategyId:
type: string
format: uuid
nullable: true
description: |
Simulate the config of a published strategy to follow. Mutually
exclusive with the inline strategy/targetAllocations/riskCeiling.
historyWindowDays:
type: integer
minimum: 1
maximum: 180
default: 90
description: Historical replay window; capped at 180 days.
assumeInitialDeposit:
type: boolean
description: |
When the caller has no active positions, replay a nominal $1000
instead of zero.
StrategySimulateResponse:
type: object
required: [immediate, historical, simulationToken, asOf, effectiveConfig, dataCaveats, label]
properties:
immediate:
$ref: '#/components/schemas/StrategyImmediateDecision'
historical:
$ref: '#/components/schemas/StrategyHistoricalReplay'
simulationToken:
type: string
description: Opaque sha-256 binding the preview to the exact config + window.
asOf:
type: string
format: date-time
effectiveConfig:
type: object
properties:
strategyName:
type: string
enum: [MAX_YIELD, TARGET_ALLOCATION, GOAL_TRACKING]
nullable: true
targetAllocations:
type: object
additionalProperties:
type: number
riskCeiling:
type: integer
nullable: true
dataCaveats:
type: array
items:
type: string
description: Window-truncation and missing-protocol caveats, never silent.
label:
type: string
StrategyImmediateDecision:
type: object
required: [action, targetProtocol, moves, trace, reasoning]
properties:
action:
type: string
enum: [rebalance, hold, blocked]
targetProtocol:
type: string
nullable: true
moves:
type: array
items:
type: object
properties:
toProtocol:
type: string
fraction:
type: number
trace:
type: object
description: Shape-parity with the persisted DecisionTrace.
reasoning:
type: string
StrategyHistoricalReplay:
type: object
required:
- rebalanceCount
- turnoverRatio
- totalFeesPaid
- endingValue
- startingValue
- counterfactualEndingValue
- finalProtocol
- timeSeries
- realizedGainPct
- counterfactualGainPct
- dataCaveats
properties:
rebalanceCount:
type: integer
turnoverRatio:
type: number
totalFeesPaid:
type: string
endingValue:
type: string
startingValue:
type: string
counterfactualEndingValue:
type: string
finalProtocol:
type: string
nullable: true
timeSeries:
type: array
items:
type: object
properties:
date:
type: string
format: date
simulatedValue:
type: string
counterfactualValue:
type: string
realizedGainPct:
type: number
nullable: true
counterfactualGainPct:
type: number
nullable: true
dataCaveats:
type: array
items:
type: string
# ── Risk metrics ─────────────────────────────────────────────────────────
RiskMetrics:
type: object
description: |
Computed risk/performance statistics for a portfolio-value series.
**Null contract**: any metric that is not computable (insufficient samples,
zero variance, degenerate series) is returned as `null` — never as `0`,
`Infinity`, or `NaN`.
**VaR / CVaR estimators**:
- `varHistorical*` / `cvarHistorical*` — empirical (plain-historical),
sorts the observed return distribution. Preferred for DeFi portfolios.
- `varParametric*` — Gaussian assumption (mean + σ). Underestimates tail
risk for fat-tailed distributions; provided for comparison only.
All loss magnitudes are **positive numbers** (0.05 = 5% potential loss).
properties:
sampleCount:
type: integer
description: Number of period-return observations used in all computations.
annualisedVolatility:
allOf:
- $ref: '#/components/schemas/NullableDecimal'
description: |
Sample standard deviation of period returns × √(periodsPerYear).
null if fewer than 2 return observations.
sortinoRatio:
allOf:
- $ref: '#/components/schemas/NullableDecimal'
description: |
(Annualised mean return − MAR) / annualised downside deviation.
null if fewer than 2 observations or downside deviation is 0 (no losses).
downsideDeviation:
allOf:
- $ref: '#/components/schemas/NullableDecimal'
description: RMS of returns below MAR, annualised. null if no returns.
maxDrawdown:
allOf:
- $ref: '#/components/schemas/NullableDecimal'
description: |
Maximum peak-to-trough decline as a positive fraction (0.15 = 15%).
null if fewer than 2 value points.
maxDrawdownDuration:
nullable: true
type: integer
description: |
Number of observation steps from peak to trough in the max drawdown
episode. null if no drawdown occurred.
varHistorical95:
allOf:
- $ref: '#/components/schemas/NullableDecimal'
description: Historical VaR at 95% confidence (positive = potential loss).
varHistorical99:
allOf:
- $ref: '#/components/schemas/NullableDecimal'
description: Historical VaR at 99% confidence.
varParametric95:
allOf:
- $ref: '#/components/schemas/NullableDecimal'
description: Parametric (Gaussian) VaR at 95% confidence.
varParametric99:
allOf:
- $ref: '#/components/schemas/NullableDecimal'
description: Parametric (Gaussian) VaR at 99% confidence.
cvarHistorical95:
allOf:
- $ref: '#/components/schemas/NullableDecimal'
description: Historical CVaR (Expected Shortfall) at 95%.
cvarHistorical99:
allOf:
- $ref: '#/components/schemas/NullableDecimal'
description: Historical CVaR at 99%.
beta:
allOf:
- $ref: '#/components/schemas/NullableDecimal'
description: |
Beta vs an exogenous benchmark series. null when no benchmark is
provided (benchmark index ingestion is deferred).
periodsPerYear:
type: number
description: |
Inferred periods-per-year used for annualisation, derived from the
median inter-observation spacing. Robust to snapshot gaps.
required:
- sampleCount
- periodsPerYear
PortfolioRiskResponse:
type: object
properties:
userId:
type: string
format: uuid
requestedWindow:
$ref: '#/components/schemas/Period'
actualWindowDays:
type: integer
description: Days of data actually used (may be shorter than requested).
insufficientHistory:
$ref: '#/components/schemas/InsufficientHistoryFlag'
dataFrom:
nullable: true
type: string
format: date-time
description: ISO timestamp of the earliest snapshot included.
dataTo:
nullable: true
type: string
format: date-time
description: ISO timestamp of the latest snapshot included.
computedAt:
type: string
format: date-time
description: When these figures were computed (staleness signal).
source:
type: string
enum: ['precomputed', 'live']
description: Whether the response was served from the precomputed cache.
metrics:
allOf:
- $ref: '#/components/schemas/RiskMetrics'
- nullable: true
type: object
description: null when sampleCount is 0 (entirely un-funded history).
required:
- userId
- requestedWindow
- actualWindowDays
- insufficientHistory
- computedAt
- source
RollingVolPoint:
type: object
properties:
timestampMs:
type: integer
format: int64
description: Epoch milliseconds of the last return in this rolling window.
volatility:
nullable: true
type: number
format: double
description: Annualised volatility over the window. null if insufficient data.
required:
- timestampMs
- volatility
DrawdownPoint:
type: object
properties:
timestampMs:
type: integer
format: int64
drawdown:
type: number
format: double
description: Drawdown from the running peak as a positive fraction.
required:
- timestampMs
- drawdown
TimeseriesResponse:
type: object
properties:
userId:
type: string
format: uuid
requestedWindow:
$ref: '#/components/schemas/Period'
insufficientHistory:
$ref: '#/components/schemas/InsufficientHistoryFlag'
rollingVolatility:
type: array
items:
$ref: '#/components/schemas/RollingVolPoint'
drawdown:
type: array
items:
$ref: '#/components/schemas/DrawdownPoint'
computedAt:
type: string
format: date-time
required:
- userId
- requestedWindow
- insufficientHistory
- rollingVolatility
- drawdown
- computedAt
ValidationError:
type: object
properties:
error:
type: string
example: Validation error
details:
type: object
required:
- error
UnauthorizedError:
type: object
properties:
error:
type: string
example: Unauthorized
required:
- error
# ── Real-time WebSocket subprotocol (#316) ───────────────────────────────
#
# These are not request/response bodies: they are the JSON frames exchanged
# over the socket opened by `GET /ws`. They live in the spec so client
# generators and reviewers have one authoritative shape per frame.
WebSocketTopic:
type: string
enum: [portfolio, transactions, agent, alerts, strategies]
description: |
Subscription, ordering, and permission unit.
**Ordering**: within a topic, events arrive in ascending `seq`. Across
topics there is NO ordering guarantee — all topics share one per-user
sequence, so use `seq` rather than arrival order. On-chain events
inherit ProcessedEvent's ledger ordering upstream.
WebSocketSubscribe:
type: object
description: Client → server. Start live delivery for the given topics.
required: [type, topics]
additionalProperties: false
properties:
type:
type: string
enum: [subscribe]
topics:
type: array
minItems: 1
items:
$ref: '#/components/schemas/WebSocketTopic'
coalesce:
type: boolean
default: false
description: |
Opt into latest-wins coalescing of same-type bursts within a short
window (WS_COALESCE_WINDOW_MS). Suppressed events remain in the
durable stream but are NOT redelivered by a later `resume`, because
`afterSeq` has already moved past them. Off by default.
WebSocketResume:
type: object
description: |
Client → server. Replay everything after `afterSeq`, then switch to live.
Send this on every reconnect.
required: [type, topics, afterSeq]
additionalProperties: false
properties:
type:
type: string
enum: [resume]
topics:
type: array
minItems: 1
items:
$ref: '#/components/schemas/WebSocketTopic'
afterSeq:
type: integer
minimum: 0
description: Last `seq` the client durably processed. 0 replays everything retained.
coalesce:
type: boolean
default: false
WebSocketUnsubscribe:
type: object
description: Client → server. Stop delivery for the given topics.
required: [type, topics]
additionalProperties: false
properties:
type:
type: string
enum: [unsubscribe]
topics:
type: array
minItems: 1
items:
$ref: '#/components/schemas/WebSocketTopic'
WebSocketPing:
type: object
description: |
Client → server. Application-level keepalive, answered with `pong`. Only
needed by clients that cannot observe protocol-level pongs (browsers);
the server pings every `heartbeatIntervalMs` regardless.
required: [type]
additionalProperties: false
properties:
type:
type: string
enum: [ping]
WebSocketClientMessage:
description: |
Every message a client may send. The receive side is a control channel
only — v1 is server→client for data. State-changing operations stay on
the REST surface, which has the validation, idempotency, and audit trail
a socket does not.
oneOf:
- $ref: '#/components/schemas/WebSocketSubscribe'
- $ref: '#/components/schemas/WebSocketResume'
- $ref: '#/components/schemas/WebSocketUnsubscribe'
- $ref: '#/components/schemas/WebSocketPing'
WebSocketHello:
type: object
description: Server → client. First frame after a successful handshake.
required: [type, actor, topics, currentSeq, heartbeatIntervalMs]
properties:
type:
type: string
enum: [hello]
actor:
type: string
enum: [self, delegated]
description: |
`delegated` when the connection was opened with `?actor=<userId>`
and an ACTIVE sub-account grant authorised it.
topics:
type: array
description: Topics this connection may subscribe to, derived server-side.
items:
$ref: '#/components/schemas/WebSocketTopic'
currentSeq:
type: integer
description: Newest `seq` on the bound stream right now.
heartbeatIntervalMs:
type: integer
WebSocketSubscribed:
type: object
description: Server → client. Acknowledges the active subscription set.
required: [type, topics, currentSeq, coalesce]
properties:
type:
type: string
enum: [subscribed]
topics:
type: array
items:
$ref: '#/components/schemas/WebSocketTopic'
currentSeq:
type: integer
coalesce:
type: boolean
WebSocketEvent:
type: object
description: |
Server → client. One domain event.
**Delivery is at-least-once.** A `resume` replays from the durable store
while live events keep arriving, and the live-switch prefers a duplicate
over a hole. Dedupe on `seq`, which is monotonic per user.
**Payloads are allowlisted per event type** by the same discipline as
REST responses (src/utils/api-formatters.ts). No `userId`, wallet
address, key, or internal field appears here.
required: [type, seq, topic, event, payload, emittedAt]
properties:
type:
type: string
enum: [event]
seq:
type: integer
description: Monotonic per-user sequence number. Track the highest you processed.
topic:
$ref: '#/components/schemas/WebSocketTopic'
event:
type: string
description: Domain event type, e.g. `deposit.received`.
example: deposit.received
payload:
type: object
additionalProperties: true
emittedAt:
type: string
format: date-time
WebSocketReplay:
type: object
description: Server → client. Brackets the replay served for a `resume`.
required: [type, status, fromSeq, toSeq, count]
properties:
type:
type: string
enum: [replay]
status:
type: string
enum: [start, end]
fromSeq:
type: integer
toSeq:
type: integer
count:
type: integer
WebSocketGap:
type: object
description: |
Server → client. The stream could not be served continuously.
* `retention` — the requested `afterSeq` is older than what is retained,
or a single replay hit its page limit with history still to come.
* `backpressure` — the client was too slow; delivery stopped at
`afterSeq`. Nothing is lost; `resume` from there.
* `unknown_stream` — the requested `afterSeq` is ahead of the server.
When `snapshotRequired` is true, replay cannot close the gap: fetch a
REST snapshot (`/portfolio`, `/transactions`, …) and then `subscribe`.
required:
[
type,
reason,
afterSeq,
currentSeq,
oldestAvailableSeq,
snapshotRequired,
]
properties:
type:
type: string
enum: [gap]
reason:
type: string
enum: [retention, backpressure, unknown_stream]
afterSeq:
type: integer
nullable: true
currentSeq:
type: integer
oldestAvailableSeq:
type: integer
nullable: true
snapshotRequired:
type: boolean
WebSocketError:
type: object
description: |
Server → client. `forbidden` mirrors REST 403 semantics — a topic the
connection's grant does not cover. `unauthorized` precedes a close with
code 4408 when the session is revoked mid-connection.
required: [type, code, message]
properties:
type:
type: string
enum: [error]
code:
type: string
enum: [bad_request, forbidden, unauthorized, rate_limited, internal]
message:
type: string
WebSocketDraining:
type: object
description: |
Server → client. Sent before a graceful shutdown closes the socket with
code 1001. Reconnect after `retryAfterMs` and `resume` from
`resumeAfterSeq`.
required: [type, reason, resumeAfterSeq, retryAfterMs]
properties:
type:
type: string
enum: [draining]
reason:
type: string
enum: [server_shutdown]
resumeAfterSeq:
type: integer
retryAfterMs:
type: integer
WebSocketPong:
type: object
description: Server → client. Reply to an application-level `ping`.
required: [type, at]
properties:
type:
type: string
enum: [pong]
at:
type: string
format: date-time
WebSocketServerFrame:
description: Every frame the server may send.
oneOf:
- $ref: '#/components/schemas/WebSocketHello'
- $ref: '#/components/schemas/WebSocketSubscribed'
- $ref: '#/components/schemas/WebSocketEvent'
- $ref: '#/components/schemas/WebSocketReplay'
- $ref: '#/components/schemas/WebSocketGap'
- $ref: '#/components/schemas/WebSocketError'
- $ref: '#/components/schemas/WebSocketDraining'
- $ref: '#/components/schemas/WebSocketPong'
responses:
Unauthorized:
description: Missing or invalid JWT.
content:
application/json:
schema:
$ref: '#/components/schemas/UnauthorizedError'
# ─── Paths ────────────────────────────────────────────────────────────────────
paths:
# ── Assistant endpoints (#318) ────────────────────────────────────────────────
/assistant/chat:
post:
operationId: assistantChat
summary: Send a message to the tool-calling assistant
description: |
Sends one message to the conversational assistant and returns its
reply. The assistant may read live account data to ground its answer,
or propose an action (deposit, withdraw, rebalance, adjust strategy,
follow/unfollow a marketplace strategy, create a recurring deposit,
create an alert rule) — action proposals are always previewed
(dry-run) and returned as a confirmation prompt; the SAME action only
executes once the caller's next message is an affirmative reply
(`pendingConfirmation: true` on this response). A negative reply
cancels it; anything else re-prompts without executing or dropping
the pending action.
**Sub-accounts**: pass `targetUserId` to act on a linked child
account. The caller must hold an ACTIVE `SubAccount` link with the
permission the specific proposed tool requires (same enforcement as
`src/middleware/subAccount.ts`); a caller with no link, or the wrong
permission, gets `403` before the message even reaches the model.
**Degradation**: if the model is unavailable or the caller's token
budget is exhausted, this still returns `200` with a graceful reply
and `usedFallback: true` — never a `5xx` or a hang.
tags: [Assistant]
security:
- bearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/AssistantChatRequest'
examples:
read_only:
summary: Open-ended read request
value:
message: "what's my portfolio worth right now?"
action_proposal:
summary: A request that proposes an action
value:
message: "withdraw 50 USDC"
sub_account:
summary: Acting on a linked sub-account
value:
message: "what's the balance on my kid's account?"
targetUserId: "3f8e1c2a-4b5d-6e7f-8a9b-0c1d2e3f4a5b"
responses:
'200':
description: The assistant's reply.
content:
application/json:
schema:
$ref: '#/components/schemas/AssistantChatResponse'
examples:
grounded_answer: