artos 1.0.0__py3-none-any.whl
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.
- artos/__init__.py +6 -0
- artos/__main__.py +4 -0
- artos/audio.py +201 -0
- artos/cli.py +128 -0
- artos/commands/__init__.py +1 -0
- artos/commands/ai.py +231 -0
- artos/commands/atlas.py +366 -0
- artos/commands/common.py +160 -0
- artos/commands/core.py +550 -0
- artos/commands/craft.py +495 -0
- artos/commands/effects.py +80 -0
- artos/commands/files.py +508 -0
- artos/commands/forge.py +170 -0
- artos/commands/mind.py +303 -0
- artos/commands/notes.py +195 -0
- artos/commands/provenance.py +66 -0
- artos/commands/runtime.py +290 -0
- artos/commands/science.py +154 -0
- artos/commands/social.py +258 -0
- artos/commands/source.py +188 -0
- artos/commands/synth.py +252 -0
- artos/commands/transfer.py +128 -0
- artos/commands/views.py +468 -0
- artos/commands/workspace.py +238 -0
- artos/completion.py +272 -0
- artos/constants.py +454 -0
- artos/deepseek.py +216 -0
- artos/effects.py +100 -0
- artos/exports.py +443 -0
- artos/generator.py +1646 -0
- artos/graphics.py +1101 -0
- artos/intelligence.py +1183 -0
- artos/parser.py +165 -0
- artos/poetics.py +1900 -0
- artos/py.typed +0 -0
- artos/registry.py +170 -0
- artos/runtime.py +476 -0
- artos/session.py +581 -0
- artos/shell.py +351 -0
- artos/storage.py +211 -0
- artos/theme.py +345 -0
- artos/tui.py +257 -0
- artos/universe.py +901 -0
- artos/util.py +536 -0
- artos/webfetch.py +97 -0
- artos/webimages.py +333 -0
- artos/webtext.py +201 -0
- artos/workspace.py +373 -0
- artos-1.0.0.dist-info/METADATA +608 -0
- artos-1.0.0.dist-info/RECORD +54 -0
- artos-1.0.0.dist-info/WHEEL +5 -0
- artos-1.0.0.dist-info/entry_points.txt +3 -0
- artos-1.0.0.dist-info/licenses/LICENSE +21 -0
- artos-1.0.0.dist-info/top_level.txt +1 -0
artos/__init__.py
ADDED
artos/__main__.py
ADDED
artos/audio.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""Procedural audio: WAV ambience and Standard MIDI Files.
|
|
2
|
+
|
|
3
|
+
Pure standard library. The music is generated from a seed, a scale and a small
|
|
4
|
+
set of rule-based transformations. Nothing is sampled; every waveform is
|
|
5
|
+
synthesised locally.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import io
|
|
11
|
+
import math
|
|
12
|
+
import random
|
|
13
|
+
import struct
|
|
14
|
+
import wave
|
|
15
|
+
|
|
16
|
+
from .util import clamp, seed_int
|
|
17
|
+
|
|
18
|
+
SCALES = {
|
|
19
|
+
"dorian": (0, 2, 3, 5, 7, 9, 10),
|
|
20
|
+
"aeolian": (0, 2, 3, 5, 7, 8, 10),
|
|
21
|
+
"lydian": (0, 2, 4, 6, 7, 9, 11),
|
|
22
|
+
"pentatonic": (0, 2, 4, 7, 9),
|
|
23
|
+
"whole": (0, 2, 4, 6, 8, 10),
|
|
24
|
+
"octatonic": (0, 1, 3, 4, 6, 7, 9, 10),
|
|
25
|
+
"mixolydian": (0, 2, 4, 5, 7, 9, 10),
|
|
26
|
+
"harmonic": (0, 2, 3, 5, 7, 8, 11),
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
ROOTS = {
|
|
30
|
+
"C": 60, "C#": 61, "D": 62, "D#": 63, "E": 64, "F": 65,
|
|
31
|
+
"F#": 66, "G": 67, "G#": 68, "A": 69, "A#": 70, "B": 71,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _midi_to_hz(note: int) -> float:
|
|
36
|
+
return 440.0 * (2 ** ((note - 69) / 12))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def make_wav(seed: int, *, seconds: float = 12.0, sample_rate: int = 22050,
|
|
40
|
+
scale: str | None = None, root: str | None = None) -> bytes:
|
|
41
|
+
rng = random.Random(seed ^ 0xA0D10)
|
|
42
|
+
scale_name = scale if scale in SCALES else rng.choice(list(SCALES))
|
|
43
|
+
root_name = root if root in ROOTS else rng.choice(list(ROOTS))
|
|
44
|
+
intervals = SCALES[scale_name]
|
|
45
|
+
root_note = ROOTS[root_name]
|
|
46
|
+
seconds = clamp(seconds, 2.0, 60.0)
|
|
47
|
+
total = int(sample_rate * seconds)
|
|
48
|
+
# A slow chord bed and a sparse melody. Everything is enveloped to avoid clicks.
|
|
49
|
+
chord_roots = [rng.choice(intervals) for _ in range(4)]
|
|
50
|
+
chord_len = max(1, total // 4)
|
|
51
|
+
melody = []
|
|
52
|
+
t = 0
|
|
53
|
+
while t < seconds:
|
|
54
|
+
step = rng.choice(intervals)
|
|
55
|
+
octave = rng.choice([0, 12, 12, 24])
|
|
56
|
+
length = rng.uniform(0.18, 0.7)
|
|
57
|
+
melody.append((t, length, root_note + step + octave, rng.uniform(0.08, 0.22)))
|
|
58
|
+
t += length + rng.uniform(0.05, 0.35)
|
|
59
|
+
|
|
60
|
+
buffer = [0.0] * total
|
|
61
|
+
two_pi = math.tau
|
|
62
|
+
for i in range(total):
|
|
63
|
+
time = i / sample_rate
|
|
64
|
+
chord = chord_roots[min(3, int(time / seconds * 4))]
|
|
65
|
+
chord_freqs = [
|
|
66
|
+
_midi_to_hz(root_note + chord + shift) for shift in (0, 7, 12, 16)
|
|
67
|
+
]
|
|
68
|
+
pad = 0.0
|
|
69
|
+
for j, freq in enumerate(chord_freqs):
|
|
70
|
+
pad += math.sin(two_pi * freq * time + j * 0.7) * (0.045 / (j + 1))
|
|
71
|
+
pad += math.sin(two_pi * freq * 0.5 * time) * (0.012 / (j + 1))
|
|
72
|
+
# slow amplitude breathing
|
|
73
|
+
breath = 0.65 + 0.35 * math.sin(two_pi * 0.055 * time + 0.4)
|
|
74
|
+
buffer[i] += pad * breath
|
|
75
|
+
# noise texture, very quiet
|
|
76
|
+
buffer[i] += (rng.random() * 2 - 1) * 0.004
|
|
77
|
+
for start, length, note, gain in melody:
|
|
78
|
+
begin = int(start * sample_rate)
|
|
79
|
+
span = int(length * sample_rate)
|
|
80
|
+
if begin >= total:
|
|
81
|
+
continue
|
|
82
|
+
freq = _midi_to_hz(note)
|
|
83
|
+
for k in range(min(span, total - begin)):
|
|
84
|
+
env = math.sin(math.pi * k / max(1, span)) ** 1.6
|
|
85
|
+
tt = k / sample_rate
|
|
86
|
+
# a soft triangle-ish tone plus a fifth
|
|
87
|
+
tone = math.sin(two_pi * freq * tt) * 0.7 + math.sin(two_pi * freq * 1.5 * tt) * 0.18
|
|
88
|
+
buffer[begin + k] += tone * gain * env
|
|
89
|
+
# gentle limiter and fade in/out
|
|
90
|
+
peak = max(0.0001, max(abs(v) for v in buffer))
|
|
91
|
+
scale_factor = min(0.92 / peak, 8.0)
|
|
92
|
+
fade = int(sample_rate * 1.2)
|
|
93
|
+
raw = bytearray()
|
|
94
|
+
for i, value in enumerate(buffer):
|
|
95
|
+
value = value * scale_factor
|
|
96
|
+
if i < fade:
|
|
97
|
+
value *= i / fade
|
|
98
|
+
if i > total - fade:
|
|
99
|
+
value *= max(0.0, (total - i) / fade)
|
|
100
|
+
sample = int(clamp(value, -1.0, 1.0) * 32767)
|
|
101
|
+
raw.extend(struct.pack("<h", sample))
|
|
102
|
+
out = io.BytesIO()
|
|
103
|
+
with wave.open(out, "wb") as wav:
|
|
104
|
+
wav.setnchannels(1)
|
|
105
|
+
wav.setsampwidth(2)
|
|
106
|
+
wav.setframerate(sample_rate)
|
|
107
|
+
wav.writeframes(bytes(raw))
|
|
108
|
+
return out.getvalue()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _vlq(value: int) -> bytes:
|
|
112
|
+
value = max(0, int(value))
|
|
113
|
+
out = [value & 0x7F]
|
|
114
|
+
value >>= 7
|
|
115
|
+
while value:
|
|
116
|
+
out.append((value & 0x7F) | 0x80)
|
|
117
|
+
value >>= 7
|
|
118
|
+
return bytes(reversed(out))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _track(events: list[tuple[int, bytes]]) -> bytes:
|
|
122
|
+
events = sorted(events, key=lambda pair: pair[0])
|
|
123
|
+
data = bytearray()
|
|
124
|
+
last = 0
|
|
125
|
+
for tick, payload in events:
|
|
126
|
+
data.extend(_vlq(tick - last))
|
|
127
|
+
data.extend(payload)
|
|
128
|
+
last = tick
|
|
129
|
+
data.extend(_vlq(0))
|
|
130
|
+
data.extend(b"\xff\x2f\x00")
|
|
131
|
+
return b"MTrk" + struct.pack(">I", len(data)) + bytes(data)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def make_midi(seed: int, *, bars: int = 24, tempo: int = 72,
|
|
135
|
+
scale: str | None = None, root: str | None = None) -> bytes:
|
|
136
|
+
rng = random.Random(seed ^ 0x3D1)
|
|
137
|
+
scale_name = scale if scale in SCALES else rng.choice(list(SCALES))
|
|
138
|
+
root_name = root if root in ROOTS else rng.choice(list(ROOTS))
|
|
139
|
+
intervals = SCALES[scale_name]
|
|
140
|
+
root_note = ROOTS[root_name]
|
|
141
|
+
ppq = 480
|
|
142
|
+
beat = ppq
|
|
143
|
+
bar_ticks = beat * 4
|
|
144
|
+
events: list[tuple[int, bytes]] = []
|
|
145
|
+
# tempo and time signature
|
|
146
|
+
events.append((0, b"\xff\x51\x03" + int(60_000_000 / max(30, tempo)).to_bytes(3, "big")))
|
|
147
|
+
events.append((0, b"\xff\x58\x04\x04\x02\x18\x08"))
|
|
148
|
+
# track name
|
|
149
|
+
name = f"ARTOS {scale_name} in {root_name}".encode("ascii", "replace")[:48]
|
|
150
|
+
events.append((0, b"\xff\x03" + _vlq(len(name)) + name))
|
|
151
|
+
# channel 0: pad chords
|
|
152
|
+
events.append((0, b"\xc0\x58")) # cello-ish
|
|
153
|
+
# channel 1: melody
|
|
154
|
+
events.append((0, b"\xc1\x00")) # piano
|
|
155
|
+
for bar in range(bars):
|
|
156
|
+
base = bar * bar_ticks
|
|
157
|
+
degree = rng.choice(intervals)
|
|
158
|
+
chord = [root_note - 12 + degree, root_note - 5 + degree, root_note + degree]
|
|
159
|
+
for idx, note in enumerate(chord):
|
|
160
|
+
pitch = max(0, min(127, note))
|
|
161
|
+
events.append((base, bytes([0x90, pitch, 42 + idx * 8])))
|
|
162
|
+
events.append((base + bar_ticks - 20, bytes([0x80, pitch, 0])))
|
|
163
|
+
# melody: 3-5 notes per bar
|
|
164
|
+
pos = 0
|
|
165
|
+
for _ in range(rng.randint(2, 5)):
|
|
166
|
+
length = rng.choice([beat // 2, beat, beat * 2, beat // 4])
|
|
167
|
+
if pos >= bar_ticks:
|
|
168
|
+
break
|
|
169
|
+
step = rng.choice(intervals)
|
|
170
|
+
octave = rng.choice([0, 0, 12, 12, 24])
|
|
171
|
+
pitch = max(0, min(127, root_note + step + octave))
|
|
172
|
+
velocity = rng.randint(48, 108)
|
|
173
|
+
events.append((base + pos, bytes([0x91, pitch, velocity])))
|
|
174
|
+
events.append((base + min(bar_ticks - 4, pos + length), bytes([0x81, pitch, 0])))
|
|
175
|
+
pos += length + rng.choice([0, 0, beat // 4])
|
|
176
|
+
track = _track(events)
|
|
177
|
+
header = b"MThd" + struct.pack(">IHHH", 6, 0, 1, ppq)
|
|
178
|
+
return header + track
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def score_lines(seed: int, *, bars: int = 12, scale: str | None = None, root: str | None = None) -> list[str]:
|
|
182
|
+
"""A human-readable sketch of the same material used by make_midi."""
|
|
183
|
+
rng = random.Random(seed ^ 0x5C0)
|
|
184
|
+
scale_name = scale if scale in SCALES else rng.choice(list(SCALES))
|
|
185
|
+
root_name = root if root in ROOTS else rng.choice(list(ROOTS))
|
|
186
|
+
intervals = SCALES[scale_name]
|
|
187
|
+
lines = [
|
|
188
|
+
f"# score · {root_name} {scale_name}",
|
|
189
|
+
f"# tempo {rng.choice([52, 60, 72, 84, 96])} bpm · {bars} bars · generated",
|
|
190
|
+
"",
|
|
191
|
+
]
|
|
192
|
+
letters = "CDEFGAB"
|
|
193
|
+
for bar in range(1, bars + 1):
|
|
194
|
+
notes = []
|
|
195
|
+
for _ in range(rng.randint(2, 5)):
|
|
196
|
+
step = rng.choice(intervals)
|
|
197
|
+
octave = rng.choice([3, 4, 4, 5])
|
|
198
|
+
notes.append(f"{letters[step % 7]}{octave}")
|
|
199
|
+
lines.append(f"{bar:>2} | " + " ".join(notes))
|
|
200
|
+
lines += ["", "Play the rests as seriously as the notes."]
|
|
201
|
+
return lines
|
artos/cli.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Console entry point for ``artos`` / ``at``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from .constants import APP_NAME, BUILD, CODENAME, VERSION
|
|
10
|
+
from .registry import load_builtin_commands
|
|
11
|
+
from .session import Session
|
|
12
|
+
from .shell import Shell, ShellExit
|
|
13
|
+
from .storage import Store
|
|
14
|
+
from .theme import default_theme
|
|
15
|
+
from . import tui
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
19
|
+
parser = argparse.ArgumentParser(
|
|
20
|
+
prog="artos",
|
|
21
|
+
description=f"{APP_NAME} {VERSION} · a sandboxed personal operating system, root of all art",
|
|
22
|
+
epilog=(
|
|
23
|
+
"Examples:\n"
|
|
24
|
+
" artos interactive atelier shell\n"
|
|
25
|
+
" artos world list the generated regions\n"
|
|
26
|
+
" artos collect all --fast survey every region\n"
|
|
27
|
+
" artos enter quiet-press inhabit a studio\n"
|
|
28
|
+
" artos gen all --count 4 generate unique works\n"
|
|
29
|
+
" artos muse \"a city of margins\" expand a creative brief\n"
|
|
30
|
+
" artos source \"night city\" fetch public-domain images (opt-in)\n"
|
|
31
|
+
" artos --script /scripts/tour.art\n"
|
|
32
|
+
"\nThe culture is synthetic. No sockets are opened unless you run\n"
|
|
33
|
+
"`source`, `library`, `fetch` or enable DeepSeek explicitly."
|
|
34
|
+
),
|
|
35
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
36
|
+
)
|
|
37
|
+
parser.add_argument("--home", help="data directory (default: $ARTOS_HOME or ~/.local/share/artos)")
|
|
38
|
+
parser.add_argument("--seed", type=int, help="atlas seed for this run")
|
|
39
|
+
parser.add_argument("--theme", help="riso, ultramarine, vermilion, celadon, nocturne, paper, neon, solar, ash, orchid, mono")
|
|
40
|
+
parser.add_argument("--ascii", action="store_true", help="ASCII glyphs only")
|
|
41
|
+
parser.add_argument("--no-color", action="store_true", help="disable ANSI colour")
|
|
42
|
+
parser.add_argument("--no-boot", action="store_true", help="skip the boot banner")
|
|
43
|
+
parser.add_argument("--no-live", action="store_true", help="disable streaming survey output")
|
|
44
|
+
parser.add_argument("--script", help="execute an ARTOS script from the workspace")
|
|
45
|
+
parser.add_argument("--stop-on-error", action="store_true", help="stop scripts at the first error")
|
|
46
|
+
parser.add_argument("--version", action="version", version=f"{APP_NAME} {VERSION} ({CODENAME}, build {BUILD})")
|
|
47
|
+
parser.add_argument("command", nargs=argparse.REMAINDER, help="command to run (omit for interactive)")
|
|
48
|
+
return parser
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def resolve_theme(args: argparse.Namespace, session: Session):
|
|
52
|
+
settings = session.settings
|
|
53
|
+
name = args.theme or os.environ.get("ARTOS_THEME") or settings.get("theme")
|
|
54
|
+
ascii_mode = bool(args.ascii or settings.get("ascii", False))
|
|
55
|
+
color: bool | None
|
|
56
|
+
if args.no_color or os.environ.get("NO_COLOR") or os.environ.get("TERM") == "dumb":
|
|
57
|
+
color = False
|
|
58
|
+
elif os.environ.get("ARTOS_FORCE_COLOR") == "1":
|
|
59
|
+
color = True
|
|
60
|
+
elif settings.get("color") is False:
|
|
61
|
+
color = False
|
|
62
|
+
else:
|
|
63
|
+
color = None
|
|
64
|
+
return default_theme(name, color=color, ascii_mode=ascii_mode)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def main(argv: list[str] | None = None) -> int:
|
|
68
|
+
parser = build_parser()
|
|
69
|
+
args = parser.parse_args(argv)
|
|
70
|
+
load_builtin_commands()
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
store = Store(args.home)
|
|
74
|
+
except OSError as exc:
|
|
75
|
+
print(f"{APP_NAME}: cannot create data directory: {exc}", file=sys.stderr)
|
|
76
|
+
return 2
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
session = Session(store, seed=args.seed)
|
|
80
|
+
except Exception as exc:
|
|
81
|
+
print(f"{APP_NAME}: session initialisation failed: {exc}", file=sys.stderr)
|
|
82
|
+
if os.environ.get("ARTOS_DEBUG"):
|
|
83
|
+
raise
|
|
84
|
+
return 2
|
|
85
|
+
|
|
86
|
+
theme = resolve_theme(args, session)
|
|
87
|
+
interactive = sys.stdin.isatty() and sys.stdout.isatty() and not args.script and not args.command
|
|
88
|
+
live = bool(interactive and not args.no_live and session.settings.get("live", True))
|
|
89
|
+
shell = Shell(store, session=session, theme=theme, interactive=interactive, live=live)
|
|
90
|
+
|
|
91
|
+
if args.script:
|
|
92
|
+
try:
|
|
93
|
+
output = shell.run_script(args.script, stop=args.stop_on_error)
|
|
94
|
+
except Exception as exc:
|
|
95
|
+
print(f"{APP_NAME}: {exc}", file=sys.stderr)
|
|
96
|
+
return 1
|
|
97
|
+
if output:
|
|
98
|
+
print(output)
|
|
99
|
+
return 0
|
|
100
|
+
|
|
101
|
+
command = list(args.command)
|
|
102
|
+
if command and command[0] in {"run", "exec", "--"}:
|
|
103
|
+
command = command[1:]
|
|
104
|
+
if command and command[0] in {"shell", "tui", "repl"} and len(command) == 1:
|
|
105
|
+
return tui.interactive(shell, show_boot=not args.no_boot)
|
|
106
|
+
if command:
|
|
107
|
+
line = " ".join(command)
|
|
108
|
+
try:
|
|
109
|
+
output = shell.execute_line(line)
|
|
110
|
+
except ShellExit:
|
|
111
|
+
return 0
|
|
112
|
+
except KeyboardInterrupt:
|
|
113
|
+
return 130
|
|
114
|
+
if output:
|
|
115
|
+
print(output)
|
|
116
|
+
return 0
|
|
117
|
+
|
|
118
|
+
if interactive:
|
|
119
|
+
return tui.interactive(shell, show_boot=not args.no_boot)
|
|
120
|
+
|
|
121
|
+
print(tui.boot_text(shell))
|
|
122
|
+
print()
|
|
123
|
+
print(shell.execute_line("help"))
|
|
124
|
+
return 0
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
if __name__ == "__main__":
|
|
128
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Command modules. Importing this package has no side effects; see registry."""
|
artos/commands/ai.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"""DeepSeek status, key, metering and pricing commands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
|
|
8
|
+
from ..deepseek import DeepSeekError
|
|
9
|
+
from ..registry import CommandError, command
|
|
10
|
+
from ..util import json_pretty, mask
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@command(
|
|
14
|
+
"ai", "forge", "DeepSeek status, key, mode, usage, pricing and test.",
|
|
15
|
+
usage="ai [status|key KEY|mode offline|auto|online|test|model NAME|temp N|usage|budget USD|pricing|reset-usage] [--clear] [--json] [--reset]",
|
|
16
|
+
aliases=("deepseek",),
|
|
17
|
+
)
|
|
18
|
+
def cmd_ai(ctx) -> str:
|
|
19
|
+
p = ctx.parse(flags={"clear", "json", "reset"})
|
|
20
|
+
t = ctx.theme
|
|
21
|
+
s = ctx.session
|
|
22
|
+
sub = p.pos[0].lower() if p.pos else "status"
|
|
23
|
+
usage = s.ai_usage
|
|
24
|
+
budget = s.ai_budget()
|
|
25
|
+
left = s.ai_budget_left()
|
|
26
|
+
|
|
27
|
+
if sub in {"status", "info"}:
|
|
28
|
+
key = s.deepseek_key()
|
|
29
|
+
env_key = bool(os.environ.get("DEEPSEEK_API_KEY"))
|
|
30
|
+
info = {
|
|
31
|
+
"mode": s.ai_mode,
|
|
32
|
+
"configured": bool(key),
|
|
33
|
+
"key_source": "environment" if env_key else ("secret.json" if key else "none"),
|
|
34
|
+
"key_preview": mask(key, 4) if key else "",
|
|
35
|
+
"model": s.settings.get("ai_model"),
|
|
36
|
+
"temperature": s.settings.get("ai_temperature"),
|
|
37
|
+
"endpoint": "https://api.deepseek.com/chat/completions",
|
|
38
|
+
"calls": int(usage.get("calls", 0)),
|
|
39
|
+
"prompt_tokens": int(usage.get("prompt_tokens", 0)),
|
|
40
|
+
"completion_tokens": int(usage.get("completion_tokens", 0)),
|
|
41
|
+
"total_tokens": int(usage.get("total_tokens", 0)),
|
|
42
|
+
"cost_usd": round(float(usage.get("cost_usd", 0.0)), 6),
|
|
43
|
+
"budget_usd": budget,
|
|
44
|
+
"budget_left_usd": None if left is None else round(left, 6),
|
|
45
|
+
"pricing": {
|
|
46
|
+
"input_per_m": s.settings.get("ai_price_input_per_m"),
|
|
47
|
+
"cached_input_per_m": s.settings.get("ai_price_cached_per_m"),
|
|
48
|
+
"output_per_m": s.settings.get("ai_price_output_per_m"),
|
|
49
|
+
},
|
|
50
|
+
"underlying": "mind, forge, remix, effects, dream, compose",
|
|
51
|
+
}
|
|
52
|
+
if p.has("json"):
|
|
53
|
+
return json_pretty(info)
|
|
54
|
+
return t.panel("DEEPSEEK // optional second source", [
|
|
55
|
+
t.kv([
|
|
56
|
+
("mode", info["mode"]),
|
|
57
|
+
("key", ("set · " + info["key_preview"]) if info["configured"] else "not set"),
|
|
58
|
+
("source", info["key_source"]),
|
|
59
|
+
("model", str(info["model"])),
|
|
60
|
+
("temperature", str(info["temperature"])),
|
|
61
|
+
("budget", f"${budget:.4f}" if budget > 0 else "unlimited"),
|
|
62
|
+
("spent", f"${info['cost_usd']:.6f}"),
|
|
63
|
+
("tokens", f"{info['total_tokens']:,}"),
|
|
64
|
+
("calls", str(info["calls"])),
|
|
65
|
+
("remaining", f"${left:.4f}" if left is not None else "unlimited"),
|
|
66
|
+
], key_width=12),
|
|
67
|
+
"",
|
|
68
|
+
t.c("WHEN IT IS USED", "accent", bold=True),
|
|
69
|
+
t.dim("Only when a key is present and mode is auto/online, or when a command says --online."),
|
|
70
|
+
t.dim("Mind answers, capture, forge text, remixes, dream lore, compose, effects."),
|
|
71
|
+
t.dim("Images, WAV, MIDI, PDF/EPUB and all mechanical state remain local."),
|
|
72
|
+
"",
|
|
73
|
+
t.c("PRICING · APPROX USD / 1M TOKENS", "accent", bold=True),
|
|
74
|
+
f" input ${float(info['pricing']['input_per_m'] or 0):.3f} · cached ${float(info['pricing']['cached_input_per_m'] or 0):.4f} · output ${float(info['pricing']['output_per_m'] or 0):.3f}",
|
|
75
|
+
"",
|
|
76
|
+
t.c("SETUP", "accent", bold=True),
|
|
77
|
+
" ai key sk-... (auto-enables auto mode)",
|
|
78
|
+
" ai usage token and dollar counter",
|
|
79
|
+
" ai budget 1.00 cap spend; 0 = unlimited",
|
|
80
|
+
" ai pricing show rates",
|
|
81
|
+
" ai test",
|
|
82
|
+
"",
|
|
83
|
+
t.dim("The key is stored in secret.json (0600) unless DEEPSEEK_API_KEY is set."),
|
|
84
|
+
])
|
|
85
|
+
|
|
86
|
+
if sub in {"usage", "cost", "tokens"}:
|
|
87
|
+
if p.has("reset") or (len(p.pos) > 1 and p.pos[1] == "reset"):
|
|
88
|
+
s.reset_ai_usage()
|
|
89
|
+
return t.ok("DeepSeek usage reset")
|
|
90
|
+
if p.has("json"):
|
|
91
|
+
return json_pretty({"usage": usage, "budget_usd": budget, "remaining_usd": left})
|
|
92
|
+
return _usage_report(ctx)
|
|
93
|
+
|
|
94
|
+
if sub in {"reset-usage", "reset_usage"}:
|
|
95
|
+
s.reset_ai_usage()
|
|
96
|
+
return t.ok("DeepSeek usage reset")
|
|
97
|
+
|
|
98
|
+
if sub in {"key", "set"}:
|
|
99
|
+
if p.has("clear"):
|
|
100
|
+
s.set_ai_key("")
|
|
101
|
+
return t.ok("DeepSeek key cleared · mode offline")
|
|
102
|
+
if len(p.pos) < 2:
|
|
103
|
+
key = s.deepseek_key()
|
|
104
|
+
if not key:
|
|
105
|
+
return t.warn("no key set") + t.dim(" · ai key <key>")
|
|
106
|
+
return t.dim("key: ") + mask(key, 4)
|
|
107
|
+
s.set_ai_key(p.pos[1])
|
|
108
|
+
return t.ok("DeepSeek key stored · mode " + s.ai_mode + " · usage will be metered")
|
|
109
|
+
|
|
110
|
+
if sub == "mode":
|
|
111
|
+
if len(p.pos) < 2:
|
|
112
|
+
return f"ai mode = {s.ai_mode}"
|
|
113
|
+
s.set_ai_mode(p.pos[1])
|
|
114
|
+
if s.ai_mode != "offline" and not s.ai_configured():
|
|
115
|
+
return t.warn(f"mode → {s.ai_mode}") + t.dim(" · no key yet; run `ai key <key>`")
|
|
116
|
+
return t.ok(f"ai mode → {s.ai_mode}")
|
|
117
|
+
|
|
118
|
+
if sub == "model":
|
|
119
|
+
if len(p.pos) < 2:
|
|
120
|
+
return str(s.settings.get("ai_model"))
|
|
121
|
+
s.settings["ai_model"] = p.pos[1]
|
|
122
|
+
s.save()
|
|
123
|
+
return t.ok(f"model → {p.pos[1]}")
|
|
124
|
+
|
|
125
|
+
if sub in {"temp", "temperature"}:
|
|
126
|
+
if len(p.pos) < 2:
|
|
127
|
+
return str(s.settings.get("ai_temperature"))
|
|
128
|
+
try:
|
|
129
|
+
value = float(p.pos[1])
|
|
130
|
+
except ValueError:
|
|
131
|
+
raise CommandError("temperature must be a number")
|
|
132
|
+
s.settings["ai_temperature"] = max(0.0, min(2.0, value))
|
|
133
|
+
s.save()
|
|
134
|
+
return t.ok(f"temperature → {s.settings['ai_temperature']}")
|
|
135
|
+
|
|
136
|
+
if sub == "budget":
|
|
137
|
+
if len(p.pos) < 2:
|
|
138
|
+
return f"budget = ${budget:.4f} · spent ${float(usage.get('cost_usd', 0.0)):.6f}" + (f" · left ${left:.4f}" if left is not None else " · unlimited")
|
|
139
|
+
try:
|
|
140
|
+
value = max(0.0, float(p.pos[1]))
|
|
141
|
+
except ValueError:
|
|
142
|
+
raise CommandError("budget must be a dollar amount; 0 = unlimited")
|
|
143
|
+
s.settings["ai_budget_usd"] = value
|
|
144
|
+
s.save()
|
|
145
|
+
return t.ok(f"DeepSeek budget → {'unlimited' if value == 0 else f'${value:.4f}'}")
|
|
146
|
+
|
|
147
|
+
if sub in {"pricing", "price"}:
|
|
148
|
+
return t.table(
|
|
149
|
+
["meter", "USD / 1M tokens"],
|
|
150
|
+
[
|
|
151
|
+
["input (cache miss)", f"${float(s.settings.get('ai_price_input_per_m', 0.28)):.3f}"],
|
|
152
|
+
["input (cache hit)", f"${float(s.settings.get('ai_price_cached_per_m', 0.028)):.4f}"],
|
|
153
|
+
["output", f"${float(s.settings.get('ai_price_output_per_m', 0.42)):.3f}"],
|
|
154
|
+
],
|
|
155
|
+
title="APPROXIMATE DEEPSEEK PRICING",
|
|
156
|
+
) + "\n" + t.dim("Change with: settings ai_price_input_per_m 0.28 · settings ai_price_output_per_m 0.42")
|
|
157
|
+
|
|
158
|
+
if sub == "test":
|
|
159
|
+
client = s.deepseek_client()
|
|
160
|
+
if client is None:
|
|
161
|
+
raise CommandError("no DeepSeek key configured", "ai key <key>")
|
|
162
|
+
try:
|
|
163
|
+
result = client.test()
|
|
164
|
+
except DeepSeekError as exc:
|
|
165
|
+
raise CommandError(str(exc), "check your key, network and `ai mode`")
|
|
166
|
+
return "\n".join([
|
|
167
|
+
t.ok("DeepSeek reachable"),
|
|
168
|
+
t.dim(f"reply: {result.text.strip()[:120]}"),
|
|
169
|
+
t.dim(f"model: {result.model} · tokens: {result.tokens} · ${result.cost_usd:.6f}"),
|
|
170
|
+
])
|
|
171
|
+
|
|
172
|
+
if sub == "on":
|
|
173
|
+
s.set_ai_mode("auto")
|
|
174
|
+
return t.ok("ai mode → auto")
|
|
175
|
+
if sub == "off":
|
|
176
|
+
s.set_ai_mode("offline")
|
|
177
|
+
return t.ok("ai mode → offline")
|
|
178
|
+
raise CommandError(f"unknown ai subcommand: {sub}", "ai status|key|mode|test|usage|budget|pricing")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _usage_report(ctx) -> str:
|
|
182
|
+
t = ctx.theme
|
|
183
|
+
s = ctx.session
|
|
184
|
+
usage = s.ai_usage
|
|
185
|
+
by_feature = usage.get("by_feature", {}) or {}
|
|
186
|
+
by_model = usage.get("by_model", {}) or {}
|
|
187
|
+
rows = []
|
|
188
|
+
for feature, data in sorted(by_feature.items()):
|
|
189
|
+
rows.append([
|
|
190
|
+
t.c(str(feature), "info"),
|
|
191
|
+
str(data.get("calls", 0)),
|
|
192
|
+
f"{int(data.get('prompt_tokens', 0)):,}",
|
|
193
|
+
f"{int(data.get('completion_tokens', 0)):,}",
|
|
194
|
+
f"{int(data.get('total_tokens', 0)):,}",
|
|
195
|
+
f"${float(data.get('cost_usd', 0.0)):.6f}",
|
|
196
|
+
])
|
|
197
|
+
model_rows = [[t.c(str(m), "accent"), str(d.get("calls", 0)), f"{int(d.get('total_tokens', 0)):,}", f"${float(d.get('cost_usd', 0.0)):.6f}"] for m, d in sorted(by_model.items())]
|
|
198
|
+
budget = s.ai_budget()
|
|
199
|
+
left = s.ai_budget_left()
|
|
200
|
+
return "\n".join([
|
|
201
|
+
t.panel("DEEPSEEK // USAGE", [
|
|
202
|
+
t.kv([
|
|
203
|
+
("calls", str(usage.get("calls", 0))),
|
|
204
|
+
("prompt tokens", f"{int(usage.get('prompt_tokens', 0)):,}"),
|
|
205
|
+
("completion tokens", f"{int(usage.get('completion_tokens', 0)):,}"),
|
|
206
|
+
("total tokens", f"{int(usage.get('total_tokens', 0)):,}"),
|
|
207
|
+
("spent", f"${float(usage.get('cost_usd', 0.0)):.6f}"),
|
|
208
|
+
("budget", f"${budget:.4f}" if budget > 0 else "unlimited"),
|
|
209
|
+
("remaining", f"${left:.4f}" if left is not None else "unlimited"),
|
|
210
|
+
], key_width=17),
|
|
211
|
+
]),
|
|
212
|
+
"",
|
|
213
|
+
t.c("BY FEATURE", "accent", bold=True),
|
|
214
|
+
t.table(["feature", "calls", "prompt", "completion", "total", "cost"], rows) if rows else t.dim("no metered calls yet"),
|
|
215
|
+
"",
|
|
216
|
+
t.c("BY MODEL", "accent", bold=True),
|
|
217
|
+
t.table(["model", "calls", "tokens", "cost"], model_rows) if model_rows else t.dim("no model usage yet"),
|
|
218
|
+
"",
|
|
219
|
+
t.dim("Pricing is approximate USD per 1M tokens; override with `settings ai_price_*`."),
|
|
220
|
+
])
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
@command(
|
|
224
|
+
"usage", "forge", "DeepSeek token and dollar usage counter.",
|
|
225
|
+
usage="usage [--json]", aliases=("tokens", "cost"),
|
|
226
|
+
)
|
|
227
|
+
def cmd_usage(ctx) -> str:
|
|
228
|
+
p = ctx.parse(flags={"json"})
|
|
229
|
+
if p.has("json"):
|
|
230
|
+
return json_pretty({"usage": ctx.session.ai_usage, "budget_usd": ctx.session.ai_budget(), "remaining_usd": ctx.session.ai_budget_left()})
|
|
231
|
+
return _usage_report(ctx)
|