@pmndre/pine 0.0.0-stage → 0.22.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.
Files changed (151) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +226 -2
  3. package/bin/pine.js +27 -0
  4. package/docs/SKILL.md +234 -0
  5. package/docs/references/agents.md +454 -0
  6. package/docs/references/coding.md +311 -0
  7. package/docs/references/computer.md +212 -0
  8. package/docs/references/configuration.md +310 -0
  9. package/docs/references/events.md +267 -0
  10. package/docs/references/mcp.md +420 -0
  11. package/docs/references/operations.md +394 -0
  12. package/docs/references/overview.md +195 -0
  13. package/docs/references/security.md +896 -0
  14. package/docs/references/setup.md +385 -0
  15. package/docs/references/sources.md +772 -0
  16. package/docs/references/stack.md +121 -0
  17. package/docs/references/tui.md +575 -0
  18. package/examples/home/.env.example +7 -0
  19. package/examples/home/USER.md +4 -0
  20. package/examples/home/agents/main/agent.json +4 -0
  21. package/examples/home/agents/main/workspace/AGENTS.md +14 -0
  22. package/examples/home/agents/main/workspace/MEMORY.md +4 -0
  23. package/examples/home/agents/main/workspace/SOUL.md +4 -0
  24. package/examples/home/models.json +62 -0
  25. package/examples/home/pine.json +34 -0
  26. package/examples/home/skills/README.txt +7 -0
  27. package/examples/launchd/com.pine.daemon.plist +32 -0
  28. package/examples/systemd/pine.service +22 -0
  29. package/mcp/browser.d.ts +99 -0
  30. package/mcp/browser.js +496 -0
  31. package/mcp/commands.d.ts +20 -0
  32. package/mcp/commands.js +88 -0
  33. package/mcp/computer.d.ts +139 -0
  34. package/mcp/computer.js +698 -0
  35. package/mcp/computer.swift +989 -0
  36. package/mcp/lib.d.ts +23 -0
  37. package/mcp/lib.js +52 -0
  38. package/mcp/web.d.ts +6 -0
  39. package/mcp/web.js +140 -0
  40. package/package.json +32 -4
  41. package/src/access.d.ts +112 -0
  42. package/src/access.js +438 -0
  43. package/src/actions.d.ts +75 -0
  44. package/src/actions.js +167 -0
  45. package/src/admin.d.ts +167 -0
  46. package/src/admin.js +625 -0
  47. package/src/agent-admin.d.ts +24 -0
  48. package/src/agent-admin.js +55 -0
  49. package/src/agents.d.ts +540 -0
  50. package/src/agents.js +2776 -0
  51. package/src/background.d.ts +29 -0
  52. package/src/background.js +100 -0
  53. package/src/cli.d.ts +2 -0
  54. package/src/cli.js +777 -0
  55. package/src/computer.d.ts +30 -0
  56. package/src/computer.js +32 -0
  57. package/src/config.d.ts +396 -0
  58. package/src/config.js +549 -0
  59. package/src/dev/claude-model.d.ts +37 -0
  60. package/src/dev/claude-model.js +204 -0
  61. package/src/env-file.d.ts +4 -0
  62. package/src/env-file.js +40 -0
  63. package/src/goals.d.ts +133 -0
  64. package/src/goals.js +316 -0
  65. package/src/http.d.ts +46 -0
  66. package/src/http.js +509 -0
  67. package/src/limiter.d.ts +32 -0
  68. package/src/limiter.js +84 -0
  69. package/src/login.d.ts +23 -0
  70. package/src/login.js +130 -0
  71. package/src/manual.d.ts +61 -0
  72. package/src/manual.js +443 -0
  73. package/src/mcp-config.d.ts +49 -0
  74. package/src/mcp-config.js +182 -0
  75. package/src/models.d.ts +90 -0
  76. package/src/models.js +274 -0
  77. package/src/net.d.ts +50 -0
  78. package/src/net.js +150 -0
  79. package/src/pine.d.ts +32 -0
  80. package/src/pine.js +134 -0
  81. package/src/programs.d.ts +123 -0
  82. package/src/programs.js +412 -0
  83. package/src/router.d.ts +56 -0
  84. package/src/router.js +164 -0
  85. package/src/sandbox-fs.d.ts +34 -0
  86. package/src/sandbox-fs.js +186 -0
  87. package/src/sandbox-linux.d.ts +96 -0
  88. package/src/sandbox-linux.js +297 -0
  89. package/src/sandbox-setup.d.ts +70 -0
  90. package/src/sandbox-setup.js +216 -0
  91. package/src/security.d.ts +238 -0
  92. package/src/security.js +660 -0
  93. package/src/skills.d.ts +67 -0
  94. package/src/skills.js +163 -0
  95. package/src/snapshots.d.ts +68 -0
  96. package/src/snapshots.js +306 -0
  97. package/src/source-types.d.ts +61 -0
  98. package/src/source-types.js +1 -0
  99. package/src/sources/command.d.ts +4 -0
  100. package/src/sources/command.js +77 -0
  101. package/src/sources/folder.d.ts +6 -0
  102. package/src/sources/folder.js +116 -0
  103. package/src/sources/ftp.d.ts +4 -0
  104. package/src/sources/ftp.js +307 -0
  105. package/src/sources/http.d.ts +4 -0
  106. package/src/sources/http.js +201 -0
  107. package/src/sources/mqtt.d.ts +18 -0
  108. package/src/sources/mqtt.js +97 -0
  109. package/src/sources/telegram.d.ts +22 -0
  110. package/src/sources/telegram.js +283 -0
  111. package/src/sources/webhook.d.ts +4 -0
  112. package/src/sources/webhook.js +52 -0
  113. package/src/sources.d.ts +344 -0
  114. package/src/sources.js +966 -0
  115. package/src/store.d.ts +99 -0
  116. package/src/store.js +277 -0
  117. package/src/timers.d.ts +83 -0
  118. package/src/timers.js +318 -0
  119. package/src/tools.d.ts +11 -0
  120. package/src/tools.js +1297 -0
  121. package/src/tui/app.d.ts +305 -0
  122. package/src/tui/app.js +3195 -0
  123. package/src/tui/client.d.ts +236 -0
  124. package/src/tui/client.js +131 -0
  125. package/src/tui/code-pane.d.ts +68 -0
  126. package/src/tui/code-pane.js +535 -0
  127. package/src/tui/highlight.d.ts +8 -0
  128. package/src/tui/highlight.js +86 -0
  129. package/src/tui/picture.d.ts +206 -0
  130. package/src/tui/picture.js +801 -0
  131. package/src/tui/run.d.ts +8 -0
  132. package/src/tui/run.js +97 -0
  133. package/src/tui/theme.d.ts +32 -0
  134. package/src/tui/theme.js +128 -0
  135. package/src/tui/undo.d.ts +5 -0
  136. package/src/tui/undo.js +50 -0
  137. package/src/tui/voice.d.ts +49 -0
  138. package/src/tui/voice.js +155 -0
  139. package/src/tui/voice.swift +223 -0
  140. package/src/types.d.ts +139 -0
  141. package/src/types.js +1 -0
  142. package/src/undo.d.ts +224 -0
  143. package/src/undo.js +465 -0
  144. package/src/update.d.ts +35 -0
  145. package/src/update.js +130 -0
  146. package/src/util.d.ts +65 -0
  147. package/src/util.js +171 -0
  148. package/src/watching.d.ts +20 -0
  149. package/src/watching.js +68 -0
  150. package/src/workspace-view.d.ts +72 -0
  151. package/src/workspace-view.js +221 -0
@@ -0,0 +1,223 @@
1
+ // pine's ears: turns what is said into text, on this Mac.
2
+ //
3
+ // The terminal UI starts this helper when its owner wants to dictate a message (src/tui/voice.ts
4
+ // builds it with swiftc on first use). It listens to the microphone, has the system recognise
5
+ // the words on the device, and writes what it hears as lines of JSON, one a line:
6
+ //
7
+ // {"type":"ready"} listening
8
+ // {"type":"partial","text":"..."} everything heard so far; the end of it may still change
9
+ // {"type":"final","text":"..."} the whole of it; the helper ends after this line
10
+ // {"type":"model","state":"downloading"} the system fetches its speech model for the language, once
11
+ // {"type":"error","code":"...","message":"..."} it cannot; the message says what to do
12
+ //
13
+ // It listens until its input is closed, which is how the UI says "that was all".
14
+ // `--check` only says what is there; `--file <audio>` reads a recording instead of the microphone.
15
+ //
16
+ // Nothing leaves the machine: on macOS 26 and later the system's own transcriber is used, which
17
+ // works on the device; before that the older recogniser, told to work on the device or not at all.
18
+ // The helper decides nothing and keeps nothing.
19
+
20
+ import AVFoundation
21
+ import Foundation
22
+ import Speech
23
+
24
+ func out(_ o: [String: Any]) {
25
+ guard let d = try? JSONSerialization.data(withJSONObject: o), let s = String(data: d, encoding: .utf8) else { return }
26
+ print(s)
27
+ fflush(stdout)
28
+ }
29
+
30
+ func fail(_ code: String, _ message: String) -> Never {
31
+ out(["type": "error", "code": code, "message": message])
32
+ exit(1)
33
+ }
34
+
35
+ // The system asks the app a program was started from whether it may listen, and shows that
36
+ // app's reasons. A terminal has none for speech. So the helper starts itself once more as a
37
+ // program of its own, which answers for itself with the reasons it carries (its Info.plist).
38
+ @_silgen_name("responsibility_spawnattrs_setdisclaim")
39
+ func responsibility_spawnattrs_setdisclaim(_ attrs: UnsafeMutablePointer<posix_spawnattr_t?>, _ disclaim: Int32) -> Int32
40
+
41
+ if ProcessInfo.processInfo.environment["PINE_VOICE_OWN"] == nil {
42
+ var attr: posix_spawnattr_t?
43
+ posix_spawnattr_init(&attr)
44
+ posix_spawnattr_setflags(&attr, Int16(POSIX_SPAWN_SETEXEC))
45
+ _ = responsibility_spawnattrs_setdisclaim(&attr, 1)
46
+ setenv("PINE_VOICE_OWN", "1", 1)
47
+ let path = Bundle.main.executablePath ?? CommandLine.arguments[0]
48
+ var argv: [UnsafeMutablePointer<CChar>?] = CommandLine.arguments.map { strdup($0) } + [nil]
49
+ var pid: pid_t = 0
50
+ let rc = posix_spawn(&pid, path, nil, &attr, &argv, environ)
51
+ fail("start", "the helper could not start as a program of its own (\(rc))")
52
+ }
53
+
54
+ let args = CommandLine.arguments
55
+ func arg(_ name: String) -> String? {
56
+ if let i = args.firstIndex(of: name), i + 1 < args.count { return args[i + 1] }
57
+ return nil
58
+ }
59
+
60
+ let wanted = arg("--locale").map { Locale(identifier: $0) } ?? Locale(identifier: Locale.current.identifier.components(separatedBy: "@")[0])
61
+ let file = arg("--file")
62
+ let authorization = ["notDetermined", "denied", "restricted", "authorized"]
63
+
64
+ /// Resolves when the UI has closed our input: the owner is done speaking.
65
+ func inputClosed() async {
66
+ await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in
67
+ DispatchQueue.global().async {
68
+ while true {
69
+ let d = FileHandle.standardInput.availableData
70
+ if d.isEmpty { break }
71
+ }
72
+ c.resume()
73
+ }
74
+ }
75
+ }
76
+
77
+ func microphone() async {
78
+ if file != nil { return }
79
+ let ok = await withCheckedContinuation { (c: CheckedContinuation<Bool, Never>) in AVCaptureDevice.requestAccess(for: .audio) { c.resume(returning: $0) } }
80
+ if !ok { fail("microphone", "pine may not use the microphone. Allow it in System Settings > Privacy & Security > Microphone (the entry is called pine voice), then try again.") }
81
+ }
82
+
83
+ // ---- macOS 26 and later: the system's transcriber, which works on the device ------------------
84
+
85
+ @available(macOS 26.0, *)
86
+ func transcribe(_ locale: Locale) async throws {
87
+ let transcriber = SpeechTranscriber(locale: locale, preset: .progressiveTranscription)
88
+ var status = await AssetInventory.status(forModules: [transcriber])
89
+ if status == .unsupported { fail("language", "this Mac has no speech recognition for \(locale.identifier).") }
90
+ if status != .installed {
91
+ out(["type": "model", "state": "downloading", "locale": locale.identifier])
92
+ if let request = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) { try await request.downloadAndInstall() }
93
+ status = await AssetInventory.status(forModules: [transcriber])
94
+ if status != .installed { fail("model", "the system could not fetch its speech model for \(locale.identifier). It needs the network for that, once.") }
95
+ out(["type": "model", "state": "installed", "locale": locale.identifier])
96
+ }
97
+ await microphone()
98
+ let analyzer = SpeechAnalyzer(modules: [transcriber])
99
+ // What is settled, and after it what is still being heard.
100
+ let reader = Task { () -> String in
101
+ var settled = ""
102
+ for try await result in transcriber.results {
103
+ let text = String(result.text.characters)
104
+ if result.isFinal { settled += text }
105
+ out(["type": "partial", "text": (result.isFinal ? settled : settled + text).trimmingCharacters(in: .whitespacesAndNewlines)])
106
+ }
107
+ return settled.trimmingCharacters(in: .whitespacesAndNewlines)
108
+ }
109
+ if let file = file {
110
+ let audio = try AVAudioFile(forReading: URL(fileURLWithPath: file))
111
+ out(["type": "ready"])
112
+ if let end = try await analyzer.analyzeSequence(from: audio) { try await analyzer.finalizeAndFinish(through: end) } else { await analyzer.cancelAndFinishNow() }
113
+ } else {
114
+ guard let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [transcriber]) else { fail("audio", "the system named no sound format for speech recognition.") }
115
+ let engine = AVAudioEngine()
116
+ let input = engine.inputNode
117
+ let from = input.outputFormat(forBus: 0)
118
+ if from.sampleRate == 0 { fail("microphone", "this Mac has no microphone to listen with. Connect one, or choose one in System Settings > Sound > Input.") }
119
+ guard let converter = AVAudioConverter(from: from, to: format) else { fail("audio", "the microphone's sound cannot be converted for speech recognition.") }
120
+ let (stream, feed) = AsyncStream<AnalyzerInput>.makeStream()
121
+ input.installTap(onBus: 0, bufferSize: 4096, format: from) { buffer, _ in
122
+ let frames = AVAudioFrameCount(Double(buffer.frameLength) * format.sampleRate / from.sampleRate) + 64
123
+ guard let converted = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frames) else { return }
124
+ var given = false
125
+ var problem: NSError?
126
+ converter.convert(to: converted, error: &problem) { _, state in
127
+ if given { state.pointee = .noDataNow; return nil }
128
+ given = true
129
+ state.pointee = .haveData
130
+ return buffer
131
+ }
132
+ if problem == nil, converted.frameLength > 0 { feed.yield(AnalyzerInput(buffer: converted)) }
133
+ }
134
+ try await analyzer.start(inputSequence: stream)
135
+ engine.prepare()
136
+ try engine.start()
137
+ out(["type": "ready"])
138
+ await inputClosed()
139
+ engine.stop()
140
+ input.removeTap(onBus: 0)
141
+ feed.finish()
142
+ try await analyzer.finalizeAndFinishThroughEndOfInput()
143
+ }
144
+ out(["type": "final", "text": try await reader.value])
145
+ exit(0)
146
+ }
147
+
148
+ // ---- before macOS 26: the older recogniser, on the device or not at all -----------------------
149
+
150
+ func transcribeClassic(_ locale: Locale) async {
151
+ let granted = await withCheckedContinuation { (c: CheckedContinuation<SFSpeechRecognizerAuthorizationStatus, Never>) in SFSpeechRecognizer.requestAuthorization { c.resume(returning: $0) } }
152
+ if granted != .authorized { fail("permission", "pine may not use speech recognition (\(authorization[granted.rawValue])). Allow it in System Settings > Privacy & Security > Speech Recognition (the entry is called pine voice), then try again.") }
153
+ guard let recognizer = SFSpeechRecognizer(locale: locale) else { fail("language", "this Mac has no speech recognition for \(locale.identifier).") }
154
+ if !recognizer.supportsOnDeviceRecognition { fail("language", "this Mac cannot recognise \(locale.identifier) on the device. Add the language in System Settings > Keyboard > Dictation, then try again.") }
155
+ await microphone()
156
+ var last = ""
157
+ let finish: (String?) -> Never = { problem in
158
+ if let problem = problem, last.isEmpty {
159
+ // What the system says when its own switch is off.
160
+ if problem.contains("Dictation") { fail("dictation", "speech recognition is switched off on this Mac. Turn on Dictation in System Settings > Keyboard > Dictation, then try again.") }
161
+ fail("recognition", problem)
162
+ }
163
+ out(["type": "final", "text": last])
164
+ exit(0)
165
+ }
166
+ let handler: (SFSpeechRecognitionResult?, Error?) -> Void = { result, error in
167
+ if let result = result {
168
+ last = result.bestTranscription.formattedString
169
+ if result.isFinal { finish(nil) }
170
+ out(["type": "partial", "text": last])
171
+ }
172
+ if let error = error { finish(error.localizedDescription) }
173
+ }
174
+ if let file = file {
175
+ let request = SFSpeechURLRecognitionRequest(url: URL(fileURLWithPath: file))
176
+ request.requiresOnDeviceRecognition = true
177
+ request.shouldReportPartialResults = true
178
+ out(["type": "ready"])
179
+ _ = recognizer.recognitionTask(with: request, resultHandler: handler)
180
+ return
181
+ }
182
+ let request = SFSpeechAudioBufferRecognitionRequest()
183
+ request.requiresOnDeviceRecognition = true
184
+ request.shouldReportPartialResults = true
185
+ let engine = AVAudioEngine()
186
+ let input = engine.inputNode
187
+ let format = input.outputFormat(forBus: 0)
188
+ if format.sampleRate == 0 { fail("microphone", "this Mac has no microphone to listen with. Connect one, or choose one in System Settings > Sound > Input.") }
189
+ input.installTap(onBus: 0, bufferSize: 4096, format: format) { buffer, _ in request.append(buffer) }
190
+ _ = recognizer.recognitionTask(with: request, resultHandler: handler)
191
+ engine.prepare()
192
+ do { try engine.start() } catch { fail("microphone", "the microphone could not be started (\(error.localizedDescription)).") }
193
+ out(["type": "ready"])
194
+ await inputClosed()
195
+ engine.stop()
196
+ input.removeTap(onBus: 0)
197
+ request.endAudio()
198
+ // The last words come a moment after the sound has ended.
199
+ try? await Task.sleep(nanoseconds: 4_000_000_000)
200
+ finish(nil)
201
+ }
202
+
203
+ Task {
204
+ if #available(macOS 26.0, *), SpeechTranscriber.isAvailable {
205
+ let supported = await SpeechTranscriber.supportedLocale(equivalentTo: wanted)
206
+ if args.contains("--check") {
207
+ let installed = await SpeechTranscriber.installedLocales.map { $0.identifier(.bcp47) }
208
+ let all = await SpeechTranscriber.supportedLocales.map { $0.identifier(.bcp47) }.sorted()
209
+ out(["type": "status", "engine": "transcriber", "locale": supported?.identifier(.bcp47) ?? NSNull(), "wanted": wanted.identifier, "installed": installed.sorted(), "supported": all])
210
+ exit(0)
211
+ }
212
+ guard let locale = supported else { fail("language", "this Mac has no speech recognition for \(wanted.identifier). Languages it knows: \((await SpeechTranscriber.supportedLocales).map { $0.identifier(.bcp47) }.sorted().joined(separator: ", ")).") }
213
+ do { try await transcribe(locale) } catch { fail("recognition", error.localizedDescription) }
214
+ } else {
215
+ if args.contains("--check") {
216
+ let r = SFSpeechRecognizer(locale: wanted)
217
+ out(["type": "status", "engine": "classic", "locale": wanted.identifier, "permission": authorization[SFSpeechRecognizer.authorizationStatus().rawValue], "onDevice": r?.supportsOnDeviceRecognition ?? false])
218
+ exit(0)
219
+ }
220
+ await transcribeClassic(wanted)
221
+ }
222
+ }
223
+ dispatchMain()
package/src/types.d.ts ADDED
@@ -0,0 +1,139 @@
1
+ import type { CallTiming } from "./util.ts";
2
+ /** Where a handler's answer should go: an event on `topic` whose payload is `payload` plus `text`. */
3
+ export interface ReplyTarget {
4
+ topic: string;
5
+ payload?: Record<string, unknown>;
6
+ }
7
+ export interface PineEvent {
8
+ /** Row id in the event log; 0 for events published with `persist: false`. */
9
+ id: number;
10
+ ts: number;
11
+ topic: string;
12
+ /** Who published it: "source:<name>", "router", "timer", "http", or "agent:<id>". */
13
+ source: string;
14
+ payload: unknown;
15
+ /** Id of the event that led to this one. */
16
+ cause?: number;
17
+ /** How many agent or router steps separate this event from an outside trigger. */
18
+ hops: number;
19
+ reply?: ReplyTarget;
20
+ /**
21
+ * "owner": the content was written by a person the configuration names as owner (an
22
+ * allow-listed chat user, the authenticated control API, a schedule). Everything else is
23
+ * "untrusted": data that may try to give instructions.
24
+ */
25
+ trust: Trust;
26
+ }
27
+ export type Trust = "owner" | "untrusted";
28
+ export interface PublishOptions {
29
+ source?: string;
30
+ cause?: PineEvent | null;
31
+ reply?: ReplyTarget;
32
+ /** false keeps the event out of the log (telemetry, progress). Subscribers still get it. */
33
+ persist?: boolean;
34
+ /** Set when the publisher is acting for an agent or a route, so loops can be cut. */
35
+ hop?: boolean;
36
+ /** Default "untrusted". */
37
+ trust?: Trust;
38
+ }
39
+ export type TaskStatus = "pending" | "running" | "done" | "failed" | "cancelled";
40
+ export type TaskKind = "event" | "prompt" | "delegate" | "subagent" | "notify";
41
+ export interface ImageRef {
42
+ /** Absolute file path, or base64 data when `data` is set. */
43
+ path?: string;
44
+ data?: string;
45
+ mimeType: string;
46
+ }
47
+ export interface TaskMeta {
48
+ images?: ImageRef[];
49
+ /** Deliver the result to this agent session as a new message when the task ends. */
50
+ notify?: {
51
+ agent: string;
52
+ session: string;
53
+ };
54
+ /** Agents above this task in the delegation chain, outermost first. */
55
+ chain?: string[];
56
+ /** The task at the top of this task's delegation tree (its own id for a top-level task). */
57
+ root?: number;
58
+ /** Child sessions of a sub-agent get no delegation tools and an optional narrower tool list. */
59
+ leaf?: boolean;
60
+ tools?: string[];
61
+ label?: string;
62
+ /** This message was given to a task that was already working (that task's id) instead of becoming work of its own. */
63
+ steered?: number;
64
+ /** Not a message for the model: the conversation is to be shortened (its earlier part summarised). */
65
+ compact?: boolean;
66
+ /** A steered message that the work it was meant for did not read any more; it is answered as work of its own. */
67
+ requeued?: boolean;
68
+ /** Trust of whatever started this task. Children inherit the weaker of theirs and their parent's. */
69
+ trust?: Trust;
70
+ /** The session that created this task had already seen outside content. */
71
+ tainted?: string;
72
+ /** The folder the owner opened for the conversation this task was handed on from. A one-off delegated run works there too. */
73
+ folder?: string;
74
+ /** `input` is what the model server had to read anew; `cached` is what it took from its prompt cache. */
75
+ stats?: {
76
+ input: number;
77
+ output: number;
78
+ cached?: number;
79
+ turns: number;
80
+ tools: string[];
81
+ ms: number;
82
+ context?: ContextUse;
83
+ timing?: CallTiming;
84
+ };
85
+ }
86
+ /** How full a session's context window is. `percent` is missing right after a compaction. */
87
+ export interface ContextUse {
88
+ tokens?: number;
89
+ window: number;
90
+ percent?: number;
91
+ }
92
+ export interface Task {
93
+ id: number;
94
+ agent: string;
95
+ /** Session key. Ephemeral sessions use "_t<id>". */
96
+ session: string;
97
+ kind: TaskKind;
98
+ prompt: string;
99
+ status: TaskStatus;
100
+ priority: number;
101
+ created: number;
102
+ started?: number;
103
+ finished?: number;
104
+ result?: string;
105
+ error?: string;
106
+ event?: number;
107
+ hops: number;
108
+ parent?: number;
109
+ depth: number;
110
+ reply?: ReplyTarget;
111
+ meta: TaskMeta;
112
+ }
113
+ /** One step of a task as its session recorded it: what it was given, what it wrote, what it called. */
114
+ export interface TranscriptEntry {
115
+ kind: "user" | "text" | "thinking" | "tool";
116
+ text?: string;
117
+ tool?: string;
118
+ subject?: string;
119
+ /** For a tool call: missing while it runs. */
120
+ ok?: boolean;
121
+ /** Pictures the tool returned, by the id the control API serves them under (GET /media/tool/<id>). */
122
+ images?: string[];
123
+ ms?: number;
124
+ result?: string;
125
+ }
126
+ export interface TaskResult {
127
+ id: number;
128
+ agent: string;
129
+ status: TaskStatus;
130
+ text: string;
131
+ error?: string;
132
+ /** Set when the run handled outside content; the reason names the first source. */
133
+ tainted?: string;
134
+ }
135
+ /** One step of the list an agent keeps of what it is doing (its `todo` tool). */
136
+ export interface Todo {
137
+ text: string;
138
+ status: "pending" | "in_progress" | "done";
139
+ }
package/src/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/src/undo.d.ts ADDED
@@ -0,0 +1,224 @@
1
+ import type { FileChange, Snap, Snapshots } from "./snapshots.ts";
2
+ import type { PineConfig } from "./config.ts";
3
+ import type { Bus, Kv, TaskStore } from "./store.ts";
4
+ import type { Task } from "./types.ts";
5
+ import { type Logger } from "./util.ts";
6
+ /** The outside-content mark of a conversation and the owner's yes to it, as the store holds them. */
7
+ export interface Marks {
8
+ taint?: string;
9
+ keep?: boolean;
10
+ }
11
+ export interface Turn {
12
+ /** The owner's message. */
13
+ task: number;
14
+ /**
15
+ * pi's session file, by its name in the conversation's session folder (the folder is renamed
16
+ * with the conversation), and the entry the conversation stood at before the message (null: at
17
+ * its very beginning).
18
+ */
19
+ file?: string;
20
+ leaf?: string | null;
21
+ /** The folder the conversation worked in: the one opened for it, else the agent's workspace. */
22
+ root: string;
23
+ /** The work done in the turn, oldest first. None: no tool has run, so nothing was changed. */
24
+ steps: Step[];
25
+ /** Why the folder could not be recorded. */
26
+ problem?: string;
27
+ marks: Marks;
28
+ }
29
+ /** One stretch of work in a turn: the message's own run with what it started, or a task that came later. */
30
+ export interface Step {
31
+ task: number;
32
+ /** The folder before the first tool call. */
33
+ before: Snap;
34
+ /** The folder when the work ended. Missing while it runs, or when it was cut short. */
35
+ after?: Snap;
36
+ }
37
+ /** A message that was taken back, with what a redo needs. */
38
+ export interface Undone {
39
+ task: number;
40
+ rows: Task[];
41
+ turn?: Turn;
42
+ /** Where the conversation stood when the message was taken back. */
43
+ file?: string;
44
+ leaf?: string | null;
45
+ /** The folder as it was then, and the files that were set back. */
46
+ cur?: Snap;
47
+ paths?: string[];
48
+ marks: Marks;
49
+ }
50
+ /** What happened to the files of the folder. */
51
+ export interface Restored {
52
+ root: string;
53
+ /** Changed files that have their earlier content again, files that are gone again, and deleted files that are back. */
54
+ changed: number;
55
+ removed: number;
56
+ back: number;
57
+ /** The first of them, by name. */
58
+ files: string[];
59
+ /** Too large to be recorded: left as they are. */
60
+ left: string[];
61
+ }
62
+ export interface UndoResult {
63
+ task: number;
64
+ /** The message as the owner wrote it. */
65
+ prompt: string;
66
+ /** How many running tasks were stopped first. */
67
+ stopped: number;
68
+ /** The message still waited its turn: it was withdrawn, and there is nothing else to say about it. */
69
+ waiting?: boolean;
70
+ restored?: Restored;
71
+ /** Why no file was touched although the message may have changed some. */
72
+ note?: string;
73
+ /** How many messages a redo can bring back, and whether there is another one to take back. */
74
+ redo: number;
75
+ more: boolean;
76
+ }
77
+ export interface TurnView {
78
+ task?: number;
79
+ prompt?: string;
80
+ root?: string;
81
+ files: FileChange[];
82
+ more: boolean;
83
+ note?: string;
84
+ }
85
+ /**
86
+ * A message the owner typed into a conversation: the only thing undo takes back. Not one that
87
+ * was steered into a running task: that is part of the task's turn and has no run of its own.
88
+ */
89
+ export declare const ownerMessage: (t: Task) => boolean;
90
+ /** The message without what pine added to it at the time. */
91
+ export declare const typed: (prompt: string) => string;
92
+ export declare class Turns {
93
+ private kv;
94
+ private tasks;
95
+ private snapshots;
96
+ private log;
97
+ /** Tasks whose turn has its "before" (or is getting it): asked with every tool call, so answered from here. */
98
+ private seen;
99
+ /**
100
+ * What a conversation was allowed before each message and when it was taken back, as far as
101
+ * the daemon holds that in memory only (see `AgentManager.rightsOf`). Gone with a restart, as
102
+ * those rights are.
103
+ */
104
+ private rights;
105
+ constructor(deps: {
106
+ kv: Kv;
107
+ tasks: TaskStore;
108
+ snapshots: Snapshots;
109
+ log: Logger;
110
+ });
111
+ of(agent: string, session: string): Turn[];
112
+ undone(agent: string, session: string): Undone[];
113
+ private save;
114
+ /** The turn a task's work belongs to: that of the owner's message at the top of it, else the last one of its conversation. */
115
+ private turnOf;
116
+ /**
117
+ * A task is about to be worked on in a conversation. Whatever was taken back there is now final:
118
+ * the conversation goes on from where it stood, and a redo would put the old continuation over
119
+ * the new one. A message of the owner's begins a turn.
120
+ */
121
+ starting(task: Task, at: {
122
+ file?: string;
123
+ leaf: string | null;
124
+ root: string;
125
+ marks: Marks;
126
+ rights: unknown;
127
+ }): void;
128
+ remember(task: number, when: "before" | "after", rights: unknown): void;
129
+ recall(task: number, when: "before" | "after"): unknown;
130
+ /**
131
+ * Before a tool call: the first one of a turn records the folder as it is. Until a tool runs
132
+ * nothing can have changed there, so a message that is only answered costs nothing.
133
+ */
134
+ touching(task: Task): Promise<void>;
135
+ /** A task ended. If it ran tools, the folder as it is now is what its turn left behind. */
136
+ ended(task: Task, tools: number): Promise<void>;
137
+ private record;
138
+ /** Take a turn out of the list (its message is being taken back). */
139
+ drop(agent: string, session: string, task: number): void;
140
+ putBack(agent: string, session: string, turn: Turn): void;
141
+ park(agent: string, session: string, rec: Undone): number;
142
+ /** The message taken back last, taken off the list. */
143
+ unpark(agent: string, session: string): {
144
+ rec?: Undone;
145
+ left: number;
146
+ };
147
+ /** A conversation was reset or removed: nothing of it can be taken back or brought back any more. */
148
+ forget(agent: string, session: string): void;
149
+ rename(agent: string, from: string, to: string): void;
150
+ /**
151
+ * The files of a turn back to what they were before it. Only files the turn's work changed are
152
+ * set, and only where they are not like that already: what the owner changed elsewhere in the
153
+ * folder since stays. `started`: whether the message was worked on at all.
154
+ */
155
+ back(turn: Turn | undefined, started: boolean): Promise<{
156
+ restored?: Restored;
157
+ note?: string;
158
+ cur?: Snap;
159
+ paths?: string[];
160
+ }>;
161
+ /** The same files as the message had left them: a redo. */
162
+ again(rec: Undone): Promise<{
163
+ restored?: Restored;
164
+ note?: string;
165
+ }>;
166
+ /** The two states between which the last message of a conversation lies, if the folder was recorded. */
167
+ private span;
168
+ /** What the last message of a conversation changed in its folder. `running`: whether a task is still being worked on. */
169
+ view(agent: string, session: string, running: (task: number) => boolean): Promise<TurnView>;
170
+ /** The difference of one file over the last message. */
171
+ viewDiff(agent: string, session: string, running: (task: number) => boolean, file: string): Promise<{
172
+ diff: string;
173
+ truncated: boolean;
174
+ } | undefined>;
175
+ /** Every state that is still referred to, by folder: the rest can be dropped. */
176
+ kept(): Map<string, Set<string>>;
177
+ }
178
+ /** What `AgentManager` lends to the two functions below. */
179
+ export interface UndoHost {
180
+ cfg: PineConfig;
181
+ kv: Kv;
182
+ tasks: TaskStore;
183
+ bus: Bus;
184
+ turns: Turns;
185
+ log: Logger;
186
+ cancel(id: number): boolean;
187
+ wait(id: number): Promise<unknown>;
188
+ /** Run when nothing runs in the conversation, with its session closed, and before whatever is sent later. */
189
+ quiet<T>(agent: string, session: string, fn: () => Promise<T>): Promise<T>;
190
+ /** What the conversation may do without asking, as far as it is held in memory: a copy, and putting one back. */
191
+ rights(perm: string): unknown;
192
+ setRights(perm: string, rights: unknown): void;
193
+ /** A task is gone from the list: nothing kept in memory about it is of use any more. */
194
+ forgetTask(id: number): void;
195
+ }
196
+ /**
197
+ * Take back the owner's last message in a conversation, with everything that followed it there.
198
+ * In this order: what runs is stopped; the session file is put back to before the message; the
199
+ * files go back; its tasks leave the task list, from which history is shown, and wait in private
200
+ * storage for a redo; the conversation's outside-content mark and what the owner allowed in it
201
+ * are again what they were before the message, because what gave rise to them is gone, as after
202
+ * a reset.
203
+ */
204
+ export declare function undoMessage(h: UndoHost, agentId: string, key: string): Promise<UndoResult>;
205
+ /** Bring back the message that was taken back last: its files, its place in the conversation, its tasks, and what was allowed. */
206
+ export declare function redoMessage(h: UndoHost, agentId: string, key: string): Promise<UndoResult>;
207
+ /**
208
+ * The lines of a session file that are the conversation as it stands: the entries on the way
209
+ * from the newest one to the first. In a file in which nothing was taken back that is all of them.
210
+ */
211
+ export declare function onBranch(lines: string[]): string[];
212
+ /** The newest session file of a conversation, as pi would continue it. */
213
+ export declare function sessionFile(dir: string): string | undefined;
214
+ /**
215
+ * Put a conversation back to before a message. `leaf` is where it stood then, when that is known;
216
+ * otherwise the message is looked for by its text. Returns where it stood until now, or undefined
217
+ * when the file holds nothing of that message (it was never worked on).
218
+ */
219
+ export declare function rewind(file: string | undefined, leaf: string | null | undefined, prompt: string, task: number): {
220
+ file: string;
221
+ leaf: string | null;
222
+ } | undefined;
223
+ /** Put a conversation back to where it stood before `rewind`. */
224
+ export declare function forward(file: string | undefined, leaf: string | null | undefined, task: number): boolean;