diff --git a/apps/albedo/src/albedo/composition/selection.gleam b/apps/albedo/src/albedo/composition/selection.gleam index 54d74dc68..2b22ff839 100644 --- a/apps/albedo/src/albedo/composition/selection.gleam +++ b/apps/albedo/src/albedo/composition/selection.gleam @@ -652,6 +652,7 @@ pub fn summaries( "managed" extension.CommandPlugin(_) -> "commands" extension.HookPlugin(_) -> "hook" + extension.ExternalAnswerPlugin(_) -> "external_answer" extension.CompactionPlugin(_) -> "compaction" extension.NotesPlugin(_) -> "notes" extension.FoldPlugin(_) -> "folds" diff --git a/apps/albedo/src/albedo/history/conversation.gleam b/apps/albedo/src/albedo/history/conversation.gleam index 021990984..27ff361aa 100644 --- a/apps/albedo/src/albedo/history/conversation.gleam +++ b/apps/albedo/src/albedo/history/conversation.gleam @@ -454,6 +454,7 @@ pub fn creation_available_in( pub fn finish_turn( ledger: store.Store, completion: RunCompletion, + record_answer: fn(sqlight.Connection) -> Result(Nil, String), ) -> Result(Int, String) { let now = usage.now() store.query(ledger, fn(db) { @@ -464,6 +465,7 @@ pub fn finish_turn( completion.state, now, )) + use _ <- result.try(record_answer(db)) store.run( db, "UPDATE sessions SET stage=?,activity_at=?,activity_seq=(SELECT COALESCE(MAX(activity_seq),0)+1 FROM sessions) WHERE id=?", diff --git a/apps/albedo/src/albedo/http/api_digest.gleam b/apps/albedo/src/albedo/http/api_digest.gleam index c8861bd6c..4b9cfb779 100644 --- a/apps/albedo/src/albedo/http/api_digest.gleam +++ b/apps/albedo/src/albedo/http/api_digest.gleam @@ -2,4 +2,4 @@ //// GET /server reports it so a client built from another contract can tell. pub const digest = - "be745564c889f6d264c8ac26a51d3b039bda68b670d325f01e73741fcdce4400" + "b87aaa6d7bba6e5a602321dbef924d86cde575b5c77cb59605fdb9c3bd6bbd8c" diff --git a/apps/albedo/src/albedo/kernel/environment.gleam b/apps/albedo/src/albedo/kernel/environment.gleam index eff12b34c..70a4d21b4 100644 --- a/apps/albedo/src/albedo/kernel/environment.gleam +++ b/apps/albedo/src/albedo/kernel/environment.gleam @@ -70,7 +70,9 @@ pub fn adopted() -> Dict(String, String) { pub fn blocked(name: String) -> Bool { case string.starts_with(name, "ALBEDO_") { True -> !list.contains(kept, name) - False -> list.any(secret_suffixes, string.ends_with(name, _)) + False -> + name == "PHOTON_PROJECT_SECRET" + || list.any(secret_suffixes, string.ends_with(name, _)) } } diff --git a/apps/albedo/src/albedo/model_loop/loop.gleam b/apps/albedo/src/albedo/model_loop/loop.gleam index 6b04af347..911eb1cad 100644 --- a/apps/albedo/src/albedo/model_loop/loop.gleam +++ b/apps/albedo/src/albedo/model_loop/loop.gleam @@ -141,6 +141,8 @@ pub type Loop { /// Whether this turn's steps keep calling the same bindings with nearly /// the same code. repeats: repetition.Watch, + /// Whether this run answers an isolated external input. + external_answer: Bool, /// Whether this turn already compacted because the provider said its /// request did not fit; a second refusal ends the turn. overflowed: Bool, @@ -298,7 +300,7 @@ pub fn run( id: String, inputs: List(transcript.Entry), step: Int, -) -> Result(Nil, Failure) { +) -> Result(Option(String), Failure) { use _ <- result.try(plain(checkpoint(state))) use selection <- result.try(plain(state.refresh())) let #(state, inputs) = case selection { @@ -318,7 +320,7 @@ pub fn run( } use prompted <- result.try(plain(prompted(state, inputs, step))) case prompted { - None -> Ok(Nil) + None -> Ok(None) Some(inputs) -> { let state = case step { 0 -> Loop(..state, reported: restored_usage(state, inputs)) @@ -430,7 +432,7 @@ fn converse( id: String, inputs: List(transcript.Entry), step: Int, -) -> Result(Nil, Failure) { +) -> Result(Option(String), Failure) { use inputs <- result.try(plain(fit_history(state, inputs))) let original_entries = list.reverse(inputs) let original = list.map(original_entries, fn(entry) { entry.input }) @@ -707,10 +709,33 @@ fn stop_or_continue( output: List(types.ReplayItem), batches: List(List(transcript.Entry)), steering: List(transcript.Entry), -) -> Result(Nil, Failure) { +) -> Result(Option(String), Failure) { use held <- result.try(plain(stopping(state, output))) case held, steering { - [], [] -> Ok(Nil) + [], [] -> { + let answer = case state.external_answer && !state.quieted() { + False -> None + True -> + output + |> list.map(types.Replay) + |> list.filter_map(fn(item) { + case message_content.assistant_phase(item, Some("final")) { + Some("final") -> + message_content.visible_assistant_text(item) + |> option.to_result(Nil) + _ -> Error(Nil) + } + }) + |> string.join("\n\n") + |> fn(text) { + case string.trim(text) { + "" -> None + _ -> Some(text) + } + } + } + Ok(answer) + } _, _ -> { state.unquiet() let state = case held { @@ -1693,8 +1718,8 @@ fn overflowed( inputs: List(transcript.Entry), step: Int, called: Result(a, Failure), - otherwise: fn() -> Result(Nil, Failure), -) -> Result(Nil, Failure) { + otherwise: fn() -> Result(Option(String), Failure), +) -> Result(Option(String), Failure) { case called, state.overflowed { Error(ProviderFailed(types.Refused(types.ContextTooLong, ..), _) as failure), False @@ -1738,8 +1763,8 @@ fn go_on( inputs: List(transcript.Entry), step: Int, called: Attempt(a), - answered: fn(a) -> Result(Nil, Failure), -) -> Result(Nil, Failure) { + answered: fn(a) -> Result(Option(String), Failure), +) -> Result(Option(String), Failure) { case called { Answered(value) -> answered(value) Resumed(timestamp, kept, next, accepted_timeouts) -> { diff --git a/apps/albedo/src/albedo/runtime.gleam b/apps/albedo/src/albedo/runtime.gleam index 674dc90c9..61e4d2a4f 100644 --- a/apps/albedo/src/albedo/runtime.gleam +++ b/apps/albedo/src/albedo/runtime.gleam @@ -55,6 +55,7 @@ import gleam/option.{type Option, None, Some} import gleam/otp/actor import gleam/result import gleam/string +import sqlight /// The handle every caller holds; see `runtime/state`. pub type Runtime = @@ -1958,6 +1959,30 @@ pub fn hook(prepared: Prepared, event: hook.Event) -> hook.Answer { ) } +/// Gets the durable answer recorders from the active turn's composition. +pub fn external_answer_recorders( + prepared: Prepared, +) -> List( + fn(sqlight.Connection, extension.ExternalAnswer) -> Result(Nil, String), +) { + composition.extensions(prepared.composition) + |> list.flat_map(fn(owner) { + let name = owner.name + list.filter_map(owner.plugins, fn(plugin) { + case plugin { + extension.ExternalAnswerPlugin(record) -> + Ok(fn(conn, answer) { + albedo_protect.guarded(fn() { record(conn, answer) }) + |> result.map_error(fn(error) { + "extension " <> name <> " could not record its answer: " <> error + }) + }) + _ -> Error(Nil) + } + }) + }) +} + /// Tells every extension this session composed about one of its events. pub fn observe( prepared: Prepared, diff --git a/apps/albedo/src/albedo/session.gleam b/apps/albedo/src/albedo/session.gleam index 2e2d954e6..ceba7084f 100644 --- a/apps/albedo/src/albedo/session.gleam +++ b/apps/albedo/src/albedo/session.gleam @@ -483,7 +483,7 @@ pub type Message { Subject(Nil), ) ReadContext(Subject(context_snapshot.Snapshot)) - Finished(String, Result(Nil, loop.Failure)) + Finished(String, Result(Option(String), loop.Failure)) Down(process.Down) Idle(Subject(Report)) /// An automatic release keeps a kernel whose save missed names; the sweep @@ -3018,7 +3018,9 @@ fn handle( // waits for the turn to end stays there and starts the next one. DrainSteering(id, answer, ack) -> { process.send(ack, Nil) - let exclusive = turn.exclusive(state.active_submissions) + let exclusive = + turn.exclusive(state.active_submissions) + || turn.isolated_event(state.active_submissions) != None let #(state, taken) = case turn.live(state.activity, id) { False -> #(state, Error(Nil)) True -> @@ -4835,7 +4837,7 @@ fn failed_queued(state: State, error: String) -> State { fn answer_parent( state: State, run_id: String, - outcome: Result(Nil, loop.Failure), + outcome: Result(Option(String), loop.Failure), ) -> #(State, Option(fn() -> List(Result(mail_value.Letter, String)))) { let db = runtime.ledger(state.host) let owed = case queue_starts(state) { @@ -5339,9 +5341,10 @@ fn turn_state( fn finish_run( state: State, run: turn.Run, - failure: Result(Nil, loop.Failure), + failure: Result(Option(String), loop.Failure), ) -> actor.Next(State, Message) { - let outcome = result.map_error(failure, loop.failure_message) + let outcome = + failure |> result.map_error(loop.failure_message) |> result.replace(Nil) case run.work { // A background call holds the session like a compaction run does, but // commits nothing and never reaches the transcript. @@ -5363,10 +5366,11 @@ fn finish_run( fn finish_turn( state: State, run: turn.Run, - failure: Result(Nil, loop.Failure), + failure: Result(Option(String), loop.Failure), ) -> actor.Next(State, Message) { use <- bool.guard(state.finishing, actor.continue(state)) - let outcome = result.map_error(failure, loop.failure_message) + let outcome = + failure |> result.map_error(loop.failure_message) |> result.replace(Nil) process.demonitor_process(run.monitor) // A session closing for deletion keeps nothing of the turn. let state = case run.work, run.cancelled, outcome { @@ -5385,11 +5389,27 @@ fn finish_turn( turn.final_stage(run, outcome), turn_state(run, outcome), ) + let record_answer = case + run.work, + run.cancelled, + state.closing, + failure, + turn.isolated_event(state.active_submissions), + session_state.composition(state) + { + turn.Turn(..), False, False, Ok(Some(text)), Some(letter_id), Some(prepared) + -> { + let answer = extension.ExternalAnswer(state.info.id, letter_id, text) + let recorders = runtime.external_answer_recorders(prepared) + fn(conn) { list.try_each(recorders, fn(record) { record(conn, answer) }) } + } + _, _, _, _, _, _ -> fn(_) { Ok(Nil) } + } // The run holds the session until its end is durable, so nothing starts // behind a turn the store still calls running. session_state.State(..state, finishing: True) |> session_state.write_then( - fn() { conversation.finish_turn(ledger, completion) }, + fn() { conversation.finish_turn(ledger, completion, record_answer) }, fn(state, persisted) { // Its requesters' answers are posted before the session reads idle, so // whoever waits on it sees them once it does. diff --git a/apps/albedo/src/albedo/session/inbox.gleam b/apps/albedo/src/albedo/session/inbox.gleam index ae11124c1..178e3fc81 100644 --- a/apps/albedo/src/albedo/session/inbox.gleam +++ b/apps/albedo/src/albedo/session/inbox.gleam @@ -20,12 +20,19 @@ import gleam/result import sqlight /// The submission a plain letter delivers. -fn letter_submission(letter: Letter) -> Submission { +fn letter_submission( + letter: Letter, + delivery: mail_value.Delivery, +) -> Submission { + let source = case letter.kind, delivery { + mail_value.Event, mail_value.Alone -> turn.IsolatedEvent(letter.id) + _, _ -> turn.Mail(letter.id, letter.kind) + } Submission( mail.display(letter), mail.text(letter), letter.id, - turn.Mail(letter.id, letter.kind), + source, [], Some(letter.id), None, @@ -60,7 +67,7 @@ fn submission(row: mail.Waiting) -> Submission { None, mail_value.Job -> made(turn.JobWake) None, mail_value.Input(mail_value.Shelled) -> made(turn.Shell(letter.id)) None, mail_value.Input(mail_value.Typed) -> made(turn.Chat) - None, _ -> letter_submission(letter) + None, _ -> letter_submission(letter, row.delivery) } } diff --git a/apps/albedo/src/albedo/session/session_run.gleam b/apps/albedo/src/albedo/session/session_run.gleam index 7a14640a6..02f981f70 100644 --- a/apps/albedo/src/albedo/session/session_run.gleam +++ b/apps/albedo/src/albedo/session/session_run.gleam @@ -82,7 +82,7 @@ pub type Messages(message) { sent: fn(String, extension.SentCall, Subject(Nil)) -> message, shell_delivery: fn(String, List(String), Subject(Nil)) -> message, compacting: fn(String, compaction.ProgressUpdate, Subject(Nil)) -> message, - finished: fn(String, Result(Nil, loop.Failure)) -> message, + finished: fn(String, Result(Option(String), loop.Failure)) -> message, collect: message, acquire: fn(String, Subject(Result(runtime.Session, String))) -> message, boundary: fn(String, Subject(Result(Option(loop.Selection), String))) -> @@ -617,6 +617,7 @@ pub fn start( fn() { turn.quieted(stop) }, fn() { turn.unquiet(stop) }, repetition.new(), + turn.isolated_event(state.active_submissions) != None, False, ) let pid = @@ -626,7 +627,9 @@ pub fn start( owner, messages.finished(run_id, case work { turn.Compaction(..) -> - loop.compact(worker, given) |> result.map_error(loop.RunFailed) + loop.compact(worker, given) + |> result.map_error(loop.RunFailed) + |> result.replace(None) // The session opens the turn once its inputs are committed; the // history read then is at least that commit's. turn.Turn(..) -> @@ -663,7 +666,7 @@ pub fn start( loop.summarize_branch(worker, given, instructions) |> result.map(fn(text) { #(text, last) }), ) - Ok(Nil) + Ok(None) } }), ) diff --git a/apps/albedo/src/albedo/session/session_submission.gleam b/apps/albedo/src/albedo/session/session_submission.gleam index 0936ec1c5..7afc6ea09 100644 --- a/apps/albedo/src/albedo/session/session_submission.gleam +++ b/apps/albedo/src/albedo/session/session_submission.gleam @@ -63,7 +63,8 @@ fn display_source(source: turn.Source) -> operations.DisplaySource { turn.Chat -> operations.DisplayChat turn.JobWake -> operations.DisplayJob turn.Mail(_, mail_value.Webhook) -> operations.DisplayWebhook - turn.Mail(_, mail_value.Event) -> operations.DisplayEvent + turn.Mail(_, mail_value.Event) | turn.IsolatedEvent(_) -> + operations.DisplayEvent turn.Mail(..) -> operations.DisplayMail turn.Note(origin) -> operations.DisplayNote(origin) turn.Shell(_) -> operations.DisplayShell @@ -165,8 +166,10 @@ fn committed( case submission.operation_id { None -> case submission.source, submission.submission_id { - turn.Mail(id, _), _ | turn.JobWake, Some(id) -> - Ok(operations.Commit(id, position, display(submission))) + turn.Mail(id, _), _ + | turn.IsolatedEvent(id), _ + | turn.JobWake, Some(id) + -> Ok(operations.Commit(id, position, display(submission))) _, _ -> Error(Nil) } Some(id) -> Ok(operations.Commit(id, position, display(submission))) @@ -189,7 +192,7 @@ fn row_kind(row: List(Submission)) -> transcript.Kind { [] -> transcript.Said(None) [first, ..] -> case first.source { - turn.Mail(..) -> transcript.Letter + turn.Mail(..) | turn.IsolatedEvent(_) -> transcript.Letter turn.JobWake -> transcript.Note("job", first.display) turn.Continue -> transcript.Notice turn.Note(origin) if origin == session_namespace.notice_origin -> diff --git a/apps/albedo/src/albedo/session/turn.gleam b/apps/albedo/src/albedo/session/turn.gleam index ceef3fc2c..d1a43f9ea 100644 --- a/apps/albedo/src/albedo/session/turn.gleam +++ b/apps/albedo/src/albedo/session/turn.gleam @@ -31,6 +31,7 @@ pub type Source { /// A letter: letters between agents steer a running turn; webhooks and /// events delivered after the turn wait in the queue until it ends. Mail(id: String, kind: mail_value.Kind) + IsolatedEvent(id: String) /// Something an extension tells the agent, such as a user's work ledger /// change. `origin` labels it in the transcript. Note(origin: String) @@ -347,7 +348,7 @@ pub fn source_name(source: Source) -> String { Chat -> "chat" JobWake -> "job" Mail(_, mail_value.Webhook) -> "webhook" - Mail(_, mail_value.Event) -> "event" + Mail(_, mail_value.Event) | IsolatedEvent(_) -> "event" Mail(..) -> "mail" Note(origin) -> origin Shell(_) -> "shell" @@ -364,6 +365,7 @@ pub fn kind(source: Source) -> mail_value.Kind { Acp -> mail_value.Input(mail_value.Editor) Shell(_) -> mail_value.Input(mail_value.Shelled) Mail(_, kind) -> kind + IsolatedEvent(_) -> mail_value.Event Note(_) -> mail_value.Note JobWake -> mail_value.Job } @@ -371,7 +373,10 @@ pub fn kind(source: Source) -> mail_value.Kind { /// When a submission the session stores itself is read: its kind's default. pub fn delivery(source: Source) -> mail_value.Delivery { - mail_value.default_delivery(kind(source)) + case source { + IsolatedEvent(_) -> mail_value.Alone + _ -> mail_value.default_delivery(kind(source)) + } } /// One row waiting in the inbox as the queue's rules see them: its id, its @@ -507,13 +512,21 @@ pub fn exclusive(members: List(Submission)) -> Bool { list.any(members, fn(submission) { submission.source == Acp }) } +/// A single external event can have its own answer, with no steering. +pub fn isolated_event(members: List(Submission)) -> Option(String) { + case members { + [Submission(source: IsolatedEvent(id), ..)] -> Some(id) + _ -> None + } +} + /// The inbox rows these submissions deliver, for the commit that writes /// them. A person's input is stored under its operation id; one saved before /// it carried its own id has only that. pub fn letters(submissions: List(Submission)) -> List(String) { list.filter_map(submissions, fn(submission) { case submission.source { - Mail(id, _) -> Ok(id) + Mail(id, _) | IsolatedEvent(id) -> Ok(id) _ -> option.or(submission.submission_id, submission.operation_id) |> option.to_result(Nil) diff --git a/apps/albedo/test/albedo/model_loop/quiet_reset_test.gleam b/apps/albedo/test/albedo/model_loop/quiet_reset_test.gleam index 06bc78fac..046c452aa 100644 --- a/apps/albedo/test/albedo/model_loop/quiet_reset_test.gleam +++ b/apps/albedo/test/albedo/model_loop/quiet_reset_test.gleam @@ -180,13 +180,14 @@ fn run_case(hold_by_hook: Bool, empty_after_reset: Bool) -> #(Int, Int) { fn() { turn.quieted(stop) }, fn() { turn.unquiet(stop) }, repetition.new(), + True, False, ) let initial = [ transcript.Entry(types.User("start"), Some(1), None, None, None, None, True), ] let result = loop.run(state, "run-1", initial, 0) - result |> should.equal(Ok(Nil)) + result |> should.equal(Ok(Some("done 2"))) let call_count = drain_count(calls, 0) let nudge_count = drain_count(nudges, 0) runtime.stop(host) diff --git a/cli/internal/cli/photon.go b/cli/internal/cli/photon.go new file mode 100644 index 000000000..34090d6e8 --- /dev/null +++ b/cli/internal/cli/photon.go @@ -0,0 +1,231 @@ +package cli + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "time" + + "albedo/cli/internal/app" + "albedo/cli/internal/config" + "albedo/cli/internal/daemon" + "github.com/spf13/cobra" +) + +type photonPairing struct { + Session string `json:"session"` + Recipient string `json:"recipient"` + AssignedNumber string `json:"assignedNumber"` + OptedIn bool `json:"optedIn"` +} + +func newPhoton(deps Dependencies) *cobra.Command { + root := &cobra.Command{Use: "photon", Short: "pair iMessage with an Albedo session"} + var phone, session, importFile string + setup := &cobra.Command{Use: "setup", Short: "connect a Photon iMessage line", Args: cobra.NoArgs} + setup.Flags().StringVar(&phone, "phone", "", "your iMessage phone number in E.164 form") + setup.Flags().StringVar(&session, "session", "", "existing session ID or prefix (default: continue the pairing or create a session here)") + setup.Flags().StringVar(&importFile, "from-hermes", "", "use the Photon project credentials in this Hermes .env file") + setup.RunE = func(cmd *cobra.Command, _ []string) error { + return setupPhoton(cmd, deps, phone, session, importFile) + } + status := &cobra.Command{Use: "status", Short: "show the paired number and whether the daemon is receiving texts", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { + return printPhotonStatus(cmd, deps) + }} + root.AddCommand(setup, status) + return root +} + +func savedPhotonSession() (string, error) { + data, err := os.ReadFile(filepath.Join(config.HomeDir(), "photon.json")) + if errors.Is(err, os.ErrNotExist) { + return "", nil + } + if err != nil { + return "", err + } + var pair photonPairing + if err = json.Unmarshal(data, &pair); err != nil { + return "", fmt.Errorf("read saved Photon pairing: %w", err) + } + return pair.Session, nil +} + +func setupPhoton(cmd *cobra.Command, deps Dependencies, phone, session, importFile string) error { + if !regexp.MustCompile(`^\+[1-9][0-9]{7,14}$`).MatchString(phone) { + return errors.New("--phone requires an international phone number, such as +15551234567") + } + helper, err := photonExecutable() + if err != nil { + return err + } + if session == "" { + session, err = savedPhotonSession() + if err != nil { + return err + } + } + prepared, err := deps.Application.PrepareOpen(cmd.Context(), app.OpenOptions{Workspace: deps.Workspace, SessionID: session, Fresh: session == ""}) + if err != nil { + return err + } + id := prepared.Selected.ID + args := []string{"setup", "--home", config.HomeDir(), "--session", id, "--phone", phone} + if importFile != "" { + args = append(args, "--from-hermes", importFile) + } + pair, err := runPhotonHelper(cmd, helper, args...) + if err != nil { + return err + } + if pair.Session != id || pair.Recipient != phone { + return errors.New("the Photon service returned a different pairing than requested") + } + if err = enablePhoton(cmd.Context(), prepared); err != nil { + return err + } + if pair.AssignedNumber == "" { + _, err = fmt.Fprintln(cmd.OutOrStdout(), "Pairing saved. Photon has not assigned a number yet. Run albedo photon status to check.") + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "iMessage line: %s\nSession: %s\n", pair.AssignedNumber, id) + if !pair.OptedIn { + _, err = fmt.Fprintf(cmd.OutOrStdout(), "To opt in, send one text to %s from %s. Run albedo photon status and wait for Ready before your first question.\n", pair.AssignedNumber, phone) + return err + } + if err = waitForPhoton(cmd.Context(), prepared.Connection, pair); err != nil { + return err + } + _, err = fmt.Fprintf(cmd.OutOrStdout(), "Ready. Text %s from %s.\n", pair.AssignedNumber, phone) + return err +} + +func waitForPhoton(ctx context.Context, conn *daemon.Connection, pair photonPairing) error { + // A saved pairing can still be connecting. Do not tell the person to + // text the line until its initial replay checkpoint has committed. + timeout, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + for { + status, err := daemon.GetPhotonStatus(timeout, conn) + if err != nil { + return fmt.Errorf("checking the saved pairing: %w", err) + } + if status.Ready && status.Session != nil && *status.Session == pair.Session { + return nil + } + select { + case <-timeout.Done(): + return errors.New("pairing saved; still connecting to Photon. Run albedo photon status before texting") + case <-ticker.C: + } + } +} + +func printPhotonStatus(cmd *cobra.Command, deps Dependencies) error { + helper, err := photonExecutable() + if err != nil { + return err + } + pair, err := runPhotonHelper(cmd, helper, "status", "--home", config.HomeDir()) + if err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "iMessage line: %s\nPaired phone: %s\nSession: %s\n", pair.AssignedNumber, pair.Recipient, pair.Session) + conn, err := deps.Application.Existing(cmd.Context()) + if err != nil { + return err + } + if conn == nil { + _, err = fmt.Fprintln(cmd.OutOrStdout(), "Daemon offline.") + return err + } + live, err := daemon.GetPhotonStatus(cmd.Context(), conn) + if err != nil { + return err + } + state := "Connecting" + if !pair.OptedIn { + state = "Awaiting opt-in" + } else if live.Ready && live.Session != nil && *live.Session == pair.Session { + state = "Ready" + } + _, err = fmt.Fprintln(cmd.OutOrStdout(), state) + return err +} + +func photonExecutable() (string, error) { + if self, err := os.Executable(); err == nil { + sibling := filepath.Join(filepath.Dir(self), "albedo-photon") + if resolved, err := exec.LookPath(sibling); err == nil { + return resolved, nil + } + } + path, err := exec.LookPath("albedo-photon") + if err != nil { + return "", errors.New("albedo-photon is missing; use the packaged CLI or put tools/photon on PATH after installing its dependencies") + } + return path, nil +} + +func runPhotonHelper(cmd *cobra.Command, helper string, args ...string) (photonPairing, error) { + child := exec.CommandContext(cmd.Context(), helper, args...) + child.Stdin = cmd.InOrStdin() + child.Stderr = cmd.ErrOrStderr() + output, err := child.Output() + if err != nil { + return photonPairing{}, fmt.Errorf("running Photon %s: %w", args[0], err) + } + var pair photonPairing + if err := json.Unmarshal(output, &pair); err != nil { + return pair, errors.New("invalid response from Photon setup helper") + } + if strings.TrimSpace(pair.Session) == "" { + return pair, errors.New("no saved Photon session; run albedo photon setup") + } + return pair, nil +} + +func enablePhoton(ctx context.Context, prepared app.PreparedOpen) error { + conn, id := prepared.Connection, prepared.Selected.ID + settings := prepared.Settings + var extensions []daemon.ExtensionSummary + var err error + if !settings.Extensions["photon"] { + extensions, err = daemon.SelectExtension(ctx, conn, id, daemon.ExtensionSelectionRequest{Name: "photon", Scope: "global", ETag: settings.ETags["extensions"], Enabled: new(true)}) + } else { + extensions, err = daemon.ListExtensions(ctx, conn, id) + } + if err != nil { + return err + } + for _, ext := range extensions { + if ext.Name != "photon" { + continue + } + if ext.Quarantined != "" { + return errors.New(ext.Quarantined) + } + if ext.Overridden && !ext.Enabled { + if _, err = daemon.SelectExtension(ctx, conn, id, daemon.ExtensionSelectionRequest{Name: "photon", Scope: "session", ETag: ext.SessionETag, Enabled: new(true)}); err != nil { + return err + } + } + result, err := daemon.ReloadSession(ctx, conn, id, daemon.ReloadRequest{Target: "session"}) + if err != nil { + return err + } + if result.Session == nil || result.Session.State != "applied" { + return errors.New(result.Message()) + } + return nil + } + return errors.New("the daemon does not have the Photon extension installed") +} diff --git a/cli/internal/cli/root.go b/cli/internal/cli/root.go index 10cd00560..ba6400333 100644 --- a/cli/internal/cli/root.go +++ b/cli/internal/cli/root.go @@ -151,7 +151,7 @@ func NewRoot(deps Dependencies) *cobra.Command { _, err = fmt.Fprintln(cmd.OutOrStdout(), result.Answer) return err } - root.AddCommand(newOpen(deps), newResume(deps), newSessions(deps), newModels(deps), newSend(deps), newStop(deps), newDaemon(deps), newStorage(deps), newLogin(deps), newWeb(deps), newProxy(deps)) + root.AddCommand(newPhoton(deps), newOpen(deps), newResume(deps), newSessions(deps), newModels(deps), newSend(deps), newStop(deps), newDaemon(deps), newStorage(deps), newLogin(deps), newWeb(deps), newProxy(deps)) return root } func open(cmd *cobra.Command, deps Dependencies, options app.OpenOptions) error { diff --git a/cli/internal/daemon/photon.go b/cli/internal/daemon/photon.go new file mode 100644 index 000000000..f149e9f42 --- /dev/null +++ b/cli/internal/daemon/photon.go @@ -0,0 +1,20 @@ +package daemon + +import ( + "context" + "io" + "net/http" + + "albedo/cli/internal/daemon/protocol" +) + +func GetPhotonStatus(ctx context.Context, conn *Connection) (protocol.PhotonStatus, error) { + var status protocol.PhotonStatus + err := executeRead(ctx, conn, operation{ + Name: "read Photon readiness", Policy: readRecovery, + BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { + return protocol.NewGetPhotonStatusRequest(base) + }, + }, func(data []byte) error { return decodeRequired(data, &status) }) + return status, err +} diff --git a/cli/internal/daemon/protocol/api.gen.go b/cli/internal/daemon/protocol/api.gen.go index f81ee124c..113230de4 100644 --- a/cli/internal/daemon/protocol/api.gen.go +++ b/cli/internal/daemon/protocol/api.gen.go @@ -2567,6 +2567,12 @@ type PendingInput struct { Preview Preview `json:"preview"` } +// PhotonStatus defines model for PhotonStatus. +type PhotonStatus struct { + Session *string `json:"session" nullable:"true"` + Ready bool `json:"ready"` +} + // PreferencePatch defines model for PreferencePatch. type PreferencePatch struct { Archived PatchField[bool] `json:"archived,omitempty"` @@ -6169,6 +6175,11 @@ type ClientInterface interface { // Corresponds with PATCH /extensions/paperclips/items/{item_id} (the `PatchPaperclips` operationId). PatchPaperclipsWithApplicationMergePatchPlusJSONBody(ctx context.Context, itemID ID, params *PatchPaperclipsParams, body PatchPaperclipsApplicationMergePatchPlusJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) + // GetPhotonStatus Read the local iMessage pairing and transport readiness + // + // Corresponds with GET /extensions/photon/status (the `GetPhotonStatus` operationId). + GetPhotonStatus(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) + // CreateProxyCompletionWithBody Run a stateless OpenAI chat completion // // Caller supplies full history. Tool IDs carry opaque provider state and must be echoed exactly. Bearer required unless anonymous loopback policy explicitly enabled. Providers apply only representable generation options; proxy transport documentation defines these differences. No automatic replay after request admission. @@ -8574,6 +8585,21 @@ func (c *Client) PatchPaperclipsWithApplicationMergePatchPlusJSONBody(ctx contex return c.Client.Do(req) } +// GetPhotonStatus Read the local iMessage pairing and transport readiness +// +// Corresponds with GET /extensions/photon/status (the `GetPhotonStatus` operationId). +func (c *Client) GetPhotonStatus(ctx context.Context, reqEditors ...RequestEditorFn) (*http.Response, error) { + req, err := NewGetPhotonStatusRequest(c.Server) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if err := c.applyEditors(ctx, req, reqEditors); err != nil { + return nil, err + } + return c.Client.Do(req) +} + // CreateProxyCompletionWithBody Run a stateless OpenAI chat completion // // Caller supplies full history. Tool IDs carry opaque provider state and must be echoed exactly. Bearer required unless anonymous loopback policy explicitly enabled. Providers apply only representable generation options; proxy transport documentation defines these differences. No automatic replay after request admission. @@ -13659,6 +13685,33 @@ func NewPatchPaperclipsRequestWithBody(server string, itemID ID, params *PatchPa return req, nil } +// NewGetPhotonStatusRequest constructs an http.Request for the GetPhotonStatus method +func NewGetPhotonStatusRequest(server string) (*http.Request, error) { + var err error + + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + + operationPath := fmt.Sprintf("/extensions/photon/status") + if operationPath[0] == '/' { + operationPath = "." + operationPath + } + + queryURL, err := serverURL.Parse(operationPath) + if err != nil { + return nil, err + } + + req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil) + if err != nil { + return nil, err + } + + return req, nil +} + // NewCreateProxyCompletionRequest calls the generic CreateProxyCompletion builder with application/json body func NewCreateProxyCompletionRequest(server string, body CreateProxyCompletionJSONRequestBody) (*http.Request, error) { var bodyReader io.Reader diff --git a/cli/internal/daemon/protocol/digest.gen.go b/cli/internal/daemon/protocol/digest.gen.go index fdab98ff0..d149c64e7 100644 --- a/cli/internal/daemon/protocol/digest.gen.go +++ b/cli/internal/daemon/protocol/digest.gen.go @@ -5,4 +5,4 @@ package protocol // APIDigest identifies the wire contract these types were generated from. // The daemon reports its own in GET /server; a different value means this // client's decoders may reject what the daemon sends. -const APIDigest = "be745564c889f6d264c8ac26a51d3b039bda68b670d325f01e73741fcdce4400" +const APIDigest = "b87aaa6d7bba6e5a602321dbef924d86cde575b5c77cb59605fdb9c3bd6bbd8c" diff --git a/cli/internal/daemon/protocol/recovery.gen.go b/cli/internal/daemon/protocol/recovery.gen.go index 81ac78ce2..949d78258 100644 --- a/cli/internal/daemon/protocol/recovery.gen.go +++ b/cli/internal/daemon/protocol/recovery.gen.go @@ -95,6 +95,8 @@ func OperationRecovery(operation string) RecoveryPolicy { return RecoveryPolicy("refresh-before-edit") case "deletePaperclips": return RecoveryPolicy("no-automatic-replay") + case "getPhotonStatus": + return RecoveryPolicy("safe-read") case "createProxyCompletion": return RecoveryPolicy("no-automatic-replay") case "listProxyModels": diff --git a/docs/api-extension.gen.md b/docs/api-extension.gen.md index 31d4b4cfe..a3628d7a2 100644 --- a/docs/api-extension.gen.md +++ b/docs/api-extension.gen.md @@ -198,6 +198,12 @@ Recovery: `refresh-before-edit`. Recovery: `no-automatic-replay`. +## getPhotonStatus + +`GET /extensions/photon/status` + +Recovery: `safe-read`. + ## createProxyCompletion `POST /extensions/proxy/v1/chat/completions` diff --git a/docs/openapi.yaml b/docs/openapi.yaml index fe6711a43..599084faf 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -42,6 +42,7 @@ tags: - name: schedule - name: links - name: webhooks + - name: photon - name: discord - name: proxy - name: terminals @@ -6623,6 +6624,33 @@ paths: description: UTF-8 JSON; duplicate keys and unknown fields are rejected. x-albedo-audience: extension x-albedo-recovery: refresh-before-edit + /extensions/photon/status: + get: + operationId: getPhotonStatus + summary: Read the local iMessage pairing and transport readiness + tags: + - photon + responses: + '200': + description: Successful result. + content: + application/json: + schema: + $ref: '#/components/schemas/PhotonStatus' + '400': + $ref: '#/components/responses/Problem400' + '401': + $ref: '#/components/responses/Problem401' + '403': + $ref: '#/components/responses/Problem403' + '405': + $ref: '#/components/responses/Problem405' + '406': + $ref: '#/components/responses/Problem406' + '503': + $ref: '#/components/responses/Problem503' + x-albedo-audience: extension + x-albedo-recovery: safe-read /extensions/discord/bots: get: operationId: listDiscordBots @@ -18901,6 +18929,19 @@ components: maxLength: 256 required: [id, username] additionalProperties: false + PhotonStatus: + type: object + additionalProperties: false + required: + - session + - ready + properties: + session: + x-order: 1 + type: [string, 'null'] + ready: + x-order: 2 + type: boolean DiscordBotPage: type: object properties: diff --git a/docs/photon.md b/docs/photon.md index fea366815..c775430fe 100644 --- a/docs/photon.md +++ b/docs/photon.md @@ -1,40 +1,56 @@ -# Text a session with iMessage - -Pair one Albedo session with one iMessage contact. Text the Photon account from -that contact in Messages. Albedo receives the text in the paired session and can -answer in the same conversation while the daemon is running. - -The Nix package includes the Photon helper. When running directly from a -checkout outside the development shell, run `npm ci --prefix tools/photon` and -add the checkout's `tools/photon` directory to the daemon's `PATH`. - -1. Get the iMessage server address and bearer token from your Photon account. - Use the hosted gRPC server address in `host:port` form. See - [Photon's iMessage setup](https://photon.codes/docs/advanced-kits/imessage/getting-started). -2. Choose a session with a working model provider. Run `albedo sessions --json` - and copy its full session ID. -3. Set the following variables in the environment that starts the daemon. If a - service manager runs Albedo, configure the variables on that service. - - | Variable | Value | - | -------------------------- | -------------------------------------------------------------------------------- | - | `ALBEDO_PHOTON_SESSION_ID` | Full ID of the session that should receive your texts | - | `ALBEDO_PHOTON_RECIPIENT` | Your iMessage email address or E.164 phone number | - | `ALBEDO_PHOTON_ADDRESS` | Photon's server address, such as `imessage.example.com:443` | - | `ALBEDO_PHOTON_TOKEN_FILE` | Absolute path to a file containing the bearer token, readable by the daemon user | - - You can supply the token directly as `PHOTON_TOKEN`. A configured token file - takes precedence. - -4. Set `enabled.photon` to `true` in the daemon's `extensions.json`. Keep it - enabled for the paired session. Restart the daemon with the new environment. - If you use outbound proxies, select the direct route for the `photon` - service. -5. Send a new text from your paired address. The first connection skips existing - history. Later connections catch up from the saved checkpoint using the - events Photon still retains. - -The pairing accepts plain text in direct iMessage conversations. Group chats, -outgoing messages and reactions do not start turns. See the -[Photon extension reference](../robot-docs/photon.md) for delivery and reply -handling. +# Text Albedo from Messages + +Pair your phone with Albedo once, then text its assigned iMessage number. Each +incoming text goes to the same session. The assistant's final answer comes back +as a regular message in that conversation. You can close the terminal while the +daemon runs. + +## Use your Hermes line + +If Hermes already has a working Photon line, use its Spectrum project with +Albedo. Replace the example phone number with the number you text from. + +```sh +albedo photon setup --phone +15551234567 --from-hermes ~/.hermes/.env +``` + +Albedo reads the two Photon project credentials and looks up your existing +assigned line. It saves its own pairing in the local Albedo home. Disable +Hermes's Photon gateway for that line when you switch over so the two agents +don't answer the same text. Use a separate project if you want both agents +running independently. + +## Set up a new line + +Run this in the workspace where you want the agent to work. Configure a model +with `albedo login` first if you haven't already. + +```sh +albedo photon setup --phone +15551234567 +``` + +Follow the printed device-login link and approve the code. Albedo creates a +Photon project, registers your phone, and prints the assigned number. If you +already have Spectrum project credentials, you can instead provide +`PHOTON_PROJECT_ID` and `PHOTON_PROJECT_SECRET` to the setup command. + +Setup creates a session on the first run and reuses the saved session on later +runs. Add `--session ID` to pair an existing session. The command enables the +extension and reloads the paired session. The daemon must use a direct network +route for the `photon` service. + +If Photon asks you to opt in, text the assigned number once from your paired +phone. Check the line before sending your first question: + +```sh +albedo photon status +``` + +**Ready** means the daemon has connected and established its initial replay +checkpoint. Older messages are skipped on the first pairing. After a restart, +the daemon catches up from its checkpoint using events still retained by Photon. + +Only direct texts from the paired number reach the session. A prompt you enter +in the terminal or web client stays there. For workings and the older hosted +server configuration, see the +[Photon extension reference](../robot-docs/photon.md). diff --git a/e2e/areas.toml b/e2e/areas.toml index 8f0e8aa10..b0172fa94 100644 --- a/e2e/areas.toml +++ b/e2e/areas.toml @@ -6,6 +6,8 @@ "e2e/fixtures/photon/*" = ["photon_test.py"] "python/albedo_photon.py" = ["photon_test.py"] "python/albedo_plugins/photon.py" = ["photon_test.py"] +"cli/internal/cli/photon.go" = ["photon_test.py"] +"cli/internal/daemon/photon.go" = ["photon_test.py"] # Specific core owners precede subsystem defaults; fnmatch * also spans /. "apps/albedo/src/albedo/storage/migrations/session_titles.gleam" = [ "session_name_test.py", @@ -23,6 +25,7 @@ "apps/albedo/src/albedo/model_loop/loop.gleam" = [ "compaction_progress_test.py", "integration_test.py", + "photon_test.py", ] "apps/albedo/src/albedo/lifecycle/host_install.gleam" = [ "standby_test.py", diff --git a/e2e/fixtures/photon/server.cjs b/e2e/fixtures/photon/server.cjs index 60efa027b..4e1c4af1a 100644 --- a/e2e/fixtures/photon/server.cjs +++ b/e2e/fixtures/photon/server.cjs @@ -2,6 +2,7 @@ const { createRequire } = require("node:module"); const fs = require("node:fs"); const path = require("node:path"); +const http = require("node:http"); const [helper, state] = process.argv.slice(2); const fromHelper = createRequire(helper); const grpc = fromHelper("@grpc/grpc-js"); @@ -18,8 +19,9 @@ const defs = grpc.loadPackageDefinition( ).photon.imessage.v1; const server = new grpc.Server(); const recipient = "+15550101111"; +const assignedNumber = "+15550101122"; +const token = "local-fixture-token"; const chatGuid = "any;-;" + recipient; -const sender = { address: recipient, service: 1 }; function record(kind, data) { fs.appendFileSync( @@ -28,47 +30,66 @@ function record(kind, data) { ); } +function readEvents() { + return JSON.parse(fs.readFileSync(path.join(state, "events"))); +} + +function messageFrame(event, index) { + const guid = event.chatGuid ?? chatGuid; + return { + sequence: index + 1, + messageChanged: { + occurredAt: { seconds: 1 }, + chatGuid: guid, + isFromMe: !!event.outgoing, + messageReceived: { + message: { + dateCreated: { seconds: 1 }, + guid: event.guid, + sender: { address: event.sender ?? recipient, service: 1 }, + content: { text: event.text }, + isFromMe: !!event.outgoing, + chatGuids: [guid], + }, + }, + }, + }; +} + +function authorized(call) { + return call.metadata.get("authorization")[0] === `Bearer ${token}`; +} + server.addService(defs.ChatService.service, { createChat(call, done) { - if ( - call.metadata.get("authorization")[0] !== "Bearer local-fixture-token" || - call.request.addresses?.[0] !== recipient - ) { + if (!authorized(call) || call.request.addresses?.[0] !== recipient) { return done({ code: grpc.status.PERMISSION_DENIED, message: "invalid pairing", }); } done(null, { - chat: { guid: chatGuid, service: 1, participants: [sender] }, + chat: { + guid: chatGuid, + service: 1, + participants: [{ address: recipient, service: 1 }], + }, }); }, }); server.addService(defs.EventService.service, { catchUpEvents(call) { - const events = JSON.parse(fs.readFileSync(path.join(state, "events"))); + if (!authorized(call)) { + call.destroy({ code: grpc.status.UNAUTHENTICATED }); + return; + } + const events = readEvents(); const after = call.request.afterSequence; record("poll", { after }); for (const [index, event] of events.entries()) { const sequence = index + 1; if (sequence <= (after ?? 0)) continue; - const message = { - dateCreated: { seconds: 1 }, - guid: event.guid, - sender, - content: { text: event.text }, - isFromMe: !!event.outgoing, - chatGuids: [chatGuid], - }; - call.write({ - sequence, - messageChanged: { - occurredAt: { seconds: 1 }, - chatGuid, - isFromMe: !!event.outgoing, - messageReceived: { message }, - }, - }); + call.write(messageFrame(event, index)); } call.write({ complete: { headSequence: events.length } }); call.end(); @@ -76,6 +97,9 @@ server.addService(defs.EventService.service, { }); server.addService(defs.MessageService.service, { sendTextMessage(call, done) { + if (!authorized(call)) { + return done({ code: grpc.status.UNAUTHENTICATED }); + } record("send", call.request); done(null, { message: { @@ -99,3 +123,57 @@ server.bindAsync( fs.writeFileSync(path.join(state, "address"), "127.0.0.1:" + port); }, ); + +const project = { id: "fixture-project" }; +const user = { + phoneNumber: recipient, + assignedPhoneNumber: assignedNumber, + meta: { opt_in: true }, +}; +let registered = false; +const cloud = http.createServer(async (request, response) => { + const expected = Buffer.from("fixture-project:fixture-secret").toString( + "base64", + ); + if (request.headers.authorization !== `Basic ${expected}`) { + response.writeHead(401).end(); + return; + } + const projectPath = `/projects/${project.id}/`; + const route = request.method + " " + request.url; + let data; + switch (route) { + case `POST ${projectPath}imessage/tokens`: + data = { type: "shared", token, expiresIn: 3600 }; + break; + case `GET ${projectPath}users/`: + data = registered ? [user] : []; + break; + case `POST ${projectPath}users/`: { + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + const input = JSON.parse(Buffer.concat(chunks)); + if (input.type !== "shared" || input.phoneNumber !== recipient) { + response.writeHead(400).end(); + return; + } + registered = true; + data = user; + break; + } + default: + record("unexpected-http", { route }); + response.writeHead(404).end(); + return; + } + record("cloud", { route }); + response + .writeHead(200, { "Content-Type": "application/json" }) + .end(JSON.stringify({ succeed: true, data })); +}); +cloud.listen(0, "127.0.0.1", () => { + fs.writeFileSync( + path.join(state, "cloud"), + `http://127.0.0.1:${cloud.address().port}`, + ); +}); diff --git a/e2e/photon_test.py b/e2e/photon_test.py index 0c966d5b7..b9fd5654c 100644 --- a/e2e/photon_test.py +++ b/e2e/photon_test.py @@ -1,4 +1,4 @@ -"""Text the real daemon through Photon's SDK and resume the chat after restart.""" +"""A paired iMessage turn can text back once, even when Photon replays it.""" import json from pathlib import Path @@ -9,6 +9,8 @@ import unittest from harness import Albedo, Provider, exclusive, python, text, wait_until FIXTURE = Path(__file__).parent.resolve() / "fixtures" / "photon" +RECIPIENT = "+15550101111" +ASSIGNED_NUMBER = "+15550101122" @exclusive @@ -42,6 +44,25 @@ class PhotonTests(unittest.TestCase): temporary.write_text(json.dumps(self.events)) temporary.replace(path) + def start_provider_fixture(self, app): + helper = shutil.which("albedo-photon") + assert helper is not None, "the development shell must provide albedo-photon" + server = subprocess.Popen( + ["node", FIXTURE / "server.cjs", Path(helper).resolve(), app.root] + ) + self.addCleanup(server.wait) + self.addCleanup(server.terminate) + address = app.root / "address" + cloud = app.root / "cloud" + wait_until( + lambda: address.exists() and cloud.exists(), 10, "fixture failed to bind" + ) + app.env.update( + SSL_CERT_FILE=str(FIXTURE / "localhost.pem"), + NIX_SSL_CERT_FILE=str(FIXTURE / "localhost.pem"), + ) + return address.read_text(), cloud.read_text() + def test_text_and_resume(self): provider = Provider(self.respond) self.addCleanup(provider.close) @@ -49,62 +70,187 @@ class PhotonTests(unittest.TestCase): session = self.app.session() self.events = [] self.publish({"guid": "old", "text": "before pairing"}) - helper = shutil.which("albedo-photon") - assert helper is not None, ( - "the development shell must provide albedo-photon" + address, _ = self.start_provider_fixture(self.app) + token_file = self.app.root / "photon-token" + token_file.write_text("local-fixture-token\n") + token_file.chmod(0o600) + + def pair(app): + app.write_extensions({"enabled": {"photon": True}}) + app.env.update( + ALBEDO_PHOTON_ADDRESS=address, + ALBEDO_PHOTON_TOKEN_FILE=str(token_file), + ALBEDO_PHOTON_RECIPIENT=RECIPIENT, + ALBEDO_PHOTON_SESSION_ID=session, + ) + + self.app.restart(prepare=pair) + wait_until( + lambda: any(c.get("after") == 1 for c in self.calls()), + 30, + "no initial Photon checkpoint", ) - with subprocess.Popen( - ["node", FIXTURE / "server.cjs", Path(helper).resolve(), self.app.root] - ) as server: - try: - address = self.app.root / "address" - wait_until(address.exists, 10, "fixture failed to bind") - - token_file = self.app.root / "photon-token" - token_file.write_text("local-fixture-token\n") - token_file.chmod(0o600) - - def pair(app): - app.write_extensions({"enabled": {"photon": True}}) - app.env.update( - ALBEDO_PHOTON_ADDRESS=address.read_text(), - ALBEDO_PHOTON_TOKEN_FILE=str(token_file), - ALBEDO_PHOTON_RECIPIENT="+15550101111", - ALBEDO_PHOTON_SESSION_ID=session, - SSL_CERT_FILE=str(FIXTURE / "localhost.pem"), - NIX_SSL_CERT_FILE=str(FIXTURE / "localhost.pem"), - ) - - self.app.restart(prepare=pair) - wait_until( - lambda: any(c.get("after") == 1 for c in self.calls()), - 30, - "no initial Photon checkpoint", - ) - self.publish( - {"guid": "echo", "text": "outgoing", "outgoing": True}, - {"guid": "first-text", "text": "hello"}, - ) - self.wait_reply("first-text") - self.app.restart( - prepare=lambda _: self.publish( - {"guid": "offline-text", "text": "hello again"} - ) - ) - self.wait_reply("offline-text") - sends = [c for c in self.calls() if c["kind"] == "send"] - self.assertEqual( - [c["text"] for c in sends], - ["answer to first-text", "answer to offline-text"], - ) - self.assertEqual( - {c["chatGuid"] for c in sends}, {"any;-;+15550101111"} - ) - prompts = json.dumps(provider.requests) - self.assertNotIn("iMessage [old]", prompts) - self.assertNotIn("iMessage [echo]", prompts) - finally: - server.terminate() + self.publish( + {"guid": "echo", "text": "outgoing", "outgoing": True}, + {"guid": "first-text", "text": "hello"}, + ) + self.wait_reply("first-text") + self.app.restart( + prepare=lambda _: self.publish( + {"guid": "offline-text", "text": "hello again"} + ) + ) + self.wait_reply("offline-text") + sends = [c for c in self.calls() if c["kind"] == "send"] + self.assertEqual( + [c["text"] for c in sends], + ["answer to first-text", "answer to offline-text"], + ) + self.assertEqual({c["chatGuid"] for c in sends}, {f"any;-;{RECIPIENT}"}) + prompts = json.dumps(provider.requests) + self.assertNotIn("iMessage [old]", prompts) + self.assertNotIn("iMessage [echo]", prompts) + + def test_spectrum_setup_and_automatic_replies(self): + def prepare(app): + self.app = app + self.events = [] + self.publish({"guid": "previous", "text": "before managed pairing"}) + address, cloud = self.start_provider_fixture(app) + app.env.update( + PHOTON_DASHBOARD_HOST=cloud, + PHOTON_SPECTRUM_HOST=cloud, + SPECTRUM_IMESSAGE_ADDRESS=address, + PHOTON_PROJECT_ID="fixture-project", + PHOTON_PROJECT_SECRET="fixture-secret", + ) + + def respond(request): + last = request["input"][-1] + if last.get("type") == "function_call_output": + return text("final after explicit reply") + prompt = json.dumps(last) + if "send an explicit response" in prompt: + return python( + "assert await photon.reply('explicit', 'explicit response')" + " == 'sent-guid'" + ) + if "first managed text" in prompt: + return text("first normal response") + if "new text during restart" in prompt: + return text("second normal response") + return text("answer to local prompt") + + provider = Provider(respond) + self.addCleanup(provider.close) + with Albedo(provider, protocol="responses", prepare=prepare): + session = self.app.session() + other = self.app.session() + setup = self.app.cli( + "photon", "setup", "--phone", RECIPIENT, "--session", session + ) + self.assertIn(ASSIGNED_NUMBER, setup) + self.assertNotIn("fixture-secret", setup) + pairing_file = self.app.home / "photon.json" + self.assertEqual(pairing_file.stat().st_mode & 0o777, 0o600) + with self.app.api("/extensions/photon/status") as response: + self.assertEqual( + json.load(response), {"session": session, "ready": True} + ) + + # The first text is sent as soon as setup reports success. The + # operator should never have to guess when the replay baseline exists. + self.publish({"guid": "first", "text": "first managed text"}) + self.wait_send("first normal response") + self.app.idle(session) + + hermes_env = self.app.root / "hermes.env" + hermes_env.write_text( + "PHOTON_PROJECT_ID=fixture-project\n" + 'PHOTON_PROJECT_SECRET="fixture-secret"\n' + ) + hermes_env.chmod(0o600) + self.app.env["PHOTON_PROJECT_SECRET"] = "wrong-fixture-secret" + imported = self.app.cli( + "photon", + "setup", + "--phone", + RECIPIENT, + "--session", + session, + "--from-hermes", + str(hermes_env), + ) + del self.app.env["PHOTON_PROJECT_ID"] + del self.app.env["PHOTON_PROJECT_SECRET"] + self.assertIn(ASSIGNED_NUMBER, imported) + self.assertNotIn("fixture-secret", imported) + + for session_id in (session, other): + # A local turn can even resemble a Photon inbox event. + self.app.prompt(session_id, "iMessage [first] manual request").close() + self.app.idle(session_id) + + self.publish( + {"guid": "echo", "text": "managed outgoing echo", "outgoing": True}, + { + "guid": "stranger", + "text": "stranger text", + "sender": ASSIGNED_NUMBER, + }, + {"guid": "group", "text": "group text", "chatGuid": "any;+;group"}, + {"guid": "explicit", "text": "send an explicit response"}, + ) + self.wait_send("explicit response") + self.app.idle(session) + + self.app.restart( + prepare=lambda _: self.publish( + {"guid": "first", "text": "replayed copy of the first text"}, + {"guid": "offline", "text": "new text during restart"}, + ) + ) + self.wait_send("second normal response") + self.app.idle(session) + sends = [c for c in self.calls() if c["kind"] == "send"] + self.assertEqual( + [c["text"] for c in sends], + [ + "first normal response", + "explicit response", + "second normal response", + ], + ) + self.assertEqual({c["chatGuid"] for c in sends}, {f"any;-;{RECIPIENT}"}) + self.assertTrue(all(not c.get("replyTo") for c in sends)) + self.assertEqual( + sum( + c.get("route") == "POST /projects/fixture-project/users/" + for c in self.calls() + ), + 1, + ) + prompts = json.dumps(provider.requests) + for ignored in ( + "before managed pairing", + "managed outgoing echo", + "stranger text", + "group text", + "replayed copy of the first text", + ): + self.assertNotIn(ignored, prompts) + status = self.app.cli("photon", "status") + self.assertIn(ASSIGNED_NUMBER, status) + self.assertNotIn("fixture-secret", status) + + def wait_send(self, text): + wait_until( + lambda: any( + c["kind"] == "send" and c["text"] == text for c in self.calls() + ), + 30, + f"no iMessage with text {text!r}", + ) def wait_reply(self, guid): wait_until( diff --git a/extensions/photon/gleam.toml b/extensions/photon/gleam.toml index e91c91d06..89ca1d127 100644 --- a/extensions/photon/gleam.toml +++ b/extensions/photon/gleam.toml @@ -7,6 +7,8 @@ gleam = ">= 1.19.0" target = "erlang" [dependencies] +albedo_file = { path = "../../packages/albedo_file" } +gleam_http = ">= 4.4.0 and < 5.0.0" gleam_stdlib = ">= 1.0.0 and < 2.0.0" gleam_erlang = ">= 1.3.0 and < 2.0.0" gleam_json = ">= 3.1.0 and < 4.0.0" diff --git a/extensions/photon/manifest.toml b/extensions/photon/manifest.toml index 88181b8fd..ffcbceeae 100644 --- a/extensions/photon/manifest.toml +++ b/extensions/photon/manifest.toml @@ -46,11 +46,13 @@ packages = [ [requirements] albedo_clock = { path = "../../packages/albedo_clock" } albedo_env = { path = "../../packages/albedo_env" } +albedo_file = { path = "../../packages/albedo_file" } albedo_http = { path = "../../packages/albedo_http" } albedo_ports = { path = "../../packages/albedo_ports" } albedo_process = { path = "../../packages/albedo_process" } albedo_sdk = { path = "../../packages/albedo_sdk" } gleam_erlang = { version = ">= 1.3.0 and < 2.0.0" } +gleam_http = { version = ">= 4.4.0 and < 5.0.0" } gleam_json = { version = ">= 3.1.0 and < 4.0.0" } gleam_otp = { version = ">= 1.3.0 and < 2.0.0" } gleam_stdlib = { version = ">= 1.0.0 and < 2.0.0" } diff --git a/extensions/photon/src/albedo_ext_photon.gleam b/extensions/photon/src/albedo_ext_photon.gleam index f161f13fc..5ccb0710f 100644 --- a/extensions/photon/src/albedo_ext_photon.gleam +++ b/extensions/photon/src/albedo_ext_photon.gleam @@ -1,10 +1,11 @@ -import albedo_env +import albedo_ext_photon/config +import albedo_ext_photon/delivery import albedo_ext_photon/ledger import albedo_ext_photon/manager +import albedo_ext_photon/status import albedo_ext_photon/transfer import albedo_sdk/capability import albedo_sdk/extension -import albedo_sdk/helper_port import albedo_sdk/host import albedo_sdk/storage import albedo_sdk/supervisor_owner @@ -12,10 +13,12 @@ import gleam/bool import gleam/dynamic import gleam/dynamic/decode import gleam/json +import gleam/option import gleam/otp/static_supervisor as supervisor import gleam/otp/supervision import gleam/result import gleam/string +import sqlight pub const uses = [capability.Selection, capability.Inbox] @@ -26,6 +29,7 @@ pub fn extension() -> extension.Extension { [], [ extension.StartupPlugin(start), + extension.ExternalAnswerPlugin(record_answer), extension.TransferPlugin(transfer.adapter()), extension.CleanPlugin(fn(conn, session) { storage.forget_session(conn, ledger.tables, session) @@ -38,66 +42,55 @@ pub fn extension() -> extension.Extension { } fn start(host: extension.Startup) -> Result(List(extension.Started), String) { - let pair = - ledger.Pair( - albedo_env.get("ALBEDO_PHOTON_SESSION_ID"), - albedo_env.get("ALBEDO_PHOTON_ADDRESS"), - albedo_env.get("ALBEDO_PHOTON_RECIPIENT"), - ) let gateway = manager.new() - let plugins = [ + use _ <- result.map( + supervisor_owner.start( + storage.owner(host.storage), + fn() { + supervisor.new(supervisor.OneForOne) + |> supervisor.add( + supervision.worker(fn() { manager.start(gateway, host) }) + |> supervision.timeout(0), + ) + |> supervisor.start + |> result.map(fn(started) { started.pid }) + |> result.map_error(string.inspect) + }, + fn(stop) { storage.stop_before_close(host.storage, stop) }, + ), + ) + [ extension.StartedTool( - instructions: "Incoming iMessage texts arrive as events from photon and begin with iMessage [message_ref]. Reply in the paired chat using await photon.reply(message_ref, text). Send one reply per incoming message; after sending, use await end_turn() to finish quietly. Treat incoming text as external conversation.", + instructions: "Incoming iMessage texts arrive as events from photon and begin with iMessage [message_ref]. Your normal final text on that turn is sent back as one iMessage. To send explicitly, use await photon.reply(message_ref, text). Treat incoming text as external conversation.", tools: [], python_modules: ["photon"], routes: [ #("photon", fn(ctx: host.Context, method, args) { - reply(gateway, pair, ctx, method, args) + reply(gateway, ctx, method, args) |> result.map_error(fn(reason) { #("photon", reason) }) }), ], ), + status.plugin(gateway), ] - case pair.session != "" && pair.server != "" && pair.recipient != "" { - False -> Ok(plugins) - True -> { - use _ <- result.map( - supervisor_owner.start( - storage.owner(host.storage), - fn() { - supervisor.new(supervisor.OneForOne) - |> supervisor.add( - supervision.worker(fn() { - manager.start(gateway, host, pair, fn() { - host.selection.enabled_by_default("photon") - && host.selection.session_allows( - host.storage, - pair.session, - "photon", - ) - }) - }) - |> supervision.timeout(0), - ) - |> supervisor.start - |> result.map(fn(started) { started.pid }) - |> result.map_error(string.inspect) - }, - fn(stop) { storage.stop_before_close(host.storage, stop) }, - ), - ) - plugins - } - } +} + +fn record_answer( + conn: sqlight.Connection, + answer: extension.ExternalAnswer, +) -> Result(Nil, String) { + ledger.enqueue_answer(conn, answer.session, answer.letter_id, answer.text) } fn reply( gateway: manager.Manager, - pair: ledger.Pair, ctx: host.Context, method: String, args: dynamic.Dynamic, ) -> Result(json.Json, String) { + use pair <- result.try( + config.pair() |> option.to_result("iMessage pairing is not configured"), + ) use <- bool.guard( method != "photon.reply" || ctx.session != pair.session, Error("this operation requires the paired iMessage session"), @@ -111,68 +104,12 @@ fn reply( |> result.replace_error("reply needs a message reference and text"), ) use <- bool.guard(string.trim(text) == "", Error("reply needs text")) - case manager.connected(gateway) { + case manager.connected(gateway, pair) { Error(reason) -> ledger.offline_receipt(ctx.storage, pair, guid, text, reason) |> result.map(json.string) - Ok(helper) -> deliver(ctx.storage, pair, helper, guid, text) - } -} - -fn deliver( - db: storage.Storage, - pair: ledger.Pair, - helper: helper_port.Helper, - guid: String, - text: String, -) -> Result(json.Json, String) { - use reservation <- result.try(ledger.reserve_reply(db, pair, guid, text)) - case reservation { - ledger.AlreadySent(sent) -> Ok(json.string(sent)) - ledger.Send -> { - use outcome <- result.try(send(helper, guid, text)) - case outcome { - Sent(sent) -> - ledger.record_sent(db, pair, guid, sent) |> result.map(json.string) - Refused(code) -> { - use _ <- result.try(ledger.release_refused(db, pair, guid)) - Error("Photon refused the reply: " <> code) - } - } - } + Ok(helper) -> + delivery.reply(ctx.storage, pair, helper, guid, text) + |> result.map(json.string) } } - -type SendOutcome { - Sent(String) - Refused(String) -} - -fn send( - helper: helper_port.Helper, - guid: String, - text: String, -) -> Result(SendOutcome, String) { - use sent <- result.try( - helper_port.call( - helper, - [ - #("op", json.string("reply")), - #("guid", json.string(guid)), - #("text", json.string(text)), - #("idempotencyKey", json.string("albedo-photon-" <> guid)), - ], - 20_000, - ) - |> result.map_error(fn(reason) { - "reply delivery is uncertain; check Messages: " <> reason - }), - ) - decode.run( - sent, - decode.one_of(decode.map(decode.string, Sent), [ - decode.map(decode.at(["refused"], decode.string), Refused), - ]), - ) - |> result.replace_error("reply delivery is uncertain: invalid receipt") -} diff --git a/extensions/photon/src/albedo_ext_photon/config.gleam b/extensions/photon/src/albedo_ext_photon/config.gleam new file mode 100644 index 000000000..e8d83149e --- /dev/null +++ b/extensions/photon/src/albedo_ext_photon/config.gleam @@ -0,0 +1,68 @@ +//// The Spectrum setup command atomically publishes the pairing in Albedo's +//// home. Only absent configuration falls back to the legacy server pairing. + +import albedo_env +import albedo_ext_photon/ledger.{type Pair, Pair} +import albedo_file +import albedo_sdk/settings +import gleam/bit_array +import gleam/dynamic/decode +import gleam/json +import gleam/option.{type Option, None, Some} +import gleam/result +import gleam/string + +pub fn project_file() -> String { + albedo_file.join(settings.home(), "photon.json") +} + +pub fn pair() -> Option(Pair) { + case albedo_file.read_optional(project_file()) { + Ok(None) -> + validated(Pair( + albedo_env.get("ALBEDO_PHOTON_SESSION_ID"), + albedo_env.get("ALBEDO_PHOTON_ADDRESS"), + albedo_env.get("ALBEDO_PHOTON_RECIPIENT"), + )) + Ok(Some(bytes)) -> { + let decoded = { + use raw <- result.try(bit_array.to_string(bytes)) + json.parse(raw, { + use project <- decode.field("projectId", decode.string) + use session <- decode.field("session", decode.string) + use recipient <- decode.field("recipient", decode.string) + decode.success(Pair(session, "spectrum:" <> project, recipient)) + }) + |> result.replace_error(Nil) + } + case decoded { + Ok(pair) if pair.server != "spectrum:" -> validated(pair) + _ -> None + } + } + Error(_) -> None + } +} + +fn validated(pair: Pair) -> Option(Pair) { + case pair.session != "" && pair.server != "" && pair.recipient != "" { + True -> Some(pair) + False -> None + } +} + +pub fn environment(pair: Pair) -> List(#(String, String)) { + let auth = case string.split_once(pair.server, ":") { + Ok(#("spectrum", project)) -> [ + #("PHOTON_PROJECT_FILE", project_file()), + #("PHOTON_PROJECT_ID", project), + ] + _ -> [ + #("PHOTON_PROJECT_FILE", ""), + #("PHOTON_ADDRESS", pair.server), + #("PHOTON_TOKEN", albedo_env.get("PHOTON_TOKEN")), + #("ALBEDO_PHOTON_TOKEN_FILE", albedo_env.get("ALBEDO_PHOTON_TOKEN_FILE")), + ] + } + [#("PHOTON_RECIPIENT", pair.recipient), ..auth] +} diff --git a/extensions/photon/src/albedo_ext_photon/delivery.gleam b/extensions/photon/src/albedo_ext_photon/delivery.gleam new file mode 100644 index 000000000..7400f91f0 --- /dev/null +++ b/extensions/photon/src/albedo_ext_photon/delivery.gleam @@ -0,0 +1,75 @@ +//// The single send path shared by automatic answers and explicit replies. + +import albedo_ext_photon/ledger +import albedo_sdk/helper_port +import albedo_sdk/storage +import gleam/dynamic/decode +import gleam/json +import gleam/result + +pub fn reply( + db: storage.Storage, + pair: ledger.Pair, + helper: helper_port.Helper, + guid: String, + text: String, +) -> Result(String, String) { + use reservation <- result.try(ledger.reserve_reply(db, pair, guid, text)) + case reservation { + ledger.AlreadySent(sent) -> Ok(sent) + ledger.Send -> send_reserved(db, pair, helper, guid, text) + } +} + +/// Sends once for a reservation the caller already owns. +pub fn send_reserved( + db: storage.Storage, + pair: ledger.Pair, + helper: helper_port.Helper, + guid: String, + text: String, +) -> Result(String, String) { + use outcome <- result.try(send(helper, guid, text)) + case outcome { + Sent("") -> Error("reply delivery is uncertain: invalid receipt") + Sent(sent) -> ledger.record_sent(db, pair, guid, sent) + Refused(code) -> { + use _ <- result.try(ledger.release_refused(db, pair, guid)) + Error("Photon refused the reply: " <> code) + } + } +} + +type SendOutcome { + Sent(String) + Refused(String) +} + +fn send( + helper: helper_port.Helper, + guid: String, + text: String, +) -> Result(SendOutcome, String) { + use sent <- result.try( + helper_port.call( + helper, + [ + #("op", json.string("reply")), + #("guid", json.string(guid)), + #("text", json.string(text)), + #("idempotencyKey", json.string("albedo-photon-" <> guid)), + ], + 20_000, + ) + |> result.map_error(fn(reason) { + "reply delivery is uncertain; check Messages: " <> reason + }), + ) + decode.run( + sent, + decode.one_of(decode.map(decode.string, Sent), [ + decode.map(decode.at(["refused"], decode.string), Refused), + ]), + ) + |> result.replace_error("reply delivery is uncertain: invalid receipt") +} diff --git a/extensions/photon/src/albedo_ext_photon/ledger.gleam b/extensions/photon/src/albedo_ext_photon/ledger.gleam index 617c87f8f..db2ba15b2 100644 --- a/extensions/photon/src/albedo_ext_photon/ledger.gleam +++ b/extensions/photon/src/albedo_ext_photon/ledger.gleam @@ -6,6 +6,7 @@ import albedo_sdk/session_info import albedo_sdk/sessions import albedo_sdk/storage import gleam/bit_array +import gleam/bool import gleam/dynamic/decode import gleam/json import gleam/list @@ -22,7 +23,9 @@ pub type Text { Text(guid: String, text: String) } -pub const tables = ["photon_checkpoints", "photon_messages", "photon_replies"] +pub const tables = [ + "photon_checkpoints", "photon_messages", "photon_replies", "photon_outbox", +] pub fn initialise( db: storage.Storage, @@ -44,6 +47,11 @@ pub fn initialise( session TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, server TEXT NOT NULL, recipient TEXT NOT NULL, guid TEXT NOT NULL, text TEXT NOT NULL, sent_guid TEXT, + PRIMARY KEY (session, server, recipient, guid)); + CREATE TABLE IF NOT EXISTS photon_outbox ( + session TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE, + server TEXT NOT NULL, recipient TEXT NOT NULL, guid TEXT NOT NULL, + text TEXT NOT NULL, PRIMARY KEY (session, server, recipient, guid));", )) } @@ -98,11 +106,7 @@ pub fn receive_event( use _ <- result.try(case message { None -> Ok(Nil) Some(text) -> { - let key = - json.to_string(json.array( - ["photon", pair.session, pair.server, pair.recipient, text.guid], - json.string, - )) + let key = letter_key(pair, text.guid) let body = bounded_body("iMessage [" <> text.guid <> "]: " <> text.text) use _ <- result.try( inbox.post_in( @@ -113,7 +117,7 @@ pub fn receive_event( letter.Event, body, body, - letter.AfterTurn, + letter.Alone, input.Once(key), ), ) @@ -133,6 +137,89 @@ pub fn receive_event( ) } +fn letter_key(pair: Pair, guid: String) -> String { + json.to_string(json.array( + ["photon", pair.session, pair.server, pair.recipient, guid], + json.string, + )) +} + +/// Called inside the turn completion transaction. The inbox row ID is trusted +/// turn metadata and must match a message received by this exact pairing. +pub fn enqueue_answer( + conn: sqlight.Connection, + session: String, + letter_id: String, + text: String, +) -> Result(Nil, String) { + case json.parse(letter_id, decode.list(decode.string)) { + Ok(["photon", addressed, server, recipient, guid]) if addressed == session -> { + let pair = Pair(session, server, recipient) + storage.run( + conn, + "INSERT INTO photon_outbox (session,server,recipient,guid,text) + SELECT session,server,recipient,guid,?5 FROM photon_messages + WHERE session=?1 AND server=?2 AND recipient=?3 AND guid=?4 + AND NOT EXISTS ( + SELECT 1 FROM photon_replies r + WHERE r.session=?1 AND r.server=?2 AND r.recipient=?3 AND r.guid=?4 + ) + ON CONFLICT DO NOTHING", + list.append(keys(pair), [sqlight.text(guid), sqlight.text(text)]), + ) + } + _ -> Ok(Nil) + } +} + +fn queued_in( + conn: sqlight.Connection, + pair: Pair, +) -> Result(List(#(String, String)), String) { + storage.rows( + conn, + "SELECT guid,text FROM photon_outbox + WHERE session=? AND server=? AND recipient=? ORDER BY rowid LIMIT 1", + keys(pair), + { + use guid <- decode.field(0, decode.string) + use text <- decode.field(1, decode.string) + decode.success(#(guid, text)) + }, + ) +} + +/// Consumes one queued reply and reserves it in the same transaction. A daemon +/// crash before that commit retains the queued reply. After the commit any +/// missing receipt is uncertain and cannot authorize another send. +pub fn claim_queued( + db: storage.Storage, + pair: Pair, +) -> Result(Option(#(String, String)), String) { + use queued <- result.try(storage.reading(db, queued_in(_, pair))) + use <- bool.guard(queued == [], Ok(None)) + use conn <- storage.writing(db) + use <- storage.transaction(conn) + use _ <- result.try(require_active(db, conn, pair)) + use queued <- result.try(queued_in(conn, pair)) + case queued { + [#(guid, text)] -> { + let key = list.append(keys(pair), [sqlight.text(guid)]) + use reserved <- result.try(reserve_in(conn, key, text)) + use _ <- result.try(storage.run( + conn, + "DELETE FROM photon_outbox WHERE session=? AND server=? AND recipient=? AND guid=?", + key, + )) + case reserved { + True -> Ok(Some(#(guid, text))) + False -> Ok(None) + } + } + _ -> Ok(None) + } +} + // A prefix can end inside a multibyte code point. Remove only that suffix. fn valid_prefix(bytes: BitArray, size: Int) -> String { case bytes { @@ -176,19 +263,10 @@ pub fn reserve_reply( use conn <- storage.writing(db) use <- storage.transaction(conn) use _ <- result.try(require_active(db, conn, pair)) - use reserved <- result.try(storage.rows( - conn, - " - INSERT INTO photon_replies(session,server,recipient,guid,text) - SELECT session,server,recipient,guid,?5 FROM photon_messages - WHERE session=?1 AND server=?2 AND recipient=?3 AND guid=?4 - ON CONFLICT DO NOTHING RETURNING 1", - list.append(key, [sqlight.text(text)]), - decode.at([0], decode.int), - )) + use reserved <- result.try(reserve_in(conn, key, text)) case reserved { - [_] -> Ok(Send) - _ -> + True -> Ok(Send) + False -> previous_reply( conn, key, @@ -199,6 +277,23 @@ pub fn reserve_reply( } } +fn reserve_in( + conn: sqlight.Connection, + key: List(sqlight.Value), + text: String, +) -> Result(Bool, String) { + use rows <- result.map(storage.rows( + conn, + "INSERT INTO photon_replies(session,server,recipient,guid,text) + SELECT session,server,recipient,guid,?5 FROM photon_messages + WHERE session=?1 AND server=?2 AND recipient=?3 AND guid=?4 + ON CONFLICT DO NOTHING RETURNING 1", + list.append(key, [sqlight.text(text)]), + decode.at([0], decode.int), + )) + rows != [] +} + fn previous_reply( conn: sqlight.Connection, key: List(sqlight.Value), diff --git a/extensions/photon/src/albedo_ext_photon/manager.gleam b/extensions/photon/src/albedo_ext_photon/manager.gleam index c8a13fa46..e079ef165 100644 --- a/extensions/photon/src/albedo_ext_photon/manager.gleam +++ b/extensions/photon/src/albedo_ext_photon/manager.gleam @@ -1,5 +1,6 @@ import albedo_clock -import albedo_env +import albedo_ext_photon/config +import albedo_ext_photon/delivery import albedo_ext_photon/ledger.{type Pair} import albedo_http/route import albedo_ports @@ -8,8 +9,10 @@ import albedo_sdk/extension import albedo_sdk/helper_port import albedo_sdk/host_resources import albedo_sdk/network +import gleam/bool import gleam/dynamic/decode import gleam/erlang/process.{type Subject} +import gleam/io import gleam/json import gleam/option.{type Option, None, Some} import gleam/otp/actor @@ -26,14 +29,15 @@ pub fn new() -> Manager { pub opaque type Message { Tick Line(generation: Int, line: String) - Lookup(reply: Subject(Option(helper_port.Helper))) + Lookup(pair: Pair, reply: Subject(Option(helper_port.Helper))) } type State { State( host: extension.Startup, - enabled: fn() -> Bool, - pair: Pair, + pair: Option(Pair), + ready: Bool, + sender: Option(process.Pid), self: Subject(Message), generation: Int, helper: Option(helper_port.Helper), @@ -43,13 +47,11 @@ type State { pub fn start( manager: Manager, host: extension.Startup, - pair: Pair, - enabled: fn() -> Bool, ) -> Result(actor.Started(Subject(Message)), actor.StartError) { actor.new_with_initialiser(5000, fn(self) { process.send(self, Tick) Ok( - actor.initialised(State(host, enabled, pair, self, 0, None)) + actor.initialised(State(host, None, False, None, self, 0, None)) |> actor.returning(self), ) }) @@ -58,8 +60,11 @@ pub fn start( |> actor.start } -pub fn connected(manager: Manager) -> Result(helper_port.Helper, String) { - actor_call.try_call(process.named_subject(manager.name), 5000, Lookup) +pub fn connected( + manager: Manager, + pair: Pair, +) -> Result(helper_port.Helper, String) { + actor_call.try_call(process.named_subject(manager.name), 5000, Lookup(pair, _)) |> result.replace_error("Photon manager is unavailable") |> result.try(fn(helper) { option.to_result(helper, "Photon is disconnected") @@ -71,63 +76,127 @@ fn disconnect(state: State) -> State { Some(port) -> helper_port.close(port) None -> Nil } - State(..state, helper: None) + State(..state, helper: None, ready: False) } fn handle(state: State, message: Message) -> actor.Next(State, Message) { case message { - Lookup(reply) -> { - process.send(reply, case online_allowed(state) { + Lookup(pair, reply) -> { + let available = + state.ready + && state.pair == Some(pair) + && configured(state.host, pair) + && option.map(state.helper, fn(h) { + process.is_alive(helper_port.pid(h)) + }) + == Some(True) + process.send(reply, case available { True -> state.helper False -> None }) actor.continue(state) } Tick -> { - albedo_clock.send_after(state.self, 2000, Tick) - case online_allowed(state), state.helper { - False, _ -> actor.continue(disconnect(state)) - True, Some(port) -> - case process.is_alive(helper_port.pid(port)) { - True -> actor.continue(state) - False -> actor.continue(disconnect(state)) - } - True, None -> actor.continue(connect(state)) + albedo_clock.send_after(state.self, 1500, Tick) + let pair = case state.host.selection.enabled_by_default("photon") { + True -> config.pair() + False -> None + } + let state = case pair == state.pair { + True -> state + False -> State(..disconnect(state), pair:) } + actor.continue(case pair { + None -> state + Some(current) -> reconcile(state, current) + }) } - Line(generation, line) -> - case state.helper { - Some(port) if generation == state.generation -> - case accept(state, line) { - Ok(sequence) -> { - helper_port.notify(port, [ - #("op", json.string("ack")), - #("sequence", json.int(sequence)), - ]) - actor.continue(state) - } - Error(_) -> actor.continue(disconnect(state)) - } - _ -> actor.continue(state) + Line(generation, line) -> { + let next = case state.pair, state.helper { + Some(pair), Some(port) if generation == state.generation -> { + handle_line(state, pair, port, line) + } + _, _ -> state + } + actor.continue(next) + } + } +} + +fn handle_line( + state: State, + pair: Pair, + helper: helper_port.Helper, + line: String, +) -> State { + use <- bool.lazy_guard(!configured(state.host, pair), fn() { + disconnect(state) + }) + case json.parse(line, decode.field("type", decode.string, decode.success)) { + Ok("ready") -> State(..state, ready: True) + Ok("event") -> + case accept(state, pair, line) { + Ok(sequence) -> { + helper_port.notify(helper, [ + #("op", json.string("ack")), + #("sequence", json.int(sequence)), + ]) + state + } + Error(_) -> disconnect(state) } + _ -> disconnect(state) } } -fn connect(state: State) -> State { +fn reconcile(state: State, pair: Pair) -> State { + case permitted(state.host, pair), state.helper { + False, _ -> disconnect(state) + True, None -> connect(state, pair) + True, Some(helper) -> + case process.is_alive(helper_port.pid(helper)) { + False -> disconnect(state) + True -> drain(state, pair, helper) + } + } +} + +fn drain(state: State, pair: Pair, helper: helper_port.Helper) -> State { + use <- bool.guard( + !state.ready || option.map(state.sender, process.is_alive) == Some(True), + state, + ) + case ledger.claim_queued(state.host.storage, pair) { + Ok(Some(#(guid, text))) -> { + let db = state.host.storage + let pid = + process.spawn(fn() { + case delivery.send_reserved(db, pair, helper, guid, text) { + Ok(_) -> Nil + Error(reason) -> + io.println_error("photon: automatic reply: " <> reason) + } + }) + State(..state, sender: Some(pid)) + } + _ -> state + } +} + +fn connect(state: State, pair: Pair) -> State { let generation = state.generation + 1 - let env = [ - #("PHOTON_ADDRESS", state.pair.server), - #("PHOTON_RECIPIENT", state.pair.recipient), - #("PHOTON_TOKEN", albedo_env.get("PHOTON_TOKEN")), - #("ALBEDO_PHOTON_TOKEN_FILE", albedo_env.get("ALBEDO_PHOTON_TOKEN_FILE")), - ] let opened = { - use after <- result.try(ledger.cursor(state.host.storage, state.pair)) + use after <- result.try(ledger.cursor(state.host.storage, pair)) use helper <- result.map( helper_port.open( - host_resources.PythonScript("albedo_photon.py", "photon-bridge", env, [ - albedo_ports.Line(65_536), - ]), + host_resources.PythonScript( + "albedo_photon.py", + "photon-bridge", + config.environment(pair), + [ + albedo_ports.Line(65_536), + ], + ), fn(line) { process.send(state.self, Line(generation, line)) }, ), ) @@ -137,10 +206,10 @@ fn connect(state: State) -> State { ]) helper } - State(..state, generation:, helper: option.from_result(opened)) + State(..state, generation:, helper: option.from_result(opened), ready: False) } -fn accept(state: State, line: String) -> Result(Int, String) { +fn accept(state: State, pair: Pair, line: String) -> Result(Int, String) { use #(sequence, message) <- result.try( json.parse(line, { use kind <- decode.field("type", decode.string) @@ -160,22 +229,24 @@ fn accept(state: State, line: String) -> Result(Int, String) { }) |> result.replace_error("invalid photon event"), ) - case online_allowed(state) { - True -> - ledger.receive_event( - state.host.storage, - state.host.inbox, - state.pair, - sequence, - message, - ) - |> result.replace(sequence) - False -> Error("Photon disabled") - } + ledger.receive_event( + state.host.storage, + state.host.inbox, + pair, + sequence, + message, + ) + |> result.replace(sequence) +} + +fn configured(host: extension.Startup, pair: Pair) -> Bool { + config.pair() == Some(pair) + && host.selection.enabled_by_default("photon") + && permitted(host, pair) } -fn online_allowed(state: State) -> Bool { - state.enabled() - && ledger.active(state.host.storage, state.pair) +fn permitted(host: extension.Startup, pair: Pair) -> Bool { + host.selection.session_allows(host.storage, pair.session, "photon") + && ledger.active(host.storage, pair) && network.resolve(network.Extension("photon")) == Ok(route.Direct) } diff --git a/extensions/photon/src/albedo_ext_photon/status.gleam b/extensions/photon/src/albedo_ext_photon/status.gleam new file mode 100644 index 000000000..e43fe723a --- /dev/null +++ b/extensions/photon/src/albedo_ext_photon/status.gleam @@ -0,0 +1,54 @@ +//// The local operator checks this before sending the first text. + +import albedo_ext_photon/config +import albedo_ext_photon/manager +import albedo_sdk/extension +import albedo_sdk/http_api as api +import gleam/http +import gleam/json +import gleam/option.{None, Some} +import gleam/result + +pub fn plugin(gateway: manager.Manager) -> extension.Started { + extension.StartedService( + extension.Service( + fn(_, _) { extension.Admission(extension.DaemonToken, 0) }, + fn(_, path, req, _) { + let response = { + use _ <- result.try(api.accepts_json(req)) + use _ <- result.try(api.parameters(req, [])) + case path, req.method { + ["status"], http.Get -> { + let #(session, ready) = case config.pair() { + Some(pair) -> #( + Some(pair.session), + result.is_ok(manager.connected(gateway, pair)), + ) + None -> #(None, False) + } + Ok(api.reply( + 200, + json.object([ + #("session", json.nullable(session, json.string)), + #("ready", json.bool(ready)), + ]), + )) + } + ["status"], _ -> + Error(api.Failure( + 405, + "method_not_allowed", + "Photon status requires GET", + )) + _, _ -> + Error(api.Failure(404, "not_found", "Photon route not found")) + } + } + case response { + Ok(reply) -> reply + Error(reason) -> api.fail(reason) + } + }, + ), + ) +} diff --git a/extensions/photon/src/albedo_ext_photon/transfer.gleam b/extensions/photon/src/albedo_ext_photon/transfer.gleam index 95293bd2d..526bf6779 100644 --- a/extensions/photon/src/albedo_ext_photon/transfer.gleam +++ b/extensions/photon/src/albedo_ext_photon/transfer.gleam @@ -10,6 +10,10 @@ pub fn adapter() -> transfer.Adapter { "photon_messages", "Message GUIDs authorize replies on the source daemon's pairing.", ), + Excluded( + "photon_outbox", + "Queued replies belong to the source daemon's configured Photon pairing.", + ), Excluded( "photon_replies", "Reply reservations and provider receipts belong to the source daemon that submitted each send.", diff --git a/nix/packages/albedo.nix b/nix/packages/albedo.nix index 22d62eb97..b270e03f6 100644 --- a/nix/packages/albedo.nix +++ b/nix/packages/albedo.nix @@ -6,14 +6,16 @@ web, render, usageCore, + photon, }: symlinkJoin { name = "albedo-${tui.version}"; - paths = [tui daemon]; + paths = [tui daemon photon]; nativeBuildInputs = [makeBinaryWrapper]; postBuild = '' rm $out/bin/albedo makeBinaryWrapper ${tui}/bin/albedo $out/bin/albedo --inherit-argv0 \ + --prefix PATH : ${photon}/bin \ --set-default ALBEDO_DAEMON ${daemon}/bin/albedo-daemon \ --set-default ALBEDO_WEB_DIST ${web} ''; diff --git a/nix/packages/default.nix b/nix/packages/default.nix index 8288d546a..2ab690c8d 100644 --- a/nix/packages/default.nix +++ b/nix/packages/default.nix @@ -13,7 +13,7 @@ photon = pkgs.callPackage ./photon.nix {}; tui = pkgs.callPackage ./tui.nix {inherit daemon;}; albedo = pkgs.callPackage ./albedo.nix { - inherit tui daemon web render usageCore; + inherit tui daemon web render usageCore photon; }; in { packages = { diff --git a/nix/packages/photon.nix b/nix/packages/photon.nix index d9cbf0e97..3bda819e3 100644 --- a/nix/packages/photon.nix +++ b/nix/packages/photon.nix @@ -12,6 +12,7 @@ buildNpmPackage { ../../tools/photon/package-lock.json ../../tools/photon/albedo-photon ../../tools/photon/bridge.mjs + ../../tools/photon/spectrum.mjs ]; }; npmDepsHash = "sha256-aRRaX7EHc4p37hlj2dlZlFfdLo4eVEAEwBY/ekYGT9A="; diff --git a/packages/albedo_sdk/src/albedo_sdk/extension.gleam b/packages/albedo_sdk/src/albedo_sdk/extension.gleam index 433e3eee8..751efccba 100644 --- a/packages/albedo_sdk/src/albedo_sdk/extension.gleam +++ b/packages/albedo_sdk/src/albedo_sdk/extension.gleam @@ -306,6 +306,10 @@ pub type Started { StartedTransfer(adapter: transfer.Adapter) } +pub type ExternalAnswer { + ExternalAnswer(session: String, letter_id: String, text: String) +} + /// What a session reports to its managed extensions as it works, in order. /// `observe` runs inside the session actor, so it must only send and return. pub type SessionEvent { @@ -682,6 +686,11 @@ pub type Plugin { /// managed contribution's hook. Use a managed contribution only when the /// hook needs something prepared, such as `Preparation.letters`. HookPlugin(hook: fn(hook.Context, hook.Event) -> hook.Verdict) + /// Records a final answer to an isolated external input. The callback runs + /// inside the turn completion transaction and may only write its own tables. + ExternalAnswerPlugin( + record: fn(sqlight.Connection, ExternalAnswer) -> Result(Nil, String), + ) CompactionPlugin(strategy: compaction.Strategy) /// A layer over whichever compaction strategy is active. NotesPlugin(notes: compaction.Notes) diff --git a/release/appimage/AppRun b/release/appimage/AppRun index b578c7b2c..c8a484abb 100755 --- a/release/appimage/AppRun +++ b/release/appimage/AppRun @@ -16,4 +16,5 @@ if [ -z "${APPIMAGE:-}" ]; then exit 1 fi export ALBEDO_DAEMON="$APPIMAGE" ALBEDO_APPIMAGE_DAEMON=1 ALBEDO_WEB_DIST="${ALBEDO_WEB_DIST:-$HERE/web}" +export PATH="$HERE/bin:$PATH" exec "$HERE/bin/albedo" "$@" diff --git a/release/inside.sh b/release/inside.sh index 3e3f81308..ee55a3885 100755 --- a/release/inside.sh +++ b/release/inside.sh @@ -92,7 +92,7 @@ rm -f "$tree/lib/albedo/albedo/priv/python/package.nix" install -m 755 /work/release/albedo-daemon "$tree/bin/albedo-daemon" # The opt-in iMessage helper owns its SDK dependencies and Node runtime. mkdir -p "$tree/lib/photon" -cp tools/photon/{package.json,package-lock.json,bridge.mjs,albedo-photon} "$tree/lib/photon/" +cp tools/photon/{package.json,package-lock.json,bridge.mjs,spectrum.mjs,albedo-photon} "$tree/lib/photon/" npm ci --prefix "$tree/lib/photon" --omit=dev --ignore-scripts --no-audit --no-fund install -m 755 /tools/node/bin/node "$tree/lib/photon/node" install -m 644 /tools/node/LICENSE "$tree/lib/photon/LICENSE.node" @@ -100,7 +100,7 @@ cp -L "$(gcc -print-file-name=libstdc++.so.6)" "$(gcc -print-file-name=libgcc_s. cat >"$tree/bin/albedo-photon" <<'EOF' #!/bin/sh root="$(dirname "$(readlink -f "$0")")/../lib/photon" -LD_LIBRARY_PATH="$root${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" exec "$root/node" "$root/albedo-photon" +LD_LIBRARY_PATH="$root${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" exec "$root/node" "$root/albedo-photon" "$@" EOF chmod +x "$tree/bin/albedo-photon" diff --git a/release/packages/albedo b/release/packages/albedo index 8203b8c70..0b7d6b365 100755 --- a/release/packages/albedo +++ b/release/packages/albedo @@ -3,4 +3,5 @@ # packaged daemon and web client unless the environment names others. export ALBEDO_DAEMON="${ALBEDO_DAEMON:-/usr/lib/albedo/bin/albedo-daemon}" export ALBEDO_WEB_DIST="${ALBEDO_WEB_DIST:-/usr/lib/albedo/web}" +export PATH="/usr/lib/albedo/bin:$PATH" exec /usr/lib/albedo/bin/albedo "$@" diff --git a/release/smoke.sh b/release/smoke.sh index e6639b395..a55563307 100755 --- a/release/smoke.sh +++ b/release/smoke.sh @@ -46,6 +46,7 @@ if [ -e /dev/fuse ]; then fuse=(--device /dev/fuse --cap-add SYS_ADMIN); fi # Load the shipped Node runtime and Photon SDK without opening a connection. release_root="$(dirname "$(dirname "$(dirname "$kernel_python")")")" PHOTON_TOKEN=smoke PHOTON_ADDRESS=localhost:443 "$release_root/bin/albedo-photon" /dev/null || break; sleep 0.1; done if kill -0 "$pid" 2>/dev/null; then echo "daemon $pid still running"; exit 1; fi diff --git a/robot-docs/photon.md b/robot-docs/photon.md index 16f8e93b9..dda776883 100644 --- a/robot-docs/photon.md +++ b/robot-docs/photon.md @@ -3,9 +3,29 @@ [Pair a contact](../docs/photon.md) to receive direct iMessage texts in an existing session. The [extension](../extensions/photon/src/albedo_ext_photon.gleam) registers its -inbox storage and the session-scoped Python reply binding. The -[manager](../extensions/photon/src/albedo_ext_photon/manager.gleam) owns the -helper process and checks selection and the direct network route. +inbox storage, external answer callback, and session-scoped Python reply +binding. The [manager](../extensions/photon/src/albedo_ext_photon/manager.gleam) +owns the helper process and checks selection and the direct network route. + +## Pairing and readiness + +The [setup helper](../tools/photon/spectrum.mjs) writes `photon.json` in the +Albedo home. The +[pairing reader](../extensions/photon/src/albedo_ext_photon/config.gleam) reads +the session, project and contact when the manager reconciles. The helper +exchanges the project credentials for renewable iMessage credentials. The +[local status endpoint](../extensions/photon/src/albedo_ext_photon/status.gleam) +reports ready after the helper finishes its first replay and the daemon +acknowledges its checkpoint. + +For an existing Advanced iMessage server, leave `photon.json` absent. Set +`ALBEDO_PHOTON_SESSION_ID`, `ALBEDO_PHOTON_ADDRESS` (`host:port`), +`ALBEDO_PHOTON_RECIPIENT` (email or E.164 number), and either +`ALBEDO_PHOTON_TOKEN_FILE` or `PHOTON_TOKEN` in the daemon environment. Enable +`photon` globally and for the session. Restart to apply daemon environment +changes. A checkout outside the development shell needs +`npm ci --prefix tools/photon` and the checkout's `tools/photon` directory on +the daemon's `PATH`. ## Receive a text @@ -18,20 +38,28 @@ incoming text from the paired sender and chat. The [ledger](../extensions/photon/src/albedo_ext_photon/ledger.gleam) posts an external event to the [inbox](inbox.md) and advances the pairing's checkpoint in the same transaction. The manager acknowledges a sequence after commit. An -incoming text waits for a running turn to finish. The inbox key includes the -message GUID, so replay can repeat a delivery without starting a second turn. +incoming text gets its own turn after the current turn finishes. The inbox key +includes the message GUID, so replay can repeat a delivery without starting a +second turn. ## Reply in Messages -The agent calls `await photon.reply(message_ref, text)` with the GUID shown on -the incoming event. The daemon checks the calling session and the saved message -reference. The helper sends the reply to the paired chat and returns the sent -message GUID. The agent can then call `await end_turn()`. The ledger reserves -one reply per incoming message before sending. Repeating the same reply returns -its stored receipt. A definite authentication or input refusal releases the -reservation for a corrected reply. If the daemon loses the outcome of a send, it -reports uncertain delivery and leaves the reservation in place to prevent a -second text. +At successful turn completion the session records its visible final answer in +the same transaction that finishes the turn. The extension matches the +daemon-issued inbox letter ID to its received message and queues the answer. The +manager drains this queue when the paired transport is ready. Text from ordinary +UI turns does not have this origin. The helper sends a regular chat message with +a stable client message ID. + +An agent can also call `await photon.reply(message_ref, text)` with the GUID +shown on the incoming event. The daemon checks the calling session and the saved +message reference. The helper sends the reply to the paired chat and returns the +sent message GUID. The agent can then call `await end_turn()`. The ledger +reserves one reply per incoming message before sending. Repeating the same reply +returns its stored receipt. The automatic and explicit paths share the +reservation. A definite authentication or input refusal releases the reservation +for a corrected reply. If the daemon loses the outcome of a send, it reports +uncertain delivery and leaves the reservation in place to prevent a second text. A session move leaves its pairing, checkpoint, and reply receipts on the source. After the move, the source stops the helper and refuses new inputs and reply diff --git a/robot-docs/plugins.md b/robot-docs/plugins.md index 692ff9a72..69b54cf17 100644 --- a/robot-docs/plugins.md +++ b/robot-docs/plugins.md @@ -54,6 +54,20 @@ both callbacks. `None` retains no resource or contribution. The opaque result prevents accidentally returning an ordinary contribution with default callbacks. Resource monitoring remains the allocator's responsibility. +## Record an external answer + +`ExternalAnswerPlugin` records the final assistant text for a successful turn +that read one outside `Event` with `Alone` delivery. The callback receives the +session ID, the inbox row ID, and the final text. Use the row ID to look up the +original delivery in your extension's tables. + +The [session's turn completion](../apps/albedo/src/albedo/session.gleam) calls +each active recorder inside the +[completion transaction](../apps/albedo/src/albedo/history/conversation.gleam). +Write only your extension's tables on the supplied connection. Leave network +delivery to a separate worker after the commit. A recorder failure rolls back +turn completion. + ## Host route context [`host.Context`](../packages/albedo_sdk/src/albedo_sdk/host.gleam) supplies the diff --git a/tools/photon/albedo-photon b/tools/photon/albedo-photon index fe5c9d01d..85d095332 100755 --- a/tools/photon/albedo-photon +++ b/tools/photon/albedo-photon @@ -9,9 +9,10 @@ import { ValidationError, } from '@photon-ai/advanced-imessage/grpc'; import { BridgeError, replayBatch } from './bridge.mjs'; +import { manage, managedConnection, readPairing } from './spectrum.mjs'; const recipient = process.env.PHOTON_RECIPIENT; -function connect() { +function advancedCredentials() { let token = process.env.PHOTON_TOKEN; if (process.env.ALBEDO_PHOTON_TOKEN_FILE) { try { @@ -23,8 +24,12 @@ function connect() { if (!token?.trim()) { throw new BridgeError('Configure PHOTON_TOKEN or ALBEDO_PHOTON_TOKEN_FILE'); } + return { address: process.env.PHOTON_ADDRESS, token }; +} + +function connect({ address, token }) { return createGrpcClient({ - address: process.env.PHOTON_ADDRESS, + address, token, // One daemon reservation authorizes one send attempt. retry: false, @@ -34,8 +39,9 @@ function connect() { }); } -const input = createInterface({ input: process.stdin, crlfDelay: Infinity }); -const commands = input[Symbol.asyncIterator](); +function writeFrame(frame) { + process.stdout.write(JSON.stringify(frame) + '\n'); +} const stop = new AbortController(); let pendingAck; @@ -43,13 +49,12 @@ async function publish(sequence, message) { const acknowledged = new Promise((resolve) => { pendingAck = { sequence, resolve }; }); - process.stdout.write( - JSON.stringify({ type: 'event', sequence, message }) + '\n', - ); + writeFrame({ type: 'event', sequence, message }); await acknowledged; } -async function receive(client, chatGuid, sequence) { +async function receive(client, chatGuid, sequence, assignedNumber) { + let ready = false; while (!stop.signal.aborted) { sequence = await replayBatch(client, { recipient, @@ -57,6 +62,10 @@ async function receive(client, chatGuid, sequence) { sequence, publish, }); + if (!ready) { + writeFrame({ type: 'ready', line: assignedNumber }); + ready = true; + } await delay(2000, undefined, { signal: stop.signal }); } } @@ -79,7 +88,7 @@ function sendFailure(error) { : { ok: false, error: `Photon send failed (${code})` }; } -async function handleCommands(client, chatGuid) { +async function handleCommands(commands, client, chatGuid) { for await (const line of commands) { const command = JSON.parse(line); if (command.op === 'ack' && pendingAck?.sequence === command.sequence) { @@ -96,22 +105,19 @@ async function handleCommands(client, chatGuid) { try { const sent = await client.messages.sendText(chatGuid, command.text, { clientMessageId: command.idempotencyKey, - replyTo: command.guid, }); response = { ok: true, result: sent.guid }; } catch (error) { response = sendFailure(error); } - process.stdout.write( - JSON.stringify({ type: 'reply', id: command.id, ...response }) + '\n', - ); + writeFrame({ type: 'reply', id: command.id, ...response }); } else { throw new BridgeError('Invalid daemon command'); } } } -async function main(client) { +async function run(commands) { const first = await commands.next(); if (first.done) return; const start = JSON.parse(first.value); @@ -122,20 +128,54 @@ async function main(client) { ) { throw new BridgeError('Invalid Photon start cursor'); } + const projectPath = process.env.PHOTON_PROJECT_FILE; + const connection = projectPath + ? await connectedProject(projectPath) + : advancedCredentials(); + const client = connect(connection); + try { + const chatGuid = connection.directChat || (await createDirectChat(client)); + await Promise.race([ + receive(client, chatGuid, start.sequence, connection.assignedNumber), + handleCommands(commands, client, chatGuid), + ]); + } finally { + stop.abort(); + await client.close(); + } +} + +async function connectedProject(path) { + const pair = await readPairing(path); + if ( + !pair || + pair.projectId !== process.env.PHOTON_PROJECT_ID || + pair.recipient !== recipient + ) { + throw new BridgeError('Photon pairing changed before starting the helper'); + } + return managedConnection(pair); +} + +async function createDirectChat(client) { const { chat } = await client.chats.create([recipient]); if (!chat.guid || chat.isGroup !== false || chat.service !== 'iMessage') { throw new BridgeError('Recipient requires a direct iMessage chat'); } - await Promise.race([ - receive(client, chat.guid, start.sequence), - handleCommands(client, chat.guid), - ]); + return chat.guid; } -let client; +let input; try { - client = connect(); - await main(client); + const [command, ...args] = process.argv.slice(2); + if (command === 'setup' || command === 'status') { + writeFrame(await manage(command, args)); + } else if (command === undefined) { + input = createInterface({ input: process.stdin, crlfDelay: Infinity }); + await run(input[Symbol.asyncIterator]()); + } else { + throw new BridgeError('Expected Photon setup or status'); + } } catch (error) { // Provider diagnostics can contain message text or addresses. console.error( @@ -148,8 +188,8 @@ try { ); process.exitCode = 1; } finally { - stop.abort(); - input.close(); - process.stdin.destroy(); - await client?.close(); + if (input) { + input.close(); + process.stdin.destroy(); + } } diff --git a/tools/photon/bridge.mjs b/tools/photon/bridge.mjs index 3e8e19eb6..dd8236511 100644 --- a/tools/photon/bridge.mjs +++ b/tools/photon/bridge.mjs @@ -1,3 +1,5 @@ +import { setTimeout as delay } from 'node:timers/promises'; + // Only messages we author may be printed in full. SDK errors can include // addresses, paths, or message content. export class BridgeError extends Error {} @@ -6,7 +8,7 @@ export class BridgeError extends Error {} export function incomingText(event, chatGuid, recipient) { if ( event.type !== 'message.received' || - event.chatGuid !== chatGuid || + event.chatGuid?.toLowerCase() !== chatGuid.toLowerCase() || event.isFromMe !== false ) { return null; @@ -19,9 +21,9 @@ export function incomingText(event, chatGuid, recipient) { message.isServiceMessage || message.reaction || message.sender?.service !== 'iMessage' || - message.sender.address.toLowerCase() !== recipient.toLowerCase() || + message.sender.address?.toLowerCase() !== recipient.toLowerCase() || !message.guid || - !message.content.text?.trim() + !message.content?.text?.trim() ) { return null; } @@ -41,12 +43,29 @@ function validSequence(value) { // become the resume cursor, including the baseline from a new pairing. export async function replayBatch( client, - { recipient, chatGuid, sequence, publish }, + { recipient, chatGuid, sequence, publish, idleTimeoutMs = 15000 }, ) { let previous = sequence; const stream = client.events.catchUp(sequence ?? undefined); + const iterator = stream[Symbol.asyncIterator](); try { - for await (const event of stream) { + for (;;) { + const timeout = new AbortController(); + let next; + try { + next = await Promise.race([ + iterator.next(), + delay(idleTimeoutMs, undefined, { signal: timeout.signal }).then( + () => { + throw new BridgeError('Photon replay stopped making progress'); + }, + ), + ]); + } finally { + timeout.abort(); + } + if (next.done) break; + const event = next.value; if (event.type === 'catchup.complete') { if ( !validSequence(event.headSequence) || @@ -73,5 +92,6 @@ export async function replayBatch( throw new BridgeError('Photon replay ended before its checkpoint'); } finally { await stream.close?.(); + await iterator.return?.(); } } diff --git a/tools/photon/spectrum.mjs b/tools/photon/spectrum.mjs new file mode 100644 index 000000000..4051b9802 --- /dev/null +++ b/tools/photon/spectrum.mjs @@ -0,0 +1,501 @@ +import { randomUUID } from 'node:crypto'; +import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import * as util from 'node:util'; +import { BridgeError } from './bridge.mjs'; + +const phonePattern = /^\+[1-9]\d{7,14}$/; +const clientId = 'photon-cli'; +const dashboard = + process.env.PHOTON_DASHBOARD_HOST || 'https://app.photon.codes'; +const spectrum = + process.env.PHOTON_SPECTRUM_HOST || 'https://spectrum.photon.codes'; + +export async function readPairing(path) { + let pairing; + try { + pairing = JSON.parse(await readFile(path, 'utf8')); + } catch (error) { + if (error.code === 'ENOENT') return null; + throw new BridgeError('Unable to read Photon pairing'); + } + if ( + !pairing || + typeof pairing.projectId !== 'string' || + !pairing.projectId || + typeof pairing.projectSecret !== 'string' || + !pairing.projectSecret || + !phonePattern.test(pairing.recipient) || + typeof pairing.session !== 'string' || + !pairing.session || + (pairing.assignedNumber !== null && + !phonePattern.test(pairing.assignedNumber)) + ) { + throw new BridgeError('Invalid Photon pairing'); + } + return pairing; +} + +async function savePairing(home, pairing) { + await mkdir(home, { recursive: true, mode: 0o700 }); + const temporary = join(home, `.photon-${randomUUID()}.json`); + try { + await writeFile(temporary, JSON.stringify(pairing) + '\n', { + mode: 0o600, + flag: 'wx', + }); + await rename(temporary, join(home, 'photon.json')); + } finally { + await rm(temporary, { force: true }); + } +} + +async function request( + host, + path, + { method = 'GET', authorization, body } = {}, +) { + const url = new URL(path, host); + if ( + url.protocol !== 'https:' && + !( + url.protocol === 'http:' && + ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) + ) + ) { + throw new BridgeError('Photon API requires HTTPS'); + } + const headers = {}; + if (authorization) headers.Authorization = authorization; + if (body !== undefined) headers['Content-Type'] = 'application/json'; + let response; + try { + response = await fetch(url, { + method, + headers, + body: body === undefined ? undefined : JSON.stringify(body), + redirect: 'error', + signal: AbortSignal.timeout(10000), + }); + } catch { + throw new BridgeError('Unable to reach Photon API'); + } + const data = await response.json().catch(() => null); + return { response, data }; +} + +async function jsonRequest(host, path, options, action) { + const { response, data } = await request(host, path, options); + if (!response.ok || !data || data.succeed === false || data.error) { + throw new BridgeError(`Photon ${action} failed (HTTP ${response.status})`); + } + return data.data ?? data; +} + +function projectOptions(pairing) { + const secret = Buffer.from( + `${pairing.projectId}:${pairing.projectSecret}`, + ).toString('base64'); + return { authorization: `Basic ${secret}` }; +} + +function projectPath(pairing, suffix) { + return `/projects/${encodeURIComponent(pairing.projectId)}/${suffix}`; +} + +function phone(value) { + const normalized = + typeof value === 'string' ? value.replace(/[^+\d]/g, '') : ''; + return phonePattern.test(normalized) ? normalized : null; +} + +function optedIn(user) { + return Boolean(user?.meta?.opt_in); +} + +async function lookupUser(pairing) { + const result = await jsonRequest( + spectrum, + projectPath(pairing, 'users/'), + projectOptions(pairing), + 'user lookup', + ); + const users = Array.isArray(result) ? result : (result.users ?? result.items); + if (!Array.isArray(users)) { + throw new BridgeError('Photon returned an invalid user list'); + } + const matches = users.filter( + (user) => phone(user?.phoneNumber) === pairing.recipient, + ); + return matches.find(optedIn) ?? matches[0]; +} + +async function createUser(pairing) { + const result = await jsonRequest( + spectrum, + projectPath(pairing, 'users/'), + { + ...projectOptions(pairing), + method: 'POST', + body: { type: 'shared', phoneNumber: pairing.recipient }, + }, + 'user registration', + ); + return result.user ?? result; +} + +function publicPairing( + pairing, + user, + assignedNumber = phone(user?.assignedPhoneNumber), +) { + return { + session: pairing.session, + recipient: pairing.recipient, + assignedNumber: assignedNumber ?? pairing.assignedNumber, + optedIn: optedIn(user), + }; +} + +async function deviceLogin() { + const code = await jsonRequest( + dashboard, + '/api/auth/device/code', + { + method: 'POST', + body: { client_id: clientId, scope: 'openid profile email' }, + }, + 'device login', + ); + if ( + typeof code.device_code !== 'string' || + typeof code.user_code !== 'string' + ) { + throw new BridgeError('Photon returned an invalid device code'); + } + const verification = new URL( + code.verification_uri_complete || code.verification_uri, + ); + if (verification.origin !== new URL(dashboard).origin) { + throw new BridgeError('Photon returned an unexpected verification URL'); + } + console.error( + `Open ${verification.href} and approve code ${code.user_code}.`, + ); + const deadline = performance.now() + (Number(code.expires_in) || 300) * 1000; + let interval = Math.max(1, Number(code.interval) || 5) * 1000; + const body = { + client_id: clientId, + device_code: code.device_code, + grant_type: 'urn:ietf:params:oauth:grant-type:device_code', + }; + while (performance.now() + interval < deadline) { + await delay(interval); + const { response, data } = await request( + dashboard, + '/api/auth/device/token', + { method: 'POST', body }, + ); + if (response.ok) { + return verifyDashboardToken(data, response.headers.get('set-auth-token')); + } + if (response.status === 429) { + interval += 10000; + continue; + } + const error = data?.error ?? data?.message; + if (error === 'slow_down') interval += 5000; + else if (error !== 'authorization_pending') { + throw new BridgeError( + `Photon device approval failed (HTTP ${response.status})`, + ); + } + } + throw new BridgeError('Photon device login timed out'); +} + +async function verifyDashboardToken(data, headerToken) { + const candidates = [ + data?.access_token, + data?.accessToken, + data?.session?.access_token, + data?.data?.access_token, + data?.data?.accessToken, + headerToken, + ]; + const tokens = new Set( + candidates + .filter((value) => typeof value === 'string') + .map((value) => + value + .trim() + .replace(/^Bearer\s+/i, '') + .trim(), + ) + .filter(Boolean), + ); + for (const token of tokens) { + const authorization = `Bearer ${token}`; + const options = { authorization }; + const session = await request(dashboard, '/api/auth/get-session', options); + const user = session.data?.user ?? session.data?.data?.user; + if ( + !session.response.ok || + !user || + typeof user !== 'object' || + !Object.keys(user).length + ) { + continue; + } + const projects = await request(dashboard, '/api/projects/', options); + const listing = projects.data; + if ( + !projects.response.ok || + !listing || + listing.succeed === false || + listing.error + ) { + continue; + } + const result = listing.data ?? listing; + const items = Array.isArray(result) + ? result + : (result.projects ?? result.items); + if (Array.isArray(items)) return { authorization, items }; + } + throw new BridgeError( + 'Photon device login returned no token authorized to manage projects', + ); +} + +async function createProject(home, recipient, session) { + const { authorization, items } = await deviceLogin(); + // Existing projects may already be sending for another gateway. + if (items.some((project) => project?.name?.toLowerCase() === 'albedo')) { + throw new BridgeError( + 'An Albedo project exists. Supply its PHOTON_PROJECT_ID and PHOTON_PROJECT_SECRET', + ); + } + const project = await jsonRequest( + dashboard, + '/api/projects', + { + method: 'POST', + authorization, + body: { + name: 'Albedo', + location: 'United States', + template: false, + observability: false, + }, + }, + 'project creation', + ); + if (typeof project.id !== 'string' || !project.id) { + throw new BridgeError('Photon returned no new project ID'); + } + const credentials = await jsonRequest( + dashboard, + `/api/projects/${encodeURIComponent(project.id)}/regenerate-secret`, + { method: 'POST', authorization, body: {} }, + 'new project credential creation', + ); + if ( + typeof credentials.projectSecret !== 'string' || + !credentials.projectSecret + ) { + throw new BridgeError('Photon returned no new project secret'); + } + const pairing = { + projectId: project.id, + projectSecret: credentials.projectSecret, + recipient, + session, + assignedNumber: null, + }; + // Save the new secret before any operation that could fail during setup. + await savePairing(home, pairing); + return pairing; +} + +async function importHermes(path, recipient, session) { + if (typeof util.parseEnv !== 'function') { + throw new BridgeError( + 'Importing Hermes needs the packaged helper or Node 20.12 or newer', + ); + } + let values; + try { + values = util.parseEnv(await readFile(path, 'utf8')); + } catch { + throw new BridgeError('Unable to read the Hermes environment file'); + } + if (!values.PHOTON_PROJECT_ID || !values.PHOTON_PROJECT_SECRET) { + throw new BridgeError( + 'The Hermes environment file has no Spectrum credentials', + ); + } + return { + projectId: values.PHOTON_PROJECT_ID, + projectSecret: values.PHOTON_PROJECT_SECRET, + recipient, + session, + assignedNumber: null, + }; +} + +async function setup( + home, + { session, phone: recipient, 'from-hermes': hermesPath }, +) { + if (!session || !phonePattern.test(recipient)) { + throw new BridgeError( + 'Photon setup requires --session and an E.164 --phone', + ); + } + if (hermesPath) { + const pairing = await importHermes(hermesPath, recipient, session); + const user = await lookupUser(pairing); + const status = publicPairing(pairing, user); + if (!user || !status.assignedNumber) { + throw new BridgeError( + 'The contact needs an assigned iMessage number in Hermes before import', + ); + } + await savePairing(home, { + ...pairing, + assignedNumber: status.assignedNumber, + }); + return status; + } + const previous = await readPairing(join(home, 'photon.json')); + const { PHOTON_PROJECT_ID: projectId, PHOTON_PROJECT_SECRET: projectSecret } = + process.env; + if (Boolean(projectId) !== Boolean(projectSecret)) { + throw new BridgeError( + 'Configure both PHOTON_PROJECT_ID and PHOTON_PROJECT_SECRET', + ); + } + const project = projectId + ? { projectId, projectSecret } + : (previous ?? (await createProject(home, recipient, session))); + const sameContact = + previous?.projectId === project.projectId && + previous.recipient === recipient; + const pairing = { + ...project, + recipient, + session, + assignedNumber: sameContact ? previous.assignedNumber : null, + }; + const user = (await lookupUser(pairing)) ?? (await createUser(pairing)); + const status = publicPairing(pairing, user); + await savePairing(home, { + ...pairing, + assignedNumber: status.assignedNumber, + }); + return status; +} + +export async function manage(command, args) { + const { values } = util.parseArgs({ + args, + options: { + home: { type: 'string' }, + ...(command === 'setup' && { + session: { type: 'string' }, + phone: { type: 'string' }, + 'from-hermes': { type: 'string' }, + }), + }, + }); + if (!values.home) + throw new BridgeError('Photon setup and status require --home'); + if (command === 'setup') return setup(values.home, values); + const pairing = await readPairing(join(values.home, 'photon.json')); + return pairing && publicPairing(pairing, await lookupUser(pairing)); +} + +export async function managedConnection(pairing) { + const user = await lookupUser(pairing); + const assignedNumber = + phone(user?.assignedPhoneNumber) ?? pairing.assignedNumber; + async function issueToken() { + return jsonRequest( + spectrum, + projectPath(pairing, 'imessage/tokens'), + { + ...projectOptions(pairing), + method: 'POST', + }, + 'iMessage authentication', + ); + } + + const initial = await issueToken(); + const dedicated = initial.type === 'dedicated'; + const shared = initial.type === 'shared'; + if (!dedicated && !shared) + throw new BridgeError('Photon returned an invalid iMessage plan'); + const instance = + dedicated && + Object.keys(initial.numbers ?? {}).find( + (id) => phone(initial.numbers[id]) === assignedNumber, + ); + if ( + dedicated && + (!assignedNumber || !instance || !/^[a-z0-9-]+$/i.test(instance)) + ) { + throw new BridgeError( + 'The paired contact has no assigned dedicated Photon line', + ); + } + const extract = (credentials) => { + const token = dedicated ? credentials.auth?.[instance] : credentials.token; + if ( + credentials.type !== initial.type || + typeof token !== 'string' || + !token + ) { + throw new BridgeError( + 'Photon returned no token for the assigned iMessage line', + ); + } + const lifetimeMs = Number(credentials.expiresIn) * 1000; + if (!Number.isFinite(lifetimeMs) || lifetimeMs <= 0) { + throw new BridgeError( + 'Photon returned an invalid iMessage token lifetime', + ); + } + return { + token, + refreshAt: + performance.now() + lifetimeMs - Math.min(lifetimeMs / 10, 30000), + }; + }; + let cached = extract(initial); + let refresh; + return { + address: dedicated + ? `${instance}.imsg.photon.codes:443` + : process.env.SPECTRUM_IMESSAGE_ADDRESS || + 'imessage.spectrum.photon.codes:443', + assignedNumber, + // Shared Spectrum projects synthesize the DM GUID without calling CreateChat. + directChat: shared ? `any;-;${pairing.recipient}` : null, + token: async () => { + if (performance.now() < cached.refreshAt) return cached.token; + refresh ??= issueToken() + .then(extract) + .then((result) => { + cached = result; + return cached.token; + }) + .finally(() => { + refresh = undefined; + }); + return refresh; + }, + }; +} diff --git a/web/src/lib/api.gen.d.ts b/web/src/lib/api.gen.d.ts index 39cbb054f..17be28fa9 100644 --- a/web/src/lib/api.gen.d.ts +++ b/web/src/lib/api.gen.d.ts @@ -1841,6 +1841,23 @@ export interface paths { patch: operations["patchHookPermission"]; trace?: never; }; + "/extensions/photon/status": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Read the local iMessage pairing and transport readiness */ + get: operations["getPhotonStatus"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/extensions/discord/bots": { parameters: { query?: never; @@ -6397,6 +6414,10 @@ export interface components { id: components["schemas"]["DiscordID"]; username: string; }; + PhotonStatus: { + session: string | null; + ready: boolean; + }; DiscordBotPage: { items: components["schemas"]["DiscordBot"][]; }; @@ -11239,6 +11260,32 @@ export interface operations { 503: components["responses"]["Problem503"]; }; }; + getPhotonStatus: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful result. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PhotonStatus"]; + }; + }; + 400: components["responses"]["Problem400"]; + 401: components["responses"]["Problem401"]; + 403: components["responses"]["Problem403"]; + 405: components["responses"]["Problem405"]; + 406: components["responses"]["Problem406"]; + 503: components["responses"]["Problem503"]; + }; + }; listDiscordBots: { parameters: { query?: never;