@openchamber/web 1.14.1 → 1.16.0
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/bin/cli.test.js +8 -0
- package/bin/lib/DOCUMENTATION.md +3 -0
- package/bin/lib/cli-args.js +10 -0
- package/bin/lib/commands-connect-url.js +169 -22
- package/dist/assets/{DiagramView-Cb58svCq.js → DiagramView-he_RFVx5.js} +1 -1
- package/dist/assets/MarkdownRendererImpl-CdBIHSPZ.js +11 -0
- package/dist/assets/{MultiRunWindow-BPSxV_B7.js → MultiRunWindow-B_C-tvVq.js} +1 -1
- package/dist/assets/OnboardingScreen-BBnTt-9w.js +1 -0
- package/dist/assets/SessionSwitcherDropdown-CWWrCFzr.js +1 -0
- package/dist/assets/SettingsWindow-CjqLdpTE.js +1 -0
- package/dist/assets/{TerminalView-fTYjnQkh.js → TerminalView-DQcdegHp.js} +1 -1
- package/dist/assets/es-r0_jT91q.js +15 -0
- package/dist/assets/fr-Bo8rtAJ1.js +13 -0
- package/dist/assets/index-8J6waVO6.js +2 -0
- package/dist/assets/index-DEMqM4Lz.css +1 -0
- package/dist/assets/ja-BPWtkG-c.js +15 -0
- package/dist/assets/ko-Bv0k-0E3.js +15 -0
- package/dist/assets/main-B-GA5Tg5.js +237 -0
- package/dist/assets/main-Dfm-VKZ9.js +2 -0
- package/dist/assets/miniChat-CfmCFFfu.js +2 -0
- package/dist/assets/mobile-CXJqeDlm.js +2 -0
- package/dist/assets/pl-CiTP50bz.js +15 -0
- package/dist/assets/pt-BR-DadIjX5L.js +15 -0
- package/dist/assets/renderElectronMiniChatApp-DS7Dy2ii.js +2 -0
- package/dist/assets/renderMobileApp-o7Fs9EBx.js +16 -0
- package/dist/assets/runtimeEndpointReset-MTaPPm4F.js +167 -0
- package/dist/assets/uk-2RpsWGoZ.js +15 -0
- package/dist/assets/{useAppFontEffects-BUUJYbAZ.js → useAppFontEffects-DkPuAMXD.js} +196 -133
- package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
- package/dist/assets/zh-CN-BwKWaTuz.js +15 -0
- package/dist/assets/zh-TW--f_BqBpD.js +15 -0
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +4 -4
- package/dist/mobile.html +4 -4
- package/package.json +2 -2
- package/server/index.js +236 -2
- package/server/lib/client-auth/pairing.js +308 -0
- package/server/lib/client-auth/pairing.test.js +142 -0
- package/server/lib/client-auth/remote-clients.js +65 -3
- package/server/lib/notifications/DOCUMENTATION.md +1 -1
- package/server/lib/notifications/apns-runtime.js +11 -16
- package/server/lib/notifications/runtime.js +135 -33
- package/server/lib/opencode/DOCUMENTATION.md +1 -0
- package/server/lib/opencode/agents.js +3 -0
- package/server/lib/opencode/bootstrap-runtime.js +15 -0
- package/server/lib/opencode/core-routes.js +321 -8
- package/server/lib/opencode/core-routes.test.js +329 -9
- package/server/lib/opencode/feature-routes-runtime.js +6 -0
- package/server/lib/opencode/network-runtime.js +14 -1
- package/server/lib/opencode/network-runtime.test.js +29 -9
- package/server/lib/opencode/proxy.js +47 -6
- package/server/lib/opencode/settings-helpers.js +24 -0
- package/server/lib/opencode/settings-helpers.test.js +25 -0
- package/server/lib/opencode/settings-normalization-runtime.js +21 -4
- package/server/lib/opencode/settings-normalization-runtime.test.js +21 -0
- package/server/lib/opencode/settings-runtime.js +25 -0
- package/server/lib/opencode/shutdown-runtime.js +2 -0
- package/server/lib/opencode/tunnel-auth.js +4 -9
- package/server/lib/package-manager.js +18 -5
- package/server/lib/permission-auto-accept/DOCUMENTATION.md +34 -0
- package/server/lib/permission-auto-accept/runtime.js +263 -0
- package/server/lib/permission-auto-accept/runtime.test.js +137 -0
- package/server/lib/projects/project-config.js +8 -0
- package/server/lib/quota/DOCUMENTATION.md +5 -2
- package/server/lib/quota/credentials/providers.js +43 -0
- package/server/lib/quota/credentials/store.js +48 -0
- package/server/lib/quota/credentials/store.test.js +26 -0
- package/server/lib/quota/opencode-go-credentials.js +11 -0
- package/server/lib/quota/opencode-go-credentials.test.js +32 -0
- package/server/lib/quota/providers/codex.js +7 -4
- package/server/lib/quota/providers/codex.test.js +48 -0
- package/server/lib/quota/providers/cursor.js +28 -39
- package/server/lib/quota/providers/index.js +7 -0
- package/server/lib/quota/providers/ollama-cloud.js +23 -42
- package/server/lib/quota/providers/ollama-cloud.test.js +12 -0
- package/server/lib/quota/providers/opencode-go.js +70 -0
- package/server/lib/quota/providers/opencode-go.test.js +17 -0
- package/server/lib/quota/routes.js +78 -7
- package/server/lib/quota/routes.test.js +40 -0
- package/server/lib/relay/DOCUMENTATION.md +98 -0
- package/server/lib/relay/cross-compat.test.js +135 -0
- package/server/lib/relay/e2ee.js +341 -0
- package/server/lib/relay/e2ee.test.js +124 -0
- package/server/lib/relay/host-client.js +389 -0
- package/server/lib/relay/host-client.test.js +280 -0
- package/server/lib/relay/host-lock.js +101 -0
- package/server/lib/relay/host-lock.test.js +129 -0
- package/server/lib/relay/identity.js +93 -0
- package/server/lib/relay/identity.test.js +78 -0
- package/server/lib/relay/service.js +334 -0
- package/server/lib/relay/signing-key.js +73 -0
- package/server/lib/relay/tunnel-codec.js +373 -0
- package/server/lib/relay/tunnel-codec.test.js +58 -0
- package/server/lib/relay/tunnel-host.js +462 -0
- package/server/lib/scheduled-tasks/runtime.js +104 -0
- package/server/lib/session-goal/DOCUMENTATION.md +176 -0
- package/server/lib/session-goal/objectives.js +61 -0
- package/server/lib/session-goal/routes.js +36 -0
- package/server/lib/session-goal/runtime.js +764 -0
- package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
- package/server/lib/ui-auth/ui-auth.js +10 -0
- package/server/opencode-proxy.test.js +38 -0
- package/dist/assets/MarkdownRendererImpl-D2yCDL5A.js +0 -7
- package/dist/assets/OnboardingScreen-Sl-6JgaP.js +0 -1
- package/dist/assets/SessionSwitcherDropdown-4FWg9xMC.js +0 -1
- package/dist/assets/SettingsWindow-CY8q4msv.js +0 -1
- package/dist/assets/es-bWcuDy_2.js +0 -15
- package/dist/assets/fr-DzRs3OzV.js +0 -13
- package/dist/assets/index-KnWk9fmM.css +0 -1
- package/dist/assets/index-ZJTzZ0_U.js +0 -2
- package/dist/assets/ja-BqUX_UD3.js +0 -15
- package/dist/assets/ko-BQo10SNx.js +0 -15
- package/dist/assets/main-BDoqLlQB.js +0 -236
- package/dist/assets/main-DUGyTrDt.js +0 -2
- package/dist/assets/miniChat-DNDiX8GA.js +0 -2
- package/dist/assets/mobile-DnghtOCb.js +0 -2
- package/dist/assets/pl-Bgx_ATJT.js +0 -15
- package/dist/assets/pt-BR-B1yXRvoX.js +0 -15
- package/dist/assets/renderElectronMiniChatApp-BB4C1K7t.js +0 -2
- package/dist/assets/renderMobileApp-CZgaXKi5.js +0 -16
- package/dist/assets/runtimeEndpointReset-By39StyB.js +0 -167
- package/dist/assets/uk-C9k8SP8q.js +0 -15
- package/dist/assets/zh-CN-Bri-Vo5y.js +0 -15
- package/dist/assets/zh-TW-DAUGzmYG.js +0 -15
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
# Session Goal
|
|
2
|
+
|
|
3
|
+
Server-side control loop that keeps a session working toward a user-defined
|
|
4
|
+
objective stored under `metadata.openchamber.goal`, with the small model as
|
|
5
|
+
an independent progress auditor. Built on OpenChamber's backend-driven
|
|
6
|
+
architecture (session-assist is the structural template): the loop lives in
|
|
7
|
+
the web server and survives UI disconnects.
|
|
8
|
+
|
|
9
|
+
## Goal payload (`metadata.openchamber.goal`)
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
{
|
|
13
|
+
id, // opaque per-logical-goal id; stale-write guard
|
|
14
|
+
objective, // inline user text (fallback), <= 5000 chars
|
|
15
|
+
objectiveFile, // true: objective text lives in a server-side file
|
|
16
|
+
status, // active | paused | blocked | budgetLimited | complete
|
|
17
|
+
tokenBudget, // optional positive int
|
|
18
|
+
tokensUsed, // tokensCommitted + current segment (snapshot - baseline)
|
|
19
|
+
tokensBaseline, // segment start snapshot (pre-goal turn; 0 after compaction)
|
|
20
|
+
tokensCommitted, // closed segments' total (one segment per compaction)
|
|
21
|
+
turnsUsed, // auto-continuations sent (capped at MAX_AUTO_TURNS)
|
|
22
|
+
blockedStreak, // consecutive blocked audit verdicts
|
|
23
|
+
auditFailStreak, // consecutive failed/unavailable audit calls
|
|
24
|
+
note, // latest audit progress note, <= 280 chars
|
|
25
|
+
statusReason, // why settled; 'resumed' is a kickoff signal from UI
|
|
26
|
+
lastAccountedMessageID, // incremental accounting cursor
|
|
27
|
+
createdAt, updatedAt
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The UI writes goals (create/edit/pause/resume/clear) by patching this
|
|
32
|
+
metadata; the runtime never creates a goal on its own. Goal creation happens
|
|
33
|
+
at send time via the arm store (`useSessionGoalArmStore`): the composer
|
|
34
|
+
target button arms "the next prompt is the objective", and the run-as-goal
|
|
35
|
+
flows (fork-from-answer dialog, plan implement dialog) arm the same way —
|
|
36
|
+
the plan flow additionally supplies an objective OVERRIDE carrying the plan
|
|
37
|
+
content, since "Implement this plan: X" alone gives the audit nothing to
|
|
38
|
+
judge against. The armed send also attaches a synthetic system-reminder
|
|
39
|
+
part telling the agent goal mode is active and that each turn should end
|
|
40
|
+
with a factual done/verified/remaining statement for the independent audit.
|
|
41
|
+
Freshness/stale-write protection is by `id`: every runtime write re-reads the
|
|
42
|
+
session and drops the write when the stored goal id no longer matches.
|
|
43
|
+
|
|
44
|
+
## File-backed objectives
|
|
45
|
+
|
|
46
|
+
The objective TEXT lives in `<data-dir>/goals/<sessionId>.md` (data dir =
|
|
47
|
+
`OPENCHAMBER_DATA_DIR` or `~/.config/openchamber`), keyed by the SESSION ID:
|
|
48
|
+
sessions are globally unique and carry one goal at a time, so the mapping is
|
|
49
|
+
deterministic and a new goal simply overwrites the file. Metadata carries
|
|
50
|
+
only `objectiveFile: true` — never a path — so user-writable metadata cannot
|
|
51
|
+
become a file-read vector (`objectives.js` also validates the id shape
|
|
52
|
+
before touching the filesystem). Rationale: metadata rides every
|
|
53
|
+
`session.updated`, so multi-KB objectives must not live there.
|
|
54
|
+
|
|
55
|
+
- `objectives.js` — write/read/delete, 5000-char clamp.
|
|
56
|
+
- `routes.js` — `PUT/GET/DELETE /api/goals/objective/:sessionId`
|
|
57
|
+
(OpenChamber-owned, registered before the generic proxy; JSON parsing via
|
|
58
|
+
the `/api/goals` family in core-routes). The UI writes the file BEFORE
|
|
59
|
+
patching the goal metadata and falls back to an inline objective when the
|
|
60
|
+
write fails; `clearSessionGoal` deletes the file best-effort.
|
|
61
|
+
- The tick resolves the effective objective fresh on every cycle (the file
|
|
62
|
+
is live-editable mid-goal) and falls back to the inline `objective` when
|
|
63
|
+
the file is unreadable — a goal never dies because a file went away.
|
|
64
|
+
- UI display fetches content via the GET route
|
|
65
|
+
(`useGoalObjectiveContent`); in VS Code the route is unavailable, so the
|
|
66
|
+
strip degrades to the audit note (display-only fallback by design).
|
|
67
|
+
- Scheduled goal tasks write the file server-side directly via
|
|
68
|
+
`objectives.js`.
|
|
69
|
+
|
|
70
|
+
## Flow
|
|
71
|
+
|
|
72
|
+
1. `createSessionGoalRuntime` subscribes to the global SSE hub (same pattern
|
|
73
|
+
as session-assist — it needs the envelope's `directory`).
|
|
74
|
+
2. `session.status: idle` arms a 15s per-session timer; `busy`/`retry` clears
|
|
75
|
+
it. A `session.updated` carrying a fresh active goal (`turnsUsed === 0` or
|
|
76
|
+
`statusReason === 'resumed'`) arms a kickoff timer — 3s for fresh goals,
|
|
77
|
+
~250ms for an explicit Resume so the nudge feels immediate — since setting
|
|
78
|
+
a goal on an idle session emits no status transition.
|
|
79
|
+
3. On fire (`tick`), gated by the `sessionGoalEnabled` setting:
|
|
80
|
+
- fetch session (skip sub-agent sessions), require an `active` goal;
|
|
81
|
+
- quiescence check via the message tail (trailing user message or
|
|
82
|
+
unfinished assistant reply → bail; the next idle transition re-arms);
|
|
83
|
+
- token accounting as a SNAPSHOT of the latest completed assistant turn:
|
|
84
|
+
`input + cache.read + output`. Earlier turns' inputs and outputs fold
|
|
85
|
+
into the next turn's cache, so the latest snapshot already carries the
|
|
86
|
+
whole run's paid tokens — no summing across messages. Goal-relative via
|
|
87
|
+
`tokensBaseline` (the same snapshot of the newest pre-goal turn,
|
|
88
|
+
captured on the first tick). Compaction (an assistant message with
|
|
89
|
+
`summary: true`) breaks the snapshot chain, so accounting is segmented:
|
|
90
|
+
the summary message closes the segment into `tokensCommitted` (the
|
|
91
|
+
summary turn read the whole context, so its snapshot prices the
|
|
92
|
+
compaction itself) and the next segment starts with a zero baseline.
|
|
93
|
+
`tokensUsed = tokensCommitted + current segment`, kept monotonic so
|
|
94
|
+
unflagged context shrinks never move the budget backwards;
|
|
95
|
+
- a user abort pauses the goal instead of blocking it: the event path in
|
|
96
|
+
`processPayload` pauses immediately on the MessageAbortedError message
|
|
97
|
+
(before any tick could send a continuation over the user's explicit
|
|
98
|
+
stop), with a tick-side safety net. Messages sent while paused leave
|
|
99
|
+
the goal alone; Resume re-arms the loop, and resuming over an aborted
|
|
100
|
+
tail skips the audit and goes straight to a continuation nudge;
|
|
101
|
+
- terminal checks, cheapest first: assistant turn error → `blocked`;
|
|
102
|
+
`tokensUsed >= tokenBudget` → `budgetLimited`;
|
|
103
|
+
`turnsUsed >= MAX_AUTO_TURNS` (20) → `blocked`;
|
|
104
|
+
- if the latest message is a compaction summary, skip the audit and
|
|
105
|
+
continue unconditionally — running into the context window mid-work is
|
|
106
|
+
by definition "in progress, not finished" (the summary is a retelling,
|
|
107
|
+
not evidence, and must not be judged);
|
|
108
|
+
- otherwise, small-model audit of the objective + the last assistant turn
|
|
109
|
+
only — no conversation history and no continuation prompts
|
|
110
|
+
(`restrictToPreferredProvider`, session's own provider/model preferred):
|
|
111
|
+
JSON `{verdict: continue|complete|blocked, note}`. The audit is the SOLE
|
|
112
|
+
termination authority besides the hard stops above — the working agent
|
|
113
|
+
has no channel to settle its own goal. `complete` settles; `blocked`
|
|
114
|
+
increments `blockedStreak` and settles only after 3 consecutive blocked
|
|
115
|
+
verdicts, so a one-off snag cannot end the goal. Audit failure/absence
|
|
116
|
+
tolerates ONE consecutive unaudited continuation (`auditFailStreak`); a
|
|
117
|
+
second consecutive failure settles the goal as `blocked` ("progress
|
|
118
|
+
audit unavailable") — resumable, and settling resets the streak so
|
|
119
|
+
Resume gets fresh tolerance. A dead small model can never drive the
|
|
120
|
+
loop blind to the turn cap;
|
|
121
|
+
- continue: persist accounting + `turnsUsed` first (a crash after the
|
|
122
|
+
write just waits for the next idle tick; the reverse could double-send),
|
|
123
|
+
re-check the tail, then `POST /session/:id/prompt_async` with the
|
|
124
|
+
continuation prompt using the last assistant message's
|
|
125
|
+
provider/model/agent — the goal spends the session's own subscription.
|
|
126
|
+
4. Settling (`complete`/`blocked`/`budgetLimited`) fires the injected
|
|
127
|
+
`emitGoalNotification` so the user hears about it even with the UI closed:
|
|
128
|
+
desktop + UI broadcast + the standard push fanout (web-push with full
|
|
129
|
+
text; APNs with a generic per-type title and the session name as body).
|
|
130
|
+
It obeys the notify-on-completion setting. Conversely, while a goal is
|
|
131
|
+
ACTIVE the notifications runtime suppresses per-turn "ready"
|
|
132
|
+
notifications on every channel — they would only echo the loop's own
|
|
133
|
+
continuations; error/question/permission notifications are untouched.
|
|
134
|
+
Pausing a goal from the UI also aborts the running turn (and vice versa —
|
|
135
|
+
an abort pauses the goal), so "stop" means stop on both axes.
|
|
136
|
+
|
|
137
|
+
## Continuation prompt
|
|
138
|
+
|
|
139
|
+
Built inline in `runtime.js`: the objective as untrusted user data in an
|
|
140
|
+
XML-escaped `<objective>` block, budget numbers, keep-the-full-objective and
|
|
141
|
+
work-from-evidence rules, a completion-audit instruction, and the requirement
|
|
142
|
+
to end every turn with a factual done/verified/remaining report — the audit
|
|
143
|
+
sees only that final turn, so the report is its evidence.
|
|
144
|
+
|
|
145
|
+
## UI consumers (packages/ui)
|
|
146
|
+
|
|
147
|
+
- `lib/sessionGoalMetadata.ts` — payload parsing/types.
|
|
148
|
+
- `lib/sessionGoalActions.ts` — create/edit/pause/resume/clear via
|
|
149
|
+
`patchSessionMetadata`; `lib/sessionGoalPresentation.ts` — status
|
|
150
|
+
colors/labels shared across surfaces.
|
|
151
|
+
- `stores/useSessionGoalArmStore.ts` — the "next prompt starts a goal" flag,
|
|
152
|
+
consumed by `sendMessage` in `sync/session-ui-store.ts` (works for drafts).
|
|
153
|
+
- `hooks/useSessionGoal.ts` — live goal state.
|
|
154
|
+
- `components/chat/SessionGoalButton.tsx` — composer target button
|
|
155
|
+
(arm / status color / cancel confirm); `SessionGoalRow.tsx` — goal strip
|
|
156
|
+
above the composer; `SessionGoalDialog.tsx` — manage dialog
|
|
157
|
+
(edit/pause/resume/complete/clear).
|
|
158
|
+
- Sidebar glyph next to the date in `SessionNodeItem`.
|
|
159
|
+
|
|
160
|
+
## Scheduled goals
|
|
161
|
+
|
|
162
|
+
Scheduled tasks can run as goals: `execution.goalEnabled` (+ optional
|
|
163
|
+
`execution.goalTokenBudget`) on a task makes the scheduled-tasks runtime
|
|
164
|
+
stamp `metadata.openchamber.goal` onto the fresh session (objective = the
|
|
165
|
+
expanded task prompt) and attach the goal-mode intro part to the prompt.
|
|
166
|
+
The loop here picks it up from session events like any other goal.
|
|
167
|
+
|
|
168
|
+
## Limitations
|
|
169
|
+
|
|
170
|
+
- Web-server feature: VS Code (extension-only) renders goal state via
|
|
171
|
+
`session.updated` but does not run the loop.
|
|
172
|
+
- A goal on a session with no assistant reply yet starts after the first
|
|
173
|
+
user exchange completes (no provider/model to continue with before that).
|
|
174
|
+
- `tokensUsed` only counts completed assistant messages seen within the
|
|
175
|
+
40-message fetch window per tick; extremely long busy stretches between
|
|
176
|
+
idles undercount (acceptable: budget is a guardrail, not billing).
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// File-backed goal objectives. Session metadata must stay light (it rides
|
|
2
|
+
// every session.updated event), so the objective TEXT lives in a file under
|
|
3
|
+
// the OpenChamber data dir, keyed by the SESSION ID: sessions are globally
|
|
4
|
+
// unique and carry at most one goal at a time, so the mapping is fully
|
|
5
|
+
// deterministic — the metadata only carries an `objectiveFile: true` flag,
|
|
6
|
+
// never a path, and user-writable metadata cannot become a file-read vector.
|
|
7
|
+
|
|
8
|
+
import fs from 'fs';
|
|
9
|
+
import os from 'os';
|
|
10
|
+
import path from 'path';
|
|
11
|
+
|
|
12
|
+
export const GOAL_OBJECTIVE_CHAR_LIMIT = 5_000;
|
|
13
|
+
|
|
14
|
+
// OpenCode session ids are URL-safe tokens; anything else is rejected before
|
|
15
|
+
// touching the filesystem.
|
|
16
|
+
const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{4,128}$/;
|
|
17
|
+
|
|
18
|
+
const goalsDir = () => path.join(
|
|
19
|
+
process.env.OPENCHAMBER_DATA_DIR
|
|
20
|
+
? path.resolve(process.env.OPENCHAMBER_DATA_DIR)
|
|
21
|
+
: path.join(os.homedir(), '.config', 'openchamber'),
|
|
22
|
+
'goals',
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
const objectiveFilePath = (sessionId) => path.join(goalsDir(), `${sessionId}.md`);
|
|
26
|
+
|
|
27
|
+
export const isValidObjectiveKey = (sessionId) =>
|
|
28
|
+
typeof sessionId === 'string' && SESSION_ID_PATTERN.test(sessionId);
|
|
29
|
+
|
|
30
|
+
const clampContent = (content) => String(content ?? '').trim().slice(0, GOAL_OBJECTIVE_CHAR_LIMIT);
|
|
31
|
+
|
|
32
|
+
/** Write (or overwrite — a new goal replaces the old one) the session's objective. */
|
|
33
|
+
export const writeObjective = async (sessionId, content) => {
|
|
34
|
+
if (!isValidObjectiveKey(sessionId)) {
|
|
35
|
+
throw Object.assign(new Error('invalid session id'), { statusCode: 400 });
|
|
36
|
+
}
|
|
37
|
+
const text = clampContent(content);
|
|
38
|
+
if (!text) {
|
|
39
|
+
throw Object.assign(new Error('objective content is required'), { statusCode: 400 });
|
|
40
|
+
}
|
|
41
|
+
await fs.promises.mkdir(goalsDir(), { recursive: true });
|
|
42
|
+
await fs.promises.writeFile(objectiveFilePath(sessionId), text, 'utf8');
|
|
43
|
+
return { content: text };
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Returns the objective text, or null when missing/invalid. */
|
|
47
|
+
export const readObjective = async (sessionId) => {
|
|
48
|
+
if (!isValidObjectiveKey(sessionId)) return null;
|
|
49
|
+
try {
|
|
50
|
+
const raw = await fs.promises.readFile(objectiveFilePath(sessionId), 'utf8');
|
|
51
|
+
return clampContent(raw);
|
|
52
|
+
} catch {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** Best-effort delete; missing files are fine. */
|
|
58
|
+
export const deleteObjective = async (sessionId) => {
|
|
59
|
+
if (!isValidObjectiveKey(sessionId)) return;
|
|
60
|
+
await fs.promises.unlink(objectiveFilePath(sessionId)).catch(() => undefined);
|
|
61
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { deleteObjective, readObjective, writeObjective } from './objectives.js';
|
|
2
|
+
|
|
3
|
+
// OpenChamber-owned routes for file-backed goal objectives, keyed by session
|
|
4
|
+
// id (one goal per session; a new goal overwrites the old file). The UI
|
|
5
|
+
// writes the objective file before stamping the goal metadata (which only
|
|
6
|
+
// carries an `objectiveFile: true` flag), reads it back for display, and
|
|
7
|
+
// deletes it when the goal is removed.
|
|
8
|
+
export function registerSessionGoalRoutes(app) {
|
|
9
|
+
app.put('/api/goals/objective/:sessionId', async (req, res) => {
|
|
10
|
+
try {
|
|
11
|
+
const { content } = req.body || {};
|
|
12
|
+
await writeObjective(req.params.sessionId, content);
|
|
13
|
+
res.json({ ok: true });
|
|
14
|
+
} catch (error) {
|
|
15
|
+
const statusCode = Number(error?.statusCode) || 500;
|
|
16
|
+
if (statusCode >= 500) {
|
|
17
|
+
console.error('Failed to write goal objective:', error);
|
|
18
|
+
}
|
|
19
|
+
res.status(statusCode).json({ error: error?.message || 'Failed to write goal objective' });
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
app.get('/api/goals/objective/:sessionId', async (req, res) => {
|
|
24
|
+
const content = await readObjective(req.params.sessionId);
|
|
25
|
+
if (content === null) {
|
|
26
|
+
res.status(404).json({ error: 'objective not found' });
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
res.json({ content });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
app.delete('/api/goals/objective/:sessionId', async (req, res) => {
|
|
33
|
+
await deleteObjective(req.params.sessionId);
|
|
34
|
+
res.json({ ok: true });
|
|
35
|
+
});
|
|
36
|
+
}
|