Spaces:
Sleeping
Sleeping
File size: 15,213 Bytes
5e0e982 57ed4c2 5e0e982 391340f 5e0e982 57ed4c2 391340f 4c23c1f 57ed4c2 4c23c1f 57ed4c2 4c23c1f 391340f 4c23c1f 391340f 8d145ad 391340f 5e0e982 57ed4c2 5e0e982 391340f 5e0e982 391340f 709db16 391340f c6253b2 fb29daa c6253b2 fb29daa c6253b2 fb29daa c6253b2 fb29daa c6253b2 9af2b22 57ed4c2 fb29daa 57ed4c2 | 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 | /** Typed API client with credentials and envelope handling. */
export type ApiErrorBody = {
code: string;
message: string;
};
export class ApiError extends Error {
code: string;
constructor(error: ApiErrorBody) {
super(error.message);
this.code = error.code;
this.name = "ApiError";
}
}
type Envelope<T> = {
ok: boolean;
data: T | null;
error: ApiErrorBody | null;
};
export type MeData = {
authenticated: boolean;
app_name: string;
};
export type WalkType = "interrupt" | "fantasy" | "mixed";
export type Entry = {
id: string;
ts: string;
created_at: string;
updated_at: string;
activity: string;
happened: string;
emotions: string[];
intensity: number;
remedy: string;
result: "worked" | "partial" | "failed" | "pending";
tags: string[];
notes: string;
fse_spike?: boolean | null;
avoidance_types?: string[];
proof_brick?: string | null;
walk_type?: WalkType | null;
coach: {
text: string | null;
source: string | null;
model: string | null;
ts: string | null;
trace_id: string | null;
};
};
export type EntryListData = {
items: Entry[];
total: number;
limit: number;
offset: number;
};
export type PrimaryBrick = "A" | "B" | "C" | "D" | "E" | "S" | "none";
export type ProofBrickKind =
| "interrupt_walk"
| "body_or_room"
| "trip_admin"
| "earn"
| "boundary"
| "food"
| "survive"
| "other"
| "leave_room"
| "admin_line"
| "send_message"
| "body_care";
export type DailyRow = {
date: string;
primary_brick: PrimaryBrick;
brick_done: boolean;
corn_sessions: number;
delay_ok: boolean;
daydream: "none" | "done" | "fc";
rerun: "clean" | "R";
court: "closed" | "court";
stayed_indoors_all_day: boolean;
left_room: boolean;
left_home: boolean;
movement_minutes: number;
interrupt_walk_minutes: number;
fantasy_walk_minutes: number;
headphones_on_walk: boolean;
music_cinematic_on_walk: boolean;
proof_brick_done: boolean;
proof_brick_kind: ProofBrickKind | null;
fantasy_minutes_scheduled: number;
fantasy_minutes_unplanned: number;
points: number;
note: string;
win?: string;
updated_at: string;
};
export type DailyRangeData = {
items: DailyRow[];
week_points: number;
band: "incomplete" | "strong" | "mixed" | "escape_heavy";
days_present: number;
};
export type EntryCreate = {
activity: string;
happened: string;
emotions: string[];
intensity: number;
remedy: string;
result: Entry["result"];
tags?: string[];
notes?: string;
fse_spike?: boolean | null;
avoidance_types?: string[];
proof_brick?: string | null;
walk_type?: WalkType | null;
};
export type EntryUpdate = Partial<EntryCreate & { ts: string }>;
export type DailyUpsert = Omit<DailyRow, "date" | "points" | "updated_at">;
export type ServerPick = {
remedy_key: string;
n: number;
p_helped: number;
p_worked?: number;
rank?: number;
pick?: number;
match?: number;
};
export type CoachResponse = {
text: string;
source: "model" | "backup" | "model_unparsed_fallback";
model: string | null;
trace_id: string;
flags: string[];
server_picks: ServerPick[];
parsed: Record<string, string> | null;
};
export type StatRow = {
key: string;
n: number;
p_helped?: number;
p_worked?: number;
p_failed?: number;
rank?: number;
};
export type StatsData = {
n_entries_total: number;
n_entries_scored: number;
outcomes: Record<Entry["result"], number>;
by_remedy: StatRow[];
by_tag: StatRow[];
by_emotion: StatRow[];
by_intensity_bucket: StatRow[];
daily: Record<string, number>;
generated_at: string;
DATA_THIN: boolean;
};
export type SettingsStatus = {
app_name: string;
app_version: string;
coach_configured: boolean;
model: string;
data_ok: boolean;
env: string;
};
function redirectLogin(): void {
if (typeof window === "undefined") return;
const hash = window.location.hash.replace(/^#/, "") || "/";
if (hash.startsWith("/login")) return;
window.location.hash = "#/login";
}
export async function api<T>(
path: string,
options: RequestInit = {},
): Promise<T> {
const headers = new Headers(options.headers || {});
if (!headers.has("Accept")) headers.set("Accept", "application/json");
if (options.body && !headers.has("Content-Type")) {
headers.set("Content-Type", "application/json");
}
const res = await fetch(path, {
...options,
credentials: "include",
headers,
});
if (res.status === 401) {
redirectLogin();
throw new ApiError({ code: "unauthorized", message: "Login required" });
}
const body = (await res.json()) as Envelope<T>;
if (!body.ok || body.error) {
throw new ApiError(
body.error || { code: "internal", message: "Request failed" },
);
}
return body.data as T;
}
export function getMe(): Promise<MeData> {
return api<MeData>("/api/auth/me");
}
export function login(password: string): Promise<{ authenticated: boolean }> {
return api("/api/auth/login", {
method: "POST",
body: JSON.stringify({ password }),
});
}
export function createEntry(payload: EntryCreate): Promise<Entry> {
return api<Entry>("/api/entries", {
method: "POST",
body: JSON.stringify(payload),
});
}
export function listEntries(params: {
result?: Entry["result"];
tag?: string;
start?: string;
end?: string;
limit?: number;
offset?: number;
}): Promise<EntryListData> {
const query = new URLSearchParams();
if (params.result) query.set("result", params.result);
if (params.tag) query.set("tag", params.tag);
if (params.start) query.set("start", params.start);
if (params.end) query.set("end", params.end);
if (params.limit) query.set("limit", String(params.limit));
if (params.offset) query.set("offset", String(params.offset));
const qs = query.toString();
return api<EntryListData>(`/api/entries${qs ? `?${qs}` : ""}`);
}
export function getEntry(id: string): Promise<Entry> {
return api<Entry>(`/api/entries/${encodeURIComponent(id)}`);
}
export function updateEntry(id: string, payload: EntryUpdate): Promise<Entry> {
return api<Entry>(`/api/entries/${encodeURIComponent(id)}`, {
method: "PATCH",
body: JSON.stringify(payload),
});
}
/** PATCH helper for resolve flows (result + optional remedy). */
export function patchEntry(
id: string,
payload: { result: Exclude<Entry["result"], "pending">; remedy?: string },
): Promise<Entry> {
return updateEntry(id, payload);
}
export function listPending(limit = 50): Promise<EntryListData> {
return listEntries({ result: "pending", limit, offset: 0 });
}
export function deleteEntry(id: string): Promise<{ deleted: boolean; id: string }> {
return api(`/api/entries/${encodeURIComponent(id)}`, { method: "DELETE" });
}
export function getDaily(day: string): Promise<DailyRow> {
return api<DailyRow>(`/api/daily/${day}`);
}
export function listDaily(start: string, end: string): Promise<DailyRangeData> {
return api<DailyRangeData>(
`/api/daily?start=${encodeURIComponent(start)}&end=${encodeURIComponent(end)}`,
);
}
export function putDaily(day: string, payload: DailyUpsert): Promise<DailyRow> {
return api<DailyRow>(`/api/daily/${day}`, {
method: "PUT",
body: JSON.stringify(payload),
});
}
export function runCoach(payload: {
text?: string;
entry_id?: string;
persist?: boolean;
}): Promise<CoachResponse> {
return api<CoachResponse>("/api/coach", {
method: "POST",
body: JSON.stringify(payload),
});
}
export function coachEntry(id: string): Promise<CoachResponse> {
return api<CoachResponse>(`/api/entries/${encodeURIComponent(id)}/coach`, {
method: "POST",
body: JSON.stringify({}),
});
}
export function getStats(): Promise<StatsData> {
return api<StatsData>("/api/stats");
}
export function getRemedies(): Promise<{ items: StatRow[]; min_n: number }> {
return api("/api/stats/remedies");
}
export function getSettingsStatus(): Promise<SettingsStatus> {
return api("/api/settings/status");
}
export function logout(): Promise<{ authenticated: boolean }> {
return api("/api/auth/logout", { method: "POST" });
}
export async function getDebugPaste(): Promise<string> {
const res = await fetch("/api/debug/last/paste", { credentials: "include" });
if (res.status === 401) {
redirectLogin();
throw new ApiError({ code: "unauthorized", message: "Login required" });
}
if (!res.ok) {
let message = "Debug paste unavailable";
try {
const body = (await res.json()) as Envelope<never>;
message = body.error?.message || message;
} catch {
// Plain response: keep the generic message.
}
throw new ApiError({ code: "request_failed", message });
}
return res.text();
}
export async function downloadExport(path: string): Promise<Blob> {
const res = await fetch(path, { credentials: "include" });
if (res.status === 401) {
redirectLogin();
throw new ApiError({ code: "unauthorized", message: "Login required" });
}
if (!res.ok) throw new ApiError({ code: "request_failed", message: "Export failed" });
return res.blob();
}
/* —— Schedule / Plan —— */
export type TaskKind =
| "earn_ship"
| "admin_spain"
| "body_care"
| "move_out"
| "boundary"
| "food_out"
| "stabilize"
| "explore"
| "restore_fun"
| "sleep_window"
| "other";
export type ScheduledBlock = {
id: string;
date: string;
start: string;
end: string;
title: string;
kind: TaskKind;
intent: "duty" | "explore" | "restore_fun" | "measure";
priority: "P0" | "P1" | "P2";
planned_min: number;
status: "planned" | "done" | "partial" | "skipped" | "moved" | "cancelled";
source: string;
locked: boolean;
notes: string;
version_added: number;
label?: string;
feedback?: BlockFeedback | null;
};
export type BlockFeedback = {
block_id: string;
date: string;
did: "done" | "partial" | "skipped";
actual_min: number | null;
quality: number | null;
fun: number | null;
energy_after: number | null;
money_amount: number | null;
money_currency: string;
would_repeat: "yes" | "no" | "maybe" | null;
skip_reason: string | null;
note: string;
emotions?: string[];
fse_event?: string;
intensity?: number | null;
strong: boolean;
ts: string;
};
export type DayReview = {
comment: string;
emotions: string[];
fse_events: string;
what_moved: string;
what_avoided: string;
tomorrow_change: string;
};
export type DayPlanView = {
date: string;
version: number;
source: string;
blocks: ScheduledBlock[];
capacity_hint: number;
notes: string;
title?: string;
intention?: string;
constraints?: string[];
day_review?: DayReview;
warnings?: string[];
updated_at: string;
parent_version: number | null;
health?: {
score: number;
strong_feedback_count: number;
planned_count: number;
p0_done_rate: number;
explore_or_restore_done: boolean;
};
import_warnings?: string[];
};
export type ChatPlan = {
schema_version: number;
date: string;
title: string;
intention: string;
constraints: string[];
blocks: Array<Record<string, unknown>>;
day_review: DayReview;
summary?: {
blocks_total: number;
blocks_done: number;
blocks_skipped: number;
p0_done: number;
p0_total: number;
planned_min_sum: number;
actual_min_sum: number;
};
};
export type ScheduleTemplate = {
id: string;
title: string;
kind: TaskKind;
intent: string;
priority: string;
default_min: number;
label: string;
};
export function getPlan(day: string): Promise<DayPlanView> {
return api(`/api/plan/${day}`);
}
export function putPlan(
day: string,
payload: {
blocks: Partial<ScheduledBlock>[];
source?: string;
notes?: string;
capacity_hint?: number;
force_p0_move?: boolean;
},
): Promise<DayPlanView> {
return api(`/api/plan/${day}`, {
method: "PUT",
body: JSON.stringify(payload),
});
}
export function addPlanBlock(
day: string,
payload: {
start: string;
end: string;
title: string;
kind: TaskKind;
intent: ScheduledBlock["intent"];
priority: ScheduledBlock["priority"];
planned_min?: number;
locked?: boolean;
notes?: string;
},
): Promise<DayPlanView> {
return api(`/api/plan/${day}/blocks`, {
method: "POST",
body: JSON.stringify(payload),
});
}
export function patchPlanBlock(
day: string,
id: string,
payload: Partial<ScheduledBlock>,
): Promise<DayPlanView> {
return api(`/api/plan/${day}/blocks/${encodeURIComponent(id)}`, {
method: "PATCH",
body: JSON.stringify(payload),
});
}
export function deletePlanBlock(day: string, id: string): Promise<DayPlanView> {
return api(`/api/plan/${day}/blocks/${encodeURIComponent(id)}`, {
method: "DELETE",
});
}
export function postBlockFeedback(
day: string,
id: string,
payload: Partial<BlockFeedback> & { did: BlockFeedback["did"] },
): Promise<{ feedback: BlockFeedback; plan: DayPlanView }> {
return api(`/api/plan/${day}/blocks/${encodeURIComponent(id)}/feedback`, {
method: "POST",
body: JSON.stringify(payload),
});
}
export function getScheduleTemplates(): Promise<{ items: ScheduleTemplate[] }> {
return api("/api/schedule/templates");
}
export function getSchedulePriors(): Promise<{ kinds: Array<Record<string, unknown>>; markdown: string }> {
return api("/api/schedule/priors");
}
export function reschedulePlan(
day: string,
payload: { reason?: string; force?: boolean } = {},
): Promise<{ plan: DayPlanView; source: string; version: number }> {
return api(`/api/plan/${day}/reschedule`, {
method: "POST",
body: JSON.stringify(payload),
});
}
export function seedPlan(day: string): Promise<DayPlanView> {
return api(`/api/plan/${day}/seed`, { method: "POST", body: "{}" });
}
export function importChatPlan(
day: string,
plan: unknown,
mode: "replace" | "merge" = "replace",
): Promise<DayPlanView> {
return api(`/api/plan/${day}/import`, {
method: "POST",
body: JSON.stringify({ plan, mode }),
});
}
export function exportChatPlan(day: string): Promise<ChatPlan> {
return api(`/api/plan/${day}/export`);
}
export function checkPlanBlock(
day: string,
id: string,
payload: { status: "done" | "partial" | "skipped" | "planned"; skip_reason?: string },
): Promise<DayPlanView> {
return api(`/api/plan/${day}/blocks/${encodeURIComponent(id)}/check`, {
method: "POST",
body: JSON.stringify(payload),
});
}
export function patchPlanMeta(
day: string,
payload: {
title?: string;
intention?: string;
constraints?: string[];
day_review?: Partial<DayReview>;
},
): Promise<DayPlanView> {
return api(`/api/plan/${day}/meta`, {
method: "PATCH",
body: JSON.stringify(payload),
});
}
export type LoopSummary = {
days: number;
as_of: string;
indoors_streak: number;
proof_rate: number;
proof_days: number;
days_with_daily: number;
label_only_fail_rate: number;
label_only_fail_n: number;
high_intensity_n: number;
movement_minutes_sum: number;
pending_count: number;
};
export function getLoopSummary(days = 7): Promise<LoopSummary> {
return api(`/api/loop/summary?days=${days}`);
}
|