@dipertq/dsh-openviking-status 0.3.0 → 0.3.1

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/lib/client.d.cts CHANGED
@@ -135,6 +135,21 @@ type TaskEventsResult = {
135
135
  };
136
136
  /** Верхняя граница `limit` списка задач у демона. */
137
137
  declare const TASKS_LIMIT_CAP = 200;
138
+ /**
139
+ * Нормализовать временную метку в ISO-строку.
140
+ *
141
+ * Демон OpenViking отдаёт `created_at` / `updated_at` как числом секунд
142
+ * (Unix timestamp), так и ISO-строками в `created_at_iso` / `updated_at_iso`.
143
+ */
144
+ declare function normalizeTimestamp(ts: unknown, isoFallback?: unknown): string | undefined;
145
+ /**
146
+ * Извлечь массив сырых задач из ответа демона OpenViking.
147
+ *
148
+ * OpenViking GET /api/v1/tasks возвращает `{ status: "ok", result: [ ... ] }`,
149
+ * где `result` — сам массив задач. Также поддерживаются варианты с `items`,
150
+ * `tasks`, вложенным `result.items` или плоским массивом в корне.
151
+ */
152
+ declare function extractTaskList(data: unknown): unknown[];
138
153
  /**
139
154
  * Привести сырую задачу демона к {@link ExtractionTask}.
140
155
  *
@@ -401,6 +416,14 @@ declare const COMMIT_THRESHOLD = 20000;
401
416
  /** Интервалы адаптивного поллинга: покой vs активная фаза извлечения. */
402
417
  declare const POLL_INTERVAL_IDLE_MS = 15000;
403
418
  declare const POLL_INTERVAL_ACTIVE_MS = 2500;
419
+ /**
420
+ * Определяет, находится ли опрос в активной фазе (2.5с вместо 15с).
421
+ *
422
+ * Активная фаза включается как при выполнении (`running >= 1`), так и при
423
+ * наличии задач в очереди (`pending >= 1`), чтобы успеть поймать запуск
424
+ * до завершения быстрой задачи.
425
+ */
426
+ declare function shouldPollActive(breakdown?: ExtractionBreakdown | null): boolean;
404
427
  /**
405
428
  * Состояние точки статуса (StateDot).
406
429
  *
@@ -645,4 +668,4 @@ declare const inject: string[];
645
668
  */
646
669
  declare function apply(ctx: any): void;
647
670
 
648
- export { COMMIT_THRESHOLD, type ChipDotState, type CommitOptions, type CommitResult, DEFAULT_OPENVIKING_ENDPOINT, type ExecutionEvent, type ExtractionBreakdown, ExtractionSection, type ExtractionTask, type ExtractionTaskStatus, type HealthStatus, OpenVikingClient, type OpenVikingConfigData, type OpenVikingHealth, type OpenVikingSessionData, OpenVikingSettingsSection, type OpenVikingSettingsSectionProps, OpenVikingStatusChip, type OpenVikingStatusChipProps, OpenVikingStatusPopover, type OpenVikingStatusPopoverProps, POLL_INTERVAL_ACTIVE_MS, POLL_INTERVAL_IDLE_MS, PROXY_OPENVIKING_ENDPOINT, type PeerId, type PendingTokens, type RecalledMemoriesResult, type RecalledMemoryItem, type SessionReadResult, type SessionStatus, TASKS_LIMIT_CAP, THEME, type TaskEventsResult, type TasksReadResult, type ThemeRole, type UseChat, WarningGlyph, apply, chatNodesToText, checkHealth, commitSession, computeBreakdown, defaultOpenVikingClient, fetchSession, formatBacklog, formatDaemonVersion, formatDuration, formatEndpoint, formatExtractionSummary, formatMemoryLeafName, formatPendingTokens, formatRelativeTime, formatStatusLabel, formatTooltipTitle, getCategoryBadgeStyle, getChipDotState, getDotColorForState, getProgressBarColor, getProgressBarPercent, getSession, getStatusIndicatorColor, handleEscapeKey, inferCategory, inject, name, normalizeExecutionEvent, normalizeExtractionTask, normalizeTaskList, parseRecalledMemories, resolveApiKey, resolveEndpoint, seedRunningTask, themeVar, truncateSessionId };
671
+ export { COMMIT_THRESHOLD, type ChipDotState, type CommitOptions, type CommitResult, DEFAULT_OPENVIKING_ENDPOINT, type ExecutionEvent, type ExtractionBreakdown, ExtractionSection, type ExtractionTask, type ExtractionTaskStatus, type HealthStatus, OpenVikingClient, type OpenVikingConfigData, type OpenVikingHealth, type OpenVikingSessionData, OpenVikingSettingsSection, type OpenVikingSettingsSectionProps, OpenVikingStatusChip, type OpenVikingStatusChipProps, OpenVikingStatusPopover, type OpenVikingStatusPopoverProps, POLL_INTERVAL_ACTIVE_MS, POLL_INTERVAL_IDLE_MS, PROXY_OPENVIKING_ENDPOINT, type PeerId, type PendingTokens, type RecalledMemoriesResult, type RecalledMemoryItem, type SessionReadResult, type SessionStatus, TASKS_LIMIT_CAP, THEME, type TaskEventsResult, type TasksReadResult, type ThemeRole, type UseChat, WarningGlyph, apply, chatNodesToText, checkHealth, commitSession, computeBreakdown, defaultOpenVikingClient, extractTaskList, fetchSession, formatBacklog, formatDaemonVersion, formatDuration, formatEndpoint, formatExtractionSummary, formatMemoryLeafName, formatPendingTokens, formatRelativeTime, formatStatusLabel, formatTooltipTitle, getCategoryBadgeStyle, getChipDotState, getDotColorForState, getProgressBarColor, getProgressBarPercent, getSession, getStatusIndicatorColor, handleEscapeKey, inferCategory, inject, name, normalizeExecutionEvent, normalizeExtractionTask, normalizeTaskList, normalizeTimestamp, parseRecalledMemories, resolveApiKey, resolveEndpoint, seedRunningTask, shouldPollActive, themeVar, truncateSessionId };
package/lib/client.js CHANGED
@@ -17,6 +17,33 @@ import ReactDOM from "react-dom";
17
17
 
18
18
  // src/client/api.ts
19
19
  var TASKS_LIMIT_CAP = 200;
20
+ function normalizeTimestamp(ts, isoFallback) {
21
+ if (typeof isoFallback === "string" && isoFallback.trim()) {
22
+ return isoFallback.trim();
23
+ }
24
+ if (typeof ts === "string" && ts.trim()) {
25
+ return ts.trim();
26
+ }
27
+ if (typeof ts === "number" && Number.isFinite(ts) && ts > 0) {
28
+ const ms = ts < 1e11 ? ts * 1e3 : ts;
29
+ return new Date(ms).toISOString();
30
+ }
31
+ return void 0;
32
+ }
33
+ function extractTaskList(data) {
34
+ if (!data || typeof data !== "object") return [];
35
+ if (Array.isArray(data)) return data;
36
+ const obj = data;
37
+ if (Array.isArray(obj.result)) return obj.result;
38
+ if (Array.isArray(obj.items)) return obj.items;
39
+ if (Array.isArray(obj.tasks)) return obj.tasks;
40
+ if (obj.result && typeof obj.result === "object") {
41
+ const res = obj.result;
42
+ if (Array.isArray(res.items)) return res.items;
43
+ if (Array.isArray(res.tasks)) return res.tasks;
44
+ }
45
+ return [];
46
+ }
20
47
  function normalizeExtractionTask(raw) {
21
48
  if (!raw || typeof raw !== "object") return null;
22
49
  const taskId = typeof raw.task_id === "string" && raw.task_id || typeof raw.id === "string" && raw.id || "";
@@ -36,8 +63,8 @@ function normalizeExtractionTask(raw) {
36
63
  task_id: taskId,
37
64
  status,
38
65
  resource_id: typeof raw.resource_id === "string" ? raw.resource_id : void 0,
39
- created_at: typeof raw.created_at === "string" ? raw.created_at : void 0,
40
- updated_at: typeof raw.updated_at === "string" ? raw.updated_at : void 0,
66
+ created_at: normalizeTimestamp(raw.created_at, raw.created_at_iso),
67
+ updated_at: normalizeTimestamp(raw.updated_at, raw.updated_at_iso),
41
68
  memory_write: numberOf(extracted.memory_write ?? extracted.written),
42
69
  memory_edit: numberOf(extracted.memory_edit ?? extracted.edited),
43
70
  token_usage: tokenUsage,
@@ -73,7 +100,7 @@ function computeBreakdown(tasks) {
73
100
  function normalizeExecutionEvent(raw) {
74
101
  return {
75
102
  seq: typeof raw.seq === "number" ? raw.seq : void 0,
76
- recorded_at: typeof raw.recorded_at === "string" ? raw.recorded_at : void 0,
103
+ recorded_at: normalizeTimestamp(raw.recorded_at, raw.recorded_at_iso),
77
104
  kind: typeof raw.kind === "string" ? raw.kind : void 0,
78
105
  status: typeof raw.status === "string" ? raw.status : void 0,
79
106
  stage: typeof raw.stage === "string" ? raw.stage : null,
@@ -479,7 +506,7 @@ var OpenVikingClient = class {
479
506
  status: "error",
480
507
  detail: typeof data.detail === "string" ? data.detail : void 0
481
508
  };
482
- const tasks = normalizeTaskList(data.tasks);
509
+ const tasks = normalizeTaskList(extractTaskList(data.tasks ?? data));
483
510
  return { status: "ok", breakdown: computeBreakdown(tasks), tasks };
484
511
  } catch (err) {
485
512
  return {
@@ -530,8 +557,7 @@ var OpenVikingClient = class {
530
557
  return { status: "error", detail: `HTTP ${res.status}` };
531
558
  }
532
559
  const data = await res.json();
533
- const items = data?.items ?? data?.tasks ?? data?.result?.items ?? (Array.isArray(data) ? data : []);
534
- const tasks = normalizeTaskList(items);
560
+ const tasks = normalizeTaskList(extractTaskList(data));
535
561
  return { status: "ok", breakdown: computeBreakdown(tasks), tasks };
536
562
  } catch (err) {
537
563
  return {
@@ -1756,6 +1782,10 @@ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
1756
1782
  var COMMIT_THRESHOLD = 2e4;
1757
1783
  var POLL_INTERVAL_IDLE_MS = 15e3;
1758
1784
  var POLL_INTERVAL_ACTIVE_MS = 2500;
1785
+ function shouldPollActive(breakdown) {
1786
+ if (!breakdown) return false;
1787
+ return breakdown.running >= 1 || breakdown.pending >= 1;
1788
+ }
1759
1789
  function getChipDotState({
1760
1790
  isOnline,
1761
1791
  sessionUnreadable,
@@ -1985,13 +2015,13 @@ function StatusChipView({
1985
2015
  }
1986
2016
  }, [sessionId, apiClient]);
1987
2017
  const breakdown = tasksRead?.status === "ok" ? tasksRead.breakdown : null;
1988
- const hasRunning = (breakdown?.running ?? 0) >= 1;
2018
+ const hasActivePhase = shouldPollActive(breakdown);
1989
2019
  useEffect2(() => {
1990
2020
  fetchStatus();
1991
- const interval = hasRunning ? POLL_INTERVAL_ACTIVE_MS : POLL_INTERVAL_IDLE_MS;
2021
+ const interval = hasActivePhase ? POLL_INTERVAL_ACTIVE_MS : POLL_INTERVAL_IDLE_MS;
1992
2022
  const timer = setInterval(fetchStatus, interval);
1993
2023
  return () => clearInterval(timer);
1994
- }, [fetchStatus, hasRunning]);
2024
+ }, [fetchStatus, hasActivePhase]);
1995
2025
  useEffect2(() => {
1996
2026
  function handleClickOutside(event) {
1997
2027
  if (popoverRef.current && !popoverRef.current.contains(event.target)) {
@@ -2776,6 +2806,7 @@ export {
2776
2806
  commitSession,
2777
2807
  computeBreakdown,
2778
2808
  defaultOpenVikingClient,
2809
+ extractTaskList,
2779
2810
  fetchSession,
2780
2811
  formatBacklog,
2781
2812
  formatDaemonVersion,
@@ -2801,10 +2832,12 @@ export {
2801
2832
  normalizeExecutionEvent,
2802
2833
  normalizeExtractionTask,
2803
2834
  normalizeTaskList,
2835
+ normalizeTimestamp,
2804
2836
  parseRecalledMemories,
2805
2837
  resolveApiKey,
2806
2838
  resolveEndpoint,
2807
2839
  seedRunningTask,
2840
+ shouldPollActive,
2808
2841
  themeVar,
2809
2842
  truncateSessionId
2810
2843
  };